text:
'use strict';

import '../Sdk/dist/strophe-1.2.8.js'
import websdk from '../Sdk'
import xmldom from 'xmldom'
import config from './WebIMConfig'
// for rest api -> http
import Api from '../Services/Api'

// init DOMParser / document for strophe and sdk
// window.WebIM.config.isDebug = true
console = console || {};
console.group = console.group || function () {
    };
console.groupEnd = console.groupEnd || function () {
    };

let WebIM = window.WebIM = websdk;
window.WebIM.config = config;
window.DOMParser = xmldom.DOMParser;
let document = window.document = new DOMParser().parseFromString("<?xml version='1.0'?>\n", 'text/xml');

if (WebIM.config.isDebug) {
    function ts() {
        var d = new Date();
        var Hours = d.getHours();       // current hour (0-23)
        var Minutes = d.getMinutes();   // current min (0-59)
        var Seconds = d.getSeconds();   // current sec (0-59)
        return (Hours < 10 ? '0' + Hours : Hours) + ':' + (Minutes < 10 ? '0' + Minutes : Minutes) + ':' + (Seconds < 10 ? '0' + Seconds : Seconds) + ' '
    }

    window.Strophe.log = function (level, msg) {
        try {
            // console.group('%crecv # ' + ts(), 'color: blue; font-size: large')
            console.log('%c ' + ts() + ' recv: ' + msg, 'color: green');
            // console.groupEnd()
        } catch (e) {
        }
    };

    window.Strophe.Connection.prototype.rawOutput = function (data) {
        try {
            // console.group('%csend # ' + ts(), 'color: blue; font-size: large')
            console.log('%c ' + ts() + ' send: ' + data, 'color: blue');
            // console.groupEnd()
        } catch (e) {
        }
    }
}

/**
 * Set autoSignIn as true (autoSignInName and autoSignInPwd are configured below),
 * You can auto signed in each time when you refresh the page in dev model.
 */
WebIM.config.autoSignIn = false;
if (WebIM.config.autoSignIn) {
    WebIM.config.autoSignInName = 'username123';
    WebIM.config.autoSignInPwd = 'password123';
}

// var stropheConn = new window.Strophe.Connection("ws://im-api.hyphenate.io/ws/", {
//                 inactivity: 30,
//                 maxRetries: 5,
//                 pollingTime: 4500
//             });
//
// stropheConn.connect(
//   'hyphenatedemo#chatdemoui_liuwz@hyphenate.io',
//   '$t$' + 'YWMtmbQEBKKIEeaGmMtXyg5n1wAAAVlkQvGO2WOJGlMCEJKM4VV9GCMnb_XLCXU',
//   function() {
//     console.log(arguments, 'ggogogo');
//   }, stropheConn.wait, stropheConn.hold);

WebIM.conn = new WebIM.connection({
    isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
    https: WebIM.config.https,
    url: WebIM.config.xmppURL,
    isAutoLogin: false,
    heartBeatWait: WebIM.config.heartBeatWait,
    autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
    autoReconnectInterval: WebIM.config.autoReconnectInterval
});

// https://api.hyphenate.io/hyphenatedemo/chatdemoui/users
let appKeyPair = WebIM.config.appkey.split('#');
export let api = Api.create(`${WebIM.config.apiURL}/${appKeyPair[0]}/${appKeyPair[1]}`);

WebIM.api = api;

export default WebIM


text:
// Copyright 2007-2008 The Apache Software Foundation.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace DistributedGrid.Worker
{
	using System;
	using System.Configuration;
	using System.IO;
	using log4net.Config;
	using MassTransit.Grid.Sagas;
	using MassTransit.Saga;
	using StructureMap;
	using StructureMap.Attributes;

	internal class Program
	{
		private static void Main(string[] args)
		{
			XmlConfigurator.ConfigureAndWatch(new FileInfo(@"log4net.config"));

			var service = new WorkerServiceProvider
				{
					ServiceName = ConfigurationManager.AppSettings["ServiceName"],
					DisplayName = ConfigurationManager.AppSettings["DisplayName"],
					Description = ConfigurationManager.AppSettings["Description"],
					SourceQueue = ConfigurationManager.AppSettings["SourceQueue"],
					SubscriptionQueue = ConfigurationManager.AppSettings["SubscriptionQueue"],
					ContainerSetup = x =>
						{
							AddSagaRepositoryForType<Node>(x);
							AddSagaRepositoryForType<ServiceType>(x);
							AddSagaRepositoryForType<ServiceMessage>(x);
							AddSagaRepositoryForType<ServiceNode>(x);
						}
				};

			service.ConfigureService<DoWork>(args);
		}

		protected static void AddSagaRepositoryForType<T>(ConfigurationExpression x) where T : class, ISaga
		{
			x.ForRequestedType<ISagaRepository<T>>()
				.CacheBy(InstanceScope.Singleton)
				.TheDefaultIsConcreteType<InMemorySagaRepository<T>>();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
from pymarkdownlint.tests.base import BaseTestCase

from pymarkdownlint.lint import MarkdownLinter
from pymarkdownlint.rules import RuleViolation
from pymarkdownlint.config import LintConfig

class RuleOptionTests(BaseTestCase):
    def test_lint(self):
        linter = MarkdownLinter(LintConfig())
        sample = self.get_sample_path("sample1.md")
        with open(sample) as f:
            errors = linter.lint(f.read())
            expected_errors = [RuleViolation("R1", "Line exceeds max length (119>80)", 3),
                               RuleViolation("R2", "Line has trailing whitespace", 4),
                               RuleViolation("R2", "Line has trailing whitespace", 5),
                               RuleViolation("R3", "Line contains hard tab characters (\\t)", 5)]
            self.assertListEqual(errors, expected_errors)


text:
package com.intirix.openmm.server.ui.html.pages;

import org.simpleframework.xml.Default;

import com.intirix.openmm.server.mt.technical.beans.LocalRootFolder;
import com.intirix.openmm.server.mt.technical.beans.RootFolder;
import com.intirix.openmm.server.ui.html.PageData;

@Default
public class AdminFoldersBean extends PageData
{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private RootFolder[] folders = new RootFolder[]{ new LocalRootFolder() };

	public RootFolder[] getFolders()
	{
		return folders;
	}

	public void setFolders( RootFolder[] folders )
	{
		this.folders = folders;
	}

}


text:
template "/etc/sudoers" do
  mode 0440
  owner "root"
  group "root"
  source "sudoers.erb"
  variables(
    :sudoers_groups => (node[:sudo_groups] ? node[:sudo_groups].keys : []),
    :sudoers_users  => (node[:sudo_users] ? node[:sudo_users].keys : [])
  )
end


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

module.exports = Readable;

/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/

/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/

Readable.ReadableState = ReadableState;

var EE = require('events').EventEmitter;

/*<replacement>*/
if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
  return emitter.listeners(type).length;
};
/*</replacement>*/

var Stream = require('stream');

/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/

var StringDecoder;

/*<replacement>*/
var debug = require('util');
if (debug && debug.debuglog) {
  debug = debug.debuglog('stream');
} else {
  debug = function () {};
}
/*</replacement>*/

util.inherits(Readable, Stream);

function ReadableState(options, stream) {
  var Duplex = require('./_stream_duplex');

  options = options || {};

  // the point at which it stops calling _read() to fill the buffer
  // Note: 0 is a valid value, means "don't call _read preemptively ever"
  var hwm = options.highWaterMark;
  var defaultHwm = options.objectMode ? 16 : 16 * 1024;
  this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;

  // cast to ints.
  this.highWaterMark = ~~this.highWaterMark;

  this.buffer = [];
  this.length = 0;
  this.pipes = null;
  this.pipesCount = 0;
  this.flowing = null;
  this.ended = false;
  this.endEmitted = false;
  this.reading = false;

  // a flag to be able to tell if the onwrite cb is called immediately,
  // or on a later tick.  We set this to true at first, because any
  // actions that shouldn't happen until "later" should generally also
  // not happen before the first write call.
  this.sync = true;

  // whenever we return null, then we set a flag to say
  // that we're awaiting a 'readable' event emission.
  this.needReadable = false;
  this.emittedReadable = false;
  this.readableListening = false;

  // object stream flag. Used to make read(n) ignore n and to
  // make all the buffer merging and length checks go away
  this.objectMode = !!options.objectMode;

  if (stream instanceof Duplex)
    this.objectMode = this.objectMode || !!options.readableObjectMode;

  // Crypto is kind of old and crusty.  Historically, its default string
  // encoding is 'binary' so we have to make this configurable.
  // Everything else in the universe uses 'utf8', though.
  this.defaultEncoding = options.defaultEncoding || 'utf8';

  // when piping, we only care about 'readable' events that happen
  // after read()ing all the bytes and not getting any pushback.
  this.ranOut = false;

  // the number of writers that are awaiting a drain event in .pipe()s
  this.awaitDrain = 0;

  // if true, a maybeReadMore has been scheduled
  this.readingMore = false;

  this.decoder = null;
  this.encoding = null;
  if (options.encoding) {
    if (!StringDecoder)
      StringDecoder = require('string_decoder/').StringDecoder;
    this.decoder = new StringDecoder(options.encoding);
    this.encoding = options.encoding;
  }
}

function Readable(options) {
  var Duplex = require('./_stream_duplex');

  if (!(this instanceof Readable))
    return new Readable(options);

  this._readableState = new ReadableState(options, this);

  // legacy
  this.readable = true;

  Stream.call(this);
}

// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
  var state = this._readableState;

  if (util.isString(chunk) && !state.objectMode) {
    encoding = encoding || state.defaultEncoding;
    if (encoding !== state.encoding) {
      chunk = new Buffer(chunk, encoding);
      encoding = '';
    }
  }

  return readableAddChunk(this, state, chunk, encoding, false);
};

// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
  var state = this._readableState;
  return readableAddChunk(this, state, chunk, '', true);
};

function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  var er = chunkInvalid(state, chunk);
  if (er) {
    stream.emit('error', er);
  } else if (util.isNullOrUndefined(chunk)) {
    state.reading = false;
    if (!state.ended)
      onEofChunk(stream, state);
  } else if (state.objectMode || chunk && chunk.length > 0) {
    if (state.ended && !addToFront) {
      var e = new Error('stream.push() after EOF');
      stream.emit('error', e);
    } else if (state.endEmitted && addToFront) {
      var e = new Error('stream.unshift() after end event');
      stream.emit('error', e);
    } else {
      if (state.decoder && !addToFront && !encoding)
        chunk = state.decoder.write(chunk);

      if (!addToFront)
        state.reading = false;

      // if we want the data now, just emit it.
      if (state.flowing && state.length === 0 && !state.sync) {
        stream.emit('data', chunk);
        stream.read(0);
      } else {
        // update the buffer info.
        state.length += state.objectMode ? 1 : chunk.length;
        if (addToFront)
          state.buffer.unshift(chunk);
        else
          state.buffer.push(chunk);

        if (state.needReadable)
          emitReadable(stream);
      }

      maybeReadMore(stream, state);
    }
  } else if (!addToFront) {
    state.reading = false;
  }

  return needMoreData(state);
}

// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes.  This is to work around cases where hwm=0,
// such as the repl.  Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
  return !state.ended &&
         (state.needReadable ||
          state.length < state.highWaterMark ||
          state.length === 0);
}

// bac


text:
// This file is automatically generated.

package adila.db;

/*
 * Medion LIFETAB S786x
 *
 * DEVICE: LIFETAB_S786X
 * MODEL: LIFETAB_S786X
 */
final class lifetab5fs786x_lifetab5fs786x {
    public static final String DATA = "Medion|LIFETAB S786x|";
}


text:
package com.castlemock.service.mock.soap.project.converter;

import com.castlemock.model.mock.soap.domain.SoapOperationIdentifier;
import com.castlemock.service.mock.soap.project.converter.types.Attribute;
import com.castlemock.service.mock.soap.project.converter.types.Namespace;

import java.util.Set;

public final class AttributeConverter {

    public AttributeConverter(){

    }

    public static SoapOperationIdentifier toSoapOperationIdentifier(final Attribute attribute,
                                                                    final Set<Namespace> namespaces){
        final String name = attribute.getLocalName();
        final String namespace = attribute.getNamespace()
                .flatMap(namespaceName -> namespaces.stream()
                        .filter(namespace1 -> namespace1.getLocalName().equals(namespaceName))
                        .findFirst()
                        .map(Namespace::getValue))
                .orElse(null);

        return SoapOperationIdentifier.builder()
                .name(name)
                .namespace(namespace)
                .build();
    }

}


text:
namespace content {

bool EnsureJniRegistered(JNIEnv* env) {
  static bool g_jni_init_done = false;

  if (!g_jni_init_done) {
    if (!base::android::RegisterJni(env))
      return false;

    if (!gfx::android::RegisterJni(env))
      return false;

    if (!net::android::RegisterJni(env))
      return false;

    if (!ui::android::RegisterJni(env))
      return false;

    if (!ui::gl::android::RegisterJni(env))
      return false;

    if (!ui::shell_dialogs::RegisterJni(env))
      return false;

    if (!content::android::RegisterCommonJni(env))
      return false;

    if (!content::android::RegisterBrowserJni(env))
      return false;

    if (!content::android::RegisterAppJni(env))
      return false;

    if (!media::RegisterJni(env))
      return false;

    g_jni_init_done = true;
  }

  return true;
}

bool LibraryLoaded(JNIEnv* env, jclass clazz,
                          jobjectArray init_command_line) {
  base::android::InitNativeCommandLineFromJavaArray(env, init_command_line);

  CommandLine* command_line = CommandLine::ForCurrentProcess();

  if (command_line->HasSwitch(switches::kTraceStartup)) {
    base::debug::CategoryFilter category_filter(
        command_line->GetSwitchValueASCII(switches::kTraceStartup));
    base::debug::TraceLog::GetInstance()->SetEnabled(category_filter,
        base::debug::TraceLog::RECORDING_MODE,
        base::debug::TraceLog::RECORD_UNTIL_FULL);
  }

  // Android's main browser loop is custom so we set the browser
  // name here as early as possible.
  TRACE_EVENT_BEGIN_ETW("BrowserMain", 0, "");
  base::debug::TraceLog::GetInstance()->SetProcessName("Browser");
  base::debug::TraceLog::GetInstance()->SetProcessSortIndex(
      kTraceEventBrowserProcessSortIndex);

  // Can only use event tracing after setting up the command line.
  TRACE_EVENT0("jni", "JNI_OnLoad continuation");

  logging::LoggingSettings settings;
  settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
  logging::InitLogging(settings);
  // To view log output with IDs and timestamps use "adb logcat -v threadtime".
  logging::SetLogItems(false,    // Process ID
                       false,    // Thread ID
                       false,    // Timestamp
                       false);   // Tick count
  VLOG(0) << "Chromium logging enabled: level = " << logging::GetMinLogLevel()
          << ", default verbosity = " << logging::GetVlogVerbosity();

  return EnsureJniRegistered(env);
}

}  // namespace content


text:
Perfect-Scrollbar Demo

			Perfect-Scrollbar is a jQuery plugin for making web page elements scrollable in
            touch, as well as desktop and laptop devices. The plugin author is
			HyeonJe Jun.


text:
<?php

/**
 * Generates site-wide global page nav.
 **/

?>

<nav class="navigation<?php if(isset($modifier_classes)): print ' ' . $modifier_classes; endif; ?>">
  <a class="navigation__logo" href="<?php print $base_path; ?>">DoSomething.org
  Show Menu

          <?php print $explore_campaigns['text']; ?>
          <?php print $explore_campaigns['subtext']; ?>

        <a href="<?php print url('node/' . $who_we_are['link']); ?>">
          <?php print $who_we_are['text']; ?>
          <?php print $who_we_are['subtext']; ?>

        <?php print $search_box; ?>

      <?php if($logged_in): ?>

          <?php print $user_identifier ?>

<?php print l("My Account", 'user/'. $user->uid); ?>

<a id="link--logout" href="<?php print $front_page; ?>user/logout"><?php print t('Log Out'); ?>

      <?php else: ?>

<a id="link--login" class="secondary-nav-item" href="<?php print $front_page; ?>user/login" data-modal-href="#modal--login"><?php print t('Log In'); ?>

      <?php endif; ?>


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateLocationsTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('locations', function(Blueprint $table) {
			$table->increments('id');
			$table->string('name');
			$table->string('image');
			$table->integer('product_id')->unsigned();
			$table->string('editableArea');
			$table->string('editableAreaUnits');
			$table->string('clipRect');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::drop('locations');
	}

}


text:
This library will assist you in automatically publishing gems to a variety of
repositories.

At present, *variety* means RubyGems.org or GemFury.

Requires Ruby 1.8.7 or later.

## How it works

It first checks whether a version tag (of the form `vX.Y.Z`) for the current
version exists in the remote repository.  If the tag does not exist, it does the following:

* Builds a gem for the updated version
* Remotely tags the new version
* Pushes the gem to the gem server

## Limitations

* Only git repositories are supported
* The remote repository must be called `origin`

## Example

### Via rake

In your `Rakefile`:

    require "gem_publisher"

    desc "Publish gem to RubyGems.org"
    task :publish_gem do |t|
      gem = GemPublisher.publish_if_updated("yourgem.gemspec", :rubygems)
      puts "Published #{gem}" if gem
    end

Use `:gemfury` instead of `:rubygems` if you want to publish to GemFury instead.

To push to an account you're a [collaborator](http://devcenter.gemfury.com/articles/collaboration.html) on, you can pass the `:as` option:

    GemPublisher.publish_if_updated("yourgem.gemspec", :gemfury, :as => 'otheraccount')

You'll probably need to add `gem_publisher` as a development dependency in
order to satisfy Bundler. In `{name of gem}.gemspec`, add the dependency:

    s.add_development_dependency "gem_publisher", "~> 1.1.1"

If you're using GemFury, add that too:

    s.add_development_dependency "gemfury"

You can now add `rake publish_gem` to your continuous integration server as a
task to run after the tests pass.

This assumes that the requisite credentials have been set up so that the
`gem push` and `fury push` commands work.

### Via command line

This method obviates the need to add extra development dependencies to your
project.

    gem publish yourgem.gemspec

(rubygems is the default repository) or

    gem publish -r gemfury yourgem.gemspec

To use a shared account to publish the gem with Gemfury, use

    gem publish -r gemfury -a yoursharedaccount yourgem.gemspec

As before, `gem push` or `fury push` must be available and configured.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.spring.cloud.core.resource;

import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.models.BlobContainerItem;
import com.azure.storage.blob.models.BlobContainerListDetails;
import com.azure.storage.blob.models.BlobListDetails;
import com.azure.storage.blob.models.ListBlobContainersOptions;
import com.azure.storage.blob.models.ListBlobsOptions;
import org.springframework.core.io.ProtocolResolver;
import org.springframework.core.io.Resource;

import java.util.stream.Stream;

/**
 * A {@link ProtocolResolver} implementation for the {@code azure-blob://} protocol.
 */
public final class AzureStorageBlobProtocolResolver extends AbstractAzureStorageProtocolResolver {

    private BlobServiceClient blobServiceClient;

    private static final BlobListDetails RETRIEVE_NOTHING_DETAILS = new BlobListDetails();
    private static final BlobContainerListDetails RETRIEVE_NOTHING_CONTAINER_DETAILS = new BlobContainerListDetails();

    static {
        RETRIEVE_NOTHING_DETAILS.setRetrieveCopy(false);
        RETRIEVE_NOTHING_DETAILS.setRetrieveDeletedBlobs(false);
        RETRIEVE_NOTHING_DETAILS.setRetrieveDeletedBlobsWithVersions(false);
        RETRIEVE_NOTHING_DETAILS.setRetrieveImmutabilityPolicy(false);
        RETRIEVE_NOTHING_DETAILS.setRetrieveMetadata(false);
        RETRIEVE_NOTHING_DETAILS.setRetrieveLegalHold(false);
        RETRIEVE_NOTHING_DETAILS.setRetrieveSnapshots(false);
        RETRIEVE_NOTHING_DETAILS.setRetrieveTags(false);
        RETRIEVE_NOTHING_DETAILS.setRetrieveUncommittedBlobs(false);
        RETRIEVE_NOTHING_CONTAINER_DETAILS.setRetrieveMetadata(false);
        RETRIEVE_NOTHING_CONTAINER_DETAILS.setRetrieveDeleted(false);
    }

    /**
     * The storageType of current protocolResolver.
     *
     * @return StorageType.BLOB;
     */
    @Override
    protected StorageType getStorageType() {
        return StorageType.BLOB;
    }

    @Override
    protected Stream<StorageContainerItem> listStorageContainers(String containerPrefix) {

        ListBlobContainersOptions options = new ListBlobContainersOptions();
        options.setPrefix(containerPrefix);
        options.setDetails(RETRIEVE_NOTHING_CONTAINER_DETAILS);
        return getBlobServiceClient().listBlobContainers(options, null)
                                     .stream()
                                     .map(BlobContainerItem::getName)
                                     .map(StorageContainerItem::new);
    }

    @Override
    protected StorageContainerClient getStorageContainerClient(String name) {
        return new StorageBlobContainerClient(name);
    }

    private class StorageBlobContainerClient implements StorageContainerClient {

        private final String name;

        StorageBlobContainerClient(String name) {
            this.name = name;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public Stream<StorageItem> listItems(String itemPrefix) {
            ListBlobsOptions options = new ListBlobsOptions();
            options.setPrefix(itemPrefix);
            options.setDetails(RETRIEVE_NOTHING_DETAILS);
            BlobContainerClient containerClient = getBlobServiceClient().getBlobContainerClient(name);
            if (containerClient.exists()) {
                return containerClient.listBlobs(options, null)
                                      .stream()
                                      .map(blob -> new StorageItem(name, blob.getName(), getStorageType()));
            } else {
                return Stream.empty();
            }
        }
    }

    @Override
    protected Resource getStorageResource(String location, Boolean autoCreate) {
        return new StorageBlobResource(getBlobServiceClient(), location, autoCreate);
    }

    private BlobServiceClient getBlobServiceClient() {
        if (blobServiceClient == null) {
            blobServiceClient = beanFactory.getBean(BlobServiceClient.class);
        }
        return blobServiceClient;
    }
}


text:
var async    = require('async');
var moment   = require('moment');
var mongoose = require('../../bootstrap');
var db       = mongoose.connection.db;
var CheckHourlyStat = require('../../models/checkHourlyStat');
var Tag      = require('../../models/tag');
var QosAggregator = require('../../lib/qosAggregator');

var migrateCheckStats = function(name, callback) {
  var nbMigratedDocuments = 0;
  var collection = db.collection(name);
  var statStream = collection.find().stream();
  var unset = {
    ups: 1,
    responsives: 1,
    time: 1
  };
  statStream.on('data', function(stat) {
    if (stat.availability) {
      // already merged
      return;
    }
    var newStat = {
      availability: stat.ups / stat.count,
      responsiveness: stat.responsives / stat.count,
      responseTime: stat.time / stat.count,
      outages: [] // no way to get that back since CheckEvents are purged
    };
    collection.update({ _id: stat._id }, { $set: newStat, $unset: unset }, {}, function() {});
    nbMigratedDocuments++;
    if (nbMigratedDocuments % 100 == 0) {
      console.log('  Migrating ' + name + ' #' + nbMigratedDocuments);
    }
  });
  statStream.on('error', function(err) {
    callback(err);
  });
  statStream.on('end', function() {
    if (nbMigratedDocuments > 0) {
      console.log('  Finished: ' + nbMigratedDocuments + ' ' + name + ' migrated');
    } else {
      console.log('  No ' + name + ' to migrate');
    }
    callback();
  });
};

var addEndToMonthlyStat = function(name, callback) {
  var nbMigratedDocuments = 0;
  var collection = db.collection(name);
  var statStream = collection.find().stream();
  statStream.on('data', function(stat) {
    if (stat.end) {
      // already merged
      return;
    }
    var end = moment(stat.timestamp).endOf('month').toDate();
    collection.update({ _id: stat._id }, { $set: { end: end } }, {}, function() {});
    nbMigratedDocuments++;
    if (nbMigratedDocuments % 100 == 0) {
      console.log('  Adding end date to ' + name + ' #' + nbMigratedDocuments);
    }
  });
  statStream.on('error', function(err) {
    callback(err);
  });
  statStream.on('end', function() {
    if (nbMigratedDocuments > 0) {
      console.log('  Finished: Added end date to' + nbMigratedDocuments + ' ' + name + ' stats');
    } else {
      console.log('  No ' + name + ' missing end date');
    }
    callback();
  });
};

var getOldestDate = function(callback) {
  CheckHourlyStat
  .find()
  .sort({ 'timestamp': 1 })
  .findOne(function(err, stat) {
    return callback(err, stat ? stat.timestamp.valueOf() : null);
  });
};

var updateMonthlyQos = function(start, callback) {
  var date = Date.now() + 28 * 24 * 60 * 60 * 1000;
  var nbDates = 0;
  async.whilst(
    function() { date -= 28 * 24 * 60 * 60 * 1000; return date > start; },
    function(cb) {
      var dateObject = new Date(date);
      QosAggregator.updateMonthlyQos(dateObject, cb);
      nbDates++;
      console.log('Computing monthly stats for ' + dateObject.toUTCString());
    },
    callback
  );
};

var updateYearlyQos = function(start, callback) {
  var date = Date.now() + 365 * 24 * 60 * 60 * 1000;
  var nbDates = 0;
  async.whilst(
    function() { date -= 365 * 24 * 60 * 60 * 1000; return date > start; },
    function(cb) {
      var dateObject = new Date(date);
      QosAggregator.updateYearlyQos(dateObject, cb);
      nbDates++;
      console.log('Computing yearly stats for ' + dateObject.getFullYear());
    },
    callback
  );
};

var ensureTagsHaveFirstTestedDate = function(callback) {
  console.log('Updating tags for firstTested date');
  Tag.ensureTagsHaveFirstTestedDate(callback);
};

mongoose.connection.on('open', function(err) {
  if (err) return console.error(err);
  getOldestDate(function (err, oldestDate) {
    if (err) return console.error(err);
    async.series([
      function(next) {
        async.forEach(['checkhourlystats', 'checkdailystats', 'taghourlystats', 'tagdailystats'], migrateCheckStats, next);
      },
      function(next) {
        async.forEach(['checkmonthlystats', 'tagmonthlystats'], addEndToMonthlyStat, next);
      },
      function(next) {
        updateMonthlyQos(oldestDate, next);
      },
      function(next) {
        updateYearlyQos(oldestDate, next);
      },
      ensureTagsHaveFirstTestedDate,
      QosAggregator.updateLast24HoursQos.bind(QosAggregator)
    ], function(err2) {
      if (err2) return console.error(err2);
      console.log('Successfully migrated ' + db.databaseName + ' database');
      setTimeout(function() { mongoose.connection.close(); }, 1000);
    });
  });
});


text:
[![npm](https://img.shields.io/npm/v/baldr.svg)](https://www.npmjs.com/package/baldr)
[![Build Status](https://travis-ci.org/Josef-Friedrich/baldr.svg?branch=master)](https://travis-ci.org/Josef-Friedrich/baldr)
[![GitHub repo size](https://img.shields.io/github/repo-size/Josef-Friedrich/baldr.svg)](https://github.com/Josef-Friedrich/baldr)

Part of the [baldr project](https://github.com/Josef-Friedrich/baldr).

# @bldr/lamp

The main app of the BALDR project: a presentation app using YAML files.

## Terminology

* `presentation`:
  * `slides`: A ordered list of slides.
    * `slide`: One fullscreen view displayed for an audience.
      * `steps`: A ordered list of display states
        * `step`: A display state of a slide
  * `master`: Each `slide` and `view` is derived from a `master`
  * `asset`: All kind of media files (audio, video, image)

## Structure of the `*.baldr.yml` YAML file format

```yml
---
meta:
  title:
  ref:
  grade:
  curriculum:

slides:

  - audio:
      - media/audio/mozart.mp3
      - media/audio/haydn.mp3
      - media/audio/beethoven.mp3

  - camera: yes

  - editor: yes

  - image: media/image

  - generic: |
      # heading 1
      ## heading 2
      ### heading 3

  - person:
      name: Ludwig van Beethoven
      image: beethoven.jpg

  - question: When did Ludwig van Beethoven die?

  - quote:
      text: |
        Der Tag der Gunst ist wie der Tag der Ernte,
        man muss geschäftig sein sobald sie reift.
      author: Johann Wolfgang von Goethe
      date: 1801
```


text:
/*
 * @(#)DictIndex.java
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package com.coleman.kingword.dict.stardict;

import java.io.Serializable;

/**
 * Dictionary index entry structure.
 * <p>
 * Each index entry in the word list contains three fields, one after the other:
 * word_str; // a utf-8 string terminated by '\0'. word_data_offset; // word
 * data's offset in .dict file word_data_size; // word data's total size in
 * .dict file
 * </p>
 * More information please refer to doc/StarDictFileFormat file
 *
 * @author 88250
 * @version 1.1.0.2, Feb 16, 2008
 */
public class DictIndex implements Serializable {

	private static final long serialVersionUID = -3522450998887309292L;

	/**
	 * word string
	 */
	public String word;

	/**
	 * word data offset
	 */
	public long offset;

	/**
	 * word data size
	 */
	public int size;

	public DictIndex(String word, long offset, int size) {
		this.word = word;
		this.offset = offset;
		this.size = size;
	}

	@Override
	public String toString() {
		return word + "\t" + offset + "\t" + size;
	}
}


text:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace XenAdmin.Core
{
    /// <summary>
    /// Used to centralise the encryption routines used for master password
    /// & session lists
    /// </summary>
    public class EncryptionUtils
    {
        private static byte[] salt;

        /// <summary>
        /// Returns a secure hash of the given input string (usually the
        /// master password). We currently use SHA-1.
        /// </summary>
        /// <param name="password">The string to hash</param>
        /// <returns>The secure hash</returns>
        public static byte[] ComputeHash(String password)
        {
            //SHA1 hasher = SHA1.Create();
            MD5 hasher = MD5.Create();
            UnicodeEncoding ue = new UnicodeEncoding();
            byte[] bytes = ue.GetBytes(password);

            byte[] hash = hasher.ComputeHash(bytes);

            return hash;
        }

        public static string Protect(string data)
        {
            byte[] dataBytes = Encoding.Unicode.GetBytes(data);

            byte[] protectedBytes = ProtectedData.Protect(dataBytes, GetSalt(), DataProtectionScope.CurrentUser);

            return Convert.ToBase64String(protectedBytes);
        }

        public static string Unprotect(string protectedstring)
        {
            byte[] protectedBytes = Convert.FromBase64String(protectedstring);

            byte[] dataBytes = ProtectedData.Unprotect(protectedBytes, GetSalt(), DataProtectionScope.CurrentUser);

            return Encoding.Unicode.GetString(dataBytes);
        }

        /// <summary>
        /// Encrypt a given string using the given key. The cipherText is Base64
        /// encoded and returned. The algorithjm currently used is "Rijndael"
        /// </summary>
        /// <param name="clearString">The string to encrypt.</param>
        /// <param name="keyBytes">The key for the encryption algorithm</param>
        /// <returns>The Base64 encoded cipher text</returns>
        public static String EncryptString(String clearString, byte[] keyBytes)
        {
            MemoryStream ms = new MemoryStream();

            //DES alg = DES.Create();
            //RC2 alg = RC2.Create();
            Rijndael alg = Rijndael.Create();

            alg.Key = keyBytes;
            alg.IV = GetSalt();

            byte[] clearBytes = Encoding.Unicode.GetBytes(clearString);

            CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(clearBytes, 0, clearBytes.Length);
            cs.Close();

            byte[] cipherText = ms.ToArray();

            return Convert.ToBase64String(cipherText);
        }

        /// <summary>
        /// Decrypt some cipher text that was created by the encryptString method.
        /// </summary>
        /// <param name="cipherText64">The base64 encoded cipher text that was produced
        /// by encryptString</param>
        /// <param name="keyBytes">The key to use to decrypt</param>
        /// <returns>The decrypted text.</returns>
        public static String DecryptString(String cipherText64, byte[] keyBytes)
        {
            MemoryStream ms = new MemoryStream();

            byte[] cipherBytes = Convert.FromBase64String(cipherText64);
            Rijndael alg = Rijndael.Create();
            alg.Key = keyBytes;
            alg.IV = GetSalt();

            CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(cipherBytes, 0, cipherBytes.Length);
            cs.Close();

            byte[] plainBytes = ms.ToArray();

            return Encoding.Unicode.GetString(plainBytes);
        }

        private static byte[] GetSalt()
        {
            // NOTE: This is what we did in Geneva - may want
            // to do something less lame in future...
            if (salt == null)
            {
                UnicodeEncoding ue = new UnicodeEncoding();
                salt = ue.GetBytes("XenRocks");
            }

            return salt;
        }
    }
}


text:
class Connector {
    // A connector is the visual representation of an edge

    static connector_coords(edge) {
        let srcbox = view.lookup(edge.src);
        let destbox = view.lookup(edge.dest);
        let srcport = view.lookup_port(srcbox, 'output', edge.output);
        let destport = view.lookup_port(destbox, 'input', edge.input);
        return {'x1':srcbox.left + (srcbox.width/2.0)*srcbox.scaleX + srcport.left,
                'y1':srcbox.top + (srcbox.height/2.0)*srcbox.scaleY + srcport.top,
                'x2':destbox.left + (destbox.width/2.0)*destbox.scaleX + destport.left,
                'y2':destbox.top + (destbox.height/2.0)*destbox.scaleY + destport.top
               };
    }

    static update_connector(view, edge) {
        // Sync geometry of connector with corresponding edge
        if (edge == undefined)  {console.log('Cannot find connector'); return}
        let connector = view.lookup(edge);
        connector.set(this.connector_coords(edge));
        connector.setCoords(); // Update selection bbox region
        view.canvas.sendToBack(connector); // z-order control
    }

    static connector_glyph(edge) {
        // Given an edge, create a new fabric object as a connector
      let coords = this.connector_coords(edge);
        return new fabric.Line([coords['x1'], coords['y1'], coords['x2'],coords['y2']],
                               { name : edge.name,
                                 strokeWidth : 3,
                                 fill : '#fff',
                                 stroke : '#666',
                                 originX : 'center',
                                 originY : 'center',
                                 lockMovementX : true,
                                 lockMovementY : true,
                                 selectable : true,
                                 hasControls: false,
                                 hasBorders : false,
                                 perPixelTargetFind : true,
                                 targetFindTolerance : 20
                               });
    }

    static make_connector(view, edge) {
        // Make the glyph, add it to the canvas and send to back
        let glyph = this.connector_glyph(edge);
        view.canvas.add(glyph);
        view.canvas.sendToBack(glyph); // z-order control
    }

}

class View {
    // A View is the visual representation of the entire graph
    constructor(canvas) {
        this.canvas = canvas;

    }

    lookup(obj) {
        // Return the fabric object corresponding to the Node/Edge (optionally by name )
        let name = (typeof obj) == 'string' ? obj : obj.name;
        for (let object of this.canvas.getObjects() ) {
            if ( object.name === name ) { return object }
        }
    }

    lookup_port(spec, port_type, name) {
        // Lookup port of given type and name on given node (by name) or group
        let group = (typeof spec) == 'string' ? this.lookup(obj) : spec;
        let prefix = (port_type === 'input') ? 'inport-' : 'outport-';
        for (let obj of group.getObjects()) {
            if (obj.name) {
                if (obj.name.startsWith(prefix) && (obj.param == name)) {
                    return obj
                }
            }
        }
    }

    add_node(graph, type, name, options={}) { // TODO: Work by group
        let opts = {
            name: name,
            type : type,
            params : graph.defs.default_params(type),
            labels : graph.defs.default_params(type, 'label'),
            buttons : graph.defs.default_buttons(type),
            inputs : graph.defs.input_names(type),
            outputs: graph.defs.output_names(type),
            param_modes: graph.defs.default_params(type, 'mode')
        }

        let nodetype = graph.defs.nodetype(type);
        graph.add_node( new nodetype(_.extend(opts, options)));
        this.canvas.clear();
        this.render(graph);
    }

    render(graph) {
        for ( let node of graph.nodes ) {
            // Need a mapping from node type to box type
            let boxtype = graph.defs.boxtype(node.type);
            this.canvas.add(
                boxtype.make_nodebox(node)
            )
        }
        for ( let edge of graph.edges ) {
            Connector.make_connector(this, edge);
        }
    }

    remove(graph, name, comm=true) {
        let object = this.lookup(name);
        if (object === undefined) { return}
        if ('node' in object ) {
            let edges = graph.node_edges(object.node, 'input')
                .concat(graph.node_edges(object.node, 'output'));
            for ( let edge of edges ) {
                canvas.remove(this.lookup(edge));
            }
        }
        this.canvas.remove(object);
        graph.remove(name, comm)
    }
}


text:
import gevent
import gevent.monkey
gevent.monkey.patch_all()

import json
from tgext.socketio import SocketIOTGNamespace
from .utils import create_app, configure_app
from tg import validate
from tg.validation import TGValidationError
from formencode import Invalid

class NoFireBallValidator(object):
    def to_python(self, value, *args, **kw):
        type_ = value['type']
        if type_ in ('auto', 'ping'):
            return {'type': 'ping'}
        elif type_ == 'formencode':
            raise Invalid('Invalid Type', value, {})
        elif type_ == 'exception_handler':
            # Let it pass to test PingPong.exception_handler_decorator
            return 'exception_handler'

        raise TGValidationError('Invalid Type')

class CustomSchema(object):
    def validate(self, params, state):
        return {'attack': NoFireBallValidator().to_python(params['attack'])}

class PingPong(SocketIOTGNamespace):
    def exception_handler_decorator(self, method):
        def wrap(*args, **kwargs):
            if kwargs['attack'] == 'exception_handler':
                self.emit('handled')
            else:
                method(*args, **kwargs)
        return wrap

    @validate({'attack': NoFireBallValidator()})
    def on_ping(self, attack):
        self.emit('pong', {'sound': 'pong'})

    @validate(CustomSchema())
    def on_custom_schema_ping(self, attack):
        self.emit('pong', {'sound': 'pong'})

    def ping_error(self, attack):
        self.emit('ping_error', {'attack': attack})

    @validate({'attack': NoFireBallValidator()},
              error_handler=ping_error)
    def on_handled_ping(self, attack):
        self.emit('pong', {'sound': 'pong'})

class TestSocketIOValidation(object):
    def test_basic_request(self):
        app = create_app(configure_app(PingPong))
        resp = app.request('/socketio/test', body=json.dumps({'type': 'event',
                                                              'name': 'ping',
                                                              'endpoint': '',
                                                              'args': [{'type': 'ping'}]}))

        socketio_send_packet = resp.req.environ['socketio'].send_packet
        socketio_send_packet.assert_called_once_with({'endpoint': '/test',
                                                      'type': 'event',
                                                      'name': 'pong',
                                                      'args': ({'sound': 'pong'},)})

    def test_auto_request(self):
        app = create_app(configure_app(PingPong))
        resp = app.request('/socketio/test', body=json.dumps({'type': 'event',
                                                              'name': 'ping',
                                                              'endpoint': '',
                                                              'args': [{'type': 'auto'}]}))

        socketio_send_packet = resp.req.environ['socketio'].send_packet
        socketio_send_packet.assert_called_once_with({'endpoint': '/test',
                                                      'type': 'event',
                                                      'name': 'pong',
                                                      'args': ({'sound': 'pong'},)})

    def test_failed_validation(self):
        app = create_app(configure_app(PingPong))
        resp = app.request('/socketio/test', body=json.dumps({'type': 'event',
                                                              'name': 'ping',
                                                              'endpoint': '',
                                                              'args': [{'type': 'invalid'}]}))

        socketio_error = resp.req.environ['socketio'].error
        socketio_error.assert_called_once_with('invalid_method_args',
                                               {'attack': 'Invalid Type'},
                                               msg_id=None, endpoint='/test', quiet=False)

    def test_failed_validation_formencode(self):
        app = create_app(configure_app(PingPong))
        resp = app.request('/socketio/test', body=json.dumps({'type': 'event',
                                                              'name': 'ping',
                                                              'endpoint': '',
                                                              'args': [{'type': 'formencode'}]}))

        socketio_error = resp.req.environ['socketio'].error
        socketio_error.assert_called_once_with('invalid_method_args',
                                               {'attack': 'Invalid Type'},
                                               msg_id=None, endpoint='/test', quiet=False)

    def test_failed_validation_custom_schema(self):
        app = create_app(configure_app(PingPong))
        resp = app.request('/socketio/test', body=json.dumps({'type': 'event',
                                                              'name': 'custom_schema_ping',
                                                              'endpoint': '',
                                                              'args': [{'type': 'formencode'}]}))

        socketio_error = resp.req.environ['socketio'].error
        socketio_error.assert_called_once_with('invalid_method_args',
                                               'Invalid Type',
                                               msg_id=None, endpoint='/test', quiet=False)

    def test_exception_handler(self):
        app = create_app(configure_app(PingPong))
        resp = app.request('/socketio/test', body=json.dumps({
            'type': 'event',
            'name': 'ping',
            'endpoint': '',
            'args': [{'type': 'exception_handler'}]
        }))

        socketio_send_packet = resp.req.environ['socketio'].send_packet
        socketio_send_packet.assert_called_once_with({'endpoint': '/test',
                                                      'type': 'event',
                                                      'name': 'handled',
                                                      'args': tuple()})

    def test_error_handled_request(self):
        app = create_app(configure_app(PingPong))
        resp = app.request('/socketio/test', body=json.dumps({'type': 'event',
                                                              'name': 'handled_ping',
                                                              'endpoint': '',
                                                              'args': [{'type': 'ping'}]}))

        socketio_send_packet = resp.req.environ['socketio'].send_packet
        socketio_send_packet.assert_called_once_with({'endpoint': '/test',
                                                      'type': 'event',
                                                      'name': 'pong',
                                                      'args': ({'sound': 'pong'},)})

    def test_error_handled_auto_request(self):
        app = create_app(configure_app(PingPong))
        resp = app.request('/socketio/test', body=json.dumps({'type': 'event',
                                                              'name': 'handled_ping',
                                                              'endpoint': '',
                                                              'args': [{'type': 'auto'}]}))

        socketio_send_packet = resp.req.environ['socketio'].send_packet
        socketio_send_packet.assert_called_once_with({'endpoint': '/test',
                                                      'type': 'event',
                                                      'name': 'pong',
                                                      'args': ({'sound': 'pong'},)})

    def test_error_handled_failed_validation(self):
        app = create_app(configure_app(PingPong))
        resp = app.request('/socketio/test', body=json.dumps({'type': 'event',
                                                              'name': 'handled_ping',
                                                              'endpoint': '',
                                                              'args': [{'type': 'invalid'}]}))

        socketio_error = resp.req.environ['socketio'].send_packet
        socketio_error.assert_called_once_with({'endpoint': '/test',
                                                'type': 'event',
                                                'name': 'ping_error',
                                                'args': ({'attack': {u'type': u'invalid'}},)})


text:
namespace System
{
    namespace Devices
    {
        struct PointerEvent
        {
            u8 Index;
        };

        struct PointerPositionEvent : PointerEvent
        {
            u16 X;
            u16 Y;
        };

        struct PointerMoveEvent : PointerEvent
        {
            s8 X;
            s8 Y;
        };

        // TODO: Refactor this into Jauge ?
        struct PointerScrollEvent : PointerEvent
        {
            s16 Delta;
        };

        class PointerDevice : public Device
        {
        public:
            Event<PointerMoveEvent> PointerMove;
            Event<PointerEvent> PointerDown;
            Event<PointerEvent> PointerUp;

            // TODO: Refactor this into Jauge ?
            Event<PointerScrollEvent> PointerScroll;
        };
    }
}

#endif


text:
<?php
abstract class Kwc_User_Detail_Abstract_Component extends Kwc_Abstract_Composite_Component
{
    public function getTemplateVars()
    {
        $ret = parent::getTemplateVars();
        $ret['row'] = $this->getData()->parent->row;
        return $ret;
    }

    public static function getStaticCacheMeta($componentClass)
    {
        $ret = parent::getStaticCacheMeta($componentClass);
        $model = Kwf_Registry::get('config')->user->model;
        $ret[] = new Kwf_Component_Cache_Meta_Static_Model($model, 'users_{id}-general');
        return $ret;
    }
}


text:
package com.cognifide.aet.validation.impl;

import com.cognifide.aet.validation.ErrorMessage;
import com.cognifide.aet.validation.ValidationResultBuilder;
import org.apache.commons.lang3.StringUtils;

public final class ValidationUtils {

  private ValidationUtils() {
    // empty utils constructor
  }

  public static String validationResultToString(ValidationResultBuilder validationResultBuilder) {
    StringBuilder stringBuilder = new StringBuilder();
    if (validationResultBuilder != null && validationResultBuilder.hasErrors()) {
      stringBuilder.append("Validation failed. ");
      stringBuilder.append(validationResultBuilder.getErrorMessages().size());
      stringBuilder.append(" errors were found:" + StringUtils.LF);

      int counter = 1;
      for (ErrorMessage errorMessage : validationResultBuilder.getErrorMessages()) {
        stringBuilder.append("Error " + counter + StringUtils.LF);
        stringBuilder.append("\tMessage: ");
        stringBuilder.append(errorMessage.getMessage());
        stringBuilder.append(StringUtils.LF);
        if (errorMessage.getThrowable() != null) {
          stringBuilder.append("\tCaused by: ");
          stringBuilder.append(errorMessage.getThrowable());
          stringBuilder.append(StringUtils.LF);
        }
        counter++;
      }
    }
    return stringBuilder.toString();
  }

}


text:
//-----------------------------------------------------------------------
// <copyright file="SetShippingMethodsInputModel.cs" company="Sitecore Corporation">
//     Copyright (c) Sitecore Corporation 1999-2014
// </copyright>
// <summary>Controller parameters required to set the shipping methods into the cart.</summary>
//-----------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
// -------------------------------------------------------------------------------------------

namespace Sitecore.Commerce.Storefront.Models.InputModels
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    /// <summary>
    /// Defines the SetShippingMethodsInputModel class.
    /// </summary>
    public class SetShippingMethodsInputModel : BaseInputModel
    {
        /// <summary>
        /// Gets or sets the type of the order shipping preference.
        /// </summary>
        /// <value>
        /// The type of the order shipping preference.
        /// </value>
        public string OrderShippingPreferenceType { get; set; }

        /// <summary>
        /// Gets or sets the shipping methods.
        /// </summary>
        /// <value>
        /// The shipping methods.
        /// </value>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public List<ShippingMethodInputModelItem> ShippingMethods { get; set; }

        /// <summary>
        /// Gets or sets the shipping addresses.
        /// </summary>
        /// <value>
        /// The shipping addresses.
        /// </value>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public List<PartyInputModelItem> ShippingAddresses { get; set; }
    }
}


text:
/**
 * tests/api/v1/samples/get.js
 */
'use strict';
const supertest = require('supertest');
const api = supertest(require('../../../../express').app);
const constants = require('../../../../api/v1/constants');
const tu = require('../../../testUtils');
const u = require('./utils');
const Sample = tu.Sample;
const path = '/v1/samples';
const expect = require('chai').expect;
const ZERO = 0;
const redisCache = require('../../../../cache/redisCache').client.cache;

describe(`tests/api/v1/samples/get.js, GET ${path} >`, () => {
  let sampleName;
  let token;
  let userId;
  let userObject;
  before((done) => {
    tu.createUserAndToken()
    .then((obj) => {
      userId = obj.user.id;
      token = obj.token;
      userObject = obj.user;
      done();
    })
    .catch(done);
  });
  after(tu.forceDeleteUser);

  before((done) => {
    u.doSetup()
    .then(({ aspectId, subjectId }) => {
      const samp = u.getBasic({ aspectId, subjectId, provider: userId });
      return Sample.create(samp, userObject);
    })
    .then((samp) => {
      sampleName = samp.name;
      done();
    })
    .catch(done);
  });

  before(u.populateRedis);
  after(u.forceDelete);

  it('get all', (done) => {
    api.get(path)
    .set('Authorization', token)
    .expect(constants.httpStatus.OK)
    .end((err, res) => {
      if (err) {
        return done(err);
      }

      expect(res.body.length).to.equal(1);
      expect(res.body[0].provider).to.equal(userId);
      expect(res.body[0].id).to.be.undefined;
      const user = res.body[0].user;
      const sample = res.body[0];
      const aspect = sample.aspect;
      expect(sample).to.have.property('name').that.is.a('string');
      expect(sample).to.have.property('status').that.is.a('string');
      expect(sample).to.have.property('previousStatus').that.is.a('string');
      expect(sample).to.have.property('statusChangedAt').that.is.a('string');
      expect(sample).to.have.property('value').that.is.a('string');
      expect(sample).to.have.property('relatedLinks').that.is.an('array');
      expect(sample).to.have.property('createdAt').that.is.a('string');
      expect(sample).to.have.property('updatedAt').that.is.a('string');
      expect(sample).to.have.property('aspectId').that.is.a('string');
      expect(sample).to.have.property('subjectId').that.is.a('string');
      expect(sample).to.have.property('apiLinks').that.is.an('array');
      expect(aspect).to.have.property('description').that.is.a('string');
      expect(aspect).to.have.property('id').that.is.a('string');
      expect(aspect).to.have.property('isPublished').that.is.a('boolean');
      expect(aspect).to.have.property('name').that.is.a('string');
      expect(aspect).to.have.property('criticalRange').that.is.an('array');
      expect(aspect).to.have.property('warningRange').that.is.an('array');
      expect(aspect).to.have.property('infoRange').that.is.an('array');
      expect(aspect).to.have.property('okRange').that.is.an('array');
      expect(aspect).to.have.property('timeout').that.is.a('string');
      expect(aspect).to.have.property('valueLabel').that.is.a('string');
      expect(aspect).to.have.property('valueType').that.is.a('string');
      expect(aspect).to.have.property('relatedLinks').that.is.an('array');
      expect(aspect).to.have.property('tags').that.is.an('array');
      expect(user).to.be.an('object');
      expect(user.name).to.be.an('string');
      expect(user.email).to.be.an('string');
      expect(user.profile.name).to.be.an('string');
      expect(res.header).to.have.property('x-total-count', '1');
      expect(sample.status).to.equal(constants.statuses.Critical);
      return done();
    });
  });

  it('get by name', (done) => {
    api.get(`${path}/${sampleName}`)
    .set('Authorization', token)
    .expect(constants.httpStatus.OK)
    .end((err, res) => {
      if (err) {
        return done(err);
      }

      expect(res.body.status).to.equal(constants.statuses.Critical);
      expect(res.body.provider).to.equal(userId);
      const user = res.body.user;
      expect(user).to.be.an('object');
      expect(user.name).to.be.an('string');
      expect(user.email).to.be.an('string');
      expect(user.profile.name).to.be.an('string');
      expect(res.body.id).to.be.undefined;
      return done();
    });
  });

  it('apiLinks in basic get end  with sample name', (done) => {
    api.get(path)
    .set('Authorization', token)
    .expect(constants.httpStatus.OK)
    .expect((res) => {
      let href = '';
      for (let i = res.body.length - 1; i >= 0; i--) {
        const apiLinks = res.body[i].apiLinks;
        for (let j = apiLinks.length - 1; j >= 0; j--) {
          href = apiLinks[j].href;
          if (apiLinks[j].method != 'POST') {
            expect(href.split('/').pop()).to.equal(u.sampleName);
          } else {
            expect(href).to.equal(path);
          }
        }
      }
    })
    .end(done);
  });

  it('basic get: samples should have statusChangedAt field but not ' +
    'aspects ', (done) => {
    api.get(path)
    .set('Authorization', token)
    .expect(constants.httpStatus.OK)
    .end((err, res) => {
      if (err) {
        return done(err);
      }

      res.body.forEach((sample) => {
        expect(sample.statusChangedAt).to.be.an('string');
        expect(sample.aspect.statusChangedAt).to.be.undefined;
      });
      return done();
    });
  });

  it('basic get: aspect does not have statusChangedAt', (done) => {
    api.get(path)
    .set('Authorization', token)
    .expect(constants.httpStatus.OK)
    .end((err, res) => {
      if (err) {
        return done(err);
      }

      res.body.forEach((sample) => {
        expect(sample.aspect.statusChangedAt).to.be.undefined;
      });
      return done();
    });
  });

  it('by name is case in-sensitive', (done) => {
    const name = u.sampleName;
    api.get(`${path}/${name.toLowerCase()}`)
    .set('Authorization', token)
    .expect(constants.httpStatus.OK)
    .end((err, res) => {
      if (err) {
        return done(err);
      }

      expect(res.body.name).to.equal(name);
      return done();
    });
  });
});

describe(`tests/api/v1/samples/get.js, GET ${path} > ` +
  'cache the response >', () => {
  let sampleName;
  let token;

  before((done) => {
    tu.createToken()
    .then((returnedToken) => {
      token = returnedToken;
      done();
    })
    .catch(done);
  });

  before((done) => {
    u.createBasic()
    .then((samp) => {
      sampleName = samp.name;
      done();
    })
    .catch(done);
  });

  before(u.populateRedis);
  after(u.forceDelete);
  after(tu.forceDeleteUser);

  it('get with wildcard should cache response', (done) => {
    api.get(`${path}?name=${sampleName}*`)
    .set('Authorization', token)
    .expect(constants.httpStatus.OK)
    .end((err, res) => {
      if (err) {
        return done(err);
      }

      redisCache.get(`${sampleName}*`, (cacheErr, reply) => {
        if (cacheErr || !reply) {
          return done(cacheErr);
        }

        expect(JSON.parse(reply).length).to.be.above(ZERO);
        expect(JSON.parse(reply)[0].name).to.equal(`${sampleName}`);
        redisCache.del(`${sampleName}*`);
        done();
      });
    });
  });

  it('get without wildcard shold not cache response', (done) => {
    api.get(`${path}?name=${sampleName}`)
    .set('Authorization', token)
    .expect(constants.httpStatus.OK)
    .end((err, res) => {
      if (err) {
        return done(err);
      }

      redisCache.get(`${sampleName}`, (cacheErr, reply) => {
        if (cacheErr || !reply) {
          expect(res.body.length).to.be.above(ZERO);
          done();
        }
      });
    });
  });
});


text:
package slieb.closure.internal;

import slieb.closure.build.internal.SourceFileBase;

import java.util.List;

public interface IDependencyCalculator<T extends SourceFileBase> {

    public List<T> getDependencyList(final String entryPoint)
            throws DependencyException;

    public List<T> getDependencyList(final List<String> entryPoints)
            throws DependencyException;

}


text:
Colloco
=======

Description
-----------

Colloco is a front-end for managing a simple map collection

## Installation & Usage ##

1. Run bundler.

        $ bundle install

2. Create config.yml from the example file.

3. Run the application

        $ bin/colloco

Author
------

James Turnbull <james@lovedthanlost.net>

License
-------

    Author:: James Turnbull (<james@lovedthanlost.net>)
    Copyright:: Copyright (c) 2012 James Turnbull
    License:: Apache License, Version 2.0

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

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

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


text:
package org.spongepowered.mod.mixin.core.status;

import com.google.common.base.Charsets;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import net.minecraft.network.NetworkSystem;
import net.minecraft.network.PingResponseHandler;
import net.minecraft.network.ServerStatusResponse;
import net.minecraft.server.MinecraftServer;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.mod.status.SpongeLegacyMinecraftVersion;
import org.spongepowered.mod.status.SpongeStatusResponse;

import java.net.InetSocketAddress;

@Mixin(PingResponseHandler.class)
public abstract class MixinPingResponseHandler extends ChannelInboundHandlerAdapter {

    @Shadow
    private static Logger logger;

    @Shadow
    private NetworkSystem networkSystem;

    public boolean isFlowerPot() {
        return false;
    }

    private ByteBuf buf;

    @Shadow
    abstract void writeAndFlush(ChannelHandlerContext ctx, ByteBuf data);

    @Shadow
    abstract ByteBuf getStringBuffer(String string);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        this.buf = ctx.alloc().buffer();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        if (this.buf != null) {
            this.buf.release();
            this.buf = null;
        }
    }

    @Override
    @Overwrite
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf m = (ByteBuf) msg;
        this.buf.writeBytes(m);
        m.release();

        this.buf.markReaderIndex();
        boolean result = false;

        try {
            result = readLegacy(ctx, this.buf);
        } finally {
            this.buf.resetReaderIndex();
            if (!result) {
                ByteBuf buf = this.buf;
                this.buf = null;

                ctx.pipeline().remove("legacy_query");
                ctx.fireChannelRead(buf);
            }
        }
    }

    private boolean readLegacy(ChannelHandlerContext ctx, ByteBuf buf) {
        if (buf.readUnsignedByte() != 0xFE) {
            return false;
        }

        MinecraftServer server = this.networkSystem.getServer();
        InetSocketAddress client = (InetSocketAddress) ctx.channel().remoteAddress();
        ServerStatusResponse response;

        int i = buf.readableBytes();
        switch (i) {
            case 0:
                logger.debug("Ping: (<=1.3) from {}:{}", client.getAddress(), client.getPort());

                response = SpongeStatusResponse.postLegacy(server, client, SpongeLegacyMinecraftVersion.V1_3, null);
                if (response != null) {
                    this.writeResponse(ctx, String.format("%s§%d§%d",
                            SpongeStatusResponse.getUnformattedMotd(response),
                            response.getPlayerCountData().getOnlinePlayerCount(),
                            response.getPlayerCountData().getMaxPlayers()));
                } else {
                    ctx.close();
                }

                break;
            case 1:
                if (buf.readUnsignedByte() != 0x01) {
                    return false;
                }

                logger.debug("Ping: (1.4-1.5) from {}:{}", client.getAddress(), client.getPort());

                response = SpongeStatusResponse.postLegacy(server, client, SpongeLegacyMinecraftVersion.V1_5, null);
                if (response != null) {
                    this.writeResponse(ctx, String.format("§1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d",
                            response.getProtocolVersionInfo().getProtocol(),
                            response.getProtocolVersionInfo().getName(),
                            SpongeStatusResponse.getMotd(response),
                            response.getPlayerCountData().getOnlinePlayerCount(),
                            response.getPlayerCountData().getMaxPlayers()));
                } else {
                    ctx.close();
                }

                break;
            default:
                if (buf.readUnsignedByte() != 0x01 || buf.readUnsignedByte() != 0xFA) {
                    return false;
                }
                if (!buf.isReadable(2)) {
                    break;
                }
                short length = buf.readShort();
                if (!buf.isReadable(length * 2)) {
                    break;
                }
                if (!buf.readBytes(length * 2).toString(Charsets.UTF_16BE).equals("MC|PingHost")) {
                    return false;
                }
                if (!buf.isReadable(2)) {
                    break;
                }
                length = buf.readShort();
                if (!buf.isReadable(length)) {
                    break;
                }

                int protocol = buf.readUnsignedByte();
                length = buf.readShort();
                String host = buf.readBytes(length * 2).toString(Charsets.UTF_16BE);
                int port = buf.readInt();

                logger.debug("Ping: (1.6) from {}:{}", client.getAddress(), client.getPort());

                response =
                        SpongeStatusResponse.postLegacy(server, client,
                                new SpongeLegacyMinecraftVersion(SpongeLegacyMinecraftVersion.V1_6, protocol),
                                InetSocketAddress.createUnresolved(host, port));
                if (response != null) {
                    this.writeResponse(ctx, String.format("§1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d",
                            response.getProtocolVersionInfo().getProtocol(),
                            response.getProtocolVersionInfo().getName(),
                            SpongeStatusResponse.getMotd(response),
                            response.getPlayerCountData().getOnlinePlayerCount(),
                            response.getPlayerCountData().getMaxPlayers()));
                } else {
                    ctx.close();
                }

                break;
        }

        return true;
    }

    private void writeResponse(ChannelHandlerContext ctx, String response) {
        writeAndFlush(ctx, getStringBuffer(response));
    }

}


text:
module Handler.AdminUsers where

import Import
import Helpers.Messages

--listUsers :: (PersistEntity User, PersistQuery b m, PersistEntityBackend Entry ~ b) => b m [Entity User]
listUsers = selectList [] [Desc UserIdent]

getAdminListUsersR :: Handler RepHtml
getAdminListUsersR = do
    users <- runDB listUsers
    defaultLayout $ do
        setTitle "Users page"
        $(widgetFile "admin/users")

getMakeUserAdminR :: UserId -> Handler RepHtml
getMakeUserAdminR uid = do
    _ <- runDB $ update uid [UserAdmin =. True]
    setMessage $ successMessage "Gave the user admin access"
    redirect AdminListUsersR

getMakeUserNormalR :: UserId -> Handler RepHtml
getMakeUserNormalR uid = do
    _ <- runDB $ update uid [UserAdmin =. False]
    setMessage $ successMessage "Took the user's admin access"
    redirect AdminListUsersR


text:
package com.chapter04.fragmentbestpractice.bean;

/**
 * Created by Archer on 2017/11/2.
 */

public class News {
    private String title;
    private String content;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}


text:
const {app,BrowserWindow} = require('electron');

var mainWindow = null;

app.on('window-all-closed', function() {
  app.quit();
});

app.on('ready', function() {
  mainWindow = new BrowserWindow({width: 1600, height: 900});

  mainWindow.loadURL('file://' + __dirname + '/../../../src/dev.html');
  mainWindow.openDevTools({detach : true})

  mainWindow.on('closed', function() {
    mainWindow = null;
  });
});


text:
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import {AngularFireDatabase, FirebaseListObservable} from "angularfire2/database";
import {Observable} from "rxjs/Observable";

/*
  Generated class for the RecipeProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular DI.
*/
export interface Recipe {
  $key?: string,
  name: string,
  ingredients: {[key: string]: number}[]
}

@Injectable()
export class RecipeProvider {
  recipes: FirebaseListObservable<Recipe[]>;

  constructor(db: AngularFireDatabase) {
    this.recipes = db.list("/recipes");
  }

  getRecipes(search?: string): Observable<Recipe[]> {
    if (search) {
      return this.recipes
        .map(_recipes => _recipes.filter(recipe => recipe.name.toLowerCase().indexOf(search.toLowerCase()) > -1));
    } else {
      return this.recipes;
    }
  }

  addRecipe(recipe: Recipe) {
    this.recipes.push(recipe);
  }

  deleteRecipe(recipe: Recipe) {
    if (recipe.$key) {
      this.recipes.remove(recipe.$key);
    }
  }

  updateRecipe(recipe: Recipe) {
    this.recipes.update(recipe.$key, {name: recipe.name, ingredients: recipe.ingredients});
  }

}


text:
@interface PBGCDListOneController : UIViewController

@end


text:
body { font-family: monospace; font-size: 80%; margin-left: 8%; margin-right: 8%; }
pre { background-color: #cccccc; padding: 2ex; }
dl { margin-left: 2.5%; }
dt { text-decoration: underline; }
strong { color: red; font-weight: bold; }
.caution { color: red; font-weight: bold; }


text:
using System;

namespace UDBase.Controllers.UTime {

	/// <summary>
	/// Local time wrapper
	/// </summary>
	public class LocalTime : ITime {
		readonly bool _useUniversalTime;

		public LocalTime(bool useUniversalTime = false) {
			_useUniversalTime = useUniversalTime;
		}

		public bool     IsAvailable { get { return true;  } }
		public bool     IsFailed    { get { return false; } }
		public DateTime CurrentTime {
			get {
				return _useUniversalTime ? DateTime.Now.ToUniversalTime() : DateTime.Now;
			}
		}
	}
}


text:
<?xml version="1.0"?>
<test>
<setup>
  <system file="2.1-smp-system.xml.gz"/>
  <channel name="packages" file="2.1-smp-packages.xml.gz"/>
  <hardwareInfo path="kernel-hardware"/>
</setup>
<!--
(2) KMP Update

    This case triggers when a KMP becomes available on an installation
    source ("catalog") that has a higher [epoch/]version/release number
    that the installed KMP.

    (2.1) The kABI of the kernel and of the KMP match

      The KMP should get updated.

-->

<trial>
<install channel="packages" kind="package" name="novfs-kmp-smp" arch="i586" version="1.2.0_2.6.16_rc5_git14_3" release="8"/>
<install channel="packages" kind="package" name="cloop-kmp-smp" arch="i586" version="2.01_2.6.16_rc5_git14_3" release="15"/>
<install channel="packages" kind="package" name="nvidia-gfx-kmp-smp" arch="i586" version="1.0.8178_2.6.16_rc5_git14_3" release="1"/>
  <distupgrade/>
  <reportproblems/>
</trial>

</test>


text:
layout: relation
title: 'advmod:emph'
shortdef: 'emphasizing word, intensifier'
---

This is a special class of [adverbial modifiers](advmod).
It corresponds to the words that are attached in the analytical layer of PDT with the label `AuxZ`.
In the tectogrammatical layer they often get the label (functor) `RHEM` (rhematizers).

~~~ sdparse
zvlášť v pondělí \n especially on Monday
advmod:emph(pondělí, zvlášť)
advmod:emph(Monday, especially)
~~~

~~~ sdparse
jen 15 procent \n only 15 percent
advmod:emph(procent, jen)
advmod:emph(percent, only)
~~~

Other examples:

* _Mohli by obvinit i některého ministra._ "They could prosecute also/even a minister."
* _Začnou až o měsíc později._ lit. _They-will-start even by month later._ "They will start one month later." (_Až_ expresses that the speaker or the listener did not expect the thing to happen that late.)
* _Ani vojáci o to nemají zájem._ "Not even soldiers are interested in it."
* _Hraje už v sobotu._ "He will play already on Saturday."
* _Chceme se sejít ještě tento týden._ lit. _We-want to meet still this week._ "We want to meet before this week ends."
* _u asi 20 titulů_ "by around/approximately 20 items"
* _Dá se to dokumentovat právě na početné skupině dětí._ "It can be shown just on a large group of children."


text:
namespace blink {

class ScriptPromiseResolver;
class ScriptState;
class USBConfiguration;
class USBControlTransferParameters;

class USBDevice : public ScriptWrappable,
                  public ExecutionContextLifecycleObserver {
  USING_GARBAGE_COLLECTED_MIXIN(USBDevice);
  DEFINE_WRAPPERTYPEINFO();

 public:
  explicit USBDevice(device::mojom::blink::UsbDeviceInfoPtr,
                     mojo::PendingRemote<device::mojom::blink::UsbDevice>,
                     ExecutionContext*);
  ~USBDevice() override;

  const device::mojom::blink::UsbDeviceInfo& Info() const {
    return *device_info_;
  }
  bool IsInterfaceClaimed(wtf_size_t configuration_index,
                          wtf_size_t interface_index) const;
  wtf_size_t SelectedAlternateInterface(wtf_size_t interface_index) const;

  // USBDevice.idl
  uint8_t usbVersionMajor() const { return Info().usb_version_major; }
  uint8_t usbVersionMinor() const { return Info().usb_version_minor; }
  uint8_t usbVersionSubminor() const { return Info().usb_version_subminor; }
  uint8_t deviceClass() const { return Info().class_code; }
  uint8_t deviceSubclass() const { return Info().subclass_code; }
  uint8_t deviceProtocol() const { return Info().protocol_code; }
  uint16_t vendorId() const { return Info().vendor_id; }
  uint16_t productId() const { return Info().product_id; }
  uint8_t deviceVersionMajor() const { return Info().device_version_major; }
  uint8_t deviceVersionMinor() const { return Info().device_version_minor; }
  uint8_t deviceVersionSubminor() const {
    return Info().device_version_subminor;
  }
  String manufacturerName() const { return Info().manufacturer_name; }
  String productName() const { return Info().product_name; }
  String serialNumber() const { return Info().serial_number; }
  USBConfiguration* configuration() const;
  HeapVector<Member<USBConfiguration>> configurations() const;
  bool opened() const { return opened_; }

  ScriptPromise open(ScriptState*);
  ScriptPromise close(ScriptState*);
  ScriptPromise selectConfiguration(ScriptState*, uint8_t configuration_value);
  ScriptPromise claimInterface(ScriptState*, uint8_t interface_number);
  ScriptPromise releaseInterface(ScriptState*, uint8_t interface_number);
  ScriptPromise selectAlternateInterface(ScriptState*,
                                         uint8_t interface_number,
                                         uint8_t alternate_setting);
  ScriptPromise controlTransferIn(ScriptState*,
                                  const USBControlTransferParameters* setup,
                                  unsigned length);
  ScriptPromise controlTransferOut(ScriptState*,
                                   const USBControlTransferParameters* setup);
  ScriptPromise controlTransferOut(ScriptState*,
                                   const USBControlTransferParameters* setup,
                                   const ArrayBufferOrArrayBufferView& data);
  ScriptPromise clearHalt(ScriptState*,
                          String direction,
                          uint8_t endpoint_number);
  ScriptPromise transferIn(ScriptState*,
                           uint8_t endpoint_number,
                           unsigned length);
  ScriptPromise transferOut(ScriptState*,
                            uint8_t endpoint_number,
                            const ArrayBufferOrArrayBufferView& data);
  ScriptPromise isochronousTransferIn(ScriptState*,
                                      uint8_t endpoint_number,
                                      Vector<unsigned> packet_lengths);
  ScriptPromise isochronousTransferOut(ScriptState*,
                                       uint8_t endpoint_number,
                                       const ArrayBufferOrArrayBufferView& data,
                                       Vector<unsigned> packet_lengths);
  ScriptPromise reset(ScriptState*);

  // ExecutionContextLifecycleObserver interface.
  void ContextDestroyed() override;

  void Trace(Visitor*) override;

 private:
  static const size_t kEndpointsBitsNumber = 16;

  wtf_size_t FindConfigurationIndex(uint8_t configuration_value) const;
  wtf_size_t FindInterfaceIndex(uint8_t interface_number) const;
  wtf_size_t FindAlternateIndex(wtf_size_t interface_index,
                                uint8_t alternate_setting) const;
  bool IsProtectedInterfaceClass(wtf_size_t interface_index) const;
  bool EnsureNoDeviceChangeInProgress(ScriptPromiseResolver*) const;
  bool EnsureNoDeviceOrInterfaceChangeInProgress(ScriptPromiseResolver*) const;
  bool EnsureDeviceConfigured(ScriptPromiseResolver*) const;
  bool EnsureInterfaceClaimed(uint8_t interface_number,
                              ScriptPromiseResolver*) const;
  bool EnsureEndpointAvailable(bool in_transfer,
                               uint8_t endpoint_number,
                               ScriptPromiseResolver*) const;
  bool AnyInterfaceChangeInProgress() const;
  device::mojom::blink::UsbControlTransferParamsPtr
  ConvertControlTransferParameters(const USBControlTransferParameters*,
                                   ScriptPromiseResolver*) const;
  void SetEndpointsForInterface(wtf_size_t interface_index, bool set);

  void AsyncOpen(ScriptPromiseResolver*,
                 device::mojom::blink::UsbOpenDeviceError);
  void AsyncClose(ScriptPromiseResolver*);
  void OnDeviceOpenedOrClosed(bool);
  void AsyncSelectConfiguration(wtf_size_t configuration_index,
                                ScriptPromiseResolver*,
                                bool success);
  void OnConfigurationSelected(bool success, wtf_size_t configuration_index);
  void AsyncClaimInterface(wtf_size_t interface_index,
                           ScriptPromiseResolver*,
                           bool success);
  void AsyncReleaseInterface(wtf_size_t interface_index,
                             ScriptPromiseResolver*,
                             bool success);
  void OnInterfaceClaimedOrUnclaimed(bool claimed, wtf_size_t interface_index);
  void AsyncSelectAlternateInterface(wtf_size_t interface_index,
                                     wtf_size_t alternate_index,
                                     ScriptPromiseResolver*,
                                     bool success);
  void AsyncControlTransferIn(ScriptPromiseResolver*,
                              device::mojom::blink::UsbTransferStatus,
                              const Vector<uint8_t>&);
  void AsyncControlTransferOut(unsigned,
                               ScriptPromiseResolver*,
                               device::mojom::blink::UsbTransferStatus);
  void AsyncClearHalt(ScriptPromiseResolver*, bool success);
  void AsyncTransferIn(ScriptPromiseResolver*,
                       device::mojom::blink::UsbTransferStatus,
                       const Vector<uint8_t>&);
  void AsyncTransferOut(unsigned,
                        ScriptPromiseResolver*,
                        device::mojom::blink::UsbTransferStatus);
  void AsyncIsochronousTransferIn(
      ScriptPromiseResolver*,
      const Vector<uint8_t>&,
      Vector<device::mojom::blink::UsbIsochronousPacketPtr>);
  void AsyncIsochronousTransferOut(
      ScriptPromiseResolver*,
      Vector<device::mojom::blink::UsbIsochronousPacketPtr>);
  void AsyncReset(ScriptPromiseResolver*, bool success);

  void OnConnectionError();
  bool MarkRequestComplete(ScriptPromiseResolver*);

  device::mojom::blink::UsbDeviceInfoPtr device_info_;
  HeapMojoRemote<device::mojom::blink::UsbDevice> device_;
  HeapHashSet<Member<ScriptPromiseResolver>> device_requests_;
  bool opened_;
  bool device_state_change_in_progress_;
  wtf_size_t configuration_index_;

  // These vectors have one entry for each interface in the currently selected
  // configured. Use the index returned by FindInterfaceIndex().
  WTF::Vector<bool> claimed_interfaces_;
  WTF::Vector<bool> interface_state_change_in_progress_;
  WTF::Vector<wtf_size_t> selected_alternates_;

  // These bit sets have one entry for each endpoint. Index using the endpoint
  // number (lower 4 bits of the endpoint address).
  std::bitset<kEndpointsBitsNumber> in_endpoints_;
  std::bitset<kEndpointsBitsNumber> out_endpoints_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBUSB_USB_DEVICE_H_


text:
new function() {

	var errors = [];
	var errorsLimit = 100;
	var tabId;
	var timer;
	var icon;
	var popup;
	var options;
	var isIFrame = window.top != window;

	function showPopup(popupUrl) {
		if(!popup) {
			popup = document.createElement('iframe');
			popup.src = popupUrl;
			popup.frameBorder = 0;
			popup.style.cssText = 'position: fixed !important; bottom: 50px !important; right: 50px !important; z-index: 2147483647 !important;';
			popup.height = '50px';
			(document.body || document.documentElement).appendChild(popup);
		}
		else {
			popup.contentWindow.postMessage({
				_reloadPopup: true,
				url: popupUrl
			}, '*');
		}
	}

	function showErrorNotification(popupUrl) {
		if(options.showPopup) {
			showPopup(popupUrl);
		}

		if(!icon && (options.showIcon || options.showPopup)) {
			icon = document.createElement('img');
			icon.src = chrome.extension.getURL('img/error_38.png');
			icon.title = 'Some errors occurred on this page. Click to see details.';
			icon.style.cssText = 'position: fixed !important; bottom: 10px !important; right: 10px !important; cursor: pointer !important; z-index: 2147483647 !important; width: 38px !important; height: 38px !important; min-height: 38px !important; min-width: 38px !important; max-height: 38px !important; max-width: 38px !important;';
			icon.onclick = function() {
				if(!popup) {
					showPopup(popupUrl);
				}
				else {
					popup.remove();
					popup = null;
				}
			};
			if(options.showPopupOnMouseOver) {
				icon.onmouseover = function() {
					if(!popup) {
						showPopup(popupUrl);
					}
				};
			}
			(document.body || document.documentElement).appendChild(icon);
		}
	}

	function handleNewError(error) {
		var lastError = errors[errors.length - 1];
		var isSameAsLast = lastError && lastError.text == error.text && lastError.url == error.url && lastError.line == error.line && lastError.col == error.col;
		var isWrongUrl = !error.url || error.url.indexOf('://') === -1;
		if(!isSameAsLast && !isWrongUrl) {
			errors.push(error);
			if(errors.length > errorsLimit) {
				errors.shift();
			}
			if(!timer) {
				timer = window.setTimeout(function() {
					timer = null;
					chrome.runtime.sendMessage({
						_errors: true,
						errors: errors,
						url: window.top.location.href
					}, function(popupUrl) {
						if(popupUrl) {
							showErrorNotification(popupUrl);
						}
					});
				}, 200);
			}
		}
	}

	document.addEventListener('ErrorToExtension', function(e) {
		var error = e.detail;
		if(isIFrame) {
			window.top.postMessage({
				_iframeError: true,
				_fromJEN: true,
				error: error
			}, '*');
		}
		else {
			handleNewError(error);
		}
	});

	function codeToInject() {

		function handleCustomError(message, stack) {
			if(!stack) {
				stack = (new Error()).stack.split("\n").splice(2, 4).join("\n");
			}

			var stackLines = stack.split("\n");
			var callSrc = (stackLines.length > 1 && (/^.*?\((.*?):(\d+):(\d+)/.exec(stackLines[1]) || /(\w+:\/\/.*?):(\d+):(\d+)/.exec(stackLines[1]))) || [null, null, null, null];

			document.dispatchEvent(new CustomEvent('ErrorToExtension', {
				detail: {
					stack: stackLines.join("\n"),
					url: callSrc[1],
					line: callSrc[2],
					col: callSrc[3],
					text: message
				}
			}));
		}

		// handle uncaught promises errors
		window.addEventListener('unhandledrejection', function(e) {
			if (typeof e.reason === 'undefined') {
				e.reason = e.detail;
			}
			handleCustomError(e.reason.message, e.reason.stack);
		});

		// handle console.error()
		var consoleErrorFunc = window.console.error;
		window.console.error = function() {
			var argsArray = [];
			for(var i in arguments) { // because arguments.join() not working! oO
				argsArray.push(arguments[i]);
			}
			consoleErrorFunc.apply(console, argsArray);

			handleCustomError(argsArray.length == 1 && typeof argsArray[0] == 'string' ? argsArray[0] : JSON.stringify(argsArray.length == 1 ? argsArray[0] : argsArray));
		};

		// handle uncaught errors
		window.addEventListener('error', function(e) {
			if(e.filename) {
				document.dispatchEvent(new CustomEvent('ErrorToExtension', {
					detail: {
						stack: e.error ? e.error.stack : null,
						url: e.filename,
						line: e.lineno,
						col: e.colno,
						text: e.message
					}
				}));
			}
		});

		// handle 404 errors
		window.addEventListener('error', function(e) {
			var src = e.target.src || e.target.href;
			var baseUrl = e.target.baseURI;
			if(src && baseUrl && src != baseUrl) {
				document.dispatchEvent(new CustomEvent('ErrorToExtension', {
					detail: {
						is404: true,
						url: src
					}
				}));
			}
		}, true);
	}

	var script = document.createElement('script');
	script.textContent = '(' + codeToInject + '())';
	(document.head || document.documentElement).appendChild(script);
	script.parentNode.removeChild(script);

	function handleInternalMessage(data) {
		if(!isIFrame && (!data.tabId || data.tabId == tabId)) {
			if(data._clear) {
				errors = [];
				if(popup) {
					popup.remove();
					popup = null;
				}
				if(icon) {
					icon.remove();
					icon = null;
				}
			}
			else if(data._resize && popup) {
				var maxHeight = Math.round(window.innerHeight * options.popupMaxHeight / 100) - 60;
				var maxWidth = Math.round(window.innerWidth * options.popupMaxWidth / 100) - 60;
				var height = data.height < maxHeight ? data.height : maxHeight;
				var width = data.width < maxWidth ? data.width : maxWidth;
				popup.height = (width == maxWidth ? height + 10 : height) + 'px'; // scroll fix
				popup.width = (height == maxHeight ? width + 10 : width) + 'px'; // scroll fix
				popup.style.height = popup.height;
				popup.style.width = popup.width;
			}
			else if(data._closePopup && popup) {
				popup.style.display = 'none';
			}
			else if(data._iframeError) {
				handleNewError(data.error);
			}
		}
	}

	chrome.runtime.onMessage.addListener(handleInternalMessage);

	window.addEventListener('message', function(event) {
		if(typeof event.data === 'object' && event.data && typeof event.data._fromJEN !== 'undefined' && event.data._fromJEN) {
			handleInternalMessage(event.data);
		}
	});

	if(!isIFrame) {
		chrome.runtime.sendMessage({
			_initPage: true,
			url: window.location.href
		}, function(response) {
			options = response;
		});
	}
};


text:
(function (d3) {
    /**
     * __Text chart component for ```d3.chart``` v0.2__
     *
     * Renders an text element on a chart. Intended to be attached to a base element
     * which is appropriately transformed by the parent chart.
     *
     * @namespace d3.chart
     * @class Text
     * @author Pete Baker
     * @version 0.1.0
     */
    d3.chart("Text", {

        /**
         * @constructor
         * @param {Object} [options] Chart constructor options
         * @param {String} [options.text] The text string. Defaults to "Text"
         * @param {String} [options.title] The hover tooltip/title string. Defaults to ""
         */
        initialize: function(options) {
            var chart = this;

            //merge default and specified options
            chart.options = $.extend({
                text: "Text",
                title: ""
            }, options);

            console.log("[d3.chart.test] initialize '%s'", chart.options.text);

            chart.text = chart.base.append("text")
                                   .classed("title", true)
                                   .text(chart.options.text);

            chart.title = chart.base.append("title")
                                    .text(chart.options.title);
        }
    });
}(d3));


text:
class ComponentWithCustomCss < Netzke::Base
  js_configure do |c|
    c.html = "A component with the body hidden by means of custom CSS"
    c.title = "ComponentWithCustomCss"
  end

  css_configure do |c|
    c.require :custom
  end
end