text:
<?php

namespace Drupal\content_moderation\Plugin\Validation\Constraint;

use Drupal\content_moderation\Entity\ModerationState as ModerationStateEntity;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\content_moderation\StateTransitionValidation;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Checks if a moderation state transition is valid.
 */
class ModerationStateConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {

  /**
   * The state transition validation.
   *
   * @var \Drupal\content_moderation\StateTransitionValidation
   */
  protected $validation;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  private $entityTypeManager;

  /**
   * The moderation info.
   *
   * @var \Drupal\content_moderation\ModerationInformationInterface
   */
  protected $moderationInformation;

  /**
   * Creates a new ModerationStateConstraintValidator instance.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\content_moderation\StateTransitionValidation $validation
   *   The state transition validation.
   * @param \Drupal\content_moderation\ModerationInformationInterface $moderation_information
   *   The moderation information.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, StateTransitionValidation $validation, ModerationInformationInterface $moderation_information) {
    $this->validation = $validation;
    $this->entityTypeManager = $entity_type_manager;
    $this->moderationInformation = $moderation_information;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('content_moderation.state_transition_validation'),
      $container->get('content_moderation.moderation_information')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function validate($value, Constraint $constraint) {
    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $value->getEntity();

    // Ignore entities that are not subject to moderation anyway.
    if (!$this->moderationInformation->isModeratedEntity($entity)) {
      return;
    }

    // Ignore entities that are being created for the first time.
    if ($entity->isNew()) {
      return;
    }

    // Ignore entities that are being moderated for the first time, such as
    // when they existed before moderation was enabled for this entity type.
    if ($this->isFirstTimeModeration($entity)) {
      return;
    }

    $original_entity = $this->moderationInformation->getLatestRevision($entity->getEntityTypeId(), $entity->id());
    if (!$entity->isDefaultTranslation() && $original_entity->hasTranslation($entity->language()->getId())) {
      $original_entity = $original_entity->getTranslation($entity->language()->getId());
    }

    if ($entity->moderation_state->target_id) {
      $new_state_id = $entity->moderation_state->target_id;
    }
    else {
      $new_state_id = $default = $this->entityTypeManager
        ->getStorage($entity->getEntityType()->getBundleEntityType())->load($entity->bundle())
        ->getThirdPartySetting('content_moderation', 'default_moderation_state');
    }
    if ($new_state_id) {
      $new_state = ModerationStateEntity::load($new_state_id);
    }
    // @todo - what if $new_state_id references something that does not exist or
    //   is null.
    if (!$this->validation->isTransitionAllowed($original_entity->moderation_state->entity, $new_state)) {
      $this->context->addViolation($constraint->message, ['%from' => $original_entity->moderation_state->entity->label(), '%to' => $new_state->label()]);
    }
  }

  /**
   * Determines if this entity is being moderated for the first time.
   *
   * If the previous version of the entity has no moderation state, we assume
   * that means it predates the presence of moderation states.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity being moderated.
   *
   * @return bool
   *   TRUE if this is the entity's first time being moderated, FALSE otherwise.
   */
  protected function isFirstTimeModeration(EntityInterface $entity) {
    $original_entity = $this->moderationInformation->getLatestRevision($entity->getEntityTypeId(), $entity->id());

    $original_id = $original_entity->moderation_state->target_id;

    return !($entity->moderation_state->target_id && $original_entity && $original_id);
  }

}


text:
package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.*;

import io.swagger.annotations.*;
import java.util.Objects;

import javax.xml.bind.annotation.*;
import org.wso2.carbon.apimgt.rest.api.util.annotations.Scope;

public class APIMonetizationUsageDTO   {

    private Map<String, String> properties = new HashMap<>();

  /**
   * Map of custom properties related to monetization usage
   **/
  public APIMonetizationUsageDTO properties(Map<String, String> properties) {
    this.properties = properties;
    return this;
  }

  @ApiModelProperty(value = "Map of custom properties related to monetization usage")
  @JsonProperty("properties")
  public Map<String, String> getProperties() {
    return properties;
  }
  public void setProperties(Map<String, String> properties) {
    this.properties = properties;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    APIMonetizationUsageDTO apIMonetizationUsage = (APIMonetizationUsageDTO) o;
    return Objects.equals(properties, apIMonetizationUsage.properties);
  }

