text:
class FilePolice::BacklogFile

  attr_accessor :collection, :box, :folder, :name, :number, :errors

  def initialize path
    parts = File.basename(path, File.extname(path)).split("_")
    self.errors = Array.new
    if parts.length == 5
      validate_collection(parts[0])
      validate_box(parts[1])
      validate_folder(parts[2])
      self.name = parts[3]
      validate_number(parts[4])
    else
      self.errors << "Filename does not have 5 segments separated by underscores (_)"
    end
  end

  # Should match strings like ARC0001
  def validate_collection collection = String.new
    self.errors << "#{collection} does not match ARC#### format" unless collection.match(/^ARC[0-9]{4,4}$/)
    self.collection = collection
  end

  # Should match strings like BX1
  def validate_box box = String.new
    self.errors << "#{box} does not have the correct format" unless box.match(/^[A-Z]{2,2}[0-9]{1,3}$/)
    self.box = box
  end

  # Should match strings like FL1, OS2, or FL22b
  def validate_folder folder = String.new
    self.errors << "#{folder} does not have the correct format" unless folder.match(/^[A-Z]{2,2}[0-9]{1,3}[a-z]{0,1}$/)
    self.folder = folder
  end

  # Sould be numbers only
  def validate_number number = String.new
    self.errors << "#{number} does not have the correct format" unless number.match(/^[0-9]{1,4}[a-z]{0,1}$/)
    self.number = number
  end

end


text:
<!DOCTYPE html>

    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <link href="user_docs.css" rel="stylesheet" type="text/css">
    <link href="local_extensions.css" rel="stylesheet" type="text/css">
    <title>
      Sharing Places Information - Google Earth User Guide
    </title>

        Google Earth User Guide

        <form action="http://www.google.com/search" class="c2" method="get">
          Search Google Earth

          User Guide

          <form action="http://www.google.com/cse" id="cse-search-box" name="cse-search-box">

              <input name="cx" type="hidden" value="006447561658385433045:da9zsap5cmm">
              <input name="q" size="18" type="text"> <input name="sa" type="submit" value="Search">

          </form>

                Table of Contents

                Introduction

                Finding Places and Directions

                Marking Places

                Using Layers

                Using Map Features

                Using Places

                About KML

                Sharing Places Information

                  Emailing an Image

                  Emailing Places Data

                  Troubleshooting Email Issues

                  Sharing Data Over a Network

                      Saving Data to a Server

                      Opening Data from a Network Server

                      About Network Links

                      Creating a Network Link

                Using Tours

                Editing Places and Folders

                Managing Search Results

                Measuring Distances and Areas

                Viewing Sky

                Drawing Paths and Polygons

                Using Image Overlays and 3D Models

                Using Flight Simulator

                Importing Your Data Into Google Earth

                Using Style Templates

                Viewing Timelines

                Making Movies with Google Earth

                Keyboard Controls

                3D Viewer Options

        </form>

          Sharing Places Information

          The section describes how you can share placemarks, shapes, and folder data with other
          people - including both users and non-users of Google Earth. You can share your places
          data by:

            Emailing an Image

            Emailing Places Data

            Sharing Data Over a Network

            Creating a Network Link

          Note - You can also share places information with other Google Earth
          users via the Google Earth Comunity BBS website. For more information, see Sharing a Point of Interest.

          Emailing an Image

          At this time, emailing a Google Earth image on the Mac is available only through the
          Mail, Entourage and Eudora applications. You can email the current view of the earth
          shown in the Google Earth 3D viewer as:

An image file for people who don't have Google Earth

A KMZ file for other users of Google Earth

          When you email an image, a JPEG file is automatically attached to an outbound email
          message. When you email the view as a KMZ, a KMZ file is automatically attached to an
          outbound email message. To email an image:

Do one of the following:

Click File > Email > Email Image.

Type Ctrl+Alt+E (Windows and Linux only)

Click on the email icon on the toolbar and choose Email Image.

In the Select Email Service window, choose your default email program or
          your Gmail account. If you use your Gmail account, you will be prompted to sign in if you
          have not already.

            Before selecting your email service, select the Remember this setting... check
            box if you want to use the same email service every time you email a view. You can
            always change your email preferences later by selecting Tools >
            Options > General (Windows/Linux) or Google Earth >
            Preferences (Mac) and clicking on the General tab.

Wait while the Google Earth software sends the data to your email application. A new
          email window appears with the image file. (This can take a few seconds.) The image is a
          JPG file of the current view in the 3D viewer.

Fill in the recipient's email address and any other information in the body and send
          the email.

          When you email an image, the quality of that image is identical to the quality available
          for the Save Image feature in Google Earth.

          Emailing Places Data

          Note - On the Mac, you can only email through the Mail, Eudora and
          Entourage applications.

          In addition to emailing a view as a KMZ file to other users of Google Earth, you
          also can email places data in two other ways:

Attach a KMZ file or folder saved to your computer's hard drive to an email. If you
          followed the instructions listed in Saving Places
          Data, locate your saved KMZ file and attach it to an outbound email as you would with
          any attachment.

Email a placemark that is centered in your 3D viewer directly from Google Earth (see
          below).

          To email places data:

Do one of the following:

Click File > Email > Email Place .

Type Ctrl + E (+ E on the Mac)

Click on the email icon on the toolbar and choose Email Place.

Right click (CTRL click on the Mac) the appropriate placemark in the Places panel and
          choose Email.

In the Select Email Service window, choose your default email program or
          your Gmail account. If you use your Gmail account, you will be prompted to sign in if you
          have not already.

            Before selecting your email service, select the Remember this setting... check
            box if you want to use the same email service every time you email a view. You can
            always change your email preferences later by selecting Tools >
            Options > General (Windows/Linux) or Google Earth >
            Preferences (Mac) and clicking on the General tab. Wait while the
            Google Earth software sends the data to your email application. A new email window
            appears with the KMZ file. (This can take a few seconds.)

Fill in the recipient's email address and any other information in the body and send
          the email.

          Things to consider:

When you email KMZ files that reference custom icons or image overlays from your
          local file system those items are included with the placemark data. For this reason, KMZ
          files that include imagery overlays might be larger than those containing a simple
          placemark.

If you are sending a placemark file to a user of a Google Earth (Keyhole) client
          version 2.2 or lower, the recipient will not be able to view the placemark. The file
          format for placemarks has changed for Google Earth versions 3.0 and higher. Send an image
          file instead.

          Troubleshooting Email Issues

          Note - On the Mac, you can only email through the Mail, Eudora and
          Entourage applications.

          If your email application does not respond to the Email View command, you may
          need to set the default email program. To do this in Windows, open the Control
          Panel from the Start menu and select Internet Options. Click the
          Programs tab, select the default email program that you use from the
          E-mail drop-down list, and click Apply. You should now be able to send
          a view with your email application. To do this on a Mac, open Mail. Click Mail >
          Preferences. Pick the email application you'd prefer as your default email handler.

          Sharing Data Over a Network

          In addition to saving placemarks or folders to your local computer, you can also save
          place data to a web server or network server. Other Google Earth users who have access to
          the server can then use the data. As with other documents, you can create links or
          references to KMZ files for easy access. Storing a placemark file on the network or on a
          web server offers the following advantages:

            Accessibility - If your place data is stored on a network or the Web,
            you can access it from any computer anywhere, provided the location is either publicly
            available or you have log in access.

            Ease in Distribution - You can develop an extensive presentation
            folder for Google Earth software and make that presentation available to everyone who
            has access to your network storage location or web server. This is more convenient than
            sending the data via email when you want to make it persistently available to a large
            number of people.

            Automatic Updates/Network Link Access - Any new information or changes
            you make to network-based KMZ information is automatically available to all users who
            access the KML data via a network link.

            Backup - If for some reason the data on your local computer is corrupt
            or lost, you can open any of the KMZ files that you have saved to a network location,
            and if so desired, save it as a local file again.

          Note: Before you can create a network link to an item in Google Earth,
          you must first store that place data on a server.

          This section covers the following topics:

            Saving Data to a Server

            Opening Data from a Network Server

            About Network Links

            Creating a Network Link

          Saving Data to a Server

          To make your placemarks or folders available to other people via a server, you need to
          first save the file to the appropriate location.

            Network Server - To save a folder or placemark to a location on your
            network, simply follow the steps in Saving Places
            Data and save the file in a location on your company network rather than to your
            local file system.

            Web Server - To save a placemark or folder to a web server, first save
            the file to your local computer as described in Saving
            Places Data. Once the file is saved on your local computer as a separate KMZ file,
            you can use an FTP or similar utility to transfer the file to the web servers.

          If you want users to be able to open KML and KMZ files from a web server, you may need to
          add MIME types for the server. These are:

application/vnd.google-earth.kml+xml kml

