text:
if (typeof django == "undefined") {
     var django = {
         "jQuery": $.noConflict()
     };
 };
(function($) {
  // Helps to make options available to all functions
  // TODO: This gives problems when there are both expandable and non-expandable
  // trees on a page. The options shouldn't be global to all these instances!
  var options;
  var defaultPaddingLeft;
  var ghost_row;

  $.fn.treeTable = function(opts) {
    options = $.extend({}, $.fn.treeTable.defaults, opts);

    var _return = this.each(function() {
      $(this).addClass("treeTable").find("tbody tr").each(function() {
        // Initialize root nodes only if possible
        if(!options.expandable || $(this)[0].className.search(options.childPrefix) == -1) {
          // To optimize performance of indentation, I retrieve the padding-left
          // value of the first root node. This way I only have to call +css+
          // once.
          if (isNaN(defaultPaddingLeft)) {
            defaultPaddingLeft = parseInt($($(this).children("td")[options.treeColumn]).css('padding-left'), 10);
          }

          initialize($(this));
        } else if(options.initialState == "collapsed") {
          this.style.display = "none"; // Performance! $(this).hide() is slow...
        }
      });
    });

    if(options.draggable)
      initDragDrop($(this));

    return _return;

  };

  $.fn.treeTable.defaults = {
    childPrefix: "child-of-",
    clickableNodeNames: false,
    expandable: true,
    indent: 19,
    initialState: "collapsed",
    treeColumn: 0,
    draggable: false,
    dragTarget: "tbody tr td.drag_handle",
    dropTarget: "tbody tr",
    dropCallback : function(node, newParent, e, ui){ },
    sortable: false,
    sortableDropCallback : function(node, newPrevious, e, ui){ },
    branchMovedAsFirstChild : function(node, parent){ },
    branchMovedAsPrevSibling : function(node, nextSibling){ },
    branchMovedAsNextSibling : function(node, prevSibling){ }
  };

  // Recursively hide all node's children in a tree
  $.fn.collapse = function() {
    $(this).addClass("collapsed");

    childrenOf($(this)).each(function() {
      initialize($(this));

      if(!$(this).hasClass("collapsed")) {
        $(this).collapse();
      }

      this.style.display = "none"; // Performance! $(this).hide() is slow...
    });
    recolor_lines();
    return this;
  };

  // Recursively show all node's children in a tree
  $.fn.expand = function() {
    $(this).removeClass("collapsed").addClass("expanded");

    childrenOf($(this)).each(function() {
      initialize($(this));

      if($(this).is(".expanded.parent")) {
        $(this).expand();
      }

      $(this).show();
    });
    recolor_lines();
    return this;
  };

  // Reveal a node by expanding all ancestors
  $.fn.reveal = function() {
    $(ancestorsOf($(this)).reverse()).each(function() {
      initialize($(this));
      $(this).expand().show();
    });
    recolor_lines();
    return this;
  };

  // Add an entire branch to +destination+
  $.fn.appendBranchTo = function(destination) {
    var node = $(this);
    var parent = parentOf(node);

    destination = $(destination);
    var ancestorNames = $.map(ancestorsOf(destination), function(a) {
      return a.id;
    });

    // Conditions:
    // 1: +node+ should not be inserted in a location in a branch if this would
    //    result in +node+ being an ancestor of itself.
    // 2: +node+ should not have a parent OR the destination should not be the
    //    same as +node+'s current parent (this last condition prevents +node+
    //    from being moved to the same location where it already is).
    // 3: +node+ should not be inserted as a child of +node+ itself.
    if($.inArray(node[0].id, ancestorNames) == -1 && (!parent || (destination.attr('id') != parent[0].id)) && destination.attr('id') != node[0].id) {
      indent(node, ancestorsOf(node).length * options.indent * -1); // Remove indentation

      if(parent) {
        node.removeClass(options.childPrefix + parent[0].id);
        add_expandable_widget($(parent));
      }

      node.addClass(options.childPrefix + destination.attr('id'));
      move(node, destination); // Recursively move nodes to new location
      indent(node, ancestorsOf(node).length * options.indent);

      add_expandable_widget(destination);

      options.branchMovedAsFirstChild(node, destination);

    }

    return this;
  };

  // Reshuffle an entire branch behind another one
  $.fn.moveBranchBefore = function(destination) {
    var node = $(this);

    // Move the node
    node.insertBefore(destination);
    childrenOf(node).reverse().each(function() {
      move($(this), node[0]);
    });

    options.branchMovedAsPrevSibling(node, destination);

    return this;

  };

  // Reshuffle an entire branch in front of another one
  $.fn.moveBranchAfter = function(destination) {
    var node = $(this);

    // Move the node
    if(childrenOf(destination).length > 0) {
      node.insertAfter(lastChildOf(destination));
    } else {
      node.insertAfter(destination);
    }

    childrenOf(node).reverse().each(function() {
      move($(this), node[0]);
    });

    options.branchMovedAsNextSibling(node, destination);

    return this;

  };

  // Add reverse() function from JS Arrays
  $.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
  };

  // Toggle an entire branch
  $.fn.toggleBranch = function() {
    if($(this).hasClass("collapsed")) {
      $(this).expand();
    } else {
      $(this).removeClass("expanded").collapse();
    }

    return this;
  };

  // Get the parent of the node
  $.fn.parentOf = function() {
    var classNames = $(this)[0].className.split(' ');

    for(key in classNames) {
      if(classNames[key].match(options.childPrefix)) {
        return $("#" + classNames[key].substring(9));
      }
    }
  };

  var cur_level = 0;

  // This will serialise a table (given a selector) and return a string
  // for passing to some sort of asyncronous request
  $.fn.serializeTreeTable = function() {
    var table_id = this[0].id;
    var serialised_contents = [];
    cur_level = 0;

    $(this).find("tbody tr").each(function() {
      if($(this)[0].className.search("child-of-") == -1 && $(this)[0].className.search("ghost_row") == -1) {
        serializeChildren(table_id, $(this), serialised_contents, "");
        cur_level++;
      }
    });

    return serialised_contents.join("&");

  };

  function serializeChildren(table_id, parent, serialed, cur_child_string) {

    serialed.push(table_id+"["+cur_level+"]"+cur_child_string+"[id]="+parent[0].id);
    var kids = $(parent).nextAll("tr.child-of-" + parent[0].id);

    cur_child_string += "[children]";

    if(kids.length > 0)
    {
      var kid_level = 0;
      kids.each(function() {
        serializeChildren(table_id, $(this), serialed, cur_child_string + "["+kid_level+"]");
        kid_level++;
      });
    }
  }

  // === Private functions

  function ancestorsOf(node) {
    var ancestors = [];
    while((node = parentOf(node))) {
      ancestors[ancestors.length] = node[0];
    }
    return ancestors;
  }

  function childrenOf(node) {
    return $("table.treeTable tbody tr." + options.childPrefix + node[0].id);
  }

  function lastChildOf(node) {
    return $("table.treeTable tbody tr." + options.childPrefix + node[0].id+":last");
  }

  function getPaddingLeft(node) {
    var paddingLeft = parseInt(node[0].style.paddingLeft, 10);
    return (isNaN(paddingLeft)) ? defaultPaddingLeft : paddingLeft;
  }

  function indent(node, value) {
    var cell = $(node.children("td")[options.treeColumn]);
    cell[0].style.paddingLeft = getPaddingLeft(cell) + value + "px";

    childrenOf(node).each(function() {
      indent($(this), value);
    });
  }

  function recolor_lines() {
      $('tbody tr').removeClass('row1').removeClass('row2');
      $('tbody tr:visible:even').addClass('row1');
      $('tbody tr:visible:odd').addClass('row2');
  };

  function initialize(node) {
    if(!node.hasClass("initialized")) {
      node.addClass("initialized");

      var childNodes = childrenOf(node);

      if(!node.hasClass("parent") && childNodes.length > 0) {
        node.addClass("parent");
      }

      if(node.hasClass("parent")) {
        var cell = $(node.children("td")[options.treeColumn]);
        var padding = getPaddingLeft(cell) + options.indent;

        childNodes.each(function() {
          $(this).children("td")[options.treeColumn].style.paddingLeft = padding + "px";
        });

        add_expandable_widget(node);

      }
      recolor_lines();
    }
  }

  function initDragDrop(table) {

    // Configure draggable nodes
    $(options.dragTarget).draggable({
      helper: function () {
        var helper = $(this).clone();
        helper.find('span.expander').remove();
        return helper;
      },
      opacity: 0.75,
      refreshPositions: true, // Performance?
      revert: "invalid",
      revertDuration: 300,
      scroll: true
    });

    // If we want a sortable one then we need to create a ghosted row
    if(options.sortable)
    {
      var cell_count = $(options.dropTarget).parents("tr").find("td").length;
      ghost_row = $("
Drop here to reorder
");
      ghost_row.insertBefore($(table).find("tr:first"));
      ghost_row.hide();
    }

    // Configure droppable nodes
    $(options.dropTarget).droppable({
      accept: options.dragTarget,
      drop: function(e, ui) {

        if(options.sortable)
          ghost_row.hide();

        var node = $($(ui.draggable).parents("tr"));
        var newParent = $(this);
        if (! newParent.is('tr')) {
          newParent = newParent.parents('tr');
        }
        // Move the branch when we drop on it
        node.appendBranchTo(newParent);

        // Custom callback
        options.dropCallback(node, newParent, e, ui);

      },
      hoverClass: "accept",
      over: function(e, ui) {

        // Deal with displaying the ghost row when sorting
        if(options.sortable)
        {
          var my_par = $(this).parentOf();
          var draggy_par = $(ui.draggable.parents("tr")).parentOf();

          if(my_par != undefined && draggy_par != undefined)
          {
            if(my_par[0].id == draggy_par[0].id && $(this)[0].id != $(ui.draggable.parents("tr"))[0].id)
            {
              ghost_row.insertAfter(this);
              ghost_row.show();
            }
            else
              $(ghost_row).hide();
          }

        }

        if(this.id != ui.draggable.parents("tr")[0].id && !$(this).is(".expanded"))
          $(this).expand();

      }
    });

    // Sort out resorting if we have it enabled
    if(options.sortable)
    {

      $("tr td span.ghost_text").each(function() {
        $(this).parents("tr").droppable( {
          accept: options.dragTarget,
          drop: function(e, ui) {
            ghost_row.hide();
            var node = $(ui.draggable.parents("tr"));
            var newPrevious = $(this).prev("tr");
            node.moveBranchAfter(newPrevious);

            // Custom callback
            options.sortableDropCallback(node, newPrevious, e, ui);

          }
        });
      });

    }

  }

  // Add expandable button to a node
  function add_expandable_widget(node)
  {

    if(options.expandable) {

      var cell = $(node.children("td")[options.treeColumn]);
      if(childrenOf(node).length == 0)
      {
        //cell.prepend('');
        cell.find("span.expander").remove();
        return;
      }

      cell.prepend('');

      $(cell[0].firstChild).click(function() {
        node.toggleBranch();
      });

      if(options.clickableNodeNames) {
        cell[0].style.cursor = "pointer";
        $(cell).click(function(e) {
          // Don't double-toggle if the click is on the existing expander icon
          if (e.target.className != 'expander') {
            node.toggleBranch();
          }
        });
      }

      // Check for a class set explicitly by the user, otherwise set the default class
      if(!(node.hasClass("expanded") || node.hasClass("collapsed"))) {
        node.addClass(options.initialState);
      }

      if(node.hasClass("expanded")) {
        node.expand();
      }
    }
  }

  function move(node, destination) {
    node.insertAfter(destination);
    childrenOf(node).reverse().each(function() {
      move($(this), node[0]);
    });
  }

  function parentOf(node) {
    return $(node).parentOf();
  }
})(django.jQuery);