  @Override
  public int hashCode() {
    return Objects.hash(properties);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class APIMonetizationUsageDTO {\n");

    sb.append("    properties: ").append(toIndentedString(properties)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Graphics.Containers;
using osu.Game.Audio;
using osu.Game.Beatmaps;

namespace osu.Game.Tests.Visual.Components
{
    public class TestScenePreviewTrackManager : OsuTestScene, IPreviewTrackOwner
    {
        private readonly IAdjustableAudioComponent gameTrackAudio = new AudioAdjustments();

        private readonly TestPreviewTrackManager trackManager;

        private AudioManager audio;

        public TestScenePreviewTrackManager()
        {
            trackManager = new TestPreviewTrackManager(gameTrackAudio);
        }

        protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
        {
            var dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
            dependencies.CacheAs(trackManager);
            dependencies.CacheAs<IPreviewTrackOwner>(this);
            return dependencies;
        }

        [BackgroundDependencyLoader]
        private void load(AudioManager audio)
        {
            this.audio = audio;

            Add(trackManager);
        }

        [Test]
        public void TestStartStop()
        {
            PreviewTrack track = null;

            AddStep("get track", () => track = getOwnedTrack());
            AddUntilStep("wait loaded", () => track.IsLoaded);
            AddStep("start", () => track.Start());
            AddAssert("started", () => track.IsRunning);
            AddStep("stop", () => track.Stop());
            AddAssert("stopped", () => !track.IsRunning);
        }

        [Test]
        public void TestStartMultipleTracks()
        {
            PreviewTrack track1 = null;
            PreviewTrack track2 = null;

            AddStep("get tracks", () =>
            {
                track1 = getOwnedTrack();
                track2 = getOwnedTrack();
            });

            AddUntilStep("wait loaded", () => track1.IsLoaded && track2.IsLoaded);

            AddStep("start track 1", () => track1.Start());
            AddStep("start track 2", () => track2.Start());
            AddAssert("track 1 stopped", () => !track1.IsRunning);
            AddAssert("track 2 started", () => track2.IsRunning);
            AddStep("start track 1", () => track1.Start());
            AddAssert("track 2 stopped", () => !track2.IsRunning);
            AddAssert("track 1 started", () => track1.IsRunning);
        }

        [Test]
        public void TestCancelFromOwner()
        {
            PreviewTrack track = null;

            AddStep("get track", () => track = getOwnedTrack());
            AddUntilStep("wait loaded", () => track.IsLoaded);
            AddStep("start", () => track.Start());
            AddStep("stop by owner", () => trackManager.StopAnyPlaying(this));
            AddAssert("stopped", () => !track.IsRunning);
        }

        [Test]
        public void TestCancelFromNonOwner()
        {
            TestTrackOwner owner = null;
            PreviewTrack track = null;

            AddStep("get track", () => Add(owner = new TestTrackOwner(track = getTrack())));
            AddUntilStep("wait loaded", () => track.IsLoaded);
            AddStep("start", () => track.Start());
            AddStep("attempt stop", () => trackManager.StopAnyPlaying(this));
            AddAssert("not stopped", () => track.IsRunning);
            AddStep("stop by true owner", () => trackManager.StopAnyPlaying(owner));
            AddAssert("stopped", () => !track.IsRunning);
        }

        [Test]
        public void TestNonPresentTrack()
        {
            TestPreviewTrackManager.TestPreviewTrack track = null;

            AddStep("get non-present track", () =>
            {
                Add(new TestTrackOwner(track = getTrack()));
                track.Alpha = 0;
            });
            AddUntilStep("wait loaded", () => track.IsLoaded);
            AddStep("start", () => track.Start());
            AddStep("seek to end", () => track.Track.Seek(track.Track.Length));
            AddAssert("track stopped", () => !track.IsRunning);
        }

        /// <summary>
        /// Ensures that <see cref="PreviewTrackManager.CurrentTrack"/> changes correctly.
        /// </summary>
        [Test]
        public void TestCurrentTrackChanges()
        {
            PreviewTrack track = null;
            TestTrackOwner owner = null;

            AddStep("get track", () => Add(owner = new TestTrackOwner(track = getTrack())));
            AddUntilStep("wait loaded", () => track.IsLoaded);
            AddStep("start track", () => track.Start());
            AddAssert("current is track", () => trackManager.CurrentTrack == track);
            AddStep("pause manager updates", () => trackManager.AllowUpdate = false);
            AddStep("stop any playing", () => trackManager.StopAnyPlaying(owner));
            AddAssert("current not changed", () => trackManager.CurrentTrack == track);
            AddStep("resume manager updates", () => trackManager.AllowUpdate = true);
            AddAssert("current is null", () => trackManager.CurrentTrack == null);
        }

        /// <summary>
        /// Ensures that <see cref="PreviewTrackManager"/> mutes game-wide audio tracks correctly.
        /// </summary>
        [TestCase(false)]
        [TestCase(true)]
        public void TestEnsureMutingCorrectly(bool stopAnyPlaying)
        {
            PreviewTrack track = null;
            TestTrackOwner owner = null;

            AddStep("ensure volume not zero", () =>
            {
                if (audio.Volume.Value == 0)
                    audio.Volume.Value = 1;

                if (audio.VolumeTrack.Value == 0)
                    audio.VolumeTrack.Value = 1;
            });

            AddAssert("game not muted", () => gameTrackAudio.AggregateVolume.Value != 0);

            AddStep("get track", () => Add(owner = new TestTrackOwner(track = getTrack())));
            AddUntilStep("wait loaded", () => track.IsLoaded);
            AddStep("start track", () => track.Start());
            AddAssert("game is muted", () => gameTrackAudio.AggregateVolume.Value == 0);

            if (stopAnyPlaying)
                AddStep("stop any playing", () => trackManager.StopAnyPlaying(owner));
            else
                AddStep("stop track", () => track.Stop());

            AddAssert("game not muted", () => gameTrackAudio.AggregateVolume.Value != 0);
        }

        [Test]
        public void TestOwnerNotRegistered()
        {
            PreviewTrack track = null;

            AddStep("get track", () => Add(new TestTrackOwner(track = getTrack(), registerAsOwner: false)));
            AddUntilStep("wait for loaded", () => track.IsLoaded);

            AddStep("start track", () => track.Start());
            AddUntilStep("track is running", () => track.IsRunning);

            AddStep("cancel from anyone", () => trackManager.StopAnyPlaying(this));
            AddAssert("track stopped", () => !track.IsRunning);
        }

        private TestPreviewTrackManager.TestPreviewTrack getTrack() => (TestPreviewTrackManager.TestPreviewTrack)trackManager.Get(null);

        private TestPreviewTrackManager.TestPreviewTrack getOwnedTrack()
        {
            var track = getTrack();

            LoadComponentAsync(track, Add);

            return track;
        }

        private class TestTrackOwner : CompositeDrawable, IPreviewTrackOwner
        {
            private readonly PreviewTrack track;
            private readonly bool registerAsOwner;

            public TestTrackOwner(PreviewTrack track, bool registerAsOwner = true)
            {
                this.track = track;
                this.registerAsOwner = registerAsOwner;
            }

            [BackgroundDependencyLoader]
            private void load()
            {
                LoadComponentAsync(track, AddInternal);
            }

            protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
            {
                var dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
                if (registerAsOwner)
                    dependencies.CacheAs<IPreviewTrackOwner>(this);
                return dependencies;
            }
        }

        public class TestPreviewTrackManager : PreviewTrackManager
        {
            public bool AllowUpdate = true;

            public new PreviewTrack CurrentTrack => base.CurrentTrack;

            public TestPreviewTrackManager(IAdjustableAudioComponent mainTrackAdjustments)
                : base(mainTrackAdjustments)
            {
            }

            protected override TrackManagerPreviewTrack CreatePreviewTrack(IBeatmapSetInfo beatmapSetInfo, ITrackStore trackStore) => new TestPreviewTrack(beatmapSetInfo, trackStore);

            public override bool UpdateSubTree()
            {
                if (!AllowUpdate)
                    return true;

                return base.UpdateSubTree();
            }

            public class TestPreviewTrack : TrackManagerPreviewTrack
            {
                private readonly ITrackStore trackManager;

                public new Track Track => base.Track;

                public TestPreviewTrack(IBeatmapSetInfo beatmapSetInfo, ITrackStore trackManager)
                    : base(beatmapSetInfo, trackManager)
                {
                    this.trackManager = trackManager;
                }

                protected override Track GetTrack() => trackManager.GetVirtual(100000);
            }
        }
    }
}


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Generation.Production;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.EnergyScheduling;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.Reservation;

namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.Financial
{

    public class TransmissionProviderOfferedByCollection : ObservableOppositeOrderedSet<ITransmissionProvider, ITransmissionService>
    {

        public TransmissionProviderOfferedByCollection(ITransmissionProvider parent) :
                base(parent)
        {
        }

        private void OnItemDeleted(object sender, System.EventArgs e)
        {
            this.Remove(((ITransmissionService)(sender)));
        }

        protected override void SetOpposite(ITransmissionService item, ITransmissionProvider parent)
        {
            if ((parent != null))
            {
                item.Deleted += this.OnItemDeleted;
                item.Offers = parent;
            }
            else
            {
                item.Deleted -= this.OnItemDeleted;
                if ((item.Offers == this.Parent))
                {
                    item.Offers = parent;
                }
            }
        }
    }
}


text: require 'bootstra386/rails/engine'


text: My slic3r configurations


text:
FROM docku/uwsgi
MAINTAINER Jon Chen <docku@burrito.sh>

RUN /usr/bin/pacman -Syu --needed --noconfirm uwsgi-plugin-python

ADD mtrpy.ini /etc/uwsgi/apps-enabled/mtrpy.ini


text:
(function() {
  'use strict';

  angular.module('treesApp', ['ui.tree', 'firebase', 'monospaced.elastic'])
  .controller('treesCtrl', function($scope, $firebase, $location) {
    $scope.noteId = $location.path().substring(1);
    if (!$scope.noteId) {
      window.location.replace("login.html");
    }

    localStorage.removeItem("clipboardData");

    var diffTree = function(remote, local, path, applyChange) {
      // console.log("diffTree")
      // console.log(path)
      // console.log(remote)
      // console.log(local)
      if (!remote || !local) return;
      var changed = false;
      if (!remote.children){
        if (0 != local.children.length)
          changed = true;
        else
          changed = false
      } else {
        if (remote.children.length != local.children.length)
          changed = true;
        else {
          for (var i = 0; i < remote.children.length; i++) {
            if (remote.children[i].key != local.children[i].key) {
              changed = true;
              break;
            } else {

            }
          }
        }
      }

      if (changed) {
        applyChange(remote, local, path);
      } else {
        if (!!remote.children && !!local.children) {
          for (var i = 0; i < remote.children.length; i++) {
            diffTree(remote.children[i], local.children[i], path+"/children/"+i, applyChange);
          };
        }
      }
    }

    var addEmtpyChildrenArray = function(node) {
      if (!node) return;
      if (!node.children)
        node.children = [];
      else {
        for (var i = 0; i < node.children.length; i++) {
          addEmtpyChildrenArray(node.children[i])
        }
      }
    }

    var modifyLocalChildren_Remove = function(local, remote) {
      // console.log("modifyLocalChildren_Remove")
      // console.log(local)
      // console.log(remote)
      for (var i = 0; i < local.children.length; i++) {
        var found = false;
        for (var j = 0; j < remote.children.length; j++) {
          if (local.children[i].key == remote.children[j].key) {
            found = true;
            break;
          }
        }
        if (found) {
          modifyLocalChildren_Remove(local.children[i], remote.children[j]);
        } else {
          // console.log("remove node")
          // console.log(local.children)
          // console.log(i)
          local.children.splice(i, 1);
          i--;
          // console.log(local.children)
        }
      }
    }

    var modifyLocalChildren_Add = function(local, remote) {
      var list = [];
      // console.log("modifyLocalChildren_Add")
      // console.log(remote)
      // console.log(local)
      for (var i = 0; i < remote.children.length; i++) {
        var found = false;
        for (var j = 0; j < local.children.length; j++) {
          // console.log("local.children[j].key:" +local.children[j].key+ " remote.children[i].key:"+remote.children[i].key)
          if (local.children[j].key == remote.children[i].key) {
            found = true;
            break;
          }
        }

        if (!found)
          list.push(i)
        else
          modifyLocalChildren_Add(local.children[j], remote.children[i])
      }
      // console.log(list)
      for (var i = 0; i < list.length; i++) {
        local.children.splice(list[i], 0, remote.children[list[i]]);
      }
    }

    var syncRemoteToLocal = function(remote, local, path) {
      // console.log(remote)
      // console.log(local)
      addEmtpyChildrenArray(remote);
      // console.log("syncRemoteToLocal")
      // console.log(path)
      modifyLocalChildren_Remove(local, remote);
      // console.log("aaaaaaaaaaaaaaaaaaa")
      // console.log(local)
      // console.log(remote)
      modifyLocalChildren_Add(local, remote);
      // console.log("bbbbbbbbbbbbbbbbbbb")
      // console.log(local)
      // console.log(remote)
      // console.log("syncRemoteToLocal")
      // console.log(remote);
      // console.log(local);
      //local.children = remote.children;

    }

    $scope.exportFuns = {}

    $scope.tree = {
      "name" : "",
      "children" : []
    };

    var ref = new Firebase(window.firebase_url);
    var authData = ref.getAuth();
    if (authData) {
      // user authenticated with Firebase
      console.log(authData);
      //console.log(tree_url)
      $scope.commandList = []
      $scope.commandList.pos = -1;
      $scope.username = authData.uid;
      $scope.app_name = "boogunote";
      $scope.base_url = window.firebase_url + "/" + $scope.username + "/" + $scope.app_name + "/notes/" +$scope.noteId;
      $scope.tree_url = $scope.base_url + "/tree";
      var remoteTree = $firebase(new Firebase($scope.tree_url)).$asObject();
      // remoteTree.$loaded().then(function() {
      //   // console.log($scope.tree_url)
      //   // console.log(remoteTree)
      //   diffTree(remoteTree, $scope.tree, $scope.tree_url+"/children", syncRemoteToLocal);
      //   //console.log(remoteTree)
      //   //console.log($scope.tree)
      remoteTree.$watch(function(){
        // console.log("remote")
        diffTree(remoteTree, $scope.tree, $scope.tree_url+"/children", syncRemoteToLocal);
        //$scope.tree.children = remoteTree.children
      // })

        // $scope.$watch(function() {
        //     return $scope.tree;
        //   },
        //   function(newVal, oldVal) {
        //   console.log("local")
        //   diffTree(remoteTree, $scope.tree, tree_url+"/children", syncLocalToRemote);
        //   console.log($scope.tree)
        // });
      });
      $scope.note_item_info_url = $scope.base_url + "/info";
      var noteItemInfo = $firebase(new Firebase($scope.note_item_info_url)).$asObject();
      noteItemInfo.$watch(function(){
        if (document.title != noteItemInfo.name) document.title = noteItemInfo.name;
        $scope.title = noteItemInfo.name;
      })

      // ref.onAuth(function(authData) {
      //   if (!authData) {
      //     alert("login again");
      //     window.location.replace("login.html");
      //   }
      // });

      $scope.exportFuns.logout = function() {
        ref.unauth();
        window.location.replace("login.html"+window.location.hash);
      }

      var logoutTime = (authData.expires - 60*60)*1000 - parseInt(new Date().getTime().toString());

      setTimeout(function(){
        if (confirm("Login expired. Go to login page or keep on this page?")) {
          window.location.replace("login.html"+window.location.hash);
        }
      }, logoutTime);

      // var firstTimeLoad = true
      $scope.isOffline = false;

      ref.child('.info/connected').on('value', function(connectedSnap) {
        if (connectedSnap.val() === true) {
          // if (!firstTimeLoad) {
          //   var authData = ref.getAuth();
          //   if (authData) {
          //     if (confirm("Reconnected. Do you want to refesh this page")) {
          //       location.reload();
          //     }
          //   }
          // } else {
          //   firstTimeLoad = false;
          // }
          $scope.isOffline = false;
        } else {
          $scope.isOffline = true;
        }
      });

      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
      // search
      $scope.search = function() {
        $scope.search_results = [];
        $scope.exportFuns.searchInTree($scope.search_string, $scope.search_results);
      }

      $scope._focusNodeAt = function(positionArray) {
        $scope.exportFuns.expandByPositionArray(positionArray);
        setTimeout(function() {
          $scope.exportFuns.focusNodeAt(positionArray)
        },0);
      }

      $scope.goListPage = function() {
        window.location.replace('list.html');
      }

    } else {
      window.location.replace("login.html"+window.location.hash);
    }

  });

})();


text:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;

namespace Photosphere.DependencyInjection.Extensions
{
    internal static class TypeExtensions
    {
        public static Type GetBaseType(this Type type, string name)
        {
            while (true)
            {
                var baseType = type.BaseType;
                if (baseType == typeof(object) || baseType == null)
                {
                    return null;
                }
                if (baseType.Name == name)
                {
                    return baseType;
                }
                type = baseType;
            }
        }

        public static bool IsInstantiatible(this Type type) => !(type.IsAbstract || type.IsInterface);

        public static bool IsInstantiatibleUserDefinedClass(this Type type) =>
            !type.IsAbstract && !type.IsInterface && !type.IsGenericType;

        public static bool IsImplements<TInterface>(this Type type) => type.IsImplements(typeof(TInterface));

        public static object GetNewInstance(this Type type) => Activator.CreateInstance(type);

        public static ConstructorInfo GetFirstPublicConstructor(this Type type) =>
            type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.Default).FirstOrDefault()
            ?? type.GetConstructor(Type.EmptyTypes);

        public static Type MakeGenericWrappedBy(this Type type, Type genericType) =>
            genericType.MakeGenericType(type);

        public static string GetFormattedName(this Type type) =>
            type.IsGenericType
                ? type.Name + "`" + string.Join("`", type.GenericTypeArguments.Select(x => x.Name).ToArray())
                : type.Name;

        public static bool IsAssignableFromGenericType(this Type genericType, Type givenType)
        {
            if (givenType == null || genericType == null)
            {
                return false;
            }

            return givenType == genericType
              || givenType.MapsToGenericTypeDefinition(genericType)
              || givenType.HasInterfaceThatMapsToGenericTypeDefinition(genericType)
              || genericType.IsAssignableFromGenericType(givenType.BaseType);
        }

        public static bool IsAttribute(this Type type) => type.IsSubclassOf(typeof(Attribute));

        private static bool IsImplements(this Type type, Type serviceType)
        {
            Contract.Assert(serviceType.IsInterface, $"Type `{serviceType.Name}` must be interface");
            return
                type.GetInterfaces().Any(it => it == serviceType)
                && !type.IsAbstract
                && !type.IsInterface;
        }

        private static bool HasInterfaceThatMapsToGenericTypeDefinition(this Type givenType, Type genericType) =>
            givenType
              .GetInterfaces()
              .Where(it => it.IsGenericType)
              .Any(it => it.GetGenericTypeDefinition() == genericType);

        private static bool MapsToGenericTypeDefinition(this Type givenType, Type genericType) =>
            genericType.IsGenericTypeDefinition
            && givenType.IsGenericType
            && givenType.GetGenericTypeDefinition() == genericType;

        public static bool IsEnumerable(this Type type) => type.GetGenericTypeDefinition() == typeof(IEnumerable<>);
    }
}


text:
package com.azure.spring.data.cosmos.repository.support;

import com.azure.spring.data.cosmos.core.CosmosTemplate;
import com.azure.spring.data.cosmos.domain.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.repository.core.EntityInformation;

import static org.junit.Assert.assertTrue;

@RunWith(MockitoJUnitRunner.class)
public class CosmosRepositoryFactoryUnitTest {

    @Mock
    CosmosTemplate cosmosTemplate;

    @Test
    public void useMappingCosmosDBEntityInfoIfMappingContextSet() {
        final CosmosRepositoryFactory factory = new CosmosRepositoryFactory(cosmosTemplate);
        final EntityInformation<Person, String> entityInfo = factory.getEntityInformation(Person.class);
        assertTrue(entityInfo instanceof CosmosEntityInformation);
    }
}


text:
(function(){

//----------------------------------------------------------------------------------------------------------------------
// Xflow.OperatorList
//----------------------------------------------------------------------------------------------------------------------

    Xflow.OperatorEntry = function(operator){
        this.index = 0;
        this.operator = operator;
        this.inputInfo = [];
        this.outputInfo = [];
    }
    Xflow.OperatorEntry.prototype.isTransferInput = function(mappingIndex){
        return this.inputInfo[mappingIndex].operatorIndex !== undefined;
    }
    Xflow.OperatorEntry.prototype.getTransferInputOperatorIndex = function(mappingIndex){
        return this.inputInfo[mappingIndex].operatorIndex;
    }
    Xflow.OperatorEntry.prototype.getTransferInputOutputIndex = function(mappingIndex){
        return this.inputInfo[mappingIndex].outputIndex;
    }

    Xflow.OperatorEntry.prototype.getTransferInputId = function(mappingIdx){
        var info = this.inputInfo[mappingIdx];
        return info.operatorIndex + "_" + info.outputIndex;
    }
    Xflow.OperatorEntry.prototype.getTransferOutputId = function(outputIndex){
        return this.index + "_" + outputIndex;
    }

    Xflow.OperatorEntry.prototype.getInputMappingName = function(mappingIdx){
        return this.inputInfo[mappingIdx].mappedName;
    }
    Xflow.OperatorEntry.prototype.getDirectInputIndex = function(mappingIdx){
        return this.inputInfo[mappingIdx].inputIndex;
    }

    Xflow.OperatorEntry.prototype.getOutputIndex = function(operatorOutputIdx){
        return this.outputInfo[operatorOutputIdx].finalOut || this.outputInfo[operatorOutputIdx].lost || 0;
    }

    Xflow.OperatorEntry.prototype.isFinalOutput = function(outputIndex){
        return this.outputInfo[outputIndex] && this.outputInfo[outputIndex].finalOut !== undefined;
    }
    Xflow.OperatorEntry.prototype.isTransferOutput = function(outputIndex){
        return this.outputInfo[outputIndex] && this.outputInfo[outputIndex].transfer;
    }
    Xflow.OperatorEntry.prototype.isLostOutput = function(outputIndex){
        return this.outputInfo[outputIndex] && this.outputInfo[outputIndex].lost !== undefined;
    }

    Xflow.OperatorEntry.prototype.setTransferInput = function(mappingIndex, operatorIndex, outputIndex){
        this.inputInfo[mappingIndex] = { operatorIndex: operatorIndex, outputIndex: outputIndex};
    }

    Xflow.OperatorEntry.prototype.setDirectInput = function(mappingIndex, inputIndex, mappedName){
        this.inputInfo[mappingIndex] = { inputIndex: inputIndex, mappedName: mappedName };
    }

    Xflow.OperatorEntry.prototype.setFinalOutput = function(operatorOutputIndex, globalOutputIndex){
        this.outputInfo[operatorOutputIndex] = { finalOut : globalOutputIndex };
    }
    Xflow.OperatorEntry.prototype.setTransferOutput = function(operatorOutputIndex){
        this.outputInfo[operatorOutputIndex] = { transfer: true };
    }
    Xflow.OperatorEntry.prototype.setLostOutput = function(operatorOutputIndex, globalOutputIndex){
        this.outputInfo[operatorOutputIndex] = { lost: globalOutputIndex};
    }

    Xflow.OperatorEntry.prototype.getKey = function(){
        var key = this.operator.name + "*O";
        for(var i = 0; i <this.outputInfo.length; ++i){
            var info = this.outputInfo[i];
            key += "*" + ( info.transfer ? "_" : info.finalOut || (info.lost + "?"));
        }
        key += + "*I";
        for(var i = 0; i <this.inputInfo.length; ++i){
            var info = this.inputInfo[i];
            key += "*" + (info.inputIndex ? info.inputInfo : info.operatorIndex + ">" + info.outputIndex);
        }
        return key;
    }

    Xflow.OperatorList = function(platform, graph){
        this.graph = graph;
        this.platform = platform;
        this.entries = [];
        this.inputInfo = {};
    }

    Xflow.OperatorList.prototype.addEntry = function(entry){
        entry.index = this.entries.length;
        this.entries.push(entry);
    }

    Xflow.OperatorList.prototype.getKey = function(){
        var keys = [];
        for(var i = 0; i < this.entries.length; ++i){
            keys.push(this.entries[i].getKey());
        }
        var result = this.platform + ">" + keys.join("!") + "|";
        for(var i in this.inputInfo){
            result += i + ">" + (this.inputInfo[i].iterate || 0) + "x" + (this.inputInfo[i].size || 0);
        }
        return result;
    }

    Xflow.OperatorList.prototype.setInputIterateType = function(inputIndex, type){
        if(!this.inputInfo[inputIndex]) this.inputInfo[inputIndex] = {};
        this.inputInfo[inputIndex].iterate = type;
    }
    Xflow.OperatorList.prototype.setInputSize = function(inputIndex, size){
        if(!this.inputInfo[inputIndex]) this.inputInfo[inputIndex] = {};
        this.inputInfo[inputIndex].size = size;
    }

    Xflow.OperatorList.prototype.isInputIterate = function(inputIndex){
        return this.inputInfo[inputIndex] && this.inputInfo[inputIndex].iterate == Xflow.ITERATION_TYPE.MANY;
    }
    Xflow.OperatorList.prototype.isInputUniform = function(inputIndex){
        return this.inputInfo[inputIndex] && this.inputInfo[inputIndex].iterate == Xflow.ITERATION_TYPE.ONE;
    }
    Xflow.OperatorList.prototype.isInputNull = function(inputIndex){
        return this.inputInfo[inputIndex] && this.inputInfo[inputIndex].iterate == Xflow.ITERATION_TYPE.NULL;
    }
    Xflow.OperatorList.prototype.getInputIterateType = function(inputIndex){
        return this.inputInfo[inputIndex] && this.inputInfo[inputIndex].iterate;
    }

    Xflow.OperatorList.prototype.getInputSize = function(inputIndex){
        return this.inputInfo[inputIndex] && this.inputInfo[inputIndex].size || 0;
    }

    Xflow.OperatorList.prototype.getIterateCount = function(programData){
        var count = -1;
        for(var i = 0; i < programData.inputs.length; ++i){
            if(this.isInputIterate(i)){
                var dataEntry = programData.getDataEntry(i);
                if(dataEntry && dataEntry.getIterateCount){
                    var size = dataEntry.getIterateCount();
                    count = count < 0 ? size : Math.min(size, count);
                }
            }
        }
        return count < 0 ? 1 : count;
    }

    var c_sizes = {};

    Xflow.OperatorList.prototype.allocateOutput = function(programData){
        for(var i = 0; i < this.entries.length; ++i){
            var entry = this.entries[i];
            var operator = entry.operator;
            var operatorData = programData.operatorData[i];
            var iterateCount = this.getIterateCount(programData);
            if(operator.alloc){
                var args = [c_sizes];
                addInputToArgs(args, entry, programData);
                args.push(iterateCount);
                operator.alloc.apply(operatorData, args);
            }
            for(var j = 0; j < operator.outputs.length; ++j){
                var d = operator.outputs[j];
                var dataEntry = programData.outputs[entry.getOutputIndex(j)].dataEntry;

                if (dataEntry.type == Xflow.DATA_TYPE.TEXTURE) {
                    // texture entry
                    if (d.customAlloc)
                    {
                        var texParams = c_sizes[d.name];
                        var newWidth = texParams.imageFormat.width;
                        var newHeight = texParams.imageFormat.height;
                        var newFormatType = texParams.imageFormat.type;
                        var newSamplerConfig = texParams.samplerConfig;
                        dataEntry._createImage(newWidth, newHeight, newFormatType, newSamplerConfig);
                    } else if (d.sizeof) {
                        var srcEntry = null;
                        for(var k = 0; k < operator.mapping.length; ++k){
                            if (operator.mapping[k].source == d.sizeof) {
                                srcEntry = programData.getDataEntry(entry.getDirectInputIndex(k));
                                break;
                            }
                        }
                        if (srcEntry) {
                            var newWidth = Math.max(srcEntry.getWidth(), 1);
                            var newHeight = Math.max(srcEntry.getHeight(), 1);
                            var newFormatType = d.formatType || srcEntry.getFormatType();
                            var newSamplerConfig = d.samplerConfig || srcEntry.getSamplerConfig();
                            dataEntry._createImage(newWidth, newHeight, newFormatType, newSamplerConfig);
                        }
                        else
                            throw new Error("Unknown texture input parameter '" + d.sizeof+"' in operator '"+operator.name+"'");
                    } else
                        throw new Error("Cannot create texture. Use customAlloc or sizeof parameter attribute");
                } else {

                    var size = (d.customAlloc ? c_sizes[d.name] : iterateCount) * dataEntry.getTupleSize();

                    if( !dataEntry._value || dataEntry._value.length != size){
                        switch(dataEntry.type){
                            case Xflow.DATA_TYPE.FLOAT:
                            case Xflow.DATA_TYPE.FLOAT2:
                            case Xflow.DATA_TYPE.FLOAT3:
                            case Xflow.DATA_TYPE.FLOAT4:
                            case Xflow.DATA_TYPE.FLOAT4X4: dataEntry._setValue(new Float32Array(size)); break;
                            case Xflow.DATA_TYPE.INT:
                            case Xflow.DATA_TYPE.INT4:
                            case Xflow.DATA_TYPE.BOOL: dataEntry._setValue(new Int32Array(size)); break;
							case Xflow.DATA_TYPE.BYTE:  dataEntry._setValue(new Int8Array(size)); break;
							case Xflow.DATA_TYPE.UBYTE: dataEntry._setValue(new Uint8Array(size)); break;
                            default: XML3D.debug.logWarning("Could not allocate output buffer of TYPE: " + dataEntry.type);
                        }
                    }
                    else{
                        dataEntry._notifyChanged();
                    }
                }
            }
        }
    }

    /*
    Xflow.OperatorList.prototype.checkInput = function(programData){
        for(var i = 0; i < this.entries.length; ++i){
            var entry = this.entries[i];
            var mapping = entry.operator.mapping;
            for(var j = 0; j < mapping.length; ++j){
                if(entry.isTransferInput(j)){
                    var outputType = this.entries[entry.getTransferInputOperatorIndex(j)].operator.outputs[
                        entry.getTransferInputOutputIndex(j)].type;

                    if(outputType != entry.type){
                        XML3D.debug.logError("Xflow: operator " + entry.operator.name + ": Input for " + entry.source +
                            " has wrong type. Expected: " + Xflow.getTypeName(entry.type)
                            + ", but got: " +  Xflow.getTypeName(outputType) );
                        return false;
                    }

                }
                else{
                    var mappingName = entry.getInputMappingName(j);
                    if(!entry.optional && !mappingName){
                        XML3D.debug.logError("Xflow: operator " + entry.operator.name + ": Missing input argument for "
                            + entry.source);
                        return false;
                    }
                    if(mappingName){
                        var channel = programData.getChannel(entry.getDirectInputIndex(j));
                        if(!channel){
                            XML3D.debug.logError("Xflow: operator " + entry.operator.name + ": Input of name '" + mappingName +
                                "' not found. Used for parameter " + entry.source);
                            return false;
                        }
                        var dataEntry = channel.getDataEntry();
                        if(!entry.optional && (!dataEntry || dataEntry.getLength() == 0)){
                            XML3D.debug.logError("Xflow: operator " + entry.operator.name + ": Input for " + entry.source +
                                ' contains no data.');
                            return false;
                        }
                        if(dataEntry && dataEntry.type != entry.type){
                            XML3D.debug.logError("Xflow: operator " + entry.operator.name + ": Input for " + entry.source +
                                " has wrong type. Expected: " + Xflow.getTypeName(entry.type)
                                + ", but got: " +  Xflow.getTypeName(dataEntry.type) );
                            return false;
                        }
                    }
                }
            }
        }
    }
    */

    Xflow.ProgramData = function(){
        this.inputs = [];
        this.outputs = [];
        this.operatorData = [];
    }

    Xflow.ProgramData.prototype.getChannel = function(index){
        return this.inputs[index].channel;
    }

    Xflow.ProgramData.prototype.getDataEntry = function(index){
        var entry = this.inputs[index];
        var channel = entry.channel;
        if(!channel) return null;
        var key = 0;
        if(entry.sequenceKeySourceChannel){
            var keyDataEntry = entry.sequenceKeySourceChannel.getDataEntry();
            key = keyDataEntry && keyDataEntry._value ? keyDataEntry._value[0] : 0;
        }

        return channel.getDataEntry(entry.sequenceAccessType, key);
    }

    Xflow.ProgramInputConnection = function(){
        this.channel = null;
        this.arrayAccess = false;
        this.sequenceAccessType = Xflow.SEQUENCE.NO_ACCESS;
        this.sequenceKeySourceChannel = null;
    }

    Xflow.ProgramInputConnection.prototype.getKey = function(){
        return (this.channel ? this.channel.id : "NULL") + ";" + this.arrayAccess + ";" + this.sequenceAccessType + ";" +
        ( this.sequenceKeySourceChannel ? this.sequenceKeySourceChannel.id : "");
    }

    var c_program_cache = {};

    Xflow.createProgram = function(operatorList){
        var firstOperator;

        if(operatorList.entries.length === 0) {
            return null;
        }

        firstOperator = operatorList.entries[0].operator;

        var key = operatorList.getKey();
        if(!c_program_cache[key]){
            // GLSL operators are implemented in a different way, so platform information is fetched from the operatorList
            // as a fallback mode to not break the old implementations
            if(operatorList.platform === Xflow.PLATFORM.GLSL){
                c_program_cache[key] = new Xflow.VSProgram(operatorList);

            } else if (firstOperator.platform === Xflow.PLATFORM.CL) {
                c_program_cache[key] = new Xflow.CLProgram(operatorList);

            }else if(firstOperator.platform === Xflow.PLATFORM.JAVASCRIPT && operatorList.entries.length === 1 ) {
                c_program_cache[key] = new Xflow.SingleProgram(operatorList);

            }else {
                Xflow.notifyError("Could not create program from operatorList");
            }
        }
        return c_program_cache[key];
    }

    Xflow.SingleProgram = function(operatorList){
        this.list = operatorList;
        this.entry = operatorList.entries[0];
        this.operator = this.entry.operator;
        this._inlineLoop = null;
    }

    Xflow.SingleProgram.prototype.run = function(programData){
        var operatorData = prepareOperatorData(this.list, 0, programData);

        if(this.operator.evaluate_core){
            applyCoreOperation(this, programData, operatorData);
        }
        else{
            applyDefaultOperation(this.entry, programData, operatorData);
        }
    }

    function applyDefaultOperation(entry, programData, operatorData){
        var args = assembleFunctionArgs(entry, programData);
        args.push(operatorData);
        entry.operator.evaluate.apply(operatorData, args);
    }

    function applyCoreOperation(program, programData, operatorData){
        var args = assembleFunctionArgs(program.entry, programData);
        args.push(operatorData.iterateCount);

        if(!program._inlineLoop){
            program._inlineLoop = createOperatorInlineLoop(program.operator, operatorData);
        }
        program._inlineLoop.apply(operatorData, args);
    }

    var c_VarPattern = /var\s+(.)+[;\n]/;
    var c_InnerVarPattern = /[^=,\s]+\s*(=[^,]+)?(,)?/;
    function createOperatorInlineLoop(operator, operatorData){

        var code = "function (";
        var funcData = parseFunction(operator.evaluate_core);
        code += funcData.args.join(",") + ",__xflowMax) {\n";
        code += "    var __xflowI = __xflowMax\n" +
            "    while(__xflowI--){\n";

        var body = funcData.body;
        body = replaceArrayAccess(body, funcData.args, operator, operatorData);
        code += body + "\n  }\n}";

        var inlineFunc = eval("(" + code + ")");
        return inlineFunc;
    }

    var c_FunctionPattern = /function\s+([^(]*)\(([^)]*)\)\s*\{([\s\S]*)\}/;

    function parseFunction(func){
        var result = {};
        var matches = func.toString().match(c_FunctionPattern);
        if(!matches){
            Xflow.notifyError("Xflow Internal: Could not parse function: " + func);
            return null;
        }
        result.args = matches[2].split(",");
        for(var i in result.args) result.args[i] = result.args[i].trim();
        result.body = matches[3];
        return result;
    }

    var c_bracketPattern = /([a-zA-Z_$][\w$]*)(\[)/;

    function replaceArrayAccess(code, args, operator, operatorData){
        var result = "";
        var index = 0, bracketIndex = code.indexOf("[", index);
        while(bracketIndex != -1){
            var key = code.substr(index).match(c_bracketPattern)[1];

            var argIdx = args.indexOf(key);
            var addIndex = false, tupleCnt = 0;
            if(argIdx != -1){
                if(argIdx < operator.outputs.length){
                    addIndex = true;
                    tupleCnt = Xflow.DATA_TYPE_TUPLE_SIZE[[operator.outputs[argIdx].type]];
                }
                else{
                    var i = argIdx - operator.outputs.length;
                    addIndex = operatorData.iterFlag[i];
                    tupleCnt = Xflow.DATA_TYPE_TUPLE_SIZE[operator.mapping[i].internalType];
                }
            }

            result += code.substring(index, bracketIndex) + "["
            if(addIndex){
                result += tupleCnt + "*__xflowI + ";
            }
            index = bracketIndex + 1;
            bracketIndex = code.indexOf("[", index);
        }
        result +=  code.substring(index);
        return result;
    }

    function prepareOperatorData(list, idx, programData){
        var data = programData.operatorData[0];
        var entry = list.entries[idx];
        var mapping = entry.operator.mapping;
        data.iterFlag = {};
        for(var i = 0; i < mapping.length; ++i){
            var doIterate = (entry.isTransferInput(i) || list.isInputIterate(entry.getDirectInputIndex(i)));
            data.iterFlag[i] = doIterate;
        }
        data.iterateCount = list.getIterateCount(programData);
        if(!data.customData)
            data.customData = {};
        return data;
    }

    function assembleFunctionArgs(entry, programData){
        var args = [];
        var outputs = entry.operator.outputs;
        for(var i = 0; i < outputs.length; ++i){
            var d = outputs[i];
            var dataEntry = programData.outputs[entry.getOutputIndex(i)].dataEntry;
            args.push(dataEntry ? dataEntry.getValue() : null);
        }
        addInputToArgs(args, entry, programData);
        return args;
    }

    function addInputToArgs(args, entry, programData){
        var mapping = entry.operator.mapping;
        for(var i = 0; i < mapping.length; ++i){
            var mapEntry = mapping[i];
            var dataEntry = programData.getDataEntry(entry.getDirectInputIndex(i));
            args.push(dataEntry && dataEntry.getValue ? dataEntry.getValue() : dataEntry || null);
        }
    }

}());


text:
title: Site Settings

access:
    admin.settings: true
    admin.super: true
---


text:
The Turing Test with Movie Subtitle Data

## Getting Started

* Alan would love to speak to you at http://passtheturing.herokuapp.com/ or 415-200-2524 (made with Twilio!)

As the name implies, the Alan Chatbot returns human-like responses when the user converses with it. We wanted to make a bot where the user wouldn't be sure if they were talking to a human or a computer when conversing with our bot. We created a database of movie scripts by using regular expressions on movie subtitles, which found the questions and answers for us. The user input is then checked if it fully matches a question, if it matches an answer (in case the user types a statement), and then if it partially matches a question if all else fails.

## Built With

* [Python](https://www.python.org/) - Extensive use of Python for Flask, Scraping, and more!
* [Flask](http://flask.pocoo.org/docs/0.11/) - The micro web framework we used
* [Pymongo](https://api.mongodb.com/python/current/) - NoSQL database
* [Twilio](https://www.twilio.com/) - Used Twilio SMS!

## Authors

* **Kenneth Rhee** - [kenrhe](https://www.github.com/kenrhe "Kenneth Rhee's Github")

* **Thomas Munduchira** - [thomasmunduchira](https://www.github.com/thomasmunduchira "Thomas Munduchira's Github")

* **Vincent Cheng** - [vrcheng](https://www.github.com/vrcheng "Vincent Cheng's Github")

* **Eliot Winchell** - [eliotwinchell](https://www.gitub.com/eliotwinchell "Eliot Winchell's Github")

* **Salman Bana** - [glaceon0](https://www.github.com/glaceon0 "Salman Bana's Github")

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details


text:
package com.crystalplanet.obsidianpoker.game.card;

import junit.framework.Assert;
import junit.framework.TestCase;

public class CardTest extends TestCase {

    public void testCompareToDifferentRanks() {
        CardSuit spades = CardSuit.SPADES;

        Assert.assertEquals(-1, new Card(spades, CardRank.TWO).compareTo(new Card(spades, CardRank.THREE)));
        Assert.assertEquals(-1, new Card(spades, CardRank.THREE).compareTo(new Card(spades, CardRank.FOUR)));
        Assert.assertEquals(-1, new Card(spades, CardRank.FOUR).compareTo(new Card(spades, CardRank.FIVE)));
        Assert.assertEquals(-1, new Card(spades, CardRank.FIVE).compareTo(new Card(spades, CardRank.SIX)));
        Assert.assertEquals(-1, new Card(spades, CardRank.SIX).compareTo(new Card(spades, CardRank.SEVEN)));
        Assert.assertEquals(-1, new Card(spades, CardRank.SEVEN).compareTo(new Card(spades, CardRank.EIGHT)));
        Assert.assertEquals(-1, new Card(spades, CardRank.EIGHT).compareTo(new Card(spades, CardRank.NINE)));
        Assert.assertEquals(-1, new Card(spades, CardRank.NINE).compareTo(new Card(spades, CardRank.TEN)));
        Assert.assertEquals(-1, new Card(spades, CardRank.TEN).compareTo(new Card(spades, CardRank.JACK)));
        Assert.assertEquals(-1, new Card(spades, CardRank.JACK).compareTo(new Card(spades, CardRank.QUEEN)));
        Assert.assertEquals(-1, new Card(spades, CardRank.QUEEN).compareTo(new Card(spades, CardRank.KING)));
        Assert.assertEquals(-1, new Card(spades, CardRank.KING).compareTo(new Card(spades, CardRank.ACE)));

        Assert.assertEquals(-12, new Card(spades, CardRank.TWO).compareTo(new Card(spades, CardRank.ACE)));
        Assert.assertEquals(4, new Card(spades, CardRank.TEN).compareTo(new Card(spades, CardRank.SIX)));
    }

    public void testCompareToDifferentSuits() {
        CardRank ace = CardRank.ACE;

        Assert.assertEquals(0, new Card(CardSuit.DIAMONDS, ace).compareTo(new Card(CardSuit.CUBS, ace)));
        Assert.assertEquals(0, new Card(CardSuit.CUBS, ace).compareTo(new Card(CardSuit.HEARTS, ace)));
        Assert.assertEquals(0, new Card(CardSuit.HEARTS, ace).compareTo(new Card(CardSuit.SPADES, ace)));
    }

    public void testCompareNull() {
        Assert.assertEquals(1, new Card(CardSuit.SPADES, CardRank.ACE).compareTo(null));
    }

    public void testEquals() {
        Assert.assertTrue(new Card(CardSuit.HEARTS, CardRank.TWO).equals(new Card(CardSuit.HEARTS, CardRank.TWO)));
        Assert.assertFalse(new Card(CardSuit.HEARTS, CardRank.TWO).equals(new Card(CardSuit.HEARTS, CardRank.SIX)));
        Assert.assertFalse(new Card(CardSuit.HEARTS, CardRank.TWO).equals(new Card(CardSuit.SPADES, CardRank.TWO)));
        Assert.assertFalse(new Card(CardSuit.HEARTS, CardRank.FOUR).equals(null));
        Assert.assertFalse(new Card(CardSuit.HEARTS, CardRank.FOUR).equals(new Object()));
    }
}


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

SCRIPT_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" > /dev/null && pwd )"

if [[ $# -eq 4 ]]; then # Running inside bazel
  echo "Updating generated clients..." >&2
elif ! command -v bazel &>/dev/null; then
  echo "Install bazel at https://bazel.build" >&2
  exit 1
else
  (
    set -o xtrace
    bazel build //test/integration/versionchecker/testdata:test_manifests.tar
    cp -f "$(bazel info bazel-bin)/test/integration/versionchecker/testdata/test_manifests.tar" "$SCRIPT_ROOT"
  )
  exit 0
fi

CURRENT_VERSION=$(cat "$1")           # $(location //:version)
current_version_yaml=$(realpath "$2") # $(location //deploy/manifests:cert-manager.yaml)
tags=$(cat "$3")                      # $(location :git_tags.txt)
test_manifests_tar=$(realpath "$4")        # $(location test_manifests.tar)

shift 4

# copy current version's manifest to current folder (will get included in tar)
cp "$current_version_yaml" "$CURRENT_VERSION.yaml"

manifest_urls=""
for tag in $tags
do
    # The "v1.2.0-alpha.1" manifest contains duplicate CRD resources
    # (2 CRD resources with the same name); don't download this manifest
    # as it will cause the test to fail when adding the CRD resources
    # to the fake client
    if [[ $tag == "v1.2.0-alpha.1" ]]; then
        continue
    fi

    manifest_urls+=",$tag"
done

# remove leading "," in string
manifest_urls=${manifest_urls#","}

# download all manifests
#  --compressed: try gzip compressed download
#  -s: don't show progress bar
#  -f: fail if non success code
#  -L: follow redirects
#  -o: output to "#1.yaml"
curl --compressed -sfLo "#1.yaml" "https://github.com/cert-manager/cert-manager/releases/download/{$manifest_urls}/cert-manager.yaml"

tar -cvf "$test_manifests_tar" *.yaml


text:
LOGS_MNT="/mnt/logs"
LOG_DIR="/var/log"
TMP_DIR="/tmp"

# Check free space; this is in KiB (1 KiB blocks), not kilobytes
check_free() {
    avail_space=$(df -k ${LOGS_MNT} | grep -v '^Filesystem' | \
        awk '{print $4}')
    echo -n ${avail_space}
}

# Mount the file system and set a file prefix
mount ${LOGS_MNT} || exit 1
archive_prefix="`hostname`_`date +%F`_`date +%s`"

# Archive the logs -- we should only fail if there is no room in /tmp (tmpfs)
mkdir -m 0755 -p ${TMP_DIR}/${archive_prefix} || exit 1
mv -f /var/log/* ${TMP_DIR}/${archive_prefix}/ || exit 1
file_path="${TMP_DIR}/${archive_prefix}.tar.gz"
tar cpfz ${file_path} -C ${TMP_DIR} ${archive_prefix} || exit 1
new_arch_size=$(du -k ${file_path} | awk '{print $1}')

# Make sure this is even feasible
total_space=$(df -k ${LOGS_MNT} | grep -v '^Filesystem' | awk '{print $2}')
if [ ${new_arch_size} -gt ${total_space} ]; then
    echo "The new log archive (${file_path}) will not fit on" \
        "the ${LOGS_MNT} file system." 1>&2
    exit 1
fi

# Get rid of old files (if needed) until we have enough space free
while [ ${new_arch_size} -gt $(check_free) ]; do
    find ${LOGS_MNT} -type f -print0 | sort -z | xargs -0 ls | head -n 1 | xargs rm
done

# Move the new archive to USB
mv -f ${file_path} ${LOGS_MNT}/ || exit 1

# Make syslogd happy again
killall -q -SIGHUP syslogd

# Done
rm -rf ${TMP_DIR}/${archive_prefix}
umount ${LOGS_MNT} || exit 1


text:
 - Using Scrapy 1.2
 - Python 2.7

### #Next Plan

 - Connect Database (2017.01.10 Complete)
 - Save Data to DB

### #Command

 - scrapy crawl crawl_page

### #P.S

 - Slow, but never stop.


text:
package org.togethwy.cheetah.handler;

import org.togethwy.cheetah.CheetahResult;
import org.togethwy.cheetah.Result;
import org.togethwy.cheetah.util.FileUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 文件下载处理器
 *
 * @author wangtonghe
 * @date 2017/10/12 21:23
 */
public class FileDownloadHandler implements Handler {
    private String path;

    private static String HTTP_PREFIX = "http://";

    private String domain;

    public FileDownloadHandler(String path) {
        this.path = path;
    }

    //TODO 文件下载处理添加cookie等
    @Override
    public void handle(CheetahResult cheetahResult) {
        List<String> lists = cheetahResult.getFileResults();
        Set<String> newUrls = new HashSet<>();
        lists.forEach(fileUrl -> {
            newUrls.add(doOriginUrl(fileUrl, domain));

        });
        FileUtils.batchDownloadFile(newUrls, path);

    }

    @Override
    public void destory() {

    }

    @Override
    public void setDomain(String domain) {
        this.domain = domain;
    }

    /**
     * 处理源路径
     *
     * @param originUrl
     * @return
     */
    private static String doOriginUrl(String originUrl, String domain) {
        if (originUrl.startsWith(HTTP_PREFIX)) {
            return originUrl;
        } else if (originUrl.startsWith("//")) {
            return HTTP_PREFIX + originUrl;
        } else if (originUrl.startsWith("/")) {
            return domain + originUrl;
        }
        return null;

    }
}


text:
<?php

namespace pff\modules;
use pff\Abs\AModule;

/**
 * Helper module to encrypt/decrypt content
 *
 * @author paolo.fagni<at>gmail.com
 */
class Encryption extends AModule{

    const METHOD = 'aes-256-ctr';

    /**
     * The cypher method to be used
     *
     * @var string
     */
    private $_cypher;

    /**
     * md5 of the key used to encrypt/decrypt data
     *
     * @var string
     */
    private $_key;

    public function __construct($confFile = 'encryption/module.conf.yaml') {
        $this->loadConfig($this->readConfig($confFile));
    }

    /**
     * Parse the configuration file
     *
     * @param array $parsedConfig
     */
    private function loadConfig($parsedConfig) {
        $this->_key    = hex2bin($parsedConfig['moduleConf']['key']);
    }

    /**
     * Encrypts (but does not authenticate) a message
     *
     * @param string $message - plaintext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encode - set to TRUE to return a base64-encoded
     * @return string (raw binary)
     */
    public static function encrypt($message, $key = false, $encode = true)
    {
        $nonceSize = openssl_cipher_iv_length(self::METHOD);
        $nonce = openssl_random_pseudo_bytes($nonceSize);

        $ciphertext = openssl_encrypt(
            $message,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );

        // Now let's pack the IV and the ciphertext together
        // Naively, we can just concatenate
        if ($encode) {
            return base64_encode($nonce.$ciphertext);
        }
        return $nonce.$ciphertext;
    }

    /**
     * Decrypts (but does not verify) a message
     *
     * @param string $message - ciphertext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encoded - are we expecting an encoded string?
     * @return string
     */
    public static function decrypt($message, $key = false, $encoded = true)
    {
        if ($encoded) {
            $message = base64_decode($message, true);
            if ($message === false) {
                throw new \Exception('Encryption failure');
            }
        }

        $nonceSize = openssl_cipher_iv_length(self::METHOD);
        $nonce = mb_substr($message, 0, $nonceSize, '8bit');
        $ciphertext = mb_substr($message, $nonceSize, null, '8bit');

        $plaintext = openssl_decrypt(
            $ciphertext,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );

        return $plaintext;
    }
}


text:
import requests

from requests.auth import HTTPBasicAuth
import sys

if len(sys.argv) != 3:
    print "usage: post-netcfg onos-node json-file-name"
    sys.exit(1)

node = sys.argv[1]
configFileName = sys.argv[2]

jsonFile = open(configFileName, 'rb')
configJson = jsonFile.read()

request = requests.post('http://' + node + ':8181/onos/v1/network/configuration',
                        auth=HTTPBasicAuth('onos', 'rocks'),
                        data=configJson)

if request.status_code != 200:
    print request.text
    sys.exit(1)

sys.exit(0)


text:
def eventGetButton(evt):
    JS("""
    var button = @{{evt}}.button;
    if(button == 0){
        return 1;
    } else {
        return button;
    }
    """)
def getAbsoluteLeft(_elem):
    JS("""
    var left = 0;
    var elem = @{{_elem}};
    var curr = elem.parentNode;
    // This intentionally excludes body
    while (curr && curr != $doc.body) {

      // see https://bugs.opera.com/show_bug.cgi?id=249965
      // The net effect is that TR and TBODY elemnts report the scroll offsets
      // of the BODY and HTML elements instead of 0.
      if (curr.tagName != 'TR' && curr.tagName != 'TBODY') {
        left -= curr.scrollLeft;
      }
      curr = curr.parentNode;
    }

    while (elem) {
      left += elem.offsetLeft;
      elem = elem.offsetParent;
    }
    return left;
    """)

def getAbsoluteTop(_elem):
    JS("""
    var top = 0;
    var elem = @{{_elem}};

    // This intentionally excludes body
    var curr = elem.parentNode;
    while (curr && curr != $doc.body) {
      // see getAbsoluteLeft()
      if (curr.tagName != 'TR' && curr.tagName != 'TBODY') {
        top -= curr.scrollTop;
      }
      curr = curr.parentNode;
    }

    while (elem) {
      top += elem.offsetTop;
      elem = elem.offsetParent;
    }
    return top;
    """)

def eventGetMouseWheelVelocityY(evt):
    JS("""
    return @{{evt}}.detail * 4 || 0;
    """)


text:
Chris has been here.
I hope this works.


text:
using Starcounter;

namespace KitchenSink {
  partial class UrlPage : Page
    {
        protected override void OnData() {
            base.OnData();

            this.Url = "/KitchenSink";
            this.Label = "This a sample link";
        }
    }
}


text:
using FluentAutomation.Interfaces;

using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;

namespace FluentAutomation.Tests
{
    /// <summary>
    /// Base Test that opens the test to the AUT
    /// </summary>
    public class BaseTest : FluentTest<IWebDriver>
    {
        public BaseTest()
        {
            FluentSession.EnableStickySession();
            Config.WaitUntilTimeout(TimeSpan.FromMilliseconds(1000));

            // Create Page Objects
            this.InputsPage = new Pages.InputsPage(this);
            this.AlertsPage = new Pages.AlertsPage(this);
            this.ScrollingPage = new Pages.ScrollingPage(this);
            this.TextPage = new Pages.TextPage(this);
            this.DragPage = new Pages.DragPage(this);
            this.SwitchPage = new Pages.SwitchPage(this);

            // Default tests use chrome and load the site
            //FluentAutomation.SeleniumWebDriver.Bootstrap(SeleniumWebDriver.Browser.Chrome); //, SeleniumWebDriver.Browser.InternetExplorer, SeleniumWebDriver.Browser.Firefox);

            // Test browserstack local
            //WbTstr.Configure()
            //    .EnableDebug()
            //    .UseBrowserStackAsRemoteDriver()
            //    .SetBrowserStackBuildIdentifier(buildResultKey)
            //    .EnableBrowserStackLocal()
            //    .PreferedBrowser().IsChrome()
            //    .PreferedOperatingSystem().IsWindows()
            //    .PreferedScreenResolution().IsAny();

            WbTstr.Bootstrap();

            FluentSession.DisableStickySession();
            I.Open(SiteUrl);
        }

        public string SiteUrl
        {
            get
            {
                return ConfigReader.GetSetting("WebsiteUnderTestBaseUrl");
            }
        }

        public Pages.InputsPage InputsPage = null;
        public Pages.AlertsPage AlertsPage = null;
        public Pages.ScrollingPage ScrollingPage = null;
        public Pages.TextPage TextPage = null;
        public Pages.DragPage DragPage = null;
        public Pages.SwitchPage SwitchPage = null;
    }

    public class AssertBaseTest : BaseTest
    {
        public AssertBaseTest()
            : base()
        {
            Config.OnExpectFailed((ex, state) =>
            {
                // For the purpose of these tests, allow expects to throw (break test)
                throw ex;
            });
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.devcenter.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.resourcemanager.devcenter.fluent.models.UsageInner;

/** An instance of this class provides access to all the operations defined in UsagesClient. */
public interface UsagesClient {
    /**
     * Lists the current usages and limits in this location for the provided subscription.
     *
     * @param location The Azure region.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of Core Usages as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<UsageInner> listByLocation(String location);

    /**
     * Lists the current usages and limits in this location for the provided subscription.
     *
     * @param location The Azure region.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of Core Usages as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<UsageInner> listByLocation(String location, Context context);
}


text:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using Vanara.Extensions;

namespace Vanara.Windows.Forms
{
	/// Determines when a border will be displayed.
	public enum CollapsiblePanelBorderCondition
	{
		/// Always.
		Always,

		/// Only when the panel is expanded.
		OnlyExpanded,

		/// Never.
		Never
	}

	/// Determines the state of the panel's header.
	public enum CollapsiblePanelHeaderState
	{
		/// Normal
		Normal = 0,

		/// The mouse is over the header.
		Hot = 1,

		/// The header is being clicked.
		Pressed = 2,

		/// The header is in the normal expanded state.
		ExpandedNormal = 3,

		/// The header is in the hot expanded state.
		ExpandedHot = 4,

		/// The header is in the pressed expanded state.
		ExpandedPressed = 5,

		/// The header is disabled.
		Disabled = 6,

		/// The header is disabled and expanded.
		ExpandedDisabled = 7
	}

	[Flags]
	internal enum CollapsiblePanelMousePosition
	{
		Body = 1,
		Header = 2,
		Button = 4
	}

	/// Control providing a panel that can be collapsed.
	[Designer(typeof(Design.CollapsiblePanelDesigner))]
	[ToolboxItem(true), ToolboxBitmap(typeof(CollapsiblePanel), "CollapsiblePanel.bmp")]
	[Description("Provides a panel that can be collapsed.")]
	public class CollapsiblePanel : Control, ISupportInitialize
	{
		internal CollapsiblePanelHeaderState buttonState = CollapsiblePanelHeaderState.Normal;
		internal EmbeddedContainer contentPanel;
		internal bool headerHot;
		private const int padding = 12;
		private ThemedTableLayoutPanel backgroundPanel;
		private ThemedPanel bottomBorder;
		private bool buttonDown;
		private ThemedTableLayoutPanel contentBackground;
		private CollapsiblePanelHeader headerPanel;
		private BaseRenderer renderer;
		private ThemedPanel topBorder;

		/// Initializes a new instance of the <see cref="CollapsiblePanel"/> class.
		public CollapsiblePanel()
		{
			InitializeComponent();
			renderer = new SystemRenderer(this);
			CustomStyle = new Style();
		}

		/// Gets or sets the bottom border condition.
		/// <value>The bottom border condition.</value>
		[DefaultValue(typeof(CollapsiblePanelBorderCondition), "Always")]
		public CollapsiblePanelBorderCondition BottomBorderCondition { get; set; } = CollapsiblePanelBorderCondition.Always;

		/// Gets or sets a value indicating whether this <see cref="CollapsiblePanel"/> is collapsed.
		/// <value><see langword="true"/> if collapsed; otherwise, <see langword="false"/>.</value>
		[DefaultValue(false)]
		public bool Collapsed { get; set; }

		/// Gets the control that holds the content.
		/// <value>The content control.</value>
		public Control Content => contentPanel;

		/// Gets the custom style.
		/// <value>The custom style.</value>
		public Style CustomStyle { get; internal set; }

		/// Gets or sets the header text.
		/// <value>The header text.</value>
		[DefaultValue("")]
		public string HeaderText
		{
			get => headerPanel.Text; set => headerPanel.Text = value;
		}

		/// Gets or sets the render style.
		/// <value>The render style.</value>
		[DefaultValue(typeof(RenderStyle), "SystemTheme")]
		public RenderStyle RenderStyle
		{
			get => renderer is CustomRenderer ? RenderStyle.Custom : RenderStyle.SystemTheme; set
			{
				if (value == RenderStyle.SystemTheme)
					renderer = new SystemRenderer(this);
				else
					renderer = new CustomRenderer(this);
			}
		}

		/// Gets or sets the top border condition.
		/// <value>The top border condition.</value>
		[DefaultValue(typeof(CollapsiblePanelBorderCondition), "Always")]
		public CollapsiblePanelBorderCondition TopBorderCondition { get; set; } = CollapsiblePanelBorderCondition.Always;

		/// Signals the object that initialization is starting.
		public virtual void BeginInit()
		{
		}

		/// Signals the object that initialization is complete.
		public virtual void EndInit()
		{
		}

		/// Retrieves the size of a rectangular area into which a control can be fitted.
		/// <param name="proposedSize">The custom-sized area for a control.</param>
		/// <returns>An ordered pair of type <see cref="T:System.Drawing.Size"/> representing the width and height of a rectangle.</returns>
		public override Size GetPreferredSize(Size proposedSize) => renderer.GetPreferredSize(proposedSize);

		/// Raises the <see cref="E:System.Windows.Forms.Control.Click"/> event.
		/// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
		protected override void OnClick(EventArgs e)
		{
			base.OnClick(e);
			Collapsed = !Collapsed;
		}

		/// Raises the <see cref="E:System.Windows.Forms.Control.HandleCreated"/> event.
		/// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
		protected override void OnHandleCreated(EventArgs e)
		{
			base.OnHandleCreated(e);
		}

		/// Raises the <see cref="E:System.Windows.Forms.Control.MouseDown"/> event.
		/// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs"/> that contains the event data.</param>
		protected override void OnMouseDown(MouseEventArgs e)
		{
			HandleMouseEvent(e);
			if (e.Button == MouseButtons.Left && headerHot)
			{
				buttonDown = true;
				Refresh();
			}
			base.OnMouseDown(e);
		}

		/// Raises the <see cref="E:System.Windows.Forms.Control.MouseLeave"/> event.
		/// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
		protected override void OnMouseLeave(EventArgs e)
		{
			base.OnMouseLeave(e);
			headerHot = false;
			buttonDown = false;
			Refresh();
		}

		/// Raises the <see cref="E:System.Windows.Forms.Control.MouseMove"/> event.
		/// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs"/> that contains the event data.</param>
		protected override void OnMouseMove(MouseEventArgs e)
		{
			HandleMouseEvent(e);
			base.OnMouseMove(e);
		}

		/// Raises the <see cref="E:System.Windows.Forms.Control.MouseUp"/> event.
		/// <param name="e">A <see cref="T:System.Windows.Forms.MouseEventArgs"/> that contains the event data.</param>
		protected override void OnMouseUp(MouseEventArgs e)
		{
			HandleMouseEvent(e);
			buttonDown = false;
			Refresh();
			base.OnMouseUp(e);
		}

		/// Raises the <see cref="E:System.Windows.Forms.Control.Paint"/> event.
		/// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"/> that contains the event data.</param>
		protected override void OnPaint(PaintEventArgs e)
		{
			// Draw header
			//renderer.Paint(e);
		}

		private void HandleMouseEvent(MouseEventArgs e)
		{
			var mp = renderer.GetMousePosition(e);
			var hh = mp.IsFlagSet(CollapsiblePanelMousePosition.Header);
			CollapsiblePanelHeaderState bs;
			if (hh)
			{
				if (buttonDown)
					bs = Collapsed ? CollapsiblePanelHeaderState.Pressed : CollapsiblePanelHeaderState.ExpandedPressed;
				else
					bs = Collapsed ? CollapsiblePanelHeaderState.Hot : CollapsiblePanelHeaderState.ExpandedHot;
			}
			else
			{
				if (Enabled)
					bs = Collapsed ? CollapsiblePanelHeaderState.Normal : CollapsiblePanelHeaderState.ExpandedNormal;
				else
					bs = Collapsed ? CollapsiblePanelHeaderState.Disabled : CollapsiblePanelHeaderState.ExpandedDisabled;
			}
			if (bs == buttonState && hh == headerHot) return;
			buttonState = bs;
			headerHot = hh;
			Refresh();
		}

		private void HeaderPanel_Click(object sender, EventArgs e)
		{
			bool collapsed = headerPanel.Collapsed;
			contentBackground.Visible = !collapsed;
			var h = collapsed ? headerPanel.Height : headerPanel.Height + contentBackground.Height;
			if (TopBorderCondition == CollapsiblePanelBorderCondition.Always || (TopBorderCondition == CollapsiblePanelBorderCondition.OnlyExpanded && !collapsed))
				h++;
			if (BottomBorderCondition == CollapsiblePanelBorderCondition.Always || (BottomBorderCondition == CollapsiblePanelBorderCondition.OnlyExpanded && !collapsed))
				h++;
			Height = h;
		}

		private void InitializeComponent()
		{
			backgroundPanel = new ThemedTableLayoutPanel();
			topBorder = new ThemedPanel();
			headerPanel = new CollapsiblePanelHeader();
			contentBackground = new ThemedTableLayoutPanel();
			contentPanel = new EmbeddedContainer();
			bottomBorder = new ThemedPanel();
			backgroundPanel.SuspendLayout();
			contentBackground.SuspendLayout();
			SuspendLayout();
			// backgroundPanel
			backgroundPanel.ColumnCount = 1;
			backgroundPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
			backgroundPanel.Controls.Add(topBorder, 0, 0);
			backgroundPanel.Controls.Add(headerPanel, 0, 1);
			backgroundPanel.Controls.Add(contentBackground, 0, 2);
			backgroundPanel.Controls.Add(bottomBorder, 0, 3);
			backgroundPanel.Dock = DockStyle.Fill;
			backgroundPanel.Name = "backgroundPanel";
			backgroundPanel.RowCount = 4;
			backgroundPanel.RowStyles.Add(new RowStyle());
			backgroundPanel.RowStyles.Add(new RowStyle());
			backgroundPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
			backgroundPanel.RowStyles.Add(new RowStyle());
			backgroundPanel.StyleClass = "CONTROLPANEL";
			backgroundPanel.StylePart = 2;
			// topBorder
			topBorder.BackColor = SystemColors.Control;
			topBorder.Dock = DockStyle.Top;
			topBorder.Height = 1;
			topBorder.Margin = new Padding(0);
			topBorder.Name = "topBorder";
			topBorder.StyleClass = "CONTROLPANEL";
			topBorder.StylePart = 17;
			// headerPanel
			headerPanel.Dock = DockStyle.Top;
			headerPanel.HorzPadding = padding;
			headerPanel.Margin = new Padding(0);
			headerPanel.Name = "headerPanel";
			headerPanel.Size = new Size(200, 37);
			headerPanel.Click += HeaderPanel_Click;
			// contentBackground
			contentBackground.ColumnCount = 3;
			contentBackground.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, padding));
			contentBackground.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
			contentBackground.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, padding));
			contentBackground.Controls.Add(contentPanel, 1, 1);
			contentBackground.Dock = DockStyle.Fill;
			contentBackground.Margin = new Padding(0);
			contentBackground.Name = "contentBackground";
			contentBackground.RowCount = 3;
			contentBackground.RowStyles.Add(new RowStyle(SizeType.Absolute, padding));
			contentBackground.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
			contentBackground.RowStyles.Add(new RowStyle(SizeType.Absolute, padding));
			contentBackground.StyleClass = "CONTROLPANEL";
			contentBackground.StylePart = 2;
			// contentPanel
			contentPanel.Dock = DockStyle.Fill;
			contentPanel.Margin = new Padding(0);
			contentPanel.Name = "contentPanel";
			contentPanel.TabIndex = 0;
			// bottomBorder
			bottomBorder.BackColor = SystemColors.Control;
			bottomBorder.Dock = DockStyle.Bottom;
			bottomBorder.Height = 1;
			bottomBorder.Margin = new Padding(0);
			bottomBorder.Name = "bottomBorder";
			bottomBorder.StyleClass = "CONTROLPANEL";
			bottomBorder.StylePart = 17;
			// CollapsiblePanel
			Controls.Add(backgroundPanel);
			backgroundPanel.ResumeLayout(false);
			contentBackground.ResumeLayout(false);
			ResumeLayout(false);
		}

		/// The panel's style.
		public class Style
		{
			/// Initializes a new instance of the <see cref="Style"/> class.
			public Style()
			{
				BackColor = Color.White;
				//Font = ;
				ForeColor = Color.Black;
				HeaderHeight = 30;
				HeaderBackColor = Color.White;
				//HeaderFont =;
				HeaderHotBackColor = Color.LightSkyBlue;
				HeaderTextColor = Color.DarkBlue;
				Padding = new Padding(12);
			}

			/// Gets or sets the backgroun color.
			/// <value>The backgroun color.</value>
			[DefaultValue(typeof(Color), "White")]
			public Color BackColor { get; set; }

			/// Gets or sets the expando images.
			/// <value>The expando images.</value>
			public Image[] ExpandoImages { get; set; }

			/// Gets or sets the font.
			/// <value>The font.</value>
			public Font Font { get; set; }

			/// Gets or sets the foreground color.
			/// <value>The foreground color.</value>
			[DefaultValue(typeof(Color), "Black")]
			public Color ForeColor { get; set; }

			/// Gets or sets the color of the header background.
			/// <value>The color of the header background.</value>
			[DefaultValue(typeof(Color), "White")]
			public Color HeaderBackColor { get; set; }

			/// Gets or sets the header font.
			/// <value>The header font.</value>
			public Font HeaderFont { get; set; }

			/// Gets or sets the height of the header.
			/// <value>The height of the header.</value>
			[DefaultValue(30)]
			public int HeaderHeight { get; set; }

			/// Gets or sets the color of the header hot background.
			/// <value>The color of the header hot background.</value>
			[DefaultValue(typeof(Color), "LightSkyBlue")]
			public Color HeaderHotBackColor { get; set; }

			/// Gets or sets the color of the header text.
			/// <value>The color of the header text.</value>
			[DefaultValue(typeof(Color), "DarkBlue")]
			public Color HeaderTextColor { get; set; }

			/// Gets or sets the padding.
			/// <value>The padding.</value>
			[DefaultValue(typeof(Padding), "12,12,12,12")]
			public Padding Padding { get; set; }

			/// Converts to string.
			/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
			public override string ToString() => @"Style: " + string.Join("; ", GetType().GetProperties().Select(p => $"{p.Name}={p.GetValue(this, null)}").ToArray());
		}

		internal abstract class BaseRenderer
		{
			protected BaseRenderer(CollapsiblePanel ctrl)
			{
				Control = ctrl;
			}

			public CollapsiblePanel Control { get; }

			public abstract CollapsiblePanelMousePosition GetMousePosition(MouseEventArgs e);

			public virtual Size GetPreferredSize(Size proposedSize)
			{
				return proposedSize;
			}

			public abstract void Layout(PaintEventArgs e);

			public abstract void Paint(PaintEventArgs e);
		}

		internal class CustomRenderer : BaseRenderer
		{
			private readonly ImageList headerImages;
			private Rectangle buttonBounds;

			public CustomRenderer(CollapsiblePanel ctrl) : base(ctrl)
			{
				headerImages = new ImageList { ColorDepth = ColorDepth.Depth32Bit, TransparentColor = Color.Transparent };
			}

			public override CollapsiblePanelMousePosition GetMousePosition(MouseEventArgs e)
			{
				CollapsiblePanelMousePosition ret = 0;
				if (e.Y <= Control.CustomStyle.HeaderHeight) ret |= CollapsiblePanelMousePosition.Header;
				if (buttonBounds.Contains(e.Location)) ret |= CollapsiblePanelMousePosition.Button;
				return ret;
			}

			public override void Layout(PaintEventArgs e)
			{
				headerImages.Images.Clear();
				headerImages.Images.AddRange(Control.CustomStyle.ExpandoImages);
			}

			public override void Paint(PaintEventArgs e)
			{
				Layout(e);
				using (var br = new SolidBrush(Control.headerHot ? Control.CustomStyle.HeaderHotBackColor : Control.CustomStyle.HeaderBackColor))
					e.Graphics.FillRectangle(br, new Rectangle(Point.Empty, new Size(Control.Width, Control.CustomStyle.HeaderHeight)));
				var imgSz = Control.CustomStyle.ExpandoImages[0].Size;
				buttonBounds = new Rectangle(e.ClipRectangle.Width - imgSz.Width - Control.CustomStyle.Padding.Right, (Control.CustomStyle.HeaderHeight - imgSz.Height) / 2, imgSz.Width, imgSz.Height);
				headerImages.Draw(e.Graphics, buttonBounds.Location, (int)Control.buttonState);
				using (var br = new SolidBrush(Control.CustomStyle.HeaderTextColor))
					e.Graphics.DrawString(Control.Text, Control.CustomStyle.HeaderFont, br, new RectangleF(Control.CustomStyle.Padding.Left, Control.CustomStyle.Padding.Top, Control.Width - Control.CustomStyle.Padding.Horizontal - imgSz.Width, Control.CustomStyle.HeaderHeight), new StringFormat(StringFormatFlags.NoWrap));
			}
		}

		internal class SystemRenderer : BaseRenderer
		{
			private const int lrpadding = 12;
			private const string taskDialogClass = @"TaskDialog";
			private const int tbpadding = 8;
			private Rectangle buttonBounds;
			private int headerHeight;
			private Size imgSz;
			private Rectangle textBounds;

			public SystemRenderer(CollapsiblePanel ctrl) : base(ctrl)
			{
			}

			public override CollapsiblePanelMousePosition GetMousePosition(MouseEventArgs e)
			{
				CollapsiblePanelMousePosition ret = 0;
				if (e.Y <= headerHeight) ret |= CollapsiblePanelMousePosition.Header;
				if (buttonBounds.Contains(e.Location)) ret |= CollapsiblePanelMousePosition.Button;
				return ret;
			}

			public override Size GetPreferredSize(Size proposedSize)
			{
				using (var g = Control.CreateGraphics())
				{
					Layout(new PaintEventArgs(g, new Rectangle(Point.Empty, proposedSize)));
					int minW = (imgSz.Width * 2) + (lrpadding * 3);
					if (proposedSize.Width < minW) proposedSize.Width = minW;
					if (proposedSize.Height < headerHeight) proposedSize.Height = headerHeight;
					return proposedSize;
				}
			}

			public override void Layout(PaintEventArgs e)
			{
				// Get TaskDialog-MainInstructionPane
				var vs = new VisualStyleRenderer(taskDialogClass, 2, 0);
				var r = vs.GetTextExtent(e.Graphics, "W", TextFormatFlags.Default);
				headerHeight = (tbpadding * 2) + r.Height;
				// Get TaskDialog-ExpandoButton
				vs = new VisualStyleRenderer(taskDialogClass, 13, (int)Control.buttonState);
				imgSz = new Size(vs.GetInteger(IntegerProperty.Width), vs.GetInteger(IntegerProperty.Height));
				buttonBounds = new Rectangle(e.ClipRectangle.Width - imgSz.Width - lrpadding, (headerHeight - imgSz.Height) / 2, imgSz.Width, imgSz.Height);
				textBounds = new Rectangle(lrpadding, tbpadding, e.ClipRectangle.Width - lrpadding - imgSz.Width, tbpadding + r.Height);
				Control.Padding = new Padding(lrpadding, headerHeight + tbpadding, lrpadding, tbpadding);
				System.Diagnostics.Debug.WriteLine($"Layout: hdrH={headerHeight}; imgSz={imgSz}; btnBnd={buttonBounds}; txtBnd={textBounds}");
			}

			public override void Paint(PaintEventArgs e)
			{
				Layout(e);

				// Get TaskDialog-PrimaryPanel
				var vs = new VisualStyleRenderer(taskDialogClass, 1, 0);
				vs.DrawParentBackground(e.Graphics, Control.ClientRectangle, Control);
				if (Control.headerHot)
				{
					// Get ListView-GroupHeader-OpenHot
					vs = new VisualStyleRenderer("ListView", 6, 2);
					var hdrRect = Control.ClientRectangle;
					hdrRect.Height = headerHeight;
					vs.DrawBackground(e.Graphics, hdrRect, e.ClipRectangle);
				}
				// Get TaskDialog-ExpandoButton
				vs = new VisualStyleRenderer(taskDialogClass, 13, ((int)Control.buttonState) + 1);
				vs.DrawBackground(e.Graphics, buttonBounds);
				// Get TaskDialog-MainInstructionPane
				vs = new VisualStyleRenderer(taskDialogClass, 2, 0);
				var tff = TextFormatFlags.SingleLine;
				if (Control.GetRightToLeftProperty() == RightToLeft.Yes)
					tff |= TextFormatFlags.RightToLeft;
				vs.DrawText(e.Graphics, textBounds, Control.Text, !Control.Enabled, tff);
			}
		}
	}
}


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

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;

import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.chimesdkvoice.model.*;
import com.amazonaws.transform.Marshaller;

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

/**
 * RestorePhoneNumberRequest Marshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RestorePhoneNumberRequestProtocolMarshaller implements Marshaller<Request<RestorePhoneNumberRequest>, RestorePhoneNumberRequest> {

    private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
            .requestUri("/phone-numbers/{phoneNumberId}?operation=restore").httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false)
            .hasPayloadMembers(false).serviceName("AmazonChimeSDKVoice").build();

    private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;

    public RestorePhoneNumberRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
        this.protocolFactory = protocolFactory;
    }

    public Request<RestorePhoneNumberRequest> marshall(RestorePhoneNumberRequest restorePhoneNumberRequest) {

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

        try {
            final ProtocolRequestMarshaller<RestorePhoneNumberRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
                    restorePhoneNumberRequest);

            protocolMarshaller.startMarshalling();
            RestorePhoneNumberRequestMarshaller.getInstance().marshall(restorePhoneNumberRequest, protocolMarshaller);
            return protocolMarshaller.finishMarshalling();
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
var ProcRPCService = require('./service').ProcRPCService;

function setup(options, imports, register) {
    // Import
    var proc = imports.proc;
    var rpc = imports.rpc;

    // Service
    var service = new ProcRPCService(proc);

    // Register RPC
    rpc.register('proc', service);

    // Register
    register(null, {});
}

// Exports
module.exports = setup;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2014-2015 Quantiply Corporation. All rights reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>parent</artifactId>
        <groupId>com.quantiply.rico</groupId>
        <version>1.0.16-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>rico-jython</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.apache.samza</groupId>
            <artifactId>samza-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
    </dependencies>

</project>


text:
from azure.cli.core.help_files import helps

helps['container'] = """
    type: group
    short-summary: (PREVIEW) Manage Azure Container Instances.
"""

helps['container create'] = """
    type: command
    short-summary: Create a container group.
    examples:
        - name: Create a container group with 1 core and 1Gb of memory.
          text: az container create -g MyResourceGroup --name myalpine --image alpine:latest --cpu 1 --memory 1
        - name: Create a container group that runs Windows, with 2 cores and 3.5Gb of memory.
          text: az container create -g MyResourceGroup --name mywinapp --image winappimage:latest --os-type Windows --cpu 2 --memory 3.5
        - name: Create a container group with public IP address.
          text: az container create -g MyResourceGroup --name myalpine --image alpine:latest --ip-address public
        - name: Create a container group that invokes a script upon start.
          text: az container create -g MyResourceGroup --name myalpine --image alpine:latest --command-line "/bin/sh -c '/path to/myscript.sh'"
        - name: Create a container group with environment variables.
          text: az container create -g MyResourceGroup --name myalpine --image alpine:latest -e key1=value1 key2=value2
        - name: Create a container group using container image from Azure Container Registry.
          text: az container create -g MyResourceGroup --name myalpine --image myAcrRegistry.azurecr.io/alpine:latest --registry-password password
        - name: Create a container group using container image from another private container image registry.
          text: az container create -g MyResourceGroup --name myapp --image myimage:latest --cpu 1 --memory 1.5 --registry-login-server myregistry.com --registry-username username --registry-password password
"""

helps['container delete'] = """
    type: command
    short-summary: Delete a container group.
"""

helps['container list'] = """
    type: command
    short-summary: List container groups.
"""

helps['container show'] = """
    type: command
    short-summary: Get the details of a container group.
"""

helps['container logs'] = """
    type: command
    short-summary: Examine the logs for a container group.
"""


text:
package com.github.ttwd80.tigerpayroll.model.entity;

import static com.mysema.query.types.PathMetadataFactory.*;

import com.mysema.query.types.path.*;

import com.mysema.query.types.PathMetadata;
import javax.annotation.Generated;
import com.mysema.query.types.Path;
import com.mysema.query.types.path.PathInits;

/**
 * QRace is a Querydsl query type for Race
 */
@Generated("com.mysema.query.codegen.EntitySerializer")
public class QRace extends EntityPathBase<Race> {

    private static final long serialVersionUID = 448224762L;

    public static final QRace race = new QRace("race");

    public final StringPath createdBy = createString("createdBy");

    public final DateTimePath<java.time.ZonedDateTime> createdDate = createDateTime("createdDate", java.time.ZonedDateTime.class);

    public final ComparablePath<Character> id = createComparable("id", Character.class);

    public final StringPath lastModifiedBy = createString("lastModifiedBy");

    public final DateTimePath<java.time.ZonedDateTime> lastModifiedDate = createDateTime("lastModifiedDate", java.time.ZonedDateTime.class);

    public final StringPath name = createString("name");

    public final SetPath<User, QUser> users = this.<User, QUser>createSet("users", User.class, QUser.class, PathInits.DIRECT2);

    public QRace(String variable) {
        super(Race.class, forVariable(variable));
    }

    public QRace(Path<? extends Race> path) {
        super(path.getType(), path.getMetadata());
    }

    public QRace(PathMetadata<?> metadata) {
        super(Race.class, metadata);
    }

}


text:
module Pentecost
  module Modules
    class VPCService
    end ## VPCService
  end ## Modules
end ## Pentecost


text:
package br.com.caelum.vraptor.musicjungle.acceptance.pages;

import static org.openqa.selenium.By.cssSelector;
import static org.openqa.selenium.By.name;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import br.com.caelum.vraptor.musicjungle.model.Music;

public class HomePage extends PageObject{

	public HomePage(WebDriver driver) {
		super(driver);
	}

	public MusicPage clickOnFirstMusic() {
		By selector = cssSelector("table a:first-child");
		driver.findElement(selector).click();
		return new MusicPage(driver);
	}

	public SearchPage searchFor(String title) {
		By cssSelector = cssSelector("form");
		PageForm form = new PageForm(driver, cssSelector);
		form.input("music.title", title).submitForm();
		return new SearchPage(driver);
	}

	public void addMusic(Music music) {
		PageForm form = refreshPageForm();
		form.input("music.title", music.getTitle());
		form.select(name("music.type"), music.getType().toString());
		form.input("music.description", music.getDescription());
		form.submitForm();
	}

	/*
	 * (non-javadoc) this refresh method is needed to prevent
	 * {@code org.openqa.selenium.StaleElementReferenceException}
	 */
	private PageForm refreshPageForm() {
		By cssSelector = cssSelector(".well form");
		return new PageForm(driver, cssSelector);
	}

}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace AlquilaCocheras.Web.MasterPages {

    public partial class Anonimo {

        /// <summary>
        /// ContentPlaceHolder_Head control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder_Head;

        /// <summary>
        /// ContentPlaceHolder_Principal control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder_Principal;
    }
}