application/vnd.google-earth.kmz kmz

          Opening Data from a Network Server

          If you are working in an organization where place data is saved to a network that you
          have access to, you can open that data in the same way you would open a saved KMZ file on
          your local computer.

            From the File menu, select Open (Ctrl + O in Windows/Linux, + O on the Mac) - Navigate to your network places and locate the KMZ or KML
            data you want to open in Google Earth. Select the file and click the Open
            button. The folder or placemark appears in the Places panel and the 3D viewer
            flies to the view set for the folder or placemark (if any).

            Files opened in this way are NOT automatically saved for the next time you use
            Google Earth. If you want the placemark or folder to appear the next time you use
            Google Earth, drag the item to your My Places folder to save it for the next
            session.

            Locate the file you want to open - Once you have located the file on
            your network places, you can simply drag and drop the KMZ file over the Places
            panel. The 3D viewer flies to the view set for the folder or placemark (if any).

            When you use the drag-and-drop method of opening a placemark or folder, you can drop
            the item over a specific folder in the Places panel. If the My Places
            folder is closed and you want to drop it there, just hold the item over the My
            Places folder until the folder opens up and you can place the item within
            subfolders or in the list. Items dropped in the My Places folder appear the
            next time you start Google Earth. Otherwise, you can drop the item in the white space
            below the Places panel so that it appears in the Temporary Places
            folder. Items opened this way appear only for the current session of Google Earth
            unless you save them.

          About Network Links

          The network link feature in Google Earth provides a way for multiple clients to view the
          same network-based or web-based KMZ data and automatically see any changes to the content
          as those changes are made. A network link allows for content publishing in a manner
          similar to web page/web browser content delivery:

            A network link provides a way to deliver dynamic data to multiple Google Earth
            users. When users connect to your KMZ file via a network link, either you or
            they can specify how often to refresh the data in the file. This way, regular updates
            made to the content by one person are automatically reflected in all connected clients.

            A network link is intended as a view-only reference to published
            content. Just as web pages are viewed by many people but only modifiable by
            those with permission, place data content can be linked to and seen by multiple users
            while set to be modifiable only by one author. As with web pages, users who are viewing
            the content can always save that content to their hard drive, but they can only receive
            dynamic content via a network link.

          The following figure illustrates the parallels between web-based content and KMZ content
          via a network link using Google Earth.

          Creating a Network Link

          Before you can create a network link, the content you
          want to link to must exist on the network or web server that you are linking to. If you
          are authoring the content, see Saving Data to a Server for
          details about saving KMZ files to a web or network server. If you are only linking to the
          content, be sure you know either the network location of the file or the URL if it is
          located on a web server.

Choose any one of the following ways to start:

Select Network Link From the Add Menu. Select Network
              Link from the pop-up menu.

Right-click (CTRL click on the Mac) on a folder in the My Places Panel.
              Select Add > Network Link from the pop-up menu. When you add a network
              link in this way, the selected folder is automatically set as the container for the
              network link.

The New Network Link dialog box appears. Enter the name of your link in
            the Name field. Enter the full path of the KMZ file in the Link
            field, or browse to the file location if the file is located on a network. You can use
            a URL to reference the KMZ, such as http://www.test.com/myKMZ.kmz. The 3D
            viewer immediately flies to the default view for the linked data.

Enter descriptive text or HTML.You can enter this data in the same way you would for
          a regular folder. See Editing Places and Folders for more
          information.

(Optional) Click the View tab to change the default view that this network link
          presents to users. Click Snapshot current view to use your current view in
          Google Earth. If your network link has more than one placemark, click Reset to
          display all these placemarks to users.

          Note - The text you enter in this description is your description of the
          link only and is not viewable by anyone else linking to the KMZ file. Only you will be
          able to see the description you enter here (unless you email your link folder to other
          people). This is similar to creating a bookmark for a web page and then adding a
          descriptive note about the bookmark.

          ©2010 Google - Privacy Policy -
          Terms and Conditions - About Google

      Updated on

redpajama_set_name: RedPajamaGithub


text:
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008 spectralmind
// All rights reserved.
//
// ------------------------------------------------------------------------
// tAudioformat.h
//
// struct that encapsulates info about audio stream (birate, etc)
// ------------------------------------------------------------------------
//
// $Id$
//
//
//
//
//
//
//
///////////////////////////////////////////////////////////////////////////

#pragma once

#include <string>

#include "smafeExportDefs.h"

//------------------------------------------------
/** info about audio stream (birate, etc)*/
class DLLEXPORT tAudioformat{
public:
	int iChannels, iSamplerate, iDatasize, iBitsPerSample, iBitrate;
	unsigned long ulNumSamples;
	std::string label, encoding;

	std::string getSummary(void) {
		char ad_string[250];
		sprintf(ad_string, "samplefrequency: %i, channels: %i, bits/sample: %i, bitrate: %i, #samples: %ul, encoding: %s",
				iSamplerate,
				iChannels,
				iBitsPerSample,
				iBitrate,
				ulNumSamples,
				encoding.c_str()
				);

		return std::string(ad_string);

	}
};


text:
local ngx_now = ngx.now
local req_get_method = ngx.req.get_method
local req_start_time = ngx.req.start_time
local req_get_headers = ngx.req.get_headers
local res_get_headers = ngx.resp.get_headers

local _M = {}

function _M.serialize(ngx)
  local runscope_ctx = ngx.ctx.runscope or {}

  return {
    request = {
      url = ngx.var.scheme.."://"..ngx.var.host..":"..ngx.var.server_port..ngx.var.request_uri,
      method = req_get_method(),
      headers = req_get_headers(),
      body = runscope_ctx.req_body,
      timestamp = req_start_time(),
      form = runscope_ctx.req_post_args
    },
    response = {
      status = ngx.status,
      headers = res_get_headers(),
      size_bytes = ngx.var.body_bytes_sent,
      body = runscope_ctx.res_body,
      timestamp = ngx_now(),
      response_time = ngx.var.request_time * 1
    }
  }
end

return _M


text:
"""Contains the base Layer class, from which all layers inherit.

This is a private class and its internal implementation is subject to changes
in the future.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import functools
import inspect
import re
from six.moves import xrange  # pylint: disable=redefined-builtin
import numpy as np
import six

from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import variables as tf_variables
from tensorflow.python.ops import variable_scope as vs

class _Layer(object):
  """Base layer class.

  WARNING: Do not subclass this layer unless you know what you are doing:
  the API is subject to future changes.

  This is the class from which all layers inherit, implementing common
  infrastructure functionality.

  A layer is a class implementing common neural networks operations, such
  as convolution, batch norm, etc. These operations require managing variables,
  losses, and updates, as well as applying TensorFlow ops to input tensors.

  Properties:
    trainable: Whether the layer should be trained (boolean).
    name: The name of the layer (string).
    dtype: Default dtype of the layer (dtypes.float32).
    trainable_variables: List of trainable variables.
    non_trainable_variables: List of non-trainable variables.
    variables: List of all variables of this layer, trainable and non-trainable.
    updates: List of update ops of this layer.
    losses: List of losses added by this layer.
  """

  def __init__(self, trainable=True, name=None,
               dtype=dtypes.float32, **kwargs):
    # We use a kwargs dict here because these kwargs only exist
    # for compatibility reasons.
    # The list of kwargs is subject to changes in the future.
    # We do not want to commit to it or to expose the list to users at all.
    # Note this is exactly as safe as defining kwargs in the function signature,
    # the only difference being that the list of valid kwargs is defined
    # below rather rather in the signature, and default values are defined
    # in calls to kwargs.get().
    allowed_kwargs = {
        '_scope',
        '_reuse',
    }
    for kwarg in kwargs:
      if kwarg not in allowed_kwargs:
        raise TypeError('Keyword argument not understood:', kwarg)

    self._trainable = trainable
    self._built = False
    self._trainable_variables = []
    self._non_trainable_variables = []
    self._updates = []
    self._losses = []
    self._reuse = kwargs.get('_reuse')
    self._dtype = dtype

    # Determine base name (non-unique).
    base_name = name
    if not name:
      base_name = _to_snake_case(self.__class__.__name__)

    # Determine variable scope.
    scope = kwargs.get('_scope')
    if scope:
      self._scope = next(vs.variable_scope(scope).gen)
    else:
      self._scope = next(vs.variable_scope(None, default_name=base_name).gen)

    # Unique name is borrowed from scope to match variable names.
    self._name = self._scope.name

  def __setattr__(self, name, value):
    if hasattr(self, name):
      # Only allow self to update its own attributes
      stack_0_locals = inspect.stack()[1][0].f_locals
      called_from_layer = stack_0_locals.get('self', None) is self
      if not called_from_layer:
        raise AttributeError('Read-only property cannot be set: %s' % name)
    super(_Layer, self).__setattr__(name, value)

  @property
  def name(self):
    return self._name

  @property
  def trainable_variables(self):
    return self._trainable_variables if self.trainable else []

  @property
  def non_trainable_variables(self):
    return self._non_trainable_variables if self.trainable else self.variables

  @property
  def variables(self):
    """Returns the list of all layer variables/weights.

    Returns:
      A list of variables.
    """
    return self._trainable_variables + self._non_trainable_variables

  @property
  def updates(self):
    return self._updates

  @property
  def losses(self):
    return self._losses

  @property
  def built(self):
    return self._built

  @property
  def trainable(self):
    return self._trainable

  @property
  def dtype(self):
    return self._dtype

  @property
  def weights(self):
    """Returns the list of all layer variables/weights.

    Returns:
      A list of variables.
    """
    return self.variables

  def build(self, _):
    """Creates the variables of the layer.
    """
    self._built = True

  def call(self, inputs, **kwargs):
    """The logic of the layer lives here.

    Arguments:
      inputs: input tensor(s).
     **kwargs: additional keyword arguments.

    Returns:
      Output tensor(s).
    """
    raise NotImplementedError

  def _add_variable(self, name, shape, dtype=None,
                    initializer=None, regularizer=None, trainable=True,
                    variable_getter=vs.get_variable):
    """Adds a new variable to the layer.

    Arguments:
      name: variable name.
      shape: variable shape.
      dtype: The type of the variable. Defaults to `self._dtype`.
      initializer: initializer instance (callable).
      regularizer: regularizer instance (callable).
      trainable: whether the variable should be part of the layer's
        "trainable_variables" (e.g. variables, biases)
        or "non_trainable_variables" (e.g. BatchNorm mean, stddev).
      variable_getter: The getter to use for TensorFlow variables.

    Returns:
      The created variable.
    """
    if dtype is None:
      dtype = self._dtype
    existing_variables = set(tf_variables.global_variables())
    variable = variable_getter(name,
                               shape=shape,
                               initializer=initializer,
                               dtype=dtype,
                               trainable=trainable and self.trainable)
    # TODO(sguada) fix name = variable.op.name
    if regularizer:
      if not self._reuse and variable not in existing_variables:
        # To match the behavior of tf.get_variable(), we only
        # apply regularization if the variable is newly created.
        if isinstance(variable, tf_variables.PartitionedVariable):
          for v in variable:
            with ops.colocate_with(v.op):
              with ops.name_scope(name + '/Regularizer'):
                regularization = regularizer(v)
            if regularization is not None:
              self._losses.append(regularization)
              _add_elements_to_collection(
                  regularization, ops.GraphKeys.REGULARIZATION_LOSSES)
        else:
          with ops.colocate_with(variable.op):
            with ops.name_scope(name + '/Regularizer'):
              regularization = regularizer(variable)
          if regularization is not None:
            self._losses.append(regularization)
            _add_elements_to_collection(
                regularization, ops.GraphKeys.REGULARIZATION_LOSSES)
    if trainable:
      self._trainable_variables.append(variable)
    else:
      self._non_trainable_variables.append(variable)
    return variable

  def __call__(self, inputs, **kwargs):
    """Wraps `call`, applying pre- and post-processing steps.

    Arguments:
      inputs: input tensor(s).
      **kwargs: additional keyword arguments to be passed to `self.call`.

    Returns:
      Output tensor(s).
    """
    # Define a custom getter to override tf.get_variable when creating layer
    # variables. We respect current custom getter, if one is set.
    current_custom_getter = vs.get_variable_scope().custom_getter
    def variable_getter(getter, name, shape, dtype=None, initializer=None,
                        regularizer=None, trainable=True, **kwargs):
      if current_custom_getter is not None:
        getter = functools.partial(current_custom_getter, getter)
      return self._add_variable(
          name, shape, initializer=initializer, regularizer=regularizer,
          dtype=dtype, trainable=trainable,
          variable_getter=functools.partial(getter, **kwargs))

    # Build (if necessary) and call the layer, inside a variable scope.
    with vs.variable_scope(self._scope, reuse=self._reuse,
                           custom_getter=variable_getter) as scope:
      with ops.name_scope(scope.original_name_scope):
        if not self.built:
          input_list = _to_list(inputs)
          input_shapes = [x.get_shape() for x in input_list]
          if len(input_shapes) == 1:
            self.build(input_shapes[0])
          else:
            self.build(input_shapes)
          self._built = True
        outputs = self.call(inputs, **kwargs)

        # Apply activity regularization.
        # Note that it should be applied every time the layer creates a new
        # output, since it is output-specific.
        if hasattr(self, 'activity_regularizer') and self.activity_regularizer:
          output_list = _to_list(outputs)
          for output in output_list:
            with ops.name_scope('ActivityRegularizer'):
              activity_regularization = self.activity_regularizer(output)
            self._losses.append(activity_regularization)
            _add_elements_to_collection(
                activity_regularization, ops.GraphKeys.REGULARIZATION_LOSSES)

    # Update global default collections.
    _add_elements_to_collection(self.updates, ops.GraphKeys.UPDATE_OPS)
    return outputs

  def apply(self, inputs, **kwargs):
    """Apply the layer on a input.

    This simply wraps `self.__call__`.

    Arguments:
      inputs: Input tensor(s).
      **kwargs: additional keyword arguments to be passed to `self.call`.

    Returns:
      Output tensor(s).
    """
    return self.__call__(inputs, **kwargs)

def _to_snake_case(name):
  intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name)
  insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower()
  # If the class is private the name starts with "_" which is not secure
  # for creating scopes. We prefix the name with "private" in this case.
  if insecure[0] != '_':
    return insecure
  return 'private' + insecure

def _to_list(x):
  """This normalizes a list/tuple or single element into a list.

  If a single element is passed, we return
  a list of size 1 containing the element.

  Arguments:
    x: list or tuple or single element.

  Returns:
    A list.
  """
  if isinstance(x, (list, tuple)):
    return list(x)
  return [x]

def _add_elements_to_collection(elements, collections):
  elements = _to_list(elements)
  collections = _to_list(collections)
  for name in collections:
    collection = ops.get_collection_ref(name)
    collection_set = set(collection)
    for element in elements:
      if element not in collection_set:
        collection.append(element)


text:
package mongodb_test

import (
	"context"
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/gofrs/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/mainflux/mainflux/consumers/writers/mongodb"
	"github.com/mainflux/mainflux/pkg/transformers/json"
	"github.com/mainflux/mainflux/pkg/transformers/senml"

	log "github.com/mainflux/mainflux/logger"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	port        string
	addr        string
	testLog, _  = log.New(os.Stdout, log.Info.String())
	testDB      = "test"
	collection  = "messages"
	msgsNum     = 100
	valueFields = 5
	subtopic    = "topic"
)

var (
	v       float64 = 5
	stringV         = "value"
	boolV           = true
	dataV           = "base64"
	sum     float64 = 42
)

func TestSaveSenml(t *testing.T) {
	client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(addr))
	require.Nil(t, err, fmt.Sprintf("Creating new MongoDB client expected to succeed: %s.\n", err))

	db := client.Database(testDB)
	repo := mongodb.New(db)

	now := time.Now().Unix()
	msg := senml.Message{
		Channel:    "45",
		Publisher:  "2580",
		Protocol:   "http",
		Name:       "test name",
		Unit:       "km",
		Time:       13451312,
		UpdateTime: 5456565466,
	}
	var msgs []senml.Message

	for i := 0; i < msgsNum; i++ {
		// Mix possible values as well as value sum.
		count := i % valueFields
		switch count {
		case 0:
			msg.Subtopic = subtopic
			msg.Value = &v
		case 1:
			msg.BoolValue = &boolV
		case 2:
			msg.StringValue = &stringV
		case 3:
			msg.DataValue = &dataV
		case 4:
			msg.Sum = &sum
		}

		msg.Time = float64(now + int64(i))
		msgs = append(msgs, msg)
	}

	err = repo.Consume(msgs)
	assert.Nil(t, err, fmt.Sprintf("Save operation expected to succeed: %s.\n", err))

	count, err := db.Collection(collection).CountDocuments(context.Background(), bson.D{})
	assert.Nil(t, err, fmt.Sprintf("Querying database expected to succeed: %s.\n", err))
	assert.Equal(t, int64(msgsNum), count, fmt.Sprintf("Expected to have %d value, found %d instead.\n", msgsNum, count))
}

func TestSaveJSON(t *testing.T) {
	client, err := mongo.Connect(context.Background(), options.Client().ApplyURI(addr))
	require.Nil(t, err, fmt.Sprintf("Creating new MongoDB client expected to succeed: %s.\n", err))

	db := client.Database(testDB)
	repo := mongodb.New(db)

	chid, err := uuid.NewV4()
	require.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err))
	pubid, err := uuid.NewV4()
	require.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err))

	msg := json.Message{
		Channel:   chid.String(),
		Publisher: pubid.String(),
		Created:   time.Now().Unix(),
		Subtopic:  "subtopic/format/some_json",
		Protocol:  "mqtt",
		Payload: map[string]interface{}{
			"field_1": 123,
			"field_2": "value",
			"field_3": false,
			"field_4": 12.344,
			"field_5": map[string]interface{}{
				"field_1": "value",
				"field_2": 42,
			},
		},
	}

	now := time.Now().Unix()
	msgs := json.Messages{
		Format: "some_json",
	}

	for i := 0; i < msgsNum; i++ {
		msg.Created = now + int64(i)
		msgs.Data = append(msgs.Data, msg)
	}

	err = repo.Consume(msgs)
	assert.Nil(t, err, fmt.Sprintf("expected no error got %s\n", err))
}


text:
module Sunspot
  module Query
    #
    # A Group groups by the unique values of a given field, or by given queries.
    #
    class Group
      attr_accessor :limit, :truncate
      attr_reader :fields, :queries

      def initialize
        @sort = SortComposite.new
        @fields = []
        @queries = []
      end

      def add_field(field)
        if field.multiple?
          raise(ArgumentError, "#{field.name} cannot be used for grouping because it is a multiple-value field")
        end
        @fields << field
      end

      def add_query(query)
        @queries << query
      end

      def add_sort(sort)
        @sort << sort
      end

      def to_params
        params = {
          :group            => "true",
          :"group.ngroups"  => "true",
        }

        params.merge!(@sort.to_params("group."))
        params[:"group.field"] = @fields.map(&:indexed_name) if @fields.any?
        params[:"group.query"] = @queries.map(&:to_boolean_phrase) if @queries.any?
        params[:"group.limit"] = @limit if @limit
        params[:"group.truncate"] = @truncate if @truncate

        params
      end
    end
  end
end


text:
import PropTypes from 'prop-types'
import React from 'react'
import classNames from 'classnames'

// This is going to be smarter evntually
const Icon = ({ name, className, style }) => {
   let icon = null

   if (name) {
      const classes = `icon ${name}`
      icon = <span className={classNames(classes, className)} style={style} />
   }

   return icon
}

Icon.propTypes = {
   className: PropTypes.string,
   name: PropTypes.string,
   style: PropTypes.object
}

export default Icon


text:
import passport from 'passport';

// our packages
import {Classroom} from '../db';
import {asyncRequest} from '../util';

export default (app) => {
  app.post('/api/classroom/create', passport.authenticate('jwt', {session: false}), asyncRequest(async (req, res) => {
    // get classroom input
    const {name, description} = req.body;

    // make sure name is not empty
    if (!name || !name.length) {
      res.status(400).send({error: 'The classroom must have a name!'});
      return;
    }

    // create classroom
    const classroom = new Classroom({
      name,
      description,
      teacher: req.user.id,
      teacherName: req.user.login,
      chat: [],
      students: [],
    });

    // save classroom
    await classroom.save();
    try {
        // send classroom back
      res.send(classroom);
    } catch (e) {
      res.stats(400).send({error: e.toString()});
    }
    res.sendStatus(201);
  }));
};


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">

  <title>4.0 beta2 - Feature layer</title>

  <link rel="stylesheet" href="//js.arcgis.com/4.0beta2/esri/css/main.css">
  <link rel="stylesheet" href="../commons/css/style.css">
  <link rel="stylesheet" href="../commons/libs/codemirror/codemirror.css">
  <link rel="stylesheet" href="../commons/libs/codemirror/monokai.css">

          <textarea id="codemirror">
var map = new Map({
  basemap: "hybrid"
});

var layer = new FeatureLayer({
  url: "http://services.arcgis.com/nzS0F0zdNLvs7nc8/ArcGIS/rest/services/05_HurricaneAndrew_1992/FeatureServer/0",
  mode: FeatureLayer.MODE_SNAPSHOT
});

map.add(layer);

var view = new SceneView({
  container: "viewDiv",
  map: map,
  camera: {
    position: [ -45.23, -1.08, 6270495 ],
    heading: 335,
    tilt: 20
  }
});
          </textarea>

          4.0 beta2

          Feature layer


text:
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#pragma once

#include "IMergeActorsTool.h"
#include "MeshUtilities.h"

/**
 * Mesh Merging Tool
 */
class FMeshMergingTool : public IMergeActorsTool
{
	friend class SMeshMergingDialog;

public:

	FMeshMergingTool();

	// IMergeActorsTool interface
	virtual TSharedRef<SWidget> GetWidget() override;
	virtual FName GetIconName() const override { return "MergeActors.MeshMergingTool"; }
	virtual FText GetTooltipText() const override;
	virtual FString GetDefaultPackageName() const override;
	virtual bool RunMerge(const FString& PackageName) override;

private:

	/** Current mesh merging settings */
	FMeshMergingSettings MergingSettings;

	/** Whether to spawn merged actor in the world */
	bool bPlaceInWorld;

	bool bExportSpecificLOD;
	int32 ExportLODIndex;
};


text: Test application for 4xxi team.


text:
<?php

namespace Flarum\Discussion;

use Carbon\Carbon;
use Flarum\Database\AbstractModel;
use Flarum\Database\ScopeVisibilityTrait;
use Flarum\Discussion\Event\Deleted;
use Flarum\Discussion\Event\Hidden;
use Flarum\Discussion\Event\Renamed;
use Flarum\Discussion\Event\Restored;
use Flarum\Discussion\Event\Started;
use Flarum\Event\GetModelIsPrivate;
use Flarum\Foundation\EventGeneratorTrait;
use Flarum\Notification\Notification;
use Flarum\Post\MergeableInterface;
use Flarum\Post\Post;
use Flarum\User\User;
use Flarum\Util\Str;

/**
 * @property int $id
 * @property string $title
 * @property string $slug
 * @property int $comment_count
 * @property int $participant_count
 * @property int $post_number_index
 * @property \Carbon\Carbon $created_at
 * @property int|null $user_id
 * @property int|null $first_post_id
 * @property \Carbon\Carbon|null $last_posted_at
 * @property int|null $last_posted_user_id
 * @property int|null $last_post_id
 * @property int|null $last_post_number
 * @property \Carbon\Carbon|null $hidden_at
 * @property int|null $hidden_user_id
 * @property UserState|null $state
 * @property \Illuminate\Database\Eloquent\Collection $posts
 * @property \Illuminate\Database\Eloquent\Collection $comments
 * @property \Illuminate\Database\Eloquent\Collection $participants
 * @property Post|null $firstPost
 * @property User|null $user
 * @property Post|null $lastPost
 * @property User|null $lastPostedUser
 * @property \Illuminate\Database\Eloquent\Collection $readers
 * @property bool $is_private
 */
class Discussion extends AbstractModel
{
    use EventGeneratorTrait;
    use ScopeVisibilityTrait;

    /**
     * An array of posts that have been modified during this request.
     *
     * @var array
     */
    protected $modifiedPosts = [];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['created_at', 'last_posted_at', 'hidden_at'];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_private' => 'boolean'
    ];

    /**
     * The user for which the state relationship should be loaded.
     *
     * @var User
     */
    protected static $stateUser;

    /**
     * Boot the model.
     *
     * @return void
     */
    public static function boot()
    {
        parent::boot();

        static::deleting(function (self $discussion) {
            Notification::whereSubjectModel(Post::class)
                ->whereIn('subject_id', function ($query) use ($discussion) {
                    $query->select('id')->from('posts')->where('discussion_id', $discussion->id);
                })
                ->delete();
        });

        static::deleted(function (self $discussion) {
            $discussion->raise(new Deleted($discussion));

            Notification::whereSubject($discussion)->delete();
        });

        static::saving(function (self $discussion) {
            $event = new GetModelIsPrivate($discussion);

            $discussion->is_private = static::$dispatcher->until($event) === true;
        });
    }

    /**
     * Start a new discussion. Raises the DiscussionWasStarted event.
     *
     * @param string $title
     * @param User $user
     * @return static
     */
    public static function start($title, User $user)
    {
        $discussion = new static;

        $discussion->title = $title;
        $discussion->created_at = Carbon::now();
        $discussion->user_id = $user->id;

        $discussion->setRelation('user', $user);

        $discussion->raise(new Started($discussion));

        return $discussion;
    }

    /**
     * Rename the discussion. Raises the DiscussionWasRenamed event.
     *
     * @param string $title
     * @return $this
     */
    public function rename($title)
    {
        if ($this->title !== $title) {
            $oldTitle = $this->title;
            $this->title = $title;

            $this->raise(new Renamed($this, $oldTitle));
        }

        return $this;
    }

    /**
     * Hide the discussion.
     *
     * @param User $actor
     * @return $this
     */
    public function hide(User $actor = null)
    {
        if (! $this->hidden_at) {
            $this->hidden_at = Carbon::now();
            $this->hidden_user_id = $actor ? $actor->id : null;

            $this->raise(new Hidden($this));
        }

        return $this;
    }

    /**
     * Restore the discussion.
     *
     * @return $this
     */
    public function restore()
    {
        if ($this->hidden_at !== null) {
            $this->hidden_at = null;
            $this->hidden_user_id = null;

            $this->raise(new Restored($this));
        }

        return $this;
    }

    /**
     * Set the discussion's first post details.
     *
     * @param Post $post
     * @return $this
     */
    public function setFirstPost(Post $post)
    {
        $this->created_at = $post->created_at;
        $this->user_id = $post->user_id;
        $this->first_post_id = $post->id;

        return $this;
    }

    /**
     * Set the discussion's last post details.
     *
     * @param Post $post
     * @return $this
     */
    public function setLastPost(Post $post)
    {
        $this->last_posted_at = $post->created_at;
        $this->last_posted_user_id = $post->user_id;
        $this->last_post_id = $post->id;
        $this->last_post_number = $post->number;

        return $this;
    }

    /**
     * Refresh a discussion's last post details.
     *
     * @return $this
     */
    public function refreshLastPost()
    {
        /** @var Post $lastPost */
        if ($lastPost = $this->comments()->latest()->first()) {
            $this->setLastPost($lastPost);
        }

        return $this;
    }

    /**
     * Refresh the discussion's comment count.
     *
     * @return $this
     */
    public function refreshCommentCount()
    {
        $this->comment_count = $this->comments()->count();

        return $this;
    }

    /**
     * Refresh the discussion's participant count.
     *
     * @return $this
     */
    public function refreshParticipantCount()
    {
        $this->participant_count = $this->participants()->count('users.id');

        return $this;
    }

    /**
     * Save a post, attempting to merge it with the discussion's last post.
     *
     * The merge logic is delegated to the new post. (As an example, a
     * DiscussionRenamedPost will merge if adjacent to another
     * DiscussionRenamedPost, and delete if the title has been reverted
     * completely.)
     *
     * @param \Flarum\Post\MergeableInterface $post The post to save.
     * @return Post The resulting post. It may or may not be the same post as
     *     was originally intended to be saved. It also may not exist, if the
     *     merge logic resulted in deletion.
     */
    public function mergePost(MergeableInterface $post)
    {
        $lastPost = $this->posts()->latest()->first();

        $post = $post->saveAfter($lastPost);

        return $this->modifiedPosts[] = $post;
    }

    /**
     * Get the posts that have been modified during this request.
     *
     * @return array
     */
    public function getModifiedPosts()
    {
        return $this->modifiedPosts;
    }

    /**
     * Define the relationship with the discussion's posts.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function posts()
    {
        return $this->hasMany(Post::class);
    }

    /**
     * Define the relationship with the discussion's publicly-visible comments.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function comments()
    {
        return $this->posts()
            ->where('is_private', false)
            ->whereNull('hidden_at')
            ->where('type', 'comment');
    }

    /**
     * Query the discussion's participants (a list of unique users who have
     * posted in the discussion).
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function participants()
    {
        return User::join('posts', 'posts.user_id', '=', 'users.id')
            ->where('posts.discussion_id', $this->id)
            ->where('posts.is_private', false)
            ->where('posts.type', 'comment')
            ->select('users.*')
            ->distinct();
    }

    /**
     * Define the relationship with the discussion's first post.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function firstPost()
    {
        return $this->belongsTo(Post::class, 'first_post_id');
    }

    /**
     * Define the relationship with the discussion's author.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Define the relationship with the discussion's last post.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function lastPost()
    {
        return $this->belongsTo(Post::class, 'last_post_id');
    }

    /**
     * Define the relationship with the discussion's most recent author.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function lastPostedUser()
    {
        return $this->belongsTo(User::class, 'last_posted_user_id');
    }

    /**
     * Define the relationship with the discussion's most relevant post.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function mostRelevantPost()
    {
        return $this->belongsTo(Post::class, 'most_relevant_post_id');
    }

    /**
     * Define the relationship with the discussion's readers.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function readers()
    {
        return $this->belongsToMany(User::class);
    }

    /**
     * Define the relationship with the discussion's state for a particular
     * user.
     *
     * If no user is passed (i.e. in the case of eager loading the 'state'
     * relation), then the static `$stateUser` property is used.
     *
     * @see Discussion::setStateUser()
     *
     * @param User|null $user
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function state(User $user = null)
    {
        $user = $user ?: static::$stateUser;

        return $this->hasOne(UserState::class)->where('user_id', $user ? $user->id : null);
    }

    /**
     * Get the state model for a user, or instantiate a new one if it does not
     * exist.
     *
     * @param User $user
     * @return \Flarum\Discussion\UserState
     */
    public function stateFor(User $user)
    {
        $state = $this->state($user)->first();

        if (! $state) {
            $state = new UserState;
            $state->discussion_id = $this->id;
            $state->user_id = $user->id;
        }

        return $state;
    }

    /**
     * Set the user for which the state relationship should be loaded.
     *
     * @param User $user
     */
    public static function setStateUser(User $user)
    {
        static::$stateUser = $user;
    }

    /**
     * Set the discussion title.
     *
     * This automatically creates a matching slug for the discussion.
     *
     * @param string $title
     */
    protected function setTitleAttribute($title)
    {
        $this->attributes['title'] = $title;
        $this->slug = Str::slug($title);
    }
}


text:
@interface MOBProjectionEPSG32253 : MOBProjection

@end


text:
import { Component, OnInit } from '@angular/core';
import { AuthToken } from "../../service";
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private authToken:AuthToken) { }
  login(){
    this.authToken.login()
  }

  ngOnInit() {
    // console.log(this.authToken)
  }

}


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

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Apple Hearth Bread</title>
      <categories>
        <cat>Breads</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1 1/2</qty>
          <unit/></amt>
        <item>To 1 3/4 cups unsifted all-purpose</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Flour</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>package</unit></amt>
        <item>Rapid-rising dry yeast</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>teaspoons</unit></amt>
        <item>Salt</item></ing>
      <ing>
        <amt>
          <qty>2/3</qty>
          <unit>cups</unit></amt>
        <item>Very warm water (120 degrees to</item></ing>
      <ing>
        <amt>
          <qty>130</qty>
          <unit/></amt>
        <item>Degrees F)</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Olive oil</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Honey</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Butter</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>large</unit></amt>
        <item>Golden delicious or other</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Sweet firm apple, peeled, cored,</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>And cut into 1/4-inch thick slices</item></ing>
      <ing>
        <amt>
          <qty>1/4</qty>
          <unit>teaspoons</unit></amt>
        <item>Coarse (kosher) salt</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>(optional)</item></ing></ingredients>
    <directions>
      <step>  Sweet apples and salty bread provide an intriguing contrast in taste. To
  ensure that the hearth bread remains light and crisp, keep the dough soft:
  Don't work in too much flour and knead it gently.

  Makes 1 loaf (6 servings)

  1. In large bowl of heavy-duty electric mixer, combine 1 1/2 cups flour,
  the yeast, and salt. Slowly beat in water, 1/4 cup olive oil, and the
  honey; vigorously beat mixture 10 minutes. Cover bowl with clean cloth and
  let dough rise in warm place, away from drafts, 40 minutes.

  2. Meanwhile, in a large skillet, melt butter. Add apple slices and saute'
  until very lightly browned; set aside.

  3. After dough has risen 40 minutes, turn out onto floured surface. Gently
  knead in as much of remaining 1/4 cup flour as necessary to form a very
  soft dough - about 1 minute. Gently work apple slices into the dough.

  4. Lightly oil large baking sheet. With floured fingers, shape dough into a
  9 inch round on oiled sheet. Cover with clean cloth and let rise in warm
  place, away from drafts, until double in size - about 30 minutes.

  5. Heat oven to 400 degrees F. With pastry brush, coat top of dough round
  with 2 tablespoons olive oil; sprinkle with coarse salt, if desired. Bake
  15 to 20 minutes or until hearth bread is browned.

  6. Drizzle hearth bread with remaining 2 tablespoons olive oil and serve
  warm.

  Nutritional information per serving - protein: 4 grams; fat: 20 grams;
  carbohydrate: 34 grams; fiber: 2 grams; sodium: 195 milligrams;
  cholesterol: 5 milligrams; calories: 335.

  From: Country Living, September, 1992.

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

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


text:
<#
.Synopsis
    This is a setup script that will run before the VM is booted,
	that will create and add a VHDx disk to the VM.

.Description
     This is a setup script that will run before the VM is booted.
     The script will create a minimum 3GB vhdx file, and mount it to
	 the specified hard drive. If the hard drive does not exist, it
     will be created.

     The .xml entry to specify this startup script would be:
         <setupScript>SetupScripts\Add-VHDXHardDisk.ps1</setupScript>

   The  scripts will always pass the vmName, hvServer, and a
   string of testParams from the test definition separated by
   semicolons. The testParams for this script identify disk
   controllers, hard drives, .vhd type, and sector size.  The
   testParamss have the format of:

      ControllerType=Controller Index, Lun or Port, vhd type, sector size, disk size

   The following are some examples:
   SCSI=0,0,Dynamic,4096,3GB : Add SCSI Controller 0, hard drive on Lun 0, .vhdx type Dynamic, sector size of 4096, 3GB disk size
   SCSI=1,0,Fixed,512,3GB    : Add SCSI Controller 1, hard drive on Lun 0, .vhdx type Fixed, sector size of 512 bytes, 3GB disk size
   IDE=0,1,Dynamic,512,3GB   : Add IDE hard drive on IDE 0, port 1, .vhdx type Fixed, sector size of 512 bytes, 3GB disk size
   IDE=1,1,Fixed,4096,3GB    : Add IDE hard drive on IDE 1, port 1, .vhdx type Fixed, sector size of 4096 bytes, 3GB disk size

   The following testParams:
     <testParams>
         <param>SCSI=0,0,Dynamic,4096,3GB</param>
         <param>IDE=1,1,Fixed,512,3GB</param>
     <testParams>

   will be parsed into the following string by the ICA scripts and passed
   to the setup script:

       "SCSI=0,0,Dynamic,4096,3GB;IDE=1,1,Fixed,512,3GB"

   All setup and cleanup scripts must return a boolean ($true or $false)
   to indicate if the script completed successfully.

   Where
      ControllerType   = The type of disk controller.  IDE or SCSI
      Controller Index = The index of the controller, 0 based.
                         Note: IDE can be 0 - 1, SCSI can be 0 - 3
      Lun or Port      = The IDE port number of SCSI Lun number
      Vhd Type         = Type of VHD to use.
                         Valid VHD types are:
                             Dynamic
                             Fixed
      Disk zise        = Size of the VHDx files
                         Valid size sample:
                             3GB
                             1TB
                             100MB
    Location            = Where you want the disk to be created

   The following are some examples:
   SCSI=0,0,Dynamic,4096,3GB,H:\ssd\ : Add a hard drive on SCSI controller 0, Lun 0, vhd type of Dynamic disk with logical sector size of 4096, 3GB disk size
   IDE=1,1,Fixed,40963GB,D:\Virtual Hard Disks\  : Add a hard drive on IDE controller 1, IDE port 1, vhd type of Fixed disk with logical sector size of 4096, 3GB disk size

.Parameter vmName
    Name of the VM to add the disk.

.Parameter hvServer
    Name of the Hyper-V server hosting the VM.

.Parameter testParams
    Test data for this test case

.Example
    setupScripts\Add-VHDXHardDiskWithLocation -vmName VM_NAME -hvServer HYPERV_SERVER -testParams "SCSI=0,0,Dynamic,4096,3GB,H:\ssd\;sshkey=YOUR_KEY.ppk;ipv4=255.255.255.255"
#>
############################################################################

param([string] $vmName, [string] $hvServer, [string] $testParams)

$global:MinDiskSize = 3GB
$global:DefaultDynamicSize = 127GB

function ConvertStringToUInt64([string] $str)
{
    $uint64Size = $null

    #
    # Make sure we received a string to convert
    #
    if (-not $str)
    {
        Write-Error -Message "ConvertStringToUInt64() - input string is null" -Category InvalidArgument -ErrorAction SilentlyContinue
        return $null
    }

    if ($newSize.EndsWith("MB"))
    {
        $num = $newSize.Replace("MB","")
        $uint64Size = ([Convert]::ToUInt64($num)) * 1MB
    }
    elseif ($newSize.EndsWith("GB"))
    {
        $num = $newSize.Replace("GB","")
        $uint64Size = ([Convert]::ToUInt64($num)) * 1GB
    }
    elseif ($newSize.EndsWith("TB"))
    {
        $num = $newSize.Replace("TB","")
        $uint64Size = ([Convert]::ToUInt64($num)) * 1TB
    }
    else
    {
        Write-Error -Message "Invalid newSize parameter: ${str}" -Category InvalidArgument -ErrorAction SilentlyContinue
        return $null
    }

    return $uint64Size
}

############################################################################
#
# CreateHardDrive
#
# Description
#     If the -SCSI options is false, an IDE drive is created
#
############################################################################
function CreateHardDrive( [string] $vmName, [string] $server, [System.Boolean] $SCSI, [int] $ControllerID,
                          [int] $Lun, [string] $vhdType, [string] $sectorSizes, [String] $newSize, [String] $location)
{
    $retVal = $false
    $initialSize = $newSize
    "CreateHardDrive $vmName $server $scsi $controllerID $lun $vhdType"

    #
    # Make sure it's a valid IDE ControllerID.  For IDE, it must 0 or 1.
    # For SCSI it must be 0, 1, 2, or 3
    #
    $controllerType = "IDE"
    if ($SCSI)
    {
        $controllerType = "SCSI"

        if ($ControllerID -lt 0 -or $ControllerID -gt 3)
        {
            "Error: CreateHardDrive was passed an bad SCSI Controller ID: $ControllerID"
            return $false
        }

        #
        # Create the SCSI controller if needed
        #
        $sts = CreateController $vmName $server $controllerID
        if (-not $sts[$sts.Length-1])
        {
            "Error: Unable to create SCSI controller $controllerID"
            return $false
        }
    }
    else # Make sure the controller ID is valid for IDE
    {
        if ($ControllerID -lt 0 -or $ControllerID -gt 1)
        {
            "Error: CreateHardDrive was passed an invalid IDE Controller ID: $ControllerID"
            return $False
        }
    }

    #
    # If the hard drive exists return an error.
    #
    $drive = Get-VMHardDiskDrive -VMName $vmName -ControllerNumber $controllerID -ControllerLocation $Lun -ControllerType $controllerType -ComputerName $server

    if ($drive)
    {
        "Error: drive $controllerType $controllerID $Lun already exists"
        return $False
    }
    else
    {

        $newVHDSize = ConvertStringToUInt64 $newSize
        if (! $location.EndsWith("\\"))
        {
            $location += "\";
        }
        $vhdName = $location + $vmName + "-" + $controllerType + "-" + $controllerID + "-" + $lun + "-" + $vhdType + ".vhdx"

        if(Test-Path $vhdName)
        {
            Remove-Item $vhdName
        }

        $fileInfo = GetRemoteFileInfo -filename $vhdName -server $server
        if (-not $fileInfo)
        {
            $nv = New-Vhd -Path $vhdName -size $newVHDSize -Dynamic:($vhdType -eq "Dynamic") -LogicalSectorSize ([int] $sectorSize)  -ComputerName $server
            if ($nv -eq $null)
            {
                "Error: New-VHD failed to create the new .vhd file: $($vhdName)"
                return $False
            }
        }

        $error.Clear()
        Add-VMHardDiskDrive -VMName $vmName -Path $vhdName -ControllerNumber $controllerID -ControllerLocation $Lun -ControllerType $controllerType -ComputerName $server
        if ($error.Count -gt 0)
        {
            "Error: Add-VMHardDiskDrive failed to add drive on ${controllerType} ${controllerID} ${Lun}s"
            $error[0].Exception
            return $retVal
        }

        "Success"
        $retVal = $True
    }

    return $retVal
}

############################################################################
#
# Main entry point for script
#
############################################################################
$retVal = $true

#
# Check input arguments
#
if ($vmName -eq $null -or $vmName.Length -eq 0)
{
    "Error: VM name is null"
    return $False
}

if ($hvServer -eq $null -or $hvServer.Length -eq 0)
{
    "Error: hvServer is null"
    return $False
}

if ($testParams -eq $null -or $testParams.Length -lt 3)
{
    "Error: setupScript requires test params"
    return $False
}

# Source TCUtils.ps1 for common functions
if (Test-Path ".\setupScripts\TCUtils.ps1") {
	. .\setupScripts\TCUtils.ps1
	"Info: Sourced TCUtils.ps1"
}
else {
	"Error: Could not find setupScripts\TCUtils.ps1"
	return $false
}

#
# Parse the testParams string
#
$params = $testParams.Split(';')
foreach ($p in $params)
{
    if ($p.Trim().Length -eq 0)
    {
        continue
    }

    $temp = $p.Trim().Split('=')

    if ($temp.Length -ne 2)
    {
    "Warn : test parameter '$p' is being ignored because it appears to be malformed"
    continue
    }

    $controllerType = $temp[0].Trim()
    if (@("IDE", "SCSI") -notcontains $controllerType)
    {
        # Not a test parameter we are concerned with
        continue
    }

    $SCSI = $false
    if ($controllerType -eq "SCSI")
    {
        $SCSI = $true
    }

    $diskArgs = $temp[1].Trim().Split(',')

    if ($diskArgs.Length -lt 5)
    {
        "Error: Incorrect number of arguments: $p"
        $retVal = $false
        continue
    }

    $controllerID = $diskArgs[0].Trim()
    $lun = $diskArgs[1].Trim()
    $vhdType = $diskArgs[2].Trim()

    $sectorSize = 512
    $sectorSize = $diskArgs[3].Trim()
    if ($sectorSize -ne "4096" -and $sectorSize -ne "512")
    {
        "Error: bad sector size: ${sectorSize}"
        return $False
    }
    $VHDxSize = $diskArgs[4].Trim()
    # Added default location support if location param not set
    $hostInfo = Get-VMHost -ComputerName $hvServer
    if (-not $hostInfo)
    {
        "Error: Unable to collect Hyper-V settings for ${hvServer}"
        return $false
    }
    else
    {
        $location = $hostInfo.VirtualHardDiskPath
        if (-not $location.EndsWith("\"))
        {
            $location += "\"
        }
    }
    if ($diskArgs.Length -eq 6)
    {
        $location = $diskArgs[5].Trim()
    }

    if (@("Fixed", "Dynamic", "PassThrough") -notcontains $vhdType)
    {
        "Error: Unknown disk type: $p"
        $retVal = $false
        continue
    }

    "CreateHardDrive $vmName $hvServer $scsi $controllerID $Lun $vhdType $sectorSize"
    $sts = CreateHardDrive -vmName $vmName -server $hvServer -SCSI:$SCSI -ControllerID $controllerID -Lun $Lun -vhdType $vhdType -sectorSize $sectorSize -newSize $VHDxSize -location $location
    if (-not $sts[$sts.Length-1])
    {
        write-output "Failed to create hard drive"
        $sts
        $retVal = $false
        continue
    }
}

return $retVal


text:
namespace Cvdm.Scheduler
{
    using System;
    using System.Collections.Generic;
    using System.Threading;

    using Cvdm.Scheduler.Helpers;

    using JetBrains.Annotations;

    /// <inheritdoc />
    /// <remarks>
    ///     This class keeps internal references to all created timers, so you don't have to do that yourself if
    ///     the scheduler lives at least as long as the timer (e.g. if the scheduler is a singleton component in your
    ///     application).
    /// </remarks>
    public class Scheduler : IScheduler
    {
        // Keep a reference to all timers to avoid garbage collection
        [UsedImplicitly] private readonly IList<Timer> timers = new List<Timer>();

        private readonly ITimerFactory timerFactory = new TimerFactory();
        private readonly ITimeProvider time = new TimeProvider();

        /// <summary>Initializes an instance of the <see cref="Scheduler" /> class.</summary>
        public Scheduler()
        {
        }

        internal Scheduler(ITimerFactory timerFactory, ITimeProvider time)
        {
            this.timerFactory = timerFactory;
            this.time = time;
        }

        /// <inheritdoc />
        public Timer ScheduleRecurring(TimerCallback callback, object state, DateTimeOffset startTime, TimeSpan interval)
        {
            if (state == null) throw new ArgumentNullException(nameof(state));

            if (interval.TotalMilliseconds <= 0)
                throw new ArgumentOutOfRangeException(nameof(interval), interval, "Interval must be positive.");

            return this.ScheduleInner(callback, state, startTime, interval);
        }

        /// <inheritdoc />
        public Timer ScheduleRecurring(TimerCallback callback, object state, TimeSpan startAfter, TimeSpan interval)
        {
            if (state == null)
                throw new ArgumentNullException(nameof(state), "State cannot be null. Use the stateless overload instead.");

            if (interval.TotalMilliseconds <= 0)
                throw new ArgumentOutOfRangeException(nameof(interval), interval, "Interval must be positive.");

            return this.ScheduleInner(callback, state, startAfter, interval);
        }

        /// <inheritdoc />
        public Timer ScheduleRecurring(Action callback, DateTimeOffset startTime, TimeSpan interval)
        {
            if (callback == null) throw new ArgumentNullException(nameof(callback));

            if (interval.TotalMilliseconds <= 0)
                throw new ArgumentOutOfRangeException(nameof(interval), interval, "Interval must be positive.");

            return this.ScheduleInner(_ => callback(), null, startTime, interval);
        }

        /// <inheritdoc />
        public Timer ScheduleRecurring(Action callback, TimeSpan startAfter, TimeSpan interval)
        {
            if (callback == null) throw new ArgumentNullException(nameof(callback));

            if (interval.TotalMilliseconds <= 0)
                throw new ArgumentOutOfRangeException(nameof(interval), interval, "Interval must be positive.");

            return this.ScheduleInner(_ => callback(), null, startAfter, interval);
        }

        /// <inheritdoc />
        public Timer ScheduleOneTime(TimerCallback callback, object state, DateTimeOffset startTime)
        {
            if (state == null)
                throw new ArgumentNullException(nameof(state), "State cannot be null. Use the stateless overload instead.");

            return this.ScheduleInner(callback, state, startTime, TimeSpan.FromMilliseconds(-1));
        }

        /// <inheritdoc />
        public Timer ScheduleOneTime(TimerCallback callback, object state, TimeSpan startAfter)
        {
            if (state == null)
                throw new ArgumentNullException(nameof(state), "State cannot be null. Use the stateless overload instead.");

            return this.ScheduleInner(callback, state, startAfter, TimeSpan.FromMilliseconds(-1));
        }

        /// <inheritdoc />
        public Timer ScheduleOneTime(Action callback, DateTimeOffset startTime)
        {
            if (callback == null) throw new ArgumentNullException(nameof(callback));

            return this.ScheduleInner(_ => callback(), null, startTime, TimeSpan.FromMilliseconds(-1));
        }

        /// <inheritdoc />
        public Timer ScheduleOneTime(Action callback, TimeSpan startAfter)
        {
            if (callback == null) throw new ArgumentNullException(nameof(callback));

            return this.ScheduleInner(_ => callback(), null, startAfter, TimeSpan.FromMilliseconds(-1));
        }

        private Timer ScheduleInner(
            [NotNull] TimerCallback callback,
            [CanBeNull] object state,
            TimeSpan startAfter,
            TimeSpan interval)
        {
            if (callback == null) throw new ArgumentNullException(nameof(callback));

            if (startAfter.TotalMilliseconds < 0)
                throw new ArgumentOutOfRangeException(nameof(startAfter), "Delay must not be negative.");

            Timer timer = this.timerFactory.Create(callback, state, startAfter, interval);
            this.timers.Add(timer);
            return timer;
        }

        private Timer ScheduleInner(
            [NotNull] TimerCallback callback,
            [CanBeNull] object state,
            DateTimeOffset startTime,
            TimeSpan interval)
        {
            TimeSpan startAfter = startTime - this.time.Now;
            if (startAfter.TotalMilliseconds < 0)
                throw new ArgumentOutOfRangeException(nameof(startTime), "Start time must be in the future.");

            return this.ScheduleInner(callback, state, startAfter, interval);
        }
    }
}


text:
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

namespace Lumix
{
	[NativeComponent( Type = "physical_heightfield")]
	public class PhysicalHeightfield :Component
	{
		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static string getHeightmapSource(IntPtr scene, int cmp);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void setHeightmapSource(IntPtr scene, int cmp, string value);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static float getHeightmapXZScale(IntPtr scene, int cmp);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void setHeightmapXZScale(IntPtr scene, int cmp, float value);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static float getHeightmapYScale(IntPtr scene, int cmp);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void setHeightmapYScale(IntPtr scene, int cmp, float value);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static int getHeightfieldLayer(IntPtr scene, int cmp);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static void setHeightfieldLayer(IntPtr scene, int cmp, int value);

		public static string GetCmpType{ get { return "physical_heightfield"; } }

		public PhysicsScene Scene
		{
			 get { return new PhysicsScene(scene_); }
		}
		/// <summary>
		/// Gets or sets the Heightmap
		/// </summary>
		public string Heightmap
		{
			get { return getHeightmapSource(scene_, componentId_); }
			set { setHeightmapSource(scene_, componentId_, value); }
		}

		/// <summary>
		/// Gets or sets the XZScale
		/// </summary>
		public float XZScale
		{
			get { return getHeightmapXZScale(scene_, componentId_); }
			set { setHeightmapXZScale(scene_, componentId_, value); }
		}

		/// <summary>
		/// Gets or sets the YScale
		/// </summary>
		public float YScale
		{
			get { return getHeightmapYScale(scene_, componentId_); }
			set { setHeightmapYScale(scene_, componentId_, value); }
		}

		/// <summary>
		/// Gets or sets the Layer
		/// </summary>
		public int Layer
		{
			get { return getHeightfieldLayer(scene_, componentId_); }
			set { setHeightfieldLayer(scene_, componentId_, value); }
		}

		public PhysicalHeightfield(Entity _entity, int _cmpId)
			: base(_entity, _cmpId, getScene(_entity.instance_, GetCmpType)) { }

	}//end class

}//end namespace


text: A sql package for the Go language.


text:
"""Title translate module."""
#
# (C) Rob W.W. Hooft, 2003
# (C) Yuri Astrakhan, 2005
# (C) Pywikibot team, 2003-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals

import re

import pywikibot
import pywikibot.date as date

from pywikibot import config
from pywikibot.tools import deprecated_args

@deprecated_args(family=None)
def translate(page=None, hints=None, auto=True, removebrackets=False,
              site=None):
    """
    Return a list of links to pages on other sites based on hints.

    Entries for single page titles list those pages. Page titles for entries
    such as "all:" or "xyz:" or "20:" are first built from the page title of
    'page' and then listed. When 'removebrackets' is True, a trailing pair of
    brackets and the text between them is removed from the page title.
    If 'auto' is true, known year and date page titles are autotranslated
    to all known target languages and inserted into the list.

    """
    result = set()

    assert page or site

    if site is None and page:
        site = page.site

    if hints:
        for h in hints:
            if ':' not in h:
                # argument given as -hint:xy where xy is a language code
                codes = h
                newname = ''
            else:
                codes, newname = h.split(':', 1)
            if newname == '':
                # if given as -hint:xy or -hint:xy:, assume that there should
                # be a page in language xy with the same title as the page
                # we're currently working on ...
                if page is None:
                    continue
                newname = page.title(withNamespace=False)
                # ... unless we do want brackets
                if removebrackets:
                    newname = re.sub(re.compile(r"\W*?\(.*?\)\W*?",
                                                re.UNICODE), u" ", newname)
            try:
                number = int(codes)
                codes = site.family.languages_by_size[:number]
            except ValueError:
                if codes == 'all':
                    codes = site.family.languages_by_size
                elif codes in site.family.language_groups:
                    codes = site.family.language_groups[codes]
                else:
                    codes = codes.split(',')

            for newcode in codes:

                if newcode in site.languages():
                    if newcode != site.code:
                        ns = page.namespace() if page else 0
                        x = pywikibot.Link(newname,
                                           site.getSite(code=newcode),
                                           defaultNamespace=ns)
                        result.add(x)
                else:
                    if config.verbose_output:
                        pywikibot.output(u"Ignoring unknown language code %s"
                                         % newcode)

    # Autotranslate dates into all other languages, the rest will come from
    # existing interwiki links.
    if auto and page:
        # search inside all dictionaries for this link
        sitelang = page.site.code
        dictName, value = date.getAutoFormat(sitelang, page.title())
        if dictName:
            pywikibot.output(
                u'TitleTranslate: %s was recognized as %s with value %d'
                % (page.title(), dictName, value))
            for entryLang, entry in date.formats[dictName].items():
                if entryLang not in site.languages():
                    continue
                if entryLang != sitelang:
                    newname = entry(value)
                    x = pywikibot.Link(
                        newname,
                        pywikibot.Site(code=entryLang,
                                       fam=site.family))
                    result.add(x)
    return list(result)


text:
package org.usfirst.frc.team2141.robot.commands.autonomous;

import org.usfirst.frc.team2141.robot.commands.chassis.DriveStraight;
import org.usfirst.frc.team2141.robot.commands.chassis.TurnDegrees;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class RightGearTurn extends CommandGroup {

    public RightGearTurn() {
        // Add Commands here:
        // e.g. addSequential(new Command1());
        //      addSequential(new Command2());
        // these will run in order.

        // To run multiple commands at the same time,
        // use addParallel()
        // e.g. addParallel(new Command1());
        //      addSequential(new Command2());
        // Command1 and Command2 will run in parallel.

        // A command group will require all of the subsystems that each member
        // would require.
        // e.g. if Command1 requires chassis, and Command2 requires arm,
        // a CommandGroup containing them would require both the chassis and the
        // arm.

    	//Nums for red right
    	addSequential(new DriveStraight(79.5, .5));
    	addSequential(new TurnDegrees(60, .2));
    	addSequential(new DriveStraight(5, 0),.5);
    	addSequential(new DriveStraight(18, .5));

    }
}


text:
"use strict" ;

const DEFAULT_OPTIONS = {
	underscoreToSpace: true ,
	lowerCaseWords: new Set( [
		// Articles
		'a' , 'an' , 'the' ,
		// Conjunctions (only coordinating conjunctions, maybe we will have to add subordinating and correlative conjunctions)
		'for' , 'and' , 'nor' , 'but' , 'or' , 'yet' , 'so' ,
		// Prepositions (there are more, but usually only preposition with 2 or 3 letters are lower-cased)
		'of' , 'on' , 'off' , 'in' , 'into' , 'by' , 'with' , 'to' , 'at' , 'up' , 'down' , 'as'
	] )
} ;

module.exports = ( str , options = DEFAULT_OPTIONS ) => {
	if ( ! str || typeof str !== 'string' ) { return '' ; }

	// Manage options
	var dashToSpace = options.dashToSpace ?? DEFAULT_OPTIONS.dashToSpace ,
		underscoreToSpace = options.underscoreToSpace ?? DEFAULT_OPTIONS.underscoreToSpace ,
		zealous = options.zealous ?? DEFAULT_OPTIONS.zealous ,
		preserveAllCaps = options.preserveAllCaps ?? DEFAULT_OPTIONS.preserveAllCaps ,
		lowerCaseWords = options.lowerCaseWords ?? DEFAULT_OPTIONS.lowerCaseWords ;

	lowerCaseWords =
		lowerCaseWords instanceof Set ? lowerCaseWords :
		Array.isArray( lowerCaseWords ) ? new Set( lowerCaseWords ) :
		null ;

	if ( dashToSpace ) { str = str.replace( /-+/g , ' ' ) ; }
	if ( underscoreToSpace ) { str = str.replace( /_+/g , ' ' ) ; }

	// Squash multiple spaces into only one, and trim
	str = str.replace( / +/g , ' ' ).trim() ;

	return str.replace( /[^\s_-]+/g , ( part , position ) => {
		// Check word that must be lower-cased (excluding the first and the last word)
		if ( lowerCaseWords && position && position + part.length < str.length ) {
			let lowerCased = part.toLowerCase() ;
			if ( lowerCaseWords.has( lowerCased ) ) { return lowerCased ; }
		}

		if ( zealous ) {
			if ( preserveAllCaps && part === part.toUpperCase() ) {
				// This is a ALLCAPS word
				return part ;
			}

			return part[ 0 ].toUpperCase() + part.slice( 1 ).toLowerCase() ;
		}

		return part[ 0 ].toUpperCase() + part.slice( 1 ) ;
	} ) ;
} ;


text:
package com.dom.observer;

import java.util.Observable;

public class BlogUser extends Observable {
public void publishBlog(String articleTitle,String articleContent){
	Article article = new Article();
	article.setArticleTitle(articleTitle);
	article.setArticleContent(articleContent);
	System.out.println("Äã·¢²¼ÁËÐÂÎÄÕÂ:"+articleTitle+"\n"+articleContent);
	this.setChanged();//ÉèÖÃÄÚÈÝÒѾ¸Ä±ä
	this.notifyObservers(article);//֪ͨ¹Û²ìÕß

}
}


text:
/**
 * A lightweight representation of an HTML element.
 * @param {String} name The element name.
 * @param {Object} attributes And object holding all attributes defined for
 *		this element.
 * @constructor
 * @example
 */
CKEDITOR.htmlParser.element = function( name, attributes )
{
	/**
	 * The element name.
	 * @type String
	 * @example
	 */
	this.name = name;

	/**
	 * Holds the attributes defined for this element.
	 * @type Object
	 * @example
	 */
	this.attributes = attributes || ( attributes = {} );

	/**
	 * The nodes that are direct children of this element.
	 * @type Array
	 * @example
	 */
	this.children = [];

	var tagName = attributes[ 'data-cke-real-element-type' ] || name || '';

	// Reveal the real semantic of our internal custom tag name (#6639).
	var internalTag = tagName.match( /^cke:(.*)/ );
  	internalTag && ( tagName = internalTag[ 1 ] );

	var dtd			= CKEDITOR.dtd,
		isBlockLike	= !!( dtd.$nonBodyContent[ tagName ]
				|| dtd.$block[ tagName ]
				|| dtd.$listItem[ tagName ]
				|| dtd.$tableContent[ tagName ]
				|| dtd.$nonEditable[ tagName ]
				|| tagName == 'br' ),
		isEmpty = !!dtd.$empty[ name ];

	this.isEmpty	= isEmpty;
	this.isUnknown	= !dtd[ name ];

	/** @private */
	this._ =
	{
		isBlockLike : isBlockLike,
		hasInlineStarted : isEmpty || !isBlockLike
	};
};

/**
 *  Object presentation of  CSS style declaration text.
 *  @param {CKEDITOR.htmlParser.element|String} elementOrStyleText A html parser element or the inline style text.
 */
CKEDITOR.htmlParser.cssStyle = function()
{
	 var styleText,
		arg = arguments[ 0 ],
		rules = {};

	styleText = arg instanceof CKEDITOR.htmlParser.element ? arg.attributes.style : arg;

	// html-encoded quote might be introduced by 'font-family'
	// from MS-Word which confused the following regexp. e.g.
	//'font-family: "Lucida, Console"'
	( styleText || '' )
		.replace( /"/g, '"' )
		.replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g,
			function( match, name, value )
			{
				name == 'font-family' && ( value = value.replace( /["']/g, '' ) );
				rules[ name.toLowerCase() ] = value;
			});

	return {

		rules : rules,

		/**
		 *  Apply the styles onto the specified element or object.
		 * @param {CKEDITOR.htmlParser.element|CKEDITOR.dom.element|Object} obj
		 */
		populate : function( obj )
		{
			var style = this.toString();
			if ( style )
			{
				obj instanceof CKEDITOR.dom.element ?
					obj.setAttribute( 'style', style ) :
					obj instanceof CKEDITOR.htmlParser.element ?
						obj.attributes.style = style :
						obj.style = style;
			}
		},

		toString : function()
		{
			var output = [];
			for ( var i in rules )
				rules[ i ] && output.push( i, ':', rules[ i ], ';' );
			return output.join( '' );
		}
	};
};

(function()
{
	// Used to sort attribute entries in an array, where the first element of
	// each object is the attribute name.
	var sortAttribs = function( a, b )
	{
		a = a[0];
		b = b[0];
		return a < b ? -1 : a > b ? 1 : 0;
	};

	CKEDITOR.htmlParser.element.prototype =
	{
		/**
		 * The node type. This is a constant value set to {@link CKEDITOR.NODE_ELEMENT}.
		 * @type Number
		 * @example
		 */
		type : CKEDITOR.NODE_ELEMENT,

		/**
		 * Adds a node to the element children list.
		 * @param {Object} node The node to be added. It can be any of of the
		 *		following types: {@link CKEDITOR.htmlParser.element},
		 *		{@link CKEDITOR.htmlParser.text} and
		 *		{@link CKEDITOR.htmlParser.comment}.
		 * @function
		 * @example
		 */
		add : CKEDITOR.htmlParser.fragment.prototype.add,

		/**
		 * Clone this element.
		 * @returns {CKEDITOR.htmlParser.element} The element clone.
		 * @example
		 */
		clone : function()
		{
			return new CKEDITOR.htmlParser.element( this.name, this.attributes );
		},

		/**
		 * Writes the element HTML to a CKEDITOR.htmlWriter.
		 * @param {CKEDITOR.htmlWriter} writer The writer to which write the HTML.
		 * @example
		 */
		writeHtml : function( writer, filter )
		{
			var attributes = this.attributes;

			// Ignore cke: prefixes when writing HTML.
			var element = this,
				writeName = element.name,
				a, newAttrName, value;

			var isChildrenFiltered;

			/**
			 * Providing an option for bottom-up filtering order ( element
			 * children to be pre-filtered before the element itself ).
			 */
			element.filterChildren = function()
			{
				if ( !isChildrenFiltered )
				{
					var writer = new CKEDITOR.htmlParser.basicWriter();
					CKEDITOR.htmlParser.fragment.prototype.writeChildrenHtml.call( element, writer, filter );
					element.children = new CKEDITOR.htmlParser.fragment.fromHtml( writer.getHtml(), 0, element.clone() ).children;
					isChildrenFiltered = 1;
				}
			};

			if ( filter )
			{
				while ( true )
				{
					if ( !( writeName = filter.onElementName( writeName ) ) )
						return;

					element.name = writeName;

					if ( !( element = filter.onElement( element ) ) )
						return;

					element.parent = this.parent;

					if ( element.name == writeName )
						break;

					// If the element has been replaced with something of a
					// different type, then make the replacement write itself.
					if ( element.type != CKEDITOR.NODE_ELEMENT )
					{
						element.writeHtml( writer, filter );
						return;
					}

					writeName = element.name;

					// This indicate that the element has been dropped by
					// filter but not the children.
					if ( !writeName )
					{
						// Fix broken parent refs.
						for ( var c = 0, length = this.children.length ; c < length ; c++ )
							this.children[ c ].parent = element.parent;

						this.writeChildrenHtml.call( element, writer, isChildrenFiltered ? null : filter );
						return;
					}
				}

				// The element may have been changed, so update the local
				// references.
				attributes = element.attributes;
			}

			// Open element tag.
			writer.openTag( writeName, attributes );

			// Copy all attributes to an array.
			var attribsArray = [];
			// Iterate over the attributes twice since filters may alter
			// other attributes.
			for ( var i = 0 ; i < 2; i++ )
			{
				for ( a in attributes )
				{
					newAttrName = a;
					value = attributes[ a ];
					if ( i == 1 )
						attribsArray.push( [ a, value ] );
					else if ( filter )
					{
						while ( true )
						{
							if ( !( newAttrName = filter.onAttributeName( a ) ) )
							{
								delete attributes[ a ];
								break;
							}
							else if ( newAttrName != a )
							{
								delete attributes[ a ];
								a = newAttrName;
								continue;
							}
							else
								break;
						}
						if ( newAttrName )
						{
							if ( ( value = filter.onAttribute( element, newAttrName, value ) ) === false )
								delete attributes[ newAttrName ];
							else
								attributes [ newAttrName ] = value;
						}
					}
				}
			}
			// Sort the attributes by name.
			if ( writer.sortAttributes )
				attribsArray.sort( sortAttribs );

			// Send the attributes.
			var len = attribsArray.length;
			for ( i = 0 ; i < len ; i++ )
			{
				var attrib = attribsArray[ i ];
				writer.attribute( attrib[0], attrib[1] );
			}

			// Close the tag.
			writer.openTagClose( writeName, element.isEmpty );

			if ( !element.isEmpty )
			{
				this.writeChildrenHtml.call( element, writer, isChildrenFiltered ? null : filter );
				// Close the element.
				writer.closeTag( writeName );
			}
		},

		writeChildrenHtml : function( writer, filter )
		{
			// Send children.
			CKEDITOR.htmlParser.fragment.prototype.writeChildrenHtml.apply( this, arguments );

		}
	};
})();