text:
using System.Globalization;
using System.Linq;
using Kerberos.NET.Crypto;
using Kerberos.NET.Entities;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Tests.Kerberos.NET
{
    [TestClass]
    public class KrbtgtTests : BaseTest
    {
        private const string Realm = "corp.test.internal";
        private const string KrbtgtSpn = "krbtgt/" + Realm;
        private const string UserUpn = "user@test.internal";
        private const string TestSamAccountName = "SamAccount";

        private const TicketFlags ExpectedFlags = TicketFlags.EncryptedPreAuthentication | TicketFlags.Renewable | TicketFlags.Forwardable;

        internal static readonly byte[] FakeKey = new byte[]
        {
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        };

        private static readonly byte[] TgtKey = FakeKey;

        private static readonly byte[] Key = new byte[]
        {
            0xef, 0x74, 0x22, 0xcb, 0x49, 0xe2, 0xf5, 0xb0, 0x92, 0x92, 0xcb, 0xd8, 0x25, 0xc2, 0x95, 0x24,
            0x9f, 0x2a, 0x31, 0x46, 0x5d, 0xc9, 0xab, 0x4a, 0x30, 0x80, 0xed, 0xf3, 0x16, 0x8a, 0x88, 0x57
        };

        [TestMethod]
        public void KrbtgtDecode()
        {
            var krbtgtKey = new KerberosKey(key: Key, etype: EncryptionType.AES256_CTS_HMAC_SHA1_96);
            var longUserTermKey = new KerberosKey("P@ssw0rd!", salt: "CORP.IDENTITYINTERVENTION.COMtestuser");

            var krbAsRepBytes = ReadDataFile("messages\\as-rep").Skip(4).ToArray();

            var asRep = new KrbAsRep().DecodeAsApplication(krbAsRepBytes);

            var encPart = asRep.EncPart.Decrypt(longUserTermKey, KeyUsage.EncAsRepPart, b => KrbEncAsRepPart.DecodeApplication(b));

            Assert.IsNotNull(encPart);

            var encTicket = asRep.Ticket.EncryptedPart;

            var krbtgt = encTicket.Decrypt(krbtgtKey, KeyUsage.Ticket, bytes => new KrbEncTicketPart().DecodeAsApplication(bytes));

            Assert.IsNotNull(krbtgt);
        }

        [TestMethod]
        public void GeneratedTgtMatchesActiveDirectory()
        {
            var realmService = new FakeRealmService(Realm);
            var principal = realmService.Principals.Find(KrbPrincipalName.FromString(UserUpn));

            var principalKey = principal.RetrieveLongTermCredential();

            var rst = new ServiceTicketRequest
            {
                Flags = ExpectedFlags,
                Principal = principal,
                EncryptedPartKey = principalKey,
                ServicePrincipalKey = new KerberosKey(key: TgtKey, etype: EncryptionType.AES256_CTS_HMAC_SHA1_96)
            };

            var tgt = KrbAsRep.GenerateTgt(rst, realmService);

            Assert.IsNotNull(tgt);

            var encoded = tgt.EncodeApplication();

            AssertIsExpectedKrbtgt(principalKey, rst.ServicePrincipalKey, encoded.ToArray());
        }

        private static void AssertIsExpectedKrbtgt(KerberosKey clientKey, KerberosKey tgtKey, byte[] message)
        {
            var asRep = new KrbAsRep().DecodeAsApplication(message);

            Assert.IsNotNull(asRep);

            var encPart = asRep.EncPart.Decrypt(
                clientKey,
                KeyUsage.EncAsRepPart,
                b => KrbEncAsRepPart.DecodeApplication(b)
            );

            Assert.IsNotNull(encPart);

            Assert.AreEqual(KrbtgtSpn, encPart.SName.FullyQualifiedName, true, CultureInfo.InvariantCulture);
            Assert.AreEqual(Realm, encPart.Realm);

            Assert.IsNotNull(encPart.Key);

            Assert.AreEqual(ExpectedFlags, encPart.Flags);

            var krbtgt = asRep.Ticket.EncryptedPart.Decrypt(
                tgtKey,
                KeyUsage.Ticket,
                d => new KrbEncTicketPart().DecodeAsApplication(d)
            );

            Assert.IsNotNull(krbtgt);

            Assert.AreEqual(krbtgt.CName.FullyQualifiedName, asRep.CName.FullyQualifiedName);

            Assert.AreEqual(UserUpn, krbtgt.CName.FullyQualifiedName, true, CultureInfo.InvariantCulture);
            Assert.AreEqual(Realm, krbtgt.CRealm);
            Assert.AreEqual(ExpectedFlags, krbtgt.Flags);

            Assert.IsTrue(Enumerable.SequenceEqual(krbtgt.Key.KeyValue.ToArray(), encPart.Key.KeyValue.ToArray()));
        }

        [TestMethod]
        public void GeneratedTgtMatchesWithOnPremisesSamAccountName()
        {
            var realmService = new FakeRealmService(Realm);
            var principal = realmService.Principals.Find(KrbPrincipalName.FromString(UserUpn));

            var principalKey = principal.RetrieveLongTermCredential();

            var rst = new ServiceTicketRequest
            {
                SamAccountName = TestSamAccountName,
                Flags = ExpectedFlags,
                Principal = principal,
                EncryptedPartKey = principalKey,
                ServicePrincipalKey = new KerberosKey(key: TgtKey, etype: EncryptionType.AES256_CTS_HMAC_SHA1_96)
            };

            var tgt = KrbAsRep.GenerateTgt(rst, realmService);

            Assert.IsNotNull(tgt);

            var encoded = tgt.EncodeApplication();

            AssertIsExpectedKrbtgtWithOnPremisesSamAccountName(principalKey, rst.ServicePrincipalKey, encoded.ToArray());
        }

        private static void AssertIsExpectedKrbtgtWithOnPremisesSamAccountName(KerberosKey clientKey, KerberosKey tgtKey, byte[] message)
        {
            var asRep = new KrbAsRep().DecodeAsApplication(message);

            Assert.IsNotNull(asRep);

            // CName under reply part should NOT be original UPN
            Assert.AreNotEqual(UserUpn, asRep.CName.FullyQualifiedName);
            Assert.AreEqual(TestSamAccountName, asRep.CName.FullyQualifiedName);

            var encPart = asRep.EncPart.Decrypt(
                clientKey,
                KeyUsage.EncAsRepPart,
                b => KrbEncAsRepPart.DecodeApplication(b)
            );

            Assert.IsNotNull(encPart);

            Assert.AreEqual(KrbtgtSpn, encPart.SName.FullyQualifiedName, true, CultureInfo.InvariantCulture);
            Assert.AreEqual(Realm, encPart.Realm);

            Assert.IsNotNull(encPart.Key);

            Assert.AreEqual(ExpectedFlags, encPart.Flags);

            var krbtgt = asRep.Ticket.EncryptedPart.Decrypt(
                tgtKey,
                KeyUsage.Ticket,
                d => new KrbEncTicketPart().DecodeAsApplication(d)
            );

            Assert.IsNotNull(krbtgt);

            // CName under encrypted ticket part should be matched with OnPremisesSamAccountName
            Assert.IsTrue(krbtgt.CName.Type == PrincipalNameType.NT_PRINCIPAL);
            Assert.IsTrue(krbtgt.CName.Name.Length == 1);
            Assert.AreEqual(TestSamAccountName, krbtgt.CName.FullyQualifiedName);

            Assert.AreEqual(Realm, krbtgt.CRealm);
            Assert.AreEqual(ExpectedFlags, krbtgt.Flags);

            Assert.IsTrue(Enumerable.SequenceEqual(krbtgt.Key.KeyValue.ToArray(), encPart.Key.KeyValue.ToArray()));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
This library was generated with [Nx](https://nx.dev).

## Running unit tests

Run `nx test examples-common-model` to execute the unit tests via [Jest](https://jestjs.io).


text:
/**
 * Created by alexandermiller on 2/12/17.
 */
export interface IProcessSMS {
    addSms: (payload: any) => void;
}


text:
import { of } from 'rxjs';
import { skipWhile } from 'rxjs/operators';

it('should support a predicate', () => {
  const o = of('foo', 'bar', 'baz').pipe(skipWhile(value => value === 'bar')); // $ExpectType Observable<string>
});

it('should support a predicate with an index', () => {
  const o = of('foo', 'bar', 'baz').pipe(skipWhile((value, index) => index < 3)); // $ExpectType Observable<string>
});

it('should enforce types', () => {
  const o = of('foo', 'bar', 'baz').pipe(skipWhile()); // $ExpectError
});

it('should enforce predicate types', () => {
  const o = of('foo', 'bar', 'baz').pipe(skipWhile(value => value < 3)); // $ExpectError
  const p = of('foo', 'bar', 'baz').pipe(skipWhile((value, index) => index < '3')); // $ExpectError
});

it('should enforce predicate return type', () => {
  const o = of('foo', 'bar', 'baz').pipe(skipWhile(value => value)); // $ExpectError
});

it('should handle Boolean constructor properly', () => {
  // this one is a bit odd, but probably okay.
  const a = of(null, undefined, 0 as const, -0 as const, '' as const, 0n as const, false as const).pipe(skipWhile(Boolean)); // $ExpectType Observable<false | "" | 0 | 0n | null | undefined>
  const b = of(null, 0 as const, -0 as const, '' as const, 0n as const, false as const).pipe(skipWhile(Boolean)); // $ExpectType Observable<false | "" | 0 | 0n | null>
  const c = of(1, 2, 3, '' as const, 0n as const, false as const, 4).pipe(skipWhile(Boolean)) // $ExpectType Observable<number | false | "" | 0n>
  const d = of(true as const, 123 as const, 'HI' as const, {}, []).pipe(skipWhile(Boolean)); // $ExpectType Observable<never>
});

it('should handle predicates that always return true properly', () => {
  const a = of(1, 2, 3, 4).pipe(skipWhile(() => true as const)); // $ExpectType Observable<never>
});


text:
package docker

import (
	"bytes"
	"errors"
	"fmt"
	"regexp"

	"github.com/docker/docker/errdefs"
	"github.com/docker/docker/pkg/jsonmessage"

	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/config"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker"
	sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors"
	"github.com/GoogleContainerTools/skaffold/proto/v1"
)

var (
	noSpaceLeft   = regexp.MustCompile(".*no space left.*")
	execFormatErr = regexp.MustCompile(".*exec format error.*")
)

// newBuildError turns Docker-specific errors into actionable errors.
// The input errors are assumed to be from the Skaffold docker invocation.
func newBuildError(err error, cfg docker.Config) error {
	if sErrors.IsSkaffoldErr(err) {
		return err
	}
	errU := errors.Unwrap(err)
	if errU == nil {
		return err
	}

	switch errU.(type) {
	case *jsonmessage.JSONError:
		return sErrors.NewError(err,
			&proto.ActionableErr{
				Message: err.Error(),
				ErrCode: proto.StatusCode_BUILD_USER_ERROR,
				Suggestions: []*proto.Suggestion{
					{
						SuggestionCode: proto.SuggestionCode_FIX_USER_BUILD_ERR,
						Action:         "Please fix the Dockerfile and try again.",
					},
				},
			})
	default:
		return sErrors.NewError(err, getActionableErr(errU, cfg))
	}
}

func getActionableErr(err error, cfg docker.Config) *proto.ActionableErr {
	var errCode proto.StatusCode
	suggestions := []*proto.Suggestion{
		{
			SuggestionCode: proto.SuggestionCode_DOCKER_BUILD_RETRY,
			Action:         "Docker build ran into internal error. Please retry.\nIf this keeps happening, please open an issue.",
		},
	}
	switch err.(type) {
	case errdefs.ErrNotFound:
		errCode = proto.StatusCode_BUILD_DOCKER_ERROR_NOT_FOUND
	case errdefs.ErrInvalidParameter:
		errCode = proto.StatusCode_BUILD_DOCKER_INVALID_PARAM_ERR
	case errdefs.ErrConflict:
		errCode = proto.StatusCode_BUILD_DOCKER_CONFLICT_ERR
	case errdefs.ErrCancelled:
		errCode = proto.StatusCode_BUILD_DOCKER_CANCELLED
	case errdefs.ErrForbidden:
		errCode = proto.StatusCode_BUILD_DOCKER_FORBIDDEN_ERR
	case errdefs.ErrDataLoss:
		errCode = proto.StatusCode_BUILD_DOCKER_DATA_LOSS_ERR
	case errdefs.ErrDeadline:
		errCode = proto.StatusCode_BUILD_DOCKER_DEADLINE
	case errdefs.ErrNotImplemented:
		errCode = proto.StatusCode_BUILD_DOCKER_NOT_IMPLEMENTED_ERR
	case errdefs.ErrNotModified:
		errCode = proto.StatusCode_BUILD_DOCKER_NOT_MODIFIED_ERR
	case errdefs.ErrSystem:
		errCode = proto.StatusCode_BUILD_DOCKER_SYSTEM_ERR
		if noSpaceLeft.MatchString(err.Error()) {
			errCode = proto.StatusCode_BUILD_DOCKER_NO_SPACE_ERR
			suggestions = []*proto.Suggestion{
				{
					SuggestionCode: proto.SuggestionCode_RUN_DOCKER_PRUNE,
					Action:         "Docker ran out of memory. Please run 'docker system prune' to removed unused docker data",
				},
			}
			if !cfg.Prune() && (cfg.Mode() == config.RunModes.Dev || cfg.Mode() == config.RunModes.Debug) {
				suggestions = append(suggestions, &proto.Suggestion{
					SuggestionCode: proto.SuggestionCode_SET_CLEANUP_FLAG,
					Action:         fmt.Sprintf("Run skaffold %s with --cleanup=true to clean up images built by skaffold", cfg.Mode()),
				})
			}
		}
	case errdefs.ErrUnauthorized:
		errCode = proto.StatusCode_BUILD_DOCKER_UNAUTHORIZED
	case errdefs.ErrUnavailable:
		errCode = proto.StatusCode_BUILD_DOCKER_UNAVAILABLE
	default:
		errCode = proto.StatusCode_BUILD_DOCKER_UNKNOWN
	}

	return &proto.ActionableErr{
		Message:     err.Error(),
		ErrCode:     errCode,
		Suggestions: suggestions,
	}
}

func dockerfileNotFound(err error, artifact string) error {
	return sErrors.NewError(err,
		&proto.ActionableErr{
			Message: err.Error(),
			ErrCode: proto.StatusCode_BUILD_DOCKERFILE_NOT_FOUND,
			Suggestions: []*proto.Suggestion{
				{
					SuggestionCode: proto.SuggestionCode_FIX_SKAFFOLD_CONFIG_DOCKERFILE,
					Action: fmt.Sprintf("Dockerfile not found. Please check config `dockerfile` for artifact %s."+
						"\nRefer https://skaffold.dev/docs/references/yaml/#build-artifacts-docker for details.", artifact),
				},
			},
		})
}

func cacheFromPullErr(err error, artifact string) error {
	return sErrors.NewError(err,
		&proto.ActionableErr{
			Message: err.Error(),
			ErrCode: proto.StatusCode_BUILD_DOCKER_CACHE_FROM_PULL_ERR,
			Suggestions: []*proto.Suggestion{
				{
					SuggestionCode: proto.SuggestionCode_FIX_CACHE_FROM_ARTIFACT_CONFIG,
					Action: fmt.Sprintf("Fix `cacheFrom` config for artifact %s."+
						"\nRefer https://skaffold.dev/docs/references/yaml/#build-artifacts-docker for details.", artifact),
				},
			},
		})
}

func tryExecFormatErr(err error, stdErr bytes.Buffer) error {
	if !execFormatErr.MatchString(stdErr.String()) {
		return err
	}
	return sErrors.NewError(err,
		&proto.ActionableErr{
			Message: err.Error(),
			ErrCode: proto.StatusCode_BUILD_CROSS_PLATFORM_ERR,
			Suggestions: []*proto.Suggestion{
				{
					SuggestionCode: proto.SuggestionCode_BUILD_INSTALL_PLATFORM_EMULATORS,
					Action:         "To run cross-platform builds, check that QEMU platform emulators are installed correctly. To install, run:\n\n\tdocker run --privileged --rm tonistiigi/binfmt --install all\n\nFor more details, see https://registry.hub.docker.com/r/tonistiigi/binfmt",
				},
			},
		})
}


text:
class GURL;
class Profile;

namespace content {
class WebContents;
}

// A set of helper functions used by the MergeSessionNavigationThrottle and the
// MergeSessionResourceThrottle to determine if an interstitial page should be
// shown for a request when the merge session process (cookie reconstruction
// from OAuth2 refresh token in ChromeOS login) is still in progress.
namespace merge_session_throttling_utils {

// Passed a boolean indicating whether or not it is OK to proceed with the
// page load.
using CompletionCallback = base::Closure;

// Policy for when it is valid to attach a MergeSessionNavigationThrottle.
// Namely, this will be false for unit tests, where the UserManager is not
// initialized.
bool ShouldAttachNavigationThrottle();

// Checks if session is already merged. This is safe to call on all threads.
bool AreAllSessionMergedAlready();

// Adds/removes |profile| to/from the blocking profiles set. This should be
// called on the UI thread.
void BlockProfile(Profile* profile);
void UnblockProfile(Profile* profile);

// Whether requests from |web_contents| or |profile| should currently be
// delayed. This should be called on the UI thread.
bool ShouldDelayRequestForProfile(Profile* profile);
bool ShouldDelayRequestForWebContents(content::WebContents* web_contents);

// True if the load of |url| should be delayed. The function is safe to be
// called on any thread.
bool ShouldDelayUrl(const GURL& url);

}  // namespace merge_session_throttling_utils

#endif  // CHROME_BROWSER_CHROMEOS_LOGIN_SIGNIN_MERGE_SESSION_THROTTLING_UTILS_H_


text:
// Copyright (c) Jeremy W. Kuhne. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Runtime.CompilerServices;

#pragma warning disable SA1015 // Closing generic brackets should be spaced correctly

namespace WInterop;

/// <summary>
///  Used for trailing native unsized (ANYSIZE) arrays of <typeparamref name="T"/>. Native example:
///  UCHAR  UniqueId[1];
/// </summary>
/// <remarks>
///  Accessing the values is only safe when you have a pointer to the containing struct in
///  a buffer. If you have an actual struct (Foo, not Foo*), the trailing array will have been
///  truncated as the values aren't actually part of the struct.
/// </remarks>
public readonly struct TrailingArray<T> where T : unmanaged
{
    private readonly T _firstItem;

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static unsafe ReadOnlySpan<T> GetBuffer(in T first, uint count, uint offset = 0)
    {
        fixed (void* p = &first)
        {
            return ((TrailingArray<T>*)p)->GetBuffer(count, offset);
        }
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static unsafe ReadOnlySpan<T> GetBufferInBytes(in T first, uint countInBytes, uint offsetInBytes = 0)
    {
        fixed (void* p = &first)
        {
            return ((TrailingArray<T>*)p)->GetBuffer(countInBytes / (uint)sizeof(T), offsetInBytes / (uint)sizeof(T));
        }
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private unsafe ReadOnlySpan<T> GetBuffer(uint count, uint offset = 0)
    {
        if (count == 0)
            return ReadOnlySpan<T>.Empty;

        fixed (T* t = &_firstItem)
            return new ReadOnlySpan<T>(t + offset, (int)count);
    }
}

#pragma warning restore SA1015 // Closing generic brackets should be spaced correctly


text:
package io.github.resilience4j.feign;

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.ratelimiter.RateLimiter;
import org.junit.Test;

import java.lang.reflect.Method;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;

public class FeignDecoratorsTest {

    @Test
    public void testWithNothing() throws Throwable {
        final FeignDecorators testSubject = FeignDecorators.builder().build();

        final Object result = testSubject.decorate(args -> args[0], null, null, null)
            .apply(new Object[]{"test01"});

        assertThat(result)
            .describedAs("Returned result is correct")
            .isEqualTo("test01");
    }

    @Test
    public void testWithCircuitBreaker() throws Throwable {
        final CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");
        final CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
        final FeignDecorators testSubject = FeignDecorators.builder()
            .withCircuitBreaker(circuitBreaker).build();
        final Method method = FeignDecoratorsTest.class.getDeclaredMethods()[0];

        final Object result = testSubject.decorate(args -> args[0], method, null, null)
            .apply(new Object[]{"test01"});

        assertThat(result)
            .describedAs("Returned result is correct")
            .isEqualTo("test01");
        assertThat(metrics.getNumberOfSuccessfulCalls())
            .describedAs("Successful Calls")
            .isEqualTo(1);
    }

    @Test
    public void testWithRateLimiter() throws Throwable {
        final RateLimiter rateLimiter = spy(RateLimiter.ofDefaults("test"));
        final FeignDecorators testSubject = FeignDecorators.builder().withRateLimiter(rateLimiter)
            .build();
        final Method method = FeignDecoratorsTest.class.getDeclaredMethods()[0];

        final Object result = testSubject.decorate(args -> args[0], method, null, null)
            .apply(new Object[]{"test01"});

        assertThat(result)
            .describedAs("Returned result is correct")
            .isEqualTo("test01");
        verify(rateLimiter, times(1)).acquirePermission(1);
    }
}


text:
/* See LICENSE for licensing information */

/**
 * \file process_sys.c
 * \brief Subsystem object for process setup.
 **/

#include "orconfig.h"
#include "lib/subsys/subsys.h"
#include "lib/process/process_sys.h"
#include "lib/process/process.h"

static int
subsys_process_initialize(void)
{
  process_init();
  return 0;
}

static void
subsys_process_shutdown(void)
{
  process_free_all();
}

const subsys_fns_t sys_process = {
  .name = "process",
  .level = -35,
  .supported = true,
  .initialize = subsys_process_initialize,
  .shutdown = subsys_process_shutdown
};


text:
package id.ac.unpar.siamodels.matakuliah;

import id.ac.unpar.siamodels.InfoMataKuliah;
import id.ac.unpar.siamodels.MataKuliah;
import id.ac.unpar.siamodels.matakuliah.interfaces.*;
import id.ac.unpar.siamodels.Mahasiswa;

import java.util.List;

@InfoMataKuliah(nama = "Desain dan Analisis Algoritma", sks = 3)
public class AIF182106 extends MataKuliah implements HasPraktikum, HasResponsi, HasPrasyarat{

    @Override
    public boolean checkPrasyarat(Mahasiswa mahasiswa, List<String> reasonsContainer) {
        boolean ok = true;
        if (!mahasiswa.hasLulusKuliah("AIF182101")) {
            reasonsContainer.add("Tidak memenuhi prasyarat lulus AIF182101");
            ok = false;
        }
        if (!mahasiswa.hasTempuhKuliah("AIF182103")) {
            reasonsContainer.add("Tidak memenuhi prasyarat tempuh AIF182103");
            ok = false;
        }
        return ok;
    }
}


text:
#include "screengrab.h"
#include "bmp_io.h"
#include "endian.h"
#include <stdlib.h> /* malloc() */

#if defined(IS_MACOSX)
	#include <OpenGL/OpenGL.h>
	#include <OpenGL/gl.h>
	#include <ApplicationServices/ApplicationServices.h>
#elif defined(USE_X11)
	#include <X11/Xlib.h>
	#include <X11/Xutil.h>
	#include "xdisplay.h"
#elif defined(IS_WINDOWS)
	#include <string.h>
#endif

MMBitmapRef copyMMBitmapFromDisplayInRect(MMRect rect)
{
#if defined(IS_MACOSX)

	size_t bytewidth;
	uint8_t bitsPerPixel, bytesPerPixel;
	//uint8_t *buffer;

	CGDirectDisplayID displayID = CGMainDisplayID();

	//Replacement for CGDisplayBitsPerPixel.
	CGDisplayModeRef mode = CGDisplayCopyDisplayMode(displayID);
	size_t depth = 0;

	CFStringRef pixEnc = CGDisplayModeCopyPixelEncoding(mode);
	if(CFStringCompare(pixEnc, CFSTR(IO32BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
		depth = 32;
	else if(CFStringCompare(pixEnc, CFSTR(IO16BitDirectPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
		depth = 16;
	else if(CFStringCompare(pixEnc, CFSTR(IO8BitIndexedPixels), kCFCompareCaseInsensitive) == kCFCompareEqualTo)
		depth = 8;

	bitsPerPixel = (uint8_t) depth;
	bytesPerPixel = bitsPerPixel / 8;
	/* Align width to padding. */
	//bytewidth = ADD_PADDING(rect.size.width * bytesPerPixel);
	bytewidth = rect.size.width * bytesPerPixel;

	/* Convert Quartz point to postscript point. */
	//rect.origin.y = CGDisplayPixelsHigh(displayID) - rect.origin.y - rect.size.height;

	CGImageRef image = CGDisplayCreateImageForRect(displayID, CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height));

    // Request access to the raw pixel data via the image's DataProvider.
    CGDataProviderRef provider = CGImageGetDataProvider(image);
    CFDataRef data = CGDataProviderCopyData(provider);

    size_t width, height;
    width = CGImageGetWidth(image);
    height = CGImageGetHeight(image);
    size_t bpp = CGImageGetBitsPerPixel(image) / 8;

    uint8 *pixels = malloc(width * height * bpp);
    memcpy(pixels, CFDataGetBytePtr(data), width * height * bpp);
    CFRelease(data);
   	CGImageRelease(image);

	return createMMBitmap(pixels, rect.size.width, rect.size.height, bytewidth,
	                      bitsPerPixel, bytesPerPixel);
#elif defined(USE_X11)
	MMBitmapRef bitmap;

	Display *display = XOpenDisplay(NULL);
	XImage *image = XGetImage(display,
	                          XDefaultRootWindow(display),
	                          (int)rect.origin.x,
	                          (int)rect.origin.y,
	                          (unsigned int)rect.size.width,
	                          (unsigned int)rect.size.height,
	                          AllPlanes, ZPixmap);
	XCloseDisplay(display);
	if (image == NULL) return NULL;

	bitmap = createMMBitmap((uint8_t *)image->data,
	                        rect.size.width,
	                        rect.size.height,
	                        (size_t)image->bytes_per_line,
	                        (uint8_t)image->bits_per_pixel,
	                        (uint8_t)image->bits_per_pixel / 8);
	image->data = NULL; /* Steal ownership of bitmap data so we don't have to
	                     * copy it. */
	XDestroyImage(image);

	return bitmap;
#elif defined(IS_WINDOWS)
	MMBitmapRef bitmap;
	void *data;
	HDC screen = NULL, screenMem = NULL;
	HBITMAP dib;
	BITMAPINFO bi;

	/* Initialize bitmap info. */
	bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
   	bi.bmiHeader.biWidth = (long)rect.size.width;
   	bi.bmiHeader.biHeight = -(long)rect.size.height; /* Non-cartesian, please */
   	bi.bmiHeader.biPlanes = 1;
   	bi.bmiHeader.biBitCount = 32;
   	bi.bmiHeader.biCompression = BI_RGB;
   	bi.bmiHeader.biSizeImage = (DWORD)(4 * rect.size.width * rect.size.height);
	bi.bmiHeader.biXPelsPerMeter = 0;
	bi.bmiHeader.biYPelsPerMeter = 0;
	bi.bmiHeader.biClrUsed = 0;
	bi.bmiHeader.biClrImportant = 0;

	screen = GetDC(NULL); /* Get entire screen */
	if (screen == NULL) return NULL;

	/* Get screen data in display device context. */
   	dib = CreateDIBSection(screen, &bi, DIB_RGB_COLORS, &data, NULL, 0);

	/* Copy the data into a bitmap struct. */
	if ((screenMem = CreateCompatibleDC(screen)) == NULL ||
	    SelectObject(screenMem, dib) == NULL ||
	    !BitBlt(screenMem,
	            (int)rect.origin.x,
	            (int)rect.origin.y,
	            (int)rect.size.width,
	            (int)rect.size.height, screen, 0, 0, SRCCOPY)) {
		/* Error copying data. */
		ReleaseDC(NULL, screen);
		DeleteObject(dib);
		if (screenMem != NULL) DeleteDC(screenMem);

		return NULL;
	}

	bitmap = createMMBitmap(NULL,
	                        rect.size.width,
	                        rect.size.height,
	                        4 * rect.size.width,
	                        (uint8_t)bi.bmiHeader.biBitCount,
	                        4);

	/* Copy the data to our pixel buffer. */
	if (bitmap != NULL) {
		bitmap->imageBuffer = malloc(bitmap->bytewidth * bitmap->height);
		memcpy(bitmap->imageBuffer, data, bitmap->bytewidth * bitmap->height);
	}

	ReleaseDC(NULL, screen);
	DeleteObject(dib);
	DeleteDC(screenMem);

	return bitmap;
#endif
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>My Project: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

My Project

PayOffBarrier Member List

This is the complete list of members for PayOffBarrier, including all inherited members.

Barrier	PayOffBarrier	protected

call enum value	PayOff

clone() const =0	PayOff	pure virtual

digitalCall enum value	PayOff

doubleDigital enum value	PayOff

GetBarrier() const	PayOffBarrier	inline

GetRebate() const	PayOffBarrier	inline

GetStrike() const	PayOff	virtual

IsTouched(double Spot) const =0	PayOffBarrier	pure virtual

operator()(double Spot) const	PayOff

operator()(double Spot) const =0	PayOff	pure virtual

operator()(double Spot) const =0	PayOff	pure virtual

OptionType enum name	PayOff

PayOff(double Strike_, OptionType TheOptionsType_)	PayOff

PayOff(double Strike_, double Strike1_, OptionType TheOptionsType_)	PayOff

PayOff()	PayOff	inline

PayOff(double Strike_=0.0)	PayOff

PayOffBarrier(double Barrier_, double Strike_, double Rebate=0.0)	PayOffBarrier

put enum value	PayOff

Rebate	PayOffBarrier	protected

SetStrike(double Strike_)	PayOff	virtual

~PayOff()	PayOff	inlinevirtual

~PayOff()	PayOff	inlinevirtual

~PayOffBarrier()	PayOffBarrier	inlinevirtual

<address class="footer">
Generated by

 1.8.12
</address>


text:
"""
    ORCID Member

    No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)  # noqa: E501

    OpenAPI spec version: Latest

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

import pprint
import re  # noqa: F401

import six
from orcid_api_v3.models.bulk_element import BulkElement  # noqa: F401,E501

class WorkBulkV20(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """
    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'bulk': 'list[BulkElement]'
    }

    attribute_map = {
        'bulk': 'bulk'
    }

    def __init__(self, bulk=None):  # noqa: E501
        """WorkBulkV20 - a model defined in Swagger"""  # noqa: E501
        self._bulk = None
        self.discriminator = None
        if bulk is not None:
            self.bulk = bulk

    @property
    def bulk(self):
        """Gets the bulk of this WorkBulkV20.  # noqa: E501

        :return: The bulk of this WorkBulkV20.  # noqa: E501
        :rtype: list[BulkElement]
        """
        return self._bulk

    @bulk.setter
    def bulk(self, bulk):
        """Sets the bulk of this WorkBulkV20.

        :param bulk: The bulk of this WorkBulkV20.  # noqa: E501
        :type: list[BulkElement]
        """

        self._bulk = bulk

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value
        if issubclass(WorkBulkV20, dict):
            for key, value in self.items():
                result[key] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, WorkBulkV20):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


text:
class ResultsController < ApplicationController
  before_filter :authenticate_user!

  def finish
    # final results
    if !current_user.current_result
      #error
      flash[:warning] = "Please upload files to run."
    elsif
      if !current_user.current_result.mass_params_id || !current_user.current_result.mass_data_id
        #error
        flash[:warning] = "Please upload files to run."
      else
        #start ssh session in background
        current_user.current_result.delay.start_ssh
        flash[:notice] = "Tag finder is successfully running. You will be able to download the results from the uploads page when your analysis is complete."
        current_user.current_result.set_as_run
      end
    end
    redirect_to finish_index_path
  end

  def index

  end

  def review
   # "review and run"
   current_result = current_user.current_result
   @message = "Please upload files before running."
   if !current_result
     flash[:warning] = "No files have been uploaded."
     @disabled = true
   elsif !current_result.mass_params_id
       flash[:warning] = "One of the files has not been uploaded."
       @message = "Please select a parameters file."
       @disabled = true
   elsif !current_result.mass_data_id
       flash[:warning] = "One of the files has not been uploaded."
       @message = "Please select a data .mzXML file."
       @disabled = true
   else
       @message = "Data: #{current_result.get_mass_data.get_title}\n\n Parameters: #{current_result.get_mass_params.get_title}"
   end
  end
end


text:
"use strict";

// const createError = require("./parser-create-error");

function parse(text /*, parsers, opts*/) {
  // Inline the require to avoid loading all the JS if we don't use it
  const parse5 = require("parse5");
  try {
    const isFragment = !/^\s*<(!doctype|html|head|body)/i.test(text);
    const ast = (isFragment ? parse5.parseFragment : parse5.parse)(text, {
      treeAdapter: parse5.treeAdapters.htmlparser2,
      locationInfo: true
    });
    return extendAst(ast);
  } catch (error) {
    //   throw createError(error.message, {
    //     start: {
    //       line: error.locations[0].line,
    //       column: error.locations[0].column
    //     }
    // } else {
    throw error;
    // }
  }
}

function extendAst(ast) {
  if (!ast || !ast.children) {
    return ast;
  }
  for (const child of ast.children) {
    extendAst(child);
    if (child.attribs) {
      child.attributes = convertAttribs(child.attribs);
    }
  }
  return ast;
}

function convertAttribs(attribs) {
  return Object.keys(attribs).map(attributeKey => {
    return {
      type: "attribute",
      key: attributeKey,
      value: attribs[attributeKey]
    };
  });
}

module.exports = parse;


text:
package org.sakaiproject.pasystem.api;

import java.io.InputStream;
import lombok.Data;

/**
 * A source of template character data.
 */
@Data
public class TemplateStream {
    private final InputStream inputStream;
    private final long length;
}


text:
/*! Buefy v0.9.20 | MIT License | github.com/buefy/buefy */
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (global = global || self, factory(global.Menu = {}));
}(this, function (exports) { 'use strict';

    //
    //
    //
    //
    //
    //
    var script = {
      name: 'BMenu',
      props: {
        accordion: {
          type: Boolean,
          default: true
        },
        activable: {
          type: Boolean,
          default: true
        }
      },
      data: function data() {
        return {
          _isMenu: true // Used by MenuItem

        };
      }
    };

    function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier
    /* server only */
    , shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
      if (typeof shadowMode !== 'boolean') {
        createInjectorSSR = createInjector;
        createInjector = shadowMode;
        shadowMode = false;
      } // Vue.extend constructor export interop.

      var options = typeof script === 'function' ? script.options : script; // render functions

      if (template && template.render) {
        options.render = template.render;
        options.staticRenderFns = template.staticRenderFns;
        options._compiled = true; // functional template

        if (isFunctionalTemplate) {
          options.functional = true;
        }
      } // scopedId

      if (scopeId) {
        options._scopeId = scopeId;
      }

      var hook;

      if (moduleIdentifier) {
        // server build
        hook = function hook(context) {
          // 2.3 injection
          context = context || // cached call
          this.$vnode && this.$vnode.ssrContext || // stateful
          this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext; // functional
          // 2.2 with runInNewContext: true

          if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
            context = __VUE_SSR_CONTEXT__;
          } // inject component styles

          if (style) {
            style.call(this, createInjectorSSR(context));
          } // register component module identifier for async chunk inference

          if (context && context._registeredComponents) {
            context._registeredComponents.add(moduleIdentifier);
          }
        }; // used by ssr in case component is cached and beforeCreate
        // never gets called

        options._ssrRegister = hook;
      } else if (style) {
        hook = shadowMode ? function () {
          style.call(this, createInjectorShadow(this.$root.$options.shadowRoot));
        } : function (context) {
          style.call(this, createInjector(context));
        };
      }

      if (hook) {
        if (options.functional) {
          // register for functional component in vue file
          var originalRender = options.render;

          options.render = function renderWithStyleInjection(h, context) {
            hook.call(context);
            return originalRender(h, context);
          };
        } else {
          // inject component registration as beforeCreate hook
          var existing = options.beforeCreate;
          options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
        }
      }

      return script;
    }

    var normalizeComponent_1 = normalizeComponent;

    /* script */
    const __vue_script__ = script;

    /* template */
    var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"menu"},[_vm._t("default")],2)};
    var __vue_staticRenderFns__ = [];

      /* style */
      const __vue_inject_styles__ = undefined;
      /* scoped */
      const __vue_scope_id__ = undefined;
      /* module identifier */
      const __vue_module_identifier__ = undefined;
      /* functional template */
      const __vue_is_functional_template__ = false;
      /* style inject */

      /* style inject SSR */

      var Menu = normalizeComponent_1(
        { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
        __vue_inject_styles__,
        __vue_script__,
        __vue_scope_id__,
        __vue_is_functional_template__,
        __vue_module_identifier__,
        undefined,
        undefined
      );

    var script$1 = {
      name: 'BMenuList',
      functional: true,
      props: {
        label: String,
        icon: String,
        iconPack: String,
        ariaRole: {
          type: String,
          default: ''
        },
        size: {
          type: String,
          default: 'is-small'
        }
      },
      render: function render(createElement, context) {
        var vlabel = null;
        var slots = context.slots();

        if (context.props.label || slots.label) {
          vlabel = createElement('p', {
            attrs: {
              'class': 'menu-label'
            }
          }, context.props.label ? context.props.icon ? [createElement('b-icon', {
            props: {
              'icon': context.props.icon,
              'pack': context.props.iconPack,
              'size': context.props.size
            }
          }), createElement('span', {}, context.props.label)] : context.props.label : slots.label);
        }

        var vnode = createElement('ul', {
          attrs: {
            'class': 'menu-list',
            'role': context.props.ariaRole === 'menu' ? context.props.ariaRole : null
          }
        }, slots.default);
        return vlabel ? [vlabel, vnode] : vnode;
      }
    };

    /* script */
    const __vue_script__$1 = script$1;

    /* template */

      /* style */
      const __vue_inject_styles__$1 = undefined;
      /* scoped */
      const __vue_scope_id__$1 = undefined;
      /* module identifier */
      const __vue_module_identifier__$1 = undefined;
      /* functional template */
      const __vue_is_functional_template__$1 = undefined;
      /* style inject */

      /* style inject SSR */

      var MenuList = normalizeComponent_1(
        {},
        __vue_inject_styles__$1,
        __vue_script__$1,
        __vue_scope_id__$1,
        __vue_is_functional_template__$1,
        __vue_module_identifier__$1,
        undefined,
        undefined
      );

    function _typeof(obj) {
      "@babel/helpers - typeof";

      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function (obj) {
          return typeof obj;
        };
      } else {
        _typeof = function (obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }

      return _typeof(obj);
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, {
          value: value,
          enumerable: true,
          configurable: true,
          writable: true
        });
      } else {
        obj[key] = value;
      }

      return obj;
    }

    function ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);

      if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });
        keys.push.apply(keys, symbols);
      }

      return keys;
    }

    function _objectSpread2(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};

        if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }

      return target;
    }

    function _toArray(arr) {
      return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
    }

    function _arrayWithHoles(arr) {
      if (Array.isArray(arr)) return arr;
    }

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    var config = {
      defaultContainerElement: null,
      defaultIconPack: 'mdi',
      defaultIconComponent: null,
      defaultIconPrev: 'chevron-left',
      defaultIconNext: 'chevron-right',
      defaultLocale: undefined,
      defaultDialogConfirmText: null,
      defaultDialogCancelText: null,
      defaultSnackbarDuration: 3500,
      defaultSnackbarPosition: null,
      defaultToastDuration: 2000,
      defaultToastPosition: null,
      defaultNotificationDuration: 2000,
      defaultNotificationPosition: null,
      defaultTooltipType: 'is-primary',
      defaultTooltipDelay: null,
      defaultSidebarDelay: null,
      defaultInputAutocomplete: 'on',
      defaultDateFormatter: null,
      defaultDateParser: null,
      defaultDateCreator: null,
      defaultTimeCreator: null,
      defaultDayNames: null,
      defaultMonthNames: null,
      defaultFirstDayOfWeek: null,
      defaultUnselectableDaysOfWeek: null,
      defaultTimeFormatter: null,
      defaultTimeParser: null,
      defaultModalCanCancel: ['escape', 'x', 'outside', 'button'],
      defaultModalScroll: null,
      defaultDatepickerMobileNative: true,
      defaultTimepickerMobileNative: true,
      defaultNoticeQueue: true,
      defaultInputHasCounter: true,
      defaultTaginputHasCounter: true,
      defaultUseHtml5Validation: true,
      defaultDropdownMobileModal: true,
      defaultFieldLabelPosition: null,
      defaultDatepickerYearsRange: [-100, 10],
      defaultDatepickerNearbyMonthDays: true,
      defaultDatepickerNearbySelectableMonthDays: false,
      defaultDatepickerShowWeekNumber: false,
      defaultDatepickerWeekNumberClickable: false,
      defaultDatepickerMobileModal: true,
      defaultTrapFocus: true,
      defaultAutoFocus: true,
      defaultButtonRounded: false,
      defaultSwitchRounded: true,
      defaultCarouselInterval: 3500,
      defaultTabsExpanded: false,
      defaultTabsAnimated: true,
      defaultTabsType: null,
      defaultStatusIcon: true,
      defaultProgrammaticPromise: false,
      defaultLinkTags: ['a', 'button', 'input', 'router-link', 'nuxt-link', 'n-link', 'RouterLink', 'NuxtLink', 'NLink'],
      defaultImageWebpFallback: null,
      defaultImageLazy: true,
      defaultImageResponsive: true,
      defaultImageRatio: null,
      defaultImageSrcsetFormatter: null,
      defaultBreadcrumbTag: 'a',
      defaultBreadcrumbAlign: 'is-left',
      defaultBreadcrumbSeparator: '',
      defaultBreadcrumbSize: 'is-medium',
      customIconPacks: null
    };

    /**
     * Merge function to replace Object.assign with deep merging possibility
     */

    var isObject = function isObject(item) {
      return _typeof(item) === 'object' && !Array.isArray(item);
    };

    var mergeFn = function mergeFn(target, source) {
      var deep = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

      if (deep || !Object.assign) {
        var isDeep = function isDeep(prop) {
          return isObject(source[prop]) && target !== null && target.hasOwnProperty(prop) && isObject(target[prop]);
        };

        var replaced = Object.getOwnPropertyNames(source).map(function (prop) {
          return _defineProperty({}, prop, isDeep(prop) ? mergeFn(target[prop], source[prop], deep) : source[prop]);
        }).reduce(function (a, b) {
          return _objectSpread2({}, a, {}, b);
        }, {});
        return _objectSpread2({}, target, {}, replaced);
      } else {
        return Object.assign(target, source);
      }
    };

    var merge = mergeFn;

    var mdiIcons = {
      sizes: {
        'default': 'mdi-24px',
        'is-small': null,
        'is-medium': 'mdi-36px',
        'is-large': 'mdi-48px'
      },
      iconPrefix: 'mdi-'
    };

    var faIcons = function faIcons() {
      var faIconPrefix = config && config.defaultIconComponent ? '' : 'fa-';
      return {
        sizes: {
          'default': null,
          'is-small': null,
          'is-medium': faIconPrefix + 'lg',
          'is-large': faIconPrefix + '2x'
        },
        iconPrefix: faIconPrefix,
        internalIcons: {
          'information': 'info-circle',
          'alert': 'exclamation-triangle',
          'alert-circle': 'exclamation-circle',
          'chevron-right': 'angle-right',
          'chevron-left': 'angle-left',
          'chevron-down': 'angle-down',
          'eye-off': 'eye-slash',
          'menu-down': 'caret-down',
          'menu-up': 'caret-up',
          'close-circle': 'times-circle'
        }
      };
    };

    var getIcons = function getIcons() {
      var icons = {
        mdi: mdiIcons,
        fa: faIcons(),
        fas: faIcons(),
        far: faIcons(),
        fad: faIcons(),
        fab: faIcons(),
        fal: faIcons(),
        'fa-solid': faIcons(),
        'fa-regular': faIcons(),
        'fa-light': faIcons(),
        'fa-thin': faIcons(),
        'fa-duotone': faIcons(),
        'fa-brands': faIcons()
      };

      if (config && config.customIconPacks) {
        icons = merge(icons, config.customIconPacks, true);
      }

      return icons;
    };

    var script$2 = {
      name: 'BIcon',
      props: {
        type: [String, Object],
        component: String,
        pack: String,
        icon: String,
        size: String,
        customSize: String,
        customClass: String,
        both: Boolean // This is used internally to show both MDI and FA icon

      },
      computed: {
        iconConfig: function iconConfig() {
          var allIcons = getIcons();
          return allIcons[this.newPack];
        },
        iconPrefix: function iconPrefix() {
          if (this.iconConfig && this.iconConfig.iconPrefix) {
            return this.iconConfig.iconPrefix;
          }

          return '';
        },

        /**
        * Internal icon name based on the pack.
        * If pack is 'fa', gets the equivalent FA icon name of the MDI,
        * internal icons are always MDI.
        */
        newIcon: function newIcon() {
          return "".concat(this.iconPrefix).concat(this.getEquivalentIconOf(this.icon));
        },
        newPack: function newPack() {
          return this.pack || config.defaultIconPack;
        },
        newType: function newType() {
          if (!this.type) return;
          var splitType = [];

          if (typeof this.type === 'string') {
            splitType = this.type.split('-');
          } else {
            for (var key in this.type) {
              if (this.type[key]) {
                splitType = key.split('-');
                break;
              }
            }
          }

          if (splitType.length <= 1) return;

          var _splitType = splitType,
              _splitType2 = _toArray(_splitType),
              type = _splitType2.slice(1);

          return "has-text-".concat(type.join('-'));
        },
        newCustomSize: function newCustomSize() {
          return this.customSize || this.customSizeByPack;
        },
        customSizeByPack: function customSizeByPack() {
          if (this.iconConfig && this.iconConfig.sizes) {
            if (this.size && this.iconConfig.sizes[this.size] !== undefined) {
              return this.iconConfig.sizes[this.size];
            } else if (this.iconConfig.sizes.default) {
              return this.iconConfig.sizes.default;
            }
          }

          return null;
        },
        useIconComponent: function useIconComponent() {
          return this.component || config.defaultIconComponent;
        }
      },
      methods: {
        /**
        * Equivalent icon name of the MDI.
        */
        getEquivalentIconOf: function getEquivalentIconOf(value) {
          // Only transform the class if the both prop is set to true
          if (!this.both) {
            return value;
          }

          if (this.iconConfig && this.iconConfig.internalIcons && this.iconConfig.internalIcons[value]) {
            return this.iconConfig.internalIcons[value];
          }

          return value;
        }
      }
    };

    /* script */
    const __vue_script__$2 = script$2;

    /* template */
    var __vue_render__$1 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('span',{staticClass:"icon",class:[_vm.newType, _vm.size]},[(!_vm.useIconComponent)?_c('i',{class:[_vm.newPack, _vm.newIcon, _vm.newCustomSize, _vm.customClass]}):_c(_vm.useIconComponent,{tag:"component",class:[_vm.customClass],attrs:{"icon":[_vm.newPack, _vm.newIcon],"size":_vm.newCustomSize}})],1)};
    var __vue_staticRenderFns__$1 = [];

      /* style */
      const __vue_inject_styles__$2 = undefined;
      /* scoped */
      const __vue_scope_id__$2 = undefined;
      /* module identifier */
      const __vue_module_identifier__$2 = undefined;
      /* functional template */
      const __vue_is_functional_template__$2 = false;
      /* style inject */

      /* style inject SSR */

      var Icon = normalizeComponent_1(
        { render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 },
        __vue_inject_styles__$2,
        __vue_script__$2,
        __vue_scope_id__$2,
        __vue_is_functional_template__$2,
        __vue_module_identifier__$2,
        undefined,
        undefined
      );

    var script$3 = {
      name: 'BMenuItem',
      components: _defineProperty({}, Icon.name, Icon),
      inheritAttrs: false,
      // deprecated, to replace with default 'value' in the next breaking change
      model: {
        prop: 'active',
        event: 'update:active'
      },
      props: {
        label: String,
        active: Boolean,
        expanded: Boolean,
        disabled: Boolean,
        iconPack: String,
        icon: String,
        animation: {
          type: String,
          default: 'slide'
        },
        tag: {
          type: String,
          default: 'a',
          validator: function validator(value) {
            return config.defaultLinkTags.indexOf(value) >= 0;
          }
        },
        ariaRole: {
          type: String,
          default: ''
        },
        size: {
          type: String,
          default: 'is-small'
        }
      },
      data: function data() {
        return {
          newActive: this.active,
          newExpanded: this.expanded
        };
      },
      computed: {
        ariaRoleMenu: function ariaRoleMenu() {
          return this.ariaRole === 'menuitem' ? this.ariaRole : null;
        }
      },
      watch: {
        active: function active(value) {
          this.newActive = value;
        },
        expanded: function expanded(value) {
          this.newExpanded = value;
        }
      },
      methods: {
        onClick: function onClick(event) {
          if (this.disabled) return;
          var menu = this.getMenu();
          this.reset(this.$parent, menu);
          this.newExpanded = this.$props.expanded || !this.newExpanded;
          this.$emit('update:expanded', this.newExpanded);

          if (menu && menu.activable) {
            this.newActive = true;
            this.$emit('update:active', this.newActive);
          }
        },
        reset: function reset(parent, menu) {
          var _this = this;

          var items = parent.$children.filter(function (c) {
            return c.name === _this.name;
          });
          items.forEach(function (item) {
            if (item !== _this) {
              _this.reset(item, menu);

              if (!parent.$data._isMenu || parent.$data._isMenu && parent.accordion) {
                item.newExpanded = false;
                item.$emit('update:expanded', item.newActive);
              }

              if (menu && menu.activable) {
                item.newActive = false;
                item.$emit('update:active', item.newActive);
              }
            }
          });
        },
        getMenu: function getMenu() {
          var parent = this.$parent;

          while (parent && !parent.$data._isMenu) {
            parent = parent.$parent;
          }

          return parent;
        }
      }
    };

    /* script */
    const __vue_script__$3 = script$3;

    /* template */
    var __vue_render__$2 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('li',{attrs:{"role":_vm.ariaRoleMenu}},[_c(_vm.tag,_vm._g(_vm._b({tag:"component",class:{
                'is-active': _vm.newActive,
                'is-expanded': _vm.newExpanded,
                'is-disabled': _vm.disabled,
                'icon-text': _vm.icon,
            },on:{"click":function($event){return _vm.onClick($event)}}},'component',_vm.$attrs,false),_vm.$listeners),[(_vm.icon)?_c('b-icon',{attrs:{"icon":_vm.icon,"pack":_vm.iconPack,"size":_vm.size}}):_vm._e(),(_vm.label)?_c('span',[_vm._v(" "+_vm._s(_vm.label)+" ")]):_vm._t("label",null,{"expanded":_vm.newExpanded,"active":_vm.newActive})],2),(_vm.$slots.default)?[_c('transition',{attrs:{"name":_vm.animation}},[_c('ul',{directives:[{name:"show",rawName:"v-show",value:(_vm.newExpanded),expression:"newExpanded"}]},[_vm._t("default")],2)])]:_vm._e()],2)};
    var __vue_staticRenderFns__$2 = [];

      /* style */
      const __vue_inject_styles__$3 = undefined;
      /* scoped */
      const __vue_scope_id__$3 = undefined;
      /* module identifier */
      const __vue_module_identifier__$3 = undefined;
      /* functional template */
      const __vue_is_functional_template__$3 = false;
      /* style inject */

      /* style inject SSR */

      var MenuItem = normalizeComponent_1(
        { render: __vue_render__$2, staticRenderFns: __vue_staticRenderFns__$2 },
        __vue_inject_styles__$3,
        __vue_script__$3,
        __vue_scope_id__$3,
        __vue_is_functional_template__$3,
        __vue_module_identifier__$3,
        undefined,
        undefined
      );

    var use = function use(plugin) {
      if (typeof window !== 'undefined' && window.Vue) {
        window.Vue.use(plugin);
      }
    };
    var registerComponent = function registerComponent(Vue, component) {
      Vue.component(component.name, component);
    };

    var Plugin = {
      install: function install(Vue) {
        registerComponent(Vue, Menu);
        registerComponent(Vue, MenuList);
        registerComponent(Vue, MenuItem);
      }
    };
    use(Plugin);

    exports.BMenu = Menu;
    exports.BMenuItem = MenuItem;
    exports.BMenuList = MenuList;
    exports.default = Plugin;

    Object.defineProperty(exports, '__esModule', { value: true });

}));


text:
package com.crawljax.web;

import javax.inject.Inject;

import java.io.File;
import java.io.IOException;

import com.crawljax.web.di.CrawljaxWebModule.OutputFolder;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingSocket extends WebSocketAdapter {

	private static final Logger LOG = LoggerFactory.getLogger(LoggingSocket.class);
	private final File outPutFolder;
	private SocketLogAppender appender;

	@Inject
	public LoggingSocket(@OutputFolder File outPutFolder) {
		this.outPutFolder = outPutFolder;
	}

	@Override
	public void onWebSocketConnect(Session session) {
		LOG.debug("Socket connected!");
		LogWebSocketServlet.sockets.add(this);
		super.onWebSocketConnect(session);
	}

	private void sendLogFile(String crawlId) {
		File log =
		        new File(outPutFolder, "crawl-records"
		                + File.separator + crawlId
		                + File.separator + "crawl.log");
		if (log.exists()) {
			try {
				LOG.debug("Reading the log file");
				String asString =
				        "log-
"
				                + Files.toString(log, Charsets.UTF_8).replace(
				                        System.getProperty("line.separator"), "

");
				asString = asString.substring(0, asString.length() - 4); // Remove last

				LOG.debug("Sending the log file");
				sendText(asString);
			} catch (IOException e) {
				LOG.warn("Could not read the log file");
			}
		}

	}

	@Override
	public void onWebSocketClose(int statusCode, String reason) {
		LOG.debug("Socket disconnected with status code {} reason: {}", statusCode, reason);
		LogWebSocketServlet.sockets.remove(this);
		if (appender != null) {
			appender.stop();
		}
	}

	@Override
	public void onWebSocketText(String message) {
		LOG.debug("Received text: {}", message);

		if (message.startsWith("startlog")) {
			String crawlId = message.split("-")[1];
			sendLogFile(crawlId);
			appender = new SocketLogAppender(this, crawlId);
		}
		if (message.startsWith("stoplog")) {
			if (appender != null)
				appender.stop();
		}
	}

	public void sendText(String text) {
		try {
			getSession().getRemote().sendString(text);
		} catch (IOException e) {
			LOG.error("Could not send message {}", text, e);
		}
	}
}


text:
namespace _11.ExtractPricesForAllAlbums5YearsAgo
{
    using System;
    using System.Xml;

    internal class Program
    {
        private const string PathToXml = "../../Catalog.xml";

        private static void Main()
        {
            // 11. Write a program, which extract from the file catalog.xml the prices for all albums, published 5 years ago or earlier.
            // Use XPath query.

            XmlDocument doc = new XmlDocument();
            doc.Load(PathToXml);
            XmlNode rootNode = doc.DocumentElement;
            string xPathYearQuery = "/albums/album[year<2010]/price";
            XmlNodeList albumPrices = rootNode.SelectNodes(xPathYearQuery);

            foreach (XmlNode currentAlbumPrice in albumPrices)
            {
                Console.WriteLine("Price: {0}", currentAlbumPrice.InnerText);
            }
        }
    }
}


text:
require 'csv'

class Account < ActiveRecord::Base
  attr_encrypted :url, :password, :comments,
    :key => Proc.new { |x| APP_CONFIG['master_key'] }
  has_and_belongs_to_many :labels
  has_many :assets, :as => :attachable, :dependent => :destroy
  has_many :logs, as: :commentable, class_name: "Comment"

  validates :name, :presence => true, :uniqueness => true,
    :format => { :with => /\A[A-Za-z0-9\s_-]+/ }
  validates :username, :presence => true
  validates :url, :presence => true,
    :format => {:with => /\Ahttps?:\/\/.*\z/}
  validates :password, :presence => true, :confirmation => true

  validate :validate_attachments
  has_paper_trail

  attr_protected :assets
  attr_accessible :name, :url, :username, :comments, :password, :versions, :updated_at
  attr_accessible :id, :encrypted_url, :encrypted_comments,
      :encrypted_password, :created_at, :label_ids, :password_confirmation
  Max_Attachments = 50
  Max_Attachment_Size = 5.megabyte

  def validate_attachments
    errors[:base] << "Too many attachments - maximum is #{Max_Attachments}" \
      if assets.length > Max_Attachments
    assets.each {|a|
      errors[:base] << "#{a.name} is over #{Max_Attachment_Size/1.megabyte}MB" \
        if a.file_size > Max_Attachment_Size
    }
  end

  before_save { |a| a.name = a.name.upcase }
  cattr_reader :per_page
  @@per_page = 10

  # This function searches the accounts and returns a
  # paginated list ordered by +order_by+ parameter
  # ==== Parameters
  #
  # * <tt>:filter</tt> - Search expression
  # * <tt>:page</tt> - Page number used for paginate function
  # * <tt>:order_by</tt> - Ordering expression used for paginate function
  #
  def self.search(filter, page, order_by, no_page=nil)
    if filter
      begin
        if no_page.nil?
          where('name like ? or username like ?',
                    "%#{filter.upcase}%", "%#{filter}%").
            order(order_by).page(page)
        else
          where('name like ? or username like ?',
                "%#{filter.upcase}%", "%#{filter}%")
        end
      rescue ActiveRecord::RecordNotFound
        []
      end
    else
      order_by = 'updated_at desc' if order_by == ' '
      Account.order(order_by).page(page)
    end
  end

  #
  # Returns tab separated string for accounts suitable for csv/excel export
  #
  def self.to_csv(accounts)
    klass = 'CSV'
    if RUBY_VERSION < "1.9"
      klass = 'FasterCSV'
    end
    tsv_str = Object::const_get(klass).generate(:col_sep => "\t") do |tsv|
      tsv << ["Name", "URL", "User Name", "Password", "Comments"]
      accounts.each do |a|
        tsv << [
          a.name,
          a.url,
          a.username,
          a.password,
          a.comments
        ]
      end
    end
    tsv_str
  end

  # Creates a spreadsheet object using spreadsheet gem and returns #StringIO object
  # correspoding to it that can be directly used with send_data
  #
  # ==== Parameters
  # <tt>:account</tt> - Array of account objects to be exported
  #
  def self.to_xls(accounts)
    str_data = StringIO.new ''
    book = Spreadsheet::Workbook.new
    book.default_format = Spreadsheet::Format.new :text_wrap => false
    header_format = Spreadsheet::Format.new :weight => :bold
    sheet1 = book.create_worksheet
    sheet1.name = 'Accounting Worksheet'
    sheet1.row(0).default_format = header_format
    sheet1.row(0).push "Name", "URL", "User Name", "Password", "Comments"
    rnum = 1
    accounts.each do |a|
      sheet1.row(rnum).push(a.name, a.url, a.username, a.password, a.comments)
      rnum += 1
    end
    book.write str_data
    str_data.string.bytes.to_a.pack("C*")
  end
end


text:
<?php

namespace BiberLtd\Bundle\BlogBundle\Entity;
use Doctrine\ORM\Mapping AS ORM;
use BiberLtd\Bundle\CoreBundle\CoreEntity;

/**
 * @ORM\Entity
 * @ORM\Table(
 *     name="featured_blog_post",
 *     options={"charset":"utf8","collate":"utf8_turkish_ci","engine":"innodb"},
 *     indexes={
 *         @ORM\Index(name="idx_n_featured_blog_post_date_added", columns={"date_added"}),
 *         @ORM\Index(name="idx_n_featured_blog_post_date_published", columns={"date_published"}),
 *         @ORM\Index(name="idx_n_featured_blog_post_unpublished", columns={"date_unpublished"})
 *     },
 *     uniqueConstraints={@ORM\UniqueConstraint(name="idx_u_featured_blog_post_id", columns={"id"})}
 * )
 */
class FeaturedBlogPost extends CoreEntity
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", length=10)
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="datetime", nullable=false)
     */
    public $date_added;

    /**
     * @ORM\Column(type="datetime", nullable=false)
     */
    private $date_published;

    /**
     * @ORM\Column(type="datetime", nullable=false)
     */
    private $date_unpublished;

    /**
     * @ORM\Column(type="integer", length=10, nullable=false)
     */
    private $sort_order;

    /**
     * @ORM\OneToMany(
     *     targetEntity="BiberLtd\Bundle\BlogBundle\Entity\FeaturedBlogPostLocalization",
     *     mappedBy="featured_blog_post"
     * )
     */
    protected $localizations;

    /**
     * @ORM\ManyToOne(targetEntity="BiberLtd\Bundle\BlogBundle\Entity\BlogPost")
     * @ORM\JoinColumn(name="post", referencedColumnName="id", nullable=false, onDelete="CASCADE")
     */
    private $blog_post;
    /******************************************************************
     * PUBLIC SET AND GET FUNCTIONS                                   *
     ******************************************************************/

    /**
     * @name            getId()
     *                  Gets $id property.
     * .
     * @author          Murat Ünal
     * @since           1.0.0
     * @version         1.0.0
     *
     * @return          integer          $this->id
     */
    public function getId(){
        return $this->id;
    }

    /**
     * @name                  setBlogPost ()
     *                                    Sets the blog_post property.
     *                                    Updates the data only if stored value and value to be set are different.
     *
     * @author          Can Berkol
     *
     * @since           1.0.0
     * @version         1.0.0
     *
     * @use             $this->setModified()
     *
     * @param           mixed $blog_post
     *
     * @return          object                $this
     */
    public function setBlogPost($blog_post) {
        if(!$this->setModified('blog_post', $blog_post)->isModified()) {
            return $this;
        }
		$this->blog_post = $blog_post;
		return $this;
    }

    /**
     * @name            getBlogPost ()
     *                              Returns the value of blog_post property.
     *
     * @author          Can Berkol
     *
     * @since           1.0.0
     * @version         1.0.0
     *
     * @return          mixed           $this->blog_post
     */
    public function getBlogPost() {
        return $this->blog_post;
    }

    /**
     * @name                  setDatePublished ()
     *                                         Sets the date_published property.
     *                                         Updates the data only if stored value and value to be set are different.
     *
     * @author          Can Berkol
     *
     * @since           1.0.0
     * @version         1.0.0
     *
     * @use             $this->setModified()
     *
     * @param           mixed $date_published
     *
     * @return          object                $this
     */
    public function setDatePublished($date_published) {
        if(!$this->setModified('date_published', $date_published)->isModified()) {
            return $this;
        }
		$this->date_published = $date_published;
		return $this;
    }

    /**
     * @name            getDatePublished ()
     *                                   Returns the value of date_published property.
     *
     * @author          Can Berkol
     *
     * @since           1.0.0
     * @version         1.0.0
     *
     * @return          mixed           $this->date_published
     */
    public function getDatePublished() {
        return $this->date_published;
    }

    /**
     * @name                  setDateUnpublished ()
     *                                           Sets the date_unpublished property.
     *                                           Updates the data only if stored value and value to be set are different.
     *
     * @author          Can Berkol
     *
     * @since           1.0.0
     * @version         1.0.0
     *
     * @use             $this->setModified()
     *
     * @param           mixed $date_unpublished
     *
     * @return          object                $this
     */
    public function setDateUnpublished($date_unpublished) {
        if(!$this->setModified('date_unpublished', $date_unpublished)->isModified()) {
            return $this;
        }
		$this->date_unpublished = $date_unpublished;
		return $this;
    }

    /**
     * @name            getDateUnpublished ()
     *                                     Returns the value of date_unpublished property.
     *
     * @author          Can Berkol
     *
     * @since           1.0.0
     * @version         1.0.0
     *
     * @return          mixed           $this->date_unpublished
     */
    public function getDateUnpublished() {
        return $this->date_unpublished;
    }

    /**
     * @name                  setSortOrder ()
     *                                     Sets the sort_order property.
     *                                     Updates the data only if stored value and value to be set are different.
     *
     * @author          Can Berkol
     *
     * @since           1.0.0
     * @version         1.0.0
     *
     * @use             $this->setModified()
     *
     * @param           mixed $sort_order
     *
     * @return          object                $this
     */
    public function setSortOrder($sort_order) {
        if(!$this->setModified('sort_order', $sort_order)->isModified()) {
            return $this;
        }
		$this->sort_order = $sort_order;
		return $this;
    }

    /**
     * @name            getSortOrder ()
     *                               Returns the value of sort_order property.
     *
     * @author          Can Berkol
     *
     * @since           1.0.0
     * @version         1.0.0
     *
     * @return          mixed           $this->sort_order
     */
    public function getSortOrder() {
        return $this->sort_order;
    }
}
/**
 * Change Log:
 * **************************************
 * v1.0.1                      Murat Ünal
 * 10.10.2013
 * **************************************
 * A getBlogPost()
 * A getDateAdded()
 * A getDatePublished()
 * A getDateUnpublished()
 * A getId()
 * A getLocalizations()
 * A getSortOrder()
 *
 * A setBlogPost()
 * A setDateAdded()
 * A setDatePublished()
 * A setDateUnpublished()
 * A setLocalizations()
 * A setSortOrder()
 *
 */


text: <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />


text:
<?php

namespace Drupal\Tests\node\Functional\Views;

use Drupal\node\Entity\NodeType;

/**
 * Tests the node_access filter handler.
 *
 * @group node
 * @see \Drupal\node\Plugin\views\filter\Access
 */
class FilterNodeAccessTest extends NodeTestBase {

  /**
   * An array of users.
   *
   * @var \Drupal\user\Entity\User[]
   */
  protected $users;

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['node_access_test'];

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = ['test_filter_node_access'];

  /**
   * {@inheritdoc}
   */
  protected function setUp($import_test_views = TRUE, $modules = ['node_test_views']): void {
    parent::setUp($import_test_views, $modules);

    $this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);

    node_access_test_add_field(NodeType::load('article'));

    node_access_rebuild();
    \Drupal::state()->set('node_access_test.private', TRUE);

    $num_simple_users = 2;
    $this->users = [];

    for ($i = 0; $i < $num_simple_users; $i++) {
      $this->users[$i] = $this->drupalCreateUser([
        'access content',
        'create article content',
      ]);
    }
    foreach ($this->users as $web_user) {
      $this->drupalLogin($web_user);
      foreach ([0 => 'Public', 1 => 'Private'] as $is_private => $type) {
        $settings = [
          'body' => [
            [
              'value' => $type . ' node',
              'format' => filter_default_format(),
            ],
          ],
          'title' => "$type Article created by " . $web_user->getAccountName(),
          'type' => 'article',
          'uid' => $web_user->id(),
          'private' => (bool) $is_private,
        ];

        $node = $this->drupalCreateNode($settings);
        $this->assertEquals($is_private, (int) $node->private->value, 'The private status of the node was properly set in the node_access_test table.');
      }
    }
  }

  /**
   * Tests the node access filter.
   */
  public function testFilterNodeAccess() {
    $this->drupalLogin($this->users[0]);
    $this->drupalGet('test_filter_node_access');
    // Test that the private node of the current user is shown.
    $this->assertSession()->pageTextContains('Private Article created by ' . $this->users[0]->getAccountName());
    // Test that the private node of the other use isn't shown.
    $this->assertSession()->pageTextNotContains('Private Article created by ' . $this->users[1]->getAccountName());
    // Test that both public nodes are shown.
    $this->assertSession()->pageTextContains('Public Article created by ' . $this->users[0]->getAccountName());
    $this->assertSession()->pageTextContains('Public Article created by ' . $this->users[1]->getAccountName());

    // Switch users and test the other private node is shown.
    $this->drupalLogin($this->users[1]);
    $this->drupalGet('test_filter_node_access');
    // Test that the private node of the current user is shown.
    $this->assertSession()->pageTextContains('Private Article created by ' . $this->users[1]->getAccountName());
    // Test that the private node of the other use isn't shown.
    $this->assertSession()->pageTextNotContains('Private Article created by ' . $this->users[0]->getAccountName());

    // Test that a user with administer nodes permission can't see all nodes.
    $administer_nodes_user = $this->drupalCreateUser([
      'access content',
      'administer nodes',
    ]);
    $this->drupalLogin($administer_nodes_user);
    $this->drupalGet('test_filter_node_access');
    $this->assertSession()->pageTextNotContains('Private Article created by ' . $this->users[0]->getAccountName());
    $this->assertSession()->pageTextNotContains('Private Article created by ' . $this->users[1]->getAccountName());
    $this->assertSession()->pageTextContains('Public Article created by ' . $this->users[0]->getAccountName());
    $this->assertSession()->pageTextContains('Public Article created by ' . $this->users[1]->getAccountName());

    // Test that a user with bypass node access can see all nodes.
    $bypass_access_user = $this->drupalCreateUser([
      'access content',
      'bypass node access',
    ]);
    $this->drupalLogin($bypass_access_user);
    $this->drupalGet('test_filter_node_access');
    $this->assertSession()->pageTextContains('Private Article created by ' . $this->users[0]->getAccountName());
    $this->assertSession()->pageTextContains('Private Article created by ' . $this->users[1]->getAccountName());
    $this->assertSession()->pageTextContains('Public Article created by ' . $this->users[0]->getAccountName());
    $this->assertSession()->pageTextContains('Public Article created by ' . $this->users[1]->getAccountName());
  }

}


text:
const common = require('../common.js');
const {expect} = require('chai');

describe('common.js', function() {
  it('test merge source to target', function() {
    let target = {name: 'jim', age: 12};
    let source = {name: 'jhon', address: 'China'};
    let result = common.merge(target, source);
    expect(target).to.be.deep.equal({ name: 'jhon', age: 12, address: 'China' })
  });
  it('test isType function', function() {
    let str = 'this is string';
    let bool = true;
    let obj = {};
    let arr = [];
    let date = new Date();
    let promise = new Promise(() => {});
    let reg = /this is reg/g;
    let fun = () => {};
    expect(common.isType(str, 'String')).to.be.ok;
    expect(common.isType(bool, 'Boolean')).to.be.ok;
    expect(common.isType(obj, 'Object')).to.be.ok;
    expect(common.isType(arr, 'Array')).to.be.ok;
    expect(common.isType(date, 'Date')).to.be.ok;
    expect(common.isType(promise, 'Promise')).to.be.ok;
    expect(common.isType(reg, 'RegExp')).to.be.ok;
    expect(common.isType(fun, 'Function')).to.be.ok;
    expect(common.isType(str, 'String')).to.be.ok;
  });
  it('test mergeStyle function', function() {
    let cssString = 'background-color:red; width:100px; ';
    let cssObj1 = {height: '200px;', 'font-size': '30px'};
    let cssObj2 = {color: 'red'};
    let mergeResult = common.mergeStyle(cssString, cssObj1, cssObj2);
    expect(mergeResult).to.be.equal(`background-color:red;width:100px;height:200px;;font-size:30px;color:red;`);
  });
  it('judge if the arguments is reactive', function() {
    expect(common.isReactive(`'index'`)).to.be.an('array')
  });
  it('test trim function', function() {
    expect(common.trim('  name   ')).to.be.equal('name');
  })

})


text:
#include <iostream>
#include <thread>         // std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

#include <cassert>

#include <system/libbcm2835.h>

#include "comm/spi/serialperipheralinterface.h"

namespace PiFly {
	namespace Comm {
		namespace SPI {
			using System::Libbcm2835;

			SerialPeripheralInterface::SerialPeripheralInterface() :
				mUsedChipSelects{false}
			{
				// TODO: Check for successful init, maybe throw if failed

				Libbcm2835::Init();

				auto ret = bcm2835_spi_begin();
				if(ret != 1) {
					std::cout << "Failed to begin spi operation" << std::endl;
				}
			}

			SerialPeripheralInterface::~SerialPeripheralInterface() {
				bcm2835_spi_end();
				Libbcm2835::Close();
			}

			ChannelPtr SerialPeripheralInterface::getChannel(ChipSelect cs, Mode mode, BitOrder bitOrder, ClockDivider clockDivider, ChipSelectPolarity polarity) {
				if(cs < ChipSelect_None) {
					if(mUsedChipSelects[cs]) {
						return ChannelPtr(nullptr);
					}
					mUsedChipSelects[cs] = true;
				} else if(cs > ChipSelect_None) {
					return ChannelPtr(nullptr);
				}

				return ChannelPtr(
					new Channel(cs, mode, bitOrder, clockDivider, polarity, *this)
				);
			}

			void SerialPeripheralInterface::freeAssociatedChannel(ChipSelect cs) {
				// Silence clang-tidy warning about code we have no control over
				assert(cs < ChipSelect_None); // NOLINT(cppcoreguidelines-pro-bounds-array-to-pointer-decay, cppcoreguidelines-pro-bounds-constant-array-index)
				mUsedChipSelects[cs] = false;
			}
		}
	}
}


text:
DROP TABLE IF EXISTS `sequence`;

CREATE TABLE `sequence`
(
    `next` int NOT NULL
) ENGINE = InnoDB;

INSERT INTO `sequence`
VALUES (1);


text:
<?php

namespace Cartong\MSFBundle\Security;

//use Guzzle\Http\Client;
use Cartong\MSFBundle\Geonetwork\Client;

use Guzzle\Parser\Cookie\CookieParser;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\SimpleFormAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class GeonetworkAuthenticator implements SimpleFormAuthenticatorInterface
{
    private $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        // Login
        $username = $token->getUsername();
        $password = $token->getCredentials();
        $payload = ['username'=>$username, 'password'=>$password];
        $response = $this->client->post('j_spring_security_check', $payload);

        if ($response->getStatusCode()===302)
        {
            $location = (string)$response->getHeader('Location');
            if (strpos($location, 'failure=true')===false)
            {
                $parser = new CookieParser();
                $cookie = $parser->parseCookie($response->getSetCookie(), null, null, true);
                $jsessionID = $cookie['cookies']['JSESSIONID'];

                // Query groups from Geonetwork and convert to roles.
                $response = $this->client->get('srv/eng/xml.info?type=groups', $jsessionID);
                if ($response->getStatusCode()===200)
                {
                    $crawler = new Crawler((string)$response->getBody());
                    $groupsQuery = $crawler->filterXPath('//group/name');
                    $roles = ['ROLE_USER'];
                    foreach ($groupsQuery as $group)
                    {
                        $groupName = $group->textContent;
                        if ($groupName==='msfadmin')
                        {
                            $roles []= 'ROLE_ADMIN';
                        }
                    }

                    $user = new User($token->getUsername(), $token->getCredentials(), $jsessionID, $roles);
                    return new UsernamePasswordToken(
                        $user,
                        $user->getPassword(),
                        $providerKey,
                        $user->getRoles()
                    );
                }
            }
        }

        throw new AuthenticationException('Invalid username or password');
    }

    public function supportsToken(TokenInterface $token, $providerKey)
    {
        return $token instanceof UsernamePasswordToken
        && $token->getProviderKey() === $providerKey;
    }

    public function createToken(Request $request, $username, $password, $providerKey)
    {
        return new UsernamePasswordToken($username, $password, $providerKey);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmugMugModel
{
    // Indicates the program used by the camera to set exposure when the picture is taken
    public enum ExposureProgramEnum
    {
        NotDefined = 0,
        Manual = 1,
        NormalProgram = 2,
        AperturePriority = 3,
        ShutterPriority = 4,
        CreativeProgram = 5,
        ActionProgram = 6,
        PortraitMode = 7,
        LandscapeMode = 8,
    };
}


text:
import DS from 'ember-data';

export default DS.Model.extend({
  plyNumber: DS.attr('number'),
  commonName: DS.attr('string'),
  patterns: DS.hasMany('pattern')
});


text:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\captcha\Captcha;

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\models\ContactForm */

$this->title = 'Обратная связь';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php if (Yii::$app->session->hasFlash('contactFormSubmitted')): ?>

        Благодарим вас за обращение.

    <?php else: ?>

            <?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
                <?= $form->field($model, 'name')->label('Ваше имя') ?>
                <?= $form->field($model, 'email')->label('Email') ?>
                <?= $form->field($model, 'subject')->label('Тема') ?>
                <?= $form->field($model, 'body')->textArea(['rows' => 6])->label('Сообщение') ?>
                <?= $form->field($model, 'verifyCode')->hint('Введите код указанный на картинке')->widget(Captcha::className(), [
                    'template' => '

{image}

{input}

',
                ]) ?>

                    <?= Html::submitButton('Отправить', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>

            <?php ActiveForm::end(); ?>

    <?php endif; ?>