text:
Imports System.Runtime.InteropServices
Imports System.IO

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim objSEApp As SolidEdgeFramework.Application
        Dim objDoc As SolidEdgeDraft.DraftDocument
        Dim objModelLinks As SolidEdgeDraft.ModelLinks = Nothing
        Dim objModelLink As SolidEdgeDraft.ModelLink = Nothing
        Dim objDrawingViews As SolidEdgeDraft.DrawingViews = Nothing
        Dim objDrawingView As SolidEdgeDraft.DrawingView = Nothing
        Dim objSheets As SolidEdgeDraft.Sheets = Nothing
        Dim objSheet As SolidEdgeDraft.Sheet = Nothing
        Dim SEInstallDir As DirectoryInfo
        Try

            Try
                objSEApp = Marshal.GetActiveObject("SolidEdge.Application")
            Catch ex As Exception
                objSEApp = Activator.CreateInstance(Type.GetTypeFromProgID("SolidEdge.Application"))
                objSEApp.DisplayAlerts = True
                objSEApp.Visible = True
            End Try
            Dim strTemplatePath As String = ""
            'Users using ST6 or prior versions may have to use different path for template.
            strTemplatePath = objSEApp.Documents.TemplatePath & "\ANSI Metric\ansi metric draft.dft"
            objDoc = objSEApp.Documents.Add("SolidEdge.DraftDocument", strTemplatePath)

            SEInstallDir = GetTrainingFolder()

            objModelLinks = objDoc.ModelLinks
            'Set Link to Assembly document
            objModelLink = objModelLinks.Add(SEInstallDir.FullName + "\carrier.asm")

            'Get Sheets Collection
            objSheets = objDoc.Sheets
            objSheet = objDoc.Sheets.Item(1)
            'Get Drawing View collection from the sheet1
            objDrawingViews = objSheet.DrawingViews
            'Add first view
            objDrawingView = objDrawingViews.AddAssemblyView(objModelLink, SolidEdgeDraft.ViewOrientationConstants.igTopView, 1.0, 0.2, 0.15, SolidEdgeDraft.AssemblyDrawingViewTypeConstants.seAssemblySimplifiedView)

            objDrawingView.CaptionDefinitionTextPrimary = "Top View"
            objDrawingView = objDrawingViews.AddAssemblyView(objModelLink, SolidEdgeDraft.ViewOrientationConstants.igLeftView, 1.0, 0.4, 0.15, SolidEdgeDraft.AssemblyDrawingViewTypeConstants.seAssemblySimplifiedView)
            objDrawingView.SetRotationAngle(1.5708)
            objDrawingView.CaptionDefinitionTextPrimary = "LHS View"
            objDrawingViews = objSheet.DrawingViews
            objDrawingView.DepthPlaneOffset = 0.05
            'Update All Drawing views using UpdateViews method
            objModelLink.UpdateViews()
            'Remove depth plane
            objDrawingView.RemoveDepthPlane()
            'Update All Drawing views using UpdateViews method
            objModelLink.UpdateViews()
        Catch ex As Exception
            MsgBox(ex.ToString)
        Finally
            ' USER DISPLAY
            ' Release objects
            objSEApp = Nothing
            objDoc = Nothing
            objModelLink = Nothing
        End Try

    End Sub
    Function GetTrainingFolder() As DirectoryInfo
        Dim objInstallData As SEInstallDataLib.SEInstallData = Nothing
        Dim objInstallFolder As DirectoryInfo = Nothing
        Dim objTrainingFolder As DirectoryInfo = Nothing

        Try
            objInstallData = New SEInstallDataLib.SEInstallData
            objInstallFolder = New DirectoryInfo(objInstallData.GetInstalledPath())
            objTrainingFolder = New DirectoryInfo(Path.Combine(objInstallFolder.Parent.FullName, "Training"))
        Catch
        Finally
            If Not (objInstallData Is Nothing) Then
                Marshal.FinalReleaseComObject(objInstallData)
                objInstallData = Nothing
            End If
        End Try

        Return objTrainingFolder
    End Function
End Class


text:
import pull = require('..');

/**
 * Stream the key names from an object (or array).
 */
declare function keys(obj: object | ReadonlyArray<any>, onAbort?: (err?: Error | null) => unknown): pull.Source<string>;
export = keys;

redpajama_set_name: RedPajamaGithub


text:
'use strict';
var path = require('path');
var yoUtils = require('yo-utils');
var chalk = require('chalk');
var controllerCfg = require('./config');
var _;

var EndpointGenerator = yoUtils.NamedBase.extend({

  constructor: function() {
    yoUtils.NamedBase.apply(this, arguments);

    // add usage options
    for (var opt in controllerCfg.options) {
      this.option(opt, controllerCfg.options[opt]);
    }

    _ = this._;
  },

  /* Init method */
  initializing: function() {
    if (!this.options['skip-message']) {
      console.log(chalk.magenta('Express controllers brought to you by generator-express-component.\n'));
    }

    // config defaults
    this.option('skip-message', {
      desc: 'Suppress generator messages',
      defaults: false
    });
    this.defaults = controllerCfg.defaults;
  },

  /* Prompting priority methods */
  prompting: {
    subGenCfg: function() {
      var done = this.async();
      var ops = yoUtils.app.pluckOps(/^controller-/, this.options);
      var cfg = this.config.get('controller') || {};
      ops = _.merge(cfg, ops);

      var prompts = controllerCfg.prompts(ops);

      this.prompt(prompts, function(answers) {
        this.ops = _.merge(ops, answers);
        done();
      }.bind(this));
    },

    instancePrompts: function() {
      var done = this.async();
      var name = this.name;
      var ops = this.ops;
      var nameTpl = this.ops.name || this.defaults.name;

      var prompts = [{
        name: 'name',
        message: 'What will the variable name of your controller be?',
        default: this.engine(nameTpl, this),
        when: yoUtils.app.promptWhen(ops)('name', 'register')
      }];

      this.prompt(prompts, function (answers) {
        this.ops.name = answers.name || controllerCfg.defaults.name;
        done();
      }.bind(this));
    }
  },

  configuring: {
    templateOps: function() {
      for (var op in this.ops) {
        var opVal = this.ops[op];
        if (typeof opVal === 'string') {
          this.ops[op] = this.engine(opVal, this);
        }
      }
    }
  },

  /* Writing priority methods */
  writing: {
    // add new controller file
    createFiles: function() {
      var tPath;
      if (!this.ops.template || this.ops.template.toLowerCase() === 'default') {
        tPath = path.join(__dirname, './templates/controller.js');
      } else {
        tPath = path.relative(this.sourceRoot(), this.ops.template);
      }

      this.template(tPath, this.ops.path, this);
    }
  },

  /* End priority methods */
  end: {
    // add controller endpoint to express route
    registerEndpoint: function() {
      if (this.ops.register) {
        var ctrlName = this.ops.name;
        var regControllerFile = this.ops.haystack;
        var controllerFile = this.ops.path;
        var relativeController = yoUtils.templating.relativePathTo(regControllerFile, controllerFile, true);
        yoUtils.templating.rewriteFile({
          file: regControllerFile,
          needle: this.ops.needle,
          splicable: [
            "var " + ctrlName + " = require(\'" + relativeController + "\'));"
          ]
        });
      }
    }
  }

});

module.exports = EndpointGenerator;


text:
'use strict';

/**
 * @module bootstrap
 */

/**
 * @private
 */
var async = require('async');
var path = require('path');
var fs = require('fs');
var bootstrapDefault = 'bootstrap.html';

var getBootstrapContent = function (res, staticRoot, bootstrapFile, callback) {

	var file = path.join(staticRoot, bootstrapFile || bootstrapDefault);
	async.series(
		{
			'exists': function (callback) {
				fs.exists(file, function (exists) {
					if (exists) {
						callback(null);
					} else {
						callback(new Error("File does not exist: " + file));
					}
				});
			},
			'readFile': async.apply(fs.readFile, file, 'UTF-8')
		},
		function (error, result) {
			if (error) {
				return callback(error);
			}
			return res.send(result.readFile);
		}
	);

};

module.exports = function (staticRoot, bootstrapFile) {

	return function (req, res, next) {
		req = require('./request').extend(req);
		if (req.isAjax()) {
			next(null);
		} else {
			getBootstrapContent(res, staticRoot, bootstrapFile, next);
		}
	};
};


text:
.PHONY: install
all: install

VERSION=v1.3.0
INSTALL_DIR=$(HOME)/.local

OS=$(shell uname -s | tr A-Z a-z)
ARCH=$(subst x86_64,amd64,$(shell uname -m))

BIN_VERSION=ghq-$(VERSION)
BIN=ghq

TARGET=$(INSTALL_DIR)/bin/$(BIN_VERSION)
TARGET_LINK=$(INSTALL_DIR)/bin/$(BIN)
_:=$(shell if [ -f "$(TARGET)" ]; then touch "$(TARGET)"; fi)

ARCHIVE=ghq_$(OS)_$(ARCH)_$(VERSION).zip

$(TARGET):
	curl -L https://github.com/x-motemen/ghq/releases/download/$(VERSION)/ghq_$(OS)_$(ARCH).zip -o $(ARCHIVE)
	mkdir -p $(INSTALL_DIR)/bin
	unzip -p $(ARCHIVE) ghq_$(OS)_$(ARCH)/$(BIN) > $(TARGET)
	chmod +x $(TARGET)

$(TARGET_LINK): $(TARGET)
	ln -nsf $(TARGET) $(TARGET_LINK)

install: $(TARGET_LINK)

GITHUB_RELEASES=https://api.github.com/repos/x-motemen/ghq/releases

.PHONY: update version versions
update:
	$(eval NEW_VERSION := $(shell curl -s $(GITHUB_RELEASES) | jq -r .[0].tag_name))
	@if [ "$(NEW_VERSION)" = "" ]; then echo failed to fetch tag; exit 1; fi
	@sed -i -e "s/VERSION=$(VERSION)/VERSION=$(NEW_VERSION)/" Makefile
	$(MAKE) install

version:
	@echo $(VERSION)

versions:
	@curl -s $(GITHUB_RELEASES) | jq -r '.[].tag_name'


text:
package com.kise.kairosdb.core.http.rest.validation;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 *
 * @author Remi Dettai <rdettai at gmail.com>
 */
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = ValidScriptValidator.class)
@Documented
public @interface ValidScript
{
	String[] arguments() default {};

	String message() default "";

	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};
}


text:
// $Id: Hash_Cache_Map_Manager_T.cpp 93359 2011-02-11 11:33:12Z mcorino $

#ifndef ACE_HASH_CACHE_MAP_MANAGER_T_CPP
#define ACE_HASH_CACHE_MAP_MANAGER_T_CPP

#include "ace/Hash_Cache_Map_Manager_T.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
#pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#if !defined (__ACE_INLINE__)
#include "ace/Hash_Cache_Map_Manager_T.inl"
#endif /* __ACE_INLINE__ */

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

ACE_ALLOC_HOOK_DEFINE(ACE_Hash_Cache_Map_Manager)

template <class KEY, class VALUE, class HASH_KEY, class COMPARE_KEYS, class CACHING_STRATEGY, class ATTRIBUTES>
ACE_Hash_Cache_Map_Manager<KEY, VALUE,  HASH_KEY, COMPARE_KEYS, CACHING_STRATEGY, ATTRIBUTES>::ACE_Hash_Cache_Map_Manager (CACHING_STRATEGY &caching_s,
                                                             size_t size,
                                                             ACE_Allocator *alloc)
  : ACE_HCMM_BASE (caching_s,
                   size,
                   alloc)
{
}

template <class KEY, class VALUE, class HASH_KEY, class COMPARE_KEYS, class CACHING_STRATEGY, class ATTRIBUTES>
ACE_Hash_Cache_Map_Manager<KEY, VALUE,  HASH_KEY, COMPARE_KEYS, CACHING_STRATEGY, ATTRIBUTES>::~ACE_Hash_Cache_Map_Manager (void)
{
}

template <class KEY, class VALUE, class HASH_KEY, class COMPARE_KEYS, class CACHING_STRATEGY, class ATTRIBUTES> int
ACE_Hash_Cache_Map_Manager<KEY, VALUE,  HASH_KEY, COMPARE_KEYS, CACHING_STRATEGY, ATTRIBUTES>::bind (const KEY &key,
                                          const VALUE &value,
                                          CACHE_ENTRY *&entry)
{
  // Insert a entry which has the <key> and the <cache_value> which is
  // the combination of the <value> and the attributes of the caching
  // strategy.
  CACHE_VALUE cache_value (value,
                           this->caching_strategy_.attributes ());

  int bind_result = this->map_.bind (key,
                                     cache_value,
                                     entry);

  if (bind_result != -1)
    {

      int result = this->caching_strategy_.notify_bind (bind_result,
                                                        cache_value.second);

      if (result == -1)
        {

          this->map_.unbind (key);

          // Unless the notification goes thru the bind operation is
          // not complete.
          bind_result = -1;

        }
    }

  return bind_result;
}

template <class KEY, class VALUE, class HASH_KEY, class COMPARE_KEYS, class CACHING_STRATEGY, class ATTRIBUTES> int
ACE_Hash_Cache_Map_Manager<KEY, VALUE,  HASH_KEY, COMPARE_KEYS, CACHING_STRATEGY, ATTRIBUTES>::rebind (const KEY &key,
                                         const VALUE &value,
                                         CACHE_ENTRY *&entry)
{
  CACHE_VALUE cache_value (value,
                           this->caching_strategy_.attributes ());

  int rebind_result = this->map_.rebind (key,
                                         cache_value,
                                         entry);

  if (rebind_result != -1)
    {

      int result = this->caching_strategy_.notify_rebind (rebind_result,
                                                          cache_value.second ());

      if (result == -1)
        {

          // Make sure the unbind operation is done only when the
          // notification fails after a bind which is denoted by
          // rebind_result = 0
          if (rebind_result == 0)
            this->map_.unbind (key);

          // Unless the notification goes thru the rebind operation is
          // not complete.
          rebind_result = -1;

        }

    }

  return rebind_result;
}

template <class KEY, class VALUE, class HASH_KEY, class COMPARE_KEYS, class CACHING_STRATEGY, class ATTRIBUTES> int
ACE_Hash_Cache_Map_Manager<KEY, VALUE,  HASH_KEY, COMPARE_KEYS, CACHING_STRATEGY, ATTRIBUTES>::trybind (const KEY &key,
                                          VALUE &value,
                                          CACHE_ENTRY *&entry)
{
  CACHE_VALUE cache_value (value,
                           this->caching_strategy_.attributes ());

  int trybind_result = this->map_.trybind (key,
                                           cache_value,
                                           entry);

  if (trybind_result != -1)
    {
      int result = this->caching_strategy_.notify_trybind (trybind_result,
                                                           cache_value.second ());

      if (result == -1)
        {

          // If the entry has got inserted into the map, it is removed
          // due to failure.
          if (trybind_result == 0)
            this->map_.unbind (key);

          trybind_result = -1;

        }
      else
        {

          // If an attempt is made to bind an existing entry the value
          // is overwritten with the value from the map.
          if (trybind_result == 1)
            value = cache_value.first ();

        }

    }

  return trybind_result;
}

template <class KEY, class VALUE, class HASH_KEY, class COMPARE_KEYS, class CACHING_STRATEGY, class ATTRIBUTES> int
ACE_Hash_Cache_Map_Manager<KEY, VALUE,  HASH_KEY, COMPARE_KEYS, CACHING_STRATEGY, ATTRIBUTES>::find (const KEY &key,
                                       CACHE_ENTRY *&entry)
{
  // Lookup the key and populate the <value>.
  int find_result = this->map_.find (key,
                                     entry);

  if (find_result != -1)
    {

      int result = this->caching_strategy_.notify_find (find_result,
                                                        entry->int_id_.second);

      // Unless the find and notification operations go thru, this
      // method is not successful.
      if (result == -1)
        find_result = -1;
      else
        find_result = 0;

    }

  return find_result;
}

template <class KEY, class VALUE, class HASH_KEY, class COMPARE_KEYS, class CACHING_STRATEGY, class ATTRIBUTES> int
ACE_Hash_Cache_Map_Manager<KEY, VALUE,  HASH_KEY, COMPARE_KEYS, CACHING_STRATEGY, ATTRIBUTES>::find (const KEY &key,
                                       VALUE &value)
{
  CACHE_ENTRY *entry = 0;

  int result = this->find (key,
                           entry);

  if (result != -1)
    {
      value = entry->int_id_.first;
    }

  return result;
}

template <class KEY, class VALUE, class HASH_KEY, class COMPARE_KEYS, class CACHING_STRATEGY, class ATTRIBUTES> int
ACE_Hash_Cache_Map_Manager<KEY, VALUE,  HASH_KEY, COMPARE_KEYS, CACHING_STRATEGY, ATTRIBUTES>::find (const KEY &key)
{
  CACHE_ENTRY *entry = 0;

  return this->find (key,
                     entry);
}

template <class KEY, class VALUE, class HASH_KEY, class COMPARE_KEYS, class CACHING_STRATEGY, class ATTRIBUTES> int
ACE_Hash_Cache_Map_Manager<KEY, VALUE,  HASH_KEY, COMPARE_KEYS, CACHING_STRATEGY, ATTRIBUTES>::unbind (CACHE_ENTRY *entry)
{
  // Remove the entry from the cache.
  int unbind_result = this->map_.unbind (entry);

  if (unbind_result != -1)
    {

      int result = this->caching_strategy_.notify_unbind (unbind_result,
                                                          entry->int_id_.second);

      if (result == -1)
        unbind_result = -1;

    }

  return unbind_result;
}

ACE_END_VERSIONED_NAMESPACE_DECL

#endif /* ACE_HASH_CACHE_MAP_MANAGER_T_CPP */


text:
#pragma once

#include "ImageBuffer.h"
#include "Pattern.h"
#include "PatternAttributes.h"
#include "RenderSVGResourceContainer.h"
#include "SVGPatternElement.h"
#include <memory>
#include <wtf/IsoMallocInlines.h>
#include <wtf/HashMap.h>

namespace WebCore {

struct PatternData {
    WTF_MAKE_FAST_ALLOCATED;
public:
    RefPtr<Pattern> pattern;
    AffineTransform transform;
};

class RenderSVGResourcePattern final : public RenderSVGResourceContainer {
    WTF_MAKE_ISO_ALLOCATED(RenderSVGResourcePattern);
public:
    RenderSVGResourcePattern(SVGPatternElement&, RenderStyle&&);
    SVGPatternElement& patternElement() const;

    void removeAllClientsFromCache(bool markForInvalidation = true) override;
    void removeClientFromCache(RenderElement&, bool markForInvalidation = true) override;

    bool applyResource(RenderElement&, const RenderStyle&, GraphicsContext*&, OptionSet<RenderSVGResourceMode>) override;
    void postApplyResource(RenderElement&, GraphicsContext*&, OptionSet<RenderSVGResourceMode>, const Path*, const RenderSVGShape*) override;
    FloatRect resourceBoundingBox(const RenderObject&) override { return FloatRect(); }

    RenderSVGResourceType resourceType() const override { return PatternResourceType; }

    void collectPatternAttributes(PatternAttributes&) const;

private:
    void element() const = delete;
    const char* renderName() const override { return "RenderSVGResourcePattern"; }

    bool buildTileImageTransform(RenderElement&, const PatternAttributes&, const SVGPatternElement&, FloatRect& patternBoundaries, AffineTransform& tileImageTransform) const;

    std::unique_ptr<ImageBuffer> createTileImage(const PatternAttributes&, const FloatRect& tileBoundaries, const FloatRect& absoluteTileBoundaries, const AffineTransform& tileImageTransform, FloatRect& clampedAbsoluteTileBoundaries, RenderingMode) const;

    PatternData* buildPattern(RenderElement&, OptionSet<RenderSVGResourceMode>, GraphicsContext&);

    PatternAttributes m_attributes;
    HashMap<RenderElement*, std::unique_ptr<PatternData>> m_patternMap;
    bool m_shouldCollectPatternAttributes { true };
};

} // namespace WebCore

SPECIALIZE_TYPE_TRAITS_RENDER_SVG_RESOURCE(RenderSVGResourcePattern, PatternResourceType)


text:
/***
Default theme
***/
/***
Reset and overrides
***/
body {
  color: #222222;
  background-color: #5a3128 !important;
}
/***
Page header
***/
.header {
  filter: none;
  background-image: none;
  background-color: #41241d;
}
.header .navbar-nav .dropdown-toggle:hover,
.header .navbar-nav .dropdown.open .dropdown-toggle {
  background-color: #6c3b30 !important;
}
.header .navbar-nav li.dropdown .dropdown-toggle i {
  color: #c99185 !important;
}
.header .navbar-nav > li.devider {
  border-left: 1px solid #5e332a !important;
}
.header .navbar-nav > li.dropdown.user .dropdown-toggle .username {
  color: #b97262;
}
.header .search-form .form-control,
.page-sidebar-menu .search-form .form-control {
  color: #b97262;
  background-color: #7d4438;
  border-color: #371e18;
}
.header .search-form .input-icon > i,
.page-sidebar-menu .search-form .input-icon > i {
  color: #482720;
}
/***
Page sidebar
***/
.page-sidebar {
  background: #5a3128;
}
ul.page-sidebar-menu > li > a {
  border-top: 1px solid #6c3b30;
  border-bottom: 1px solid #482720;
  color: #ffffff;
}
ul.page-sidebar-menu > li:last-child > a {
  border-bottom: 1px solid transparent;
}
ul.page-sidebar-menu > li a i {
  color: #c99185;
}
ul.page-sidebar-menu > li.open > a,
ul.page-sidebar-menu > li > a:hover,
ul.page-sidebar-menu > li:hover > a {
  background: #3e221b;
}
ul.page-sidebar-menu > li.active > a {
  color: #ffffff;
  background: #3e221b !important;
  border-top: 1px solid #3e221b !important;
  border-bottom: 1px solid #3e221b !important;
}
ul.page-sidebar-menu > li.active > a i {
  color: #ffffff;
}
ul.page-sidebar-menu > li > ul.sub-menu > li:first-child > a {
  border-top: 0px !important;
}
ul.page-sidebar-menu > li > ul.sub-menu > li.active > a,
ul.page-sidebar-menu > li > ul.sub-menu > li > a:hover {
  color: #ffffff !important;
  background: #6c3b30 !important;
}
ul.page-sidebar-menu > li > ul.sub-menu > li > a:hover {
  background: #6c3b30 !important;
}
/* 3rd level sub menu */
ul.page-sidebar-menu > li > ul.sub-menu li > ul.sub-menu > li.active > a,
ul.page-sidebar-menu > li > ul.sub-menu li > ul.sub-menu > li > a:hover,
ul.page-sidebar-menu > li > ul.sub-menu li.open > a {
  color: #ffffff !important;
  background: #6c3b30 !important;
}
/* font color for all sub menu links*/
ul.page-sidebar-menu li > ul.sub-menu > li > a {
  color: #e8d1cc;
}
/* menu arrows */
ul.page-sidebar-menu > li > a .arrow:before,
ul.page-sidebar-menu > li > a .arrow.open:before {
  color: #c18173 !important;
}
ul.page-sidebar-menu > li > ul.sub-menu a .arrow:before,
ul.page-sidebar-menu > li > ul.sub-menu a .arrow.open:before {
  color: #c99185 !important;
}
ul.page-sidebar-menu > li > a > .arrow.open:before {
  color: #d1a197 !important;
}
ul.page-sidebar-menu > li.active > a .arrow:before,
ul.page-sidebar-menu > li.active > a .arrow.open:before {
  color: #ffffff !important;
}
/* sub menu bg color on hover menu item */
.page-sidebar-closed ul.page-sidebar-menu > li:hover .sub-menu {
  background-color: #5a3128;
}
/***
Footer
***/
.footer .footer-inner {
  color: #c99185;
}
.footer .footer-tools .go-top {
  background-color: #7d4438;
}
.footer .footer-tools .go-top:hover {
  opacity: 0.7;
  filter: alpha(opacity=70);
}
.footer .footer-tools .go-top i {
  color: #b97262;
}
/* begin:fixed footer */
.page-footer-fixed .footer {
  background-color: #482720;
}
.page-footer-fixed .footer .footer-inner {
  color: #b97262;
}
.page-footer-fixed .footer .footer-tools .go-top {
  background-color: #8f4e40;
}
.page-footer-fixed .footer .footer-tools .go-top i {
  color: #e0c1ba;
}
/* end:fixed footer */
/***

/* begin: boxed page */
@media (min-width: 992px) {
  .page-boxed {
    background-color: #5a3128 !important;
  }
  .page-boxed .page-container {
    background-color: #5a3128;
    border-left: 1px solid #7d4438;
    border-bottom: 1px solid #7d4438;
  }
  .page-boxed.page-sidebar-reversed .page-container {
    border-left: 0;
    border-right: 1px solid #7d4438;
  }
  .page-boxed.page-sidebar-fixed .page-container {
    border-left: 0;
    border-bottom: 0;
  }
  .page-boxed.page-sidebar-reversed.page-sidebar-fixed .page-container {
    border-left: 0;
    border-right: 0;
    border-bottom: 0;
  }
  .page-boxed.page-sidebar-fixed .page-sidebar {
    border-left: 1px solid #7d4438;
  }
  .page-boxed.page-sidebar-reversed.page-sidebar-fixed .page-sidebar {
    border-right: 1px solid #7d4438;
    border-left: 0;
  }
  .page-boxed.page-sidebar-fixed.page-footer-fixed .footer {
    background-color: #482720 !important;
  }
}
/* end: boxed page */
/***
Landscape phone to portrait tablet
***/
@media (max-width: 991px) {
  /***
    page sidebar
    ***/
  .page-sidebar {
    background-color: #371e18 !important;
    -webkit-border-radius: 4px !important;
    -moz-border-radius: 4px !important;
    border-radius: 4px !important;
  }
  ul.page-sidebar-menu > li > a {
    border-top: 1px solid #482720;
    border-bottom: 1px solid #251410;
  }
  ul.page-sidebar-menu > li:last-child > a {
    border-bottom: 0 !important;
  }
  ul.page-sidebar-menu > li.open > a,
  ul.page-sidebar-menu > li > a:hover,
  ul.page-sidebar-menu > li:hover > a {
    background: #1a0e0c;
  }
}
@media (max-width: 480px) {
  .header .navbar-nav > li.devider {
    border-left: 1px solid #6c3b30 !important;
  }
}

#projectMenuBox {background: #5a3128}
#projectMenuBox .yuimenubar {   border-color: #6c3b30;}
#projectMenuBox .yuimenubaritemlabel {border-color: #6c3b30;}
#projectMenuBox .yuimenubarnav .yuimenubaritem {border-right: solid 1px #6c3b30;}
#projectMenuBox .yuimenu ul {border-color: #3e221b}
#projectMenuBox .yuimenu .bd {background: #6c3b30; border: 1px solid #6c3b30;}
#projectMenuBox .yuimenuitemlabel-selected{background:#3e221b}
#projectMenuBox .yuimenuitem-selected { background-color: #3e221b; }
#projectMenuBox .yuimenubaritemlabel-selected { background: #3e221b; }
#projectMenuBox .yuimenuselecteditem {background:#3e221b}
#projectMenuBox .yuimenubaritemlabel-hassubmenu {background: url(img/menubaritem_submenuindicator.png) right center no-repeat;}
#projectMenuBox .yuimenuitemlabel-hassubmenu {background: url(img/menuitem_submenuindicator.png) right center no-repeat;}
#projectMenuBox .yuimenubaritemlabel-hassubmenu-selected { background-color: #3e221b; }

a {color: #3e221b}
a:hover {color: #5a3128}

.btn-primary{
  background-color: #5a3128;
  border-color: #5a3128;
}

.panel-info {
  border-color: #5a3128;
}

.panel-info>.panel-heading {
  color: #5a3128;
  background-color: #fff;
  border-color: #5a3128;
}

.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
  background-color: #6c3b30;
  border-color: #6c3b30;
}


text:
package sk.tuke.xhl.util;

import sk.tuke.xhl.core.Error;
import sk.tuke.xhl.core.*;
import sk.tuke.xhl.core.elements.Block;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

/**
 * Checker is a command line program that allows to check source codes of the
 * XHL program according to XHL grammar and language schema.
 *
 * @author Sergej Chodarev
 */
public class Checker {

    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("No input files specified\n" +
                    "Usage: java Checker <file-name> [<language>]");
            System.exit(1);
        }

        File input = new File(args[0]);
        String language = null;
        if (args.length >= 2)
            language = args[1];

        try {
            check(input, language);
        } catch (FileNotFoundException e) {
            System.err.println("File '" + args[0] + "' not found");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("I/O error while reading file '" + args[0] + "'");
            System.exit(1);
        }
    }

    private static void check(File input, String language) throws
            IOException {
        MaybeError<Block> result = Reader.read(input);
        if (!result.succeed()) {
            printErrors(result.getErrors());
        } else {
            ModulesProvider.ModulesLoader loader = new ModulesProvider
                    .ModulesLoader();
            Module module = loader.loadModule(language);
            if (module == null) {
                System.err.print("Unknown language '" + language + "'");
                System.exit(1);
            }
            LanguageProcessor processor = new LanguageProcessor(module);
            List<Error> errors = processor.validate(result.get());
            printErrors(errors);
        }
    }

    private static void printErrors(List<Error> errors) {
        for (Error error : errors) {
            System.out.println(error.position + ": " + error.message);
        }
    }
}


text:
@interface TestStackedPhotosTests : SenTestCase

@end


text:
package io.fabric8.crd.example.json;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;

import java.util.HashMap;
import java.util.Map;

public class Foo {

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

  @JsonAnyGetter
  public Map<String, Object> getConfigAsMap() {
    return configAsMap;
  }

  @JsonAnySetter
  public void setConfigAsMap(String name, Object value) {
    this.configAsMap.put(name, value);
  }

}


text:
module Plant
  module Query

    @@wheres = nil

    def self.wheres= wheres
      @@wheres = wheres
    end

    def self.wheres
      @@wheres
    end

    def self.find_all klass
      Plant.all[klass] || []
    end

    def self.find_by_ids klass, ids
      plants = Plant.all[klass].select{|plant| ids.include?(plant.id)}
      return plants.first if plants.size == 1
      plants
    end

    def self.select klass
      Plant::Selector.new(:klass => klass, :wheres => @@wheres, :plants => Plant.all[klass].to_a).select
    end

    def self.order objects, args
      attribute, order = args.split(" ")
      objects.sort {|x, y| (x,y = y,x if order == 'desc'); x.send(attribute.to_sym) <=> y.send(attribute.to_sym)}
    end

    def self.limit objects, limit_value
      @@objects = objects
      @@limit = limit_value
      objects.first(limit_value)
    end

    def self.offset objects, offset_value
      @@objects[offset_value..-1].first(@@limit)
    end

  end
end


text:
# This file provides library support for MSVC builds.
#  * Allows for detailed specification of file/product versions.
#  * Installs PDB files.

#
# If the compiler is Visual Studio set up installation of .pdb files
#
# Sample: install_pdb (qpidcommon ${QPID_COMPONENT_COMMON})
#
MACRO (install_pdb theLibrary theComponent)
    if (MSVC)
        get_target_property(library_dll ${theLibrary} LOCATION)
        string(REPLACE .dll .pdb library_pdb ${library_dll})
        string(REPLACE $(OutDir)        \${CMAKE_INSTALL_CONFIG_NAME} library_pdb ${library_pdb})
        string(REPLACE $(Configuration) \${CMAKE_INSTALL_CONFIG_NAME} library_pdb ${library_pdb})
        string(REPLACE .pdb d.pdb libraryd_pdb ${library_pdb})
        #message(STATUS "_pdb: ${library_pdb}, ${libraryd_pdb}")
        install (PROGRAMS
                ${library_pdb}
                DESTINATION ${QPID_INSTALL_LIBDIR}/ReleasePDB
                COMPONENT ${theComponent}
                OPTIONAL
                CONFIGURATIONS Release|MinSizeRel)
        install (PROGRAMS
                ${library_pdb}
                DESTINATION ${QPID_INSTALL_LIBDIR}/ReleasePDB
                COMPONENT ${theComponent}
                CONFIGURATIONS RelWithDebInfo)
        install (PROGRAMS
                ${libraryd_pdb}
                DESTINATION ${QPID_INSTALL_LIBDIR}/DebugPDB
                COMPONENT ${theComponent}
                CONFIGURATIONS Debug)
    endif (MSVC)
ENDMACRO (install_pdb)

#
# inherit_value - if the symbol is undefined then set it to the given value.
# Set flag to indicate this symbol was defined here.
#
MACRO (inherit_value theSymbol theValue)
    if (NOT DEFINED ${theSymbol})
        set (${theSymbol} ${theValue})
        # message ("Set symbol '${theSymbol}' to value '${theValue}'")
        set (${theSymbol}_inherited = "true")
    endif (NOT DEFINED ${theSymbol})
ENDMACRO (inherit_value)

#
# If compiler is Visual Studio then create a "version resource" for the project.
# Use this call to override CPACK and file global settings but not file per-project settings.
# Two groups of four version numbers specify "file" and "product" versions separately.
#
# Sample: add_msvc_version_full (qmfengine library dll 1 0 0 1 1 0 0 1)
#
MACRO (add_msvc_version_full verProject verProjectType verProjectFileExt verFN1 verFN2 verFN3 verFN4 verPN1 verPN2 verPN3 verPN4)
    if (MSVC)
        # Create project-specific version strings
        inherit_value ("winver_${verProject}_FileVersionBinary"    "${verFN1},${verFN2},${verFN3},${verFN4}")
        inherit_value ("winver_${verProject}_ProductVersionBinary" "${verPN1},${verPN2},${verPN3},${verPN4}")
        inherit_value ("winver_${verProject}_FileVersionString"    "${verFN1}, ${verFN2}, ${verFN3}, ${verFN4}")
        inherit_value ("winver_${verProject}_ProductVersionString" "${verPN1}, ${verPN2}, ${verPN3}, ${verPN4}")
        inherit_value ("winver_${verProject}_FileDescription"      "${winver_PACKAGE_NAME}-${verProject} ${verProjectType}")
        inherit_value ("winver_${verProject}_LegalCopyright"       "${winver_LEGAL_COPYRIGHT}")
        inherit_value ("winver_${verProject}_InternalName"         "${verProject}")
        inherit_value ("winver_${verProject}_OriginalFilename"     "${verProject}.${verProjectFileExt}")
        inherit_value ("winver_${verProject}_ProductName"          "${winver_DESCRIPTION_SUMMARY}")

        # Create strings to be substituted into the template file
        set ("winverFileVersionBinary"     "${winver_${verProject}_FileVersionBinary}")
        set ("winverProductVersionBinary"  "${winver_${verProject}_ProductVersionBinary}")
        set ("winverFileVersionString"     "${winver_${verProject}_FileVersionString}")
        set ("winverProductVersionString"  "${winver_${verProject}_ProductVersionString}")
        set ("winverFileDescription"       "${winver_${verProject}_FileDescription}")
        set ("winverLegalCopyright"        "${winver_${verProject}_LegalCopyright}")
        set ("winverInternalName"          "${winver_${verProject}_InternalName}")
        set ("winverOriginalFilename"      "${winver_${verProject}_OriginalFilename}")
        set ("winverProductName"           "${winver_${verProject}_ProductName}")

        configure_file(${CMAKE_CURRENT_SOURCE_DIR}/windows/resources/template-resource.rc
                       ${CMAKE_CURRENT_BINARY_DIR}/windows/resources/${verProject}-resource.rc)
        set (${verProject}_SOURCES
            ${${verProject}_SOURCES}
            ${CMAKE_CURRENT_BINARY_DIR}/windows/resources/${verProject}-resource.rc
        )
    endif (MSVC)
ENDMACRO (add_msvc_version_full)

#
# If compiler is Visual Studio then create a "version resource" for the project.
# Use this call to accept file override version settings or
#  inherited CPACK_PACKAGE_VERSION version settings.
#
# Sample: add_msvc_version (qpidcommon library dll)
#
MACRO (add_msvc_version verProject verProjectType verProjectFileExt)
    if (MSVC)
        add_msvc_version_full (${verProject}
                               ${verProjectType}
                               ${verProjectFileExt}
                               ${winver_FILE_VERSION_N1}
                               ${winver_FILE_VERSION_N2}
                               ${winver_FILE_VERSION_N3}
                               ${winver_FILE_VERSION_N4}
                               ${winver_PRODUCT_VERSION_N1}
                               ${winver_PRODUCT_VERSION_N2}
                               ${winver_PRODUCT_VERSION_N3}
                               ${winver_PRODUCT_VERSION_N4})
    endif (MSVC)
ENDMACRO (add_msvc_version)

#
# Install optional windows version settings. Override variables are specified in a file.
#
include (./CMakeWinVersions.cmake OPTIONAL)

#
# Inherit global windows version settings from CPACK settings.
#
inherit_value ("winver_PACKAGE_NAME"         "${CPACK_PACKAGE_NAME}")
inherit_value ("winver_DESCRIPTION_SUMMARY"  "${CPACK_PACKAGE_DESCRIPTION_SUMMARY}")
inherit_value ("winver_FILE_VERSION_N1"      "${CPACK_PACKAGE_VERSION_MAJOR}")
inherit_value ("winver_FILE_VERSION_N2"      "${CPACK_PACKAGE_VERSION_MINOR}")
inherit_value ("winver_FILE_VERSION_N3"      "${CPACK_PACKAGE_VERSION_PATCH}")
inherit_value ("winver_FILE_VERSION_N4"      "1")
inherit_value ("winver_PRODUCT_VERSION_N1"   "${winver_FILE_VERSION_N1}")
inherit_value ("winver_PRODUCT_VERSION_N2"   "${winver_FILE_VERSION_N2}")
inherit_value ("winver_PRODUCT_VERSION_N3"   "${winver_FILE_VERSION_N3}")
inherit_value ("winver_PRODUCT_VERSION_N4"   "${winver_FILE_VERSION_N4}")
inherit_value ("winver_LEGAL_COPYRIGHT"      "")


text:
package com.facebook.buck.apple.project_generator;

public enum IDEForceKill {
  /** Prompt the user, if possible, whether to kill the IDE. */
  PROMPT,

  /** Always kill, without prompting. */
  ALWAYS,

  /** Never kill and do not prompt. */
  NEVER
}


text:
package com.facebook.buck.features.project.intellij.model.folders;

import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;

/** A path which contains a set of sources we wish to present to IntelliJ. */
public class ExcludeFolder extends IjFolder {

  public static final IJFolderFactory FACTORY =
      (path, wantsPrefix, inputs) -> {
        if (wantsPrefix) {
          throw new IllegalArgumentException("ExcludeFolder does not support prefixes");
        }
        return new ExcludeFolder(path, inputs);
      };

  public static final String FOLDER_IJ_NAME = "excludeFolder";

  ExcludeFolder(Path path, ImmutableSortedSet<Path> inputs) {
    super(path, false, inputs);
  }

  public ExcludeFolder(Path path) {
    super(path);
  }

  @Override
  public IJFolderFactory getFactory() {
    return FACTORY;
  }

  /** @return name IntelliJ would use to refer to this type of folder. */
  @Override
  public String getIjName() {
    return FOLDER_IJ_NAME;
  }
}


text:
<!DOCTYPE html>

  <title>Rodrigo's Webpage</title>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1" name=
  "viewport">
  <link href="styles/main.css" rel="stylesheet">

  <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css" rel="stylesheet" type="text/css">
 <link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" rel="stylesheet" type="text/css">
  <link crossorigin="anonymous" href=
  "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
  integrity=
  "sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
  rel="stylesheet">
  <link crossorigin="anonymous" href=
  "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
  integrity=
  "sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
  rel="stylesheet">
  <link href="./font-awesome/css/font-awesome.min.css" rel="stylesheet">
  <link rel="shortcut icon" href="./pictures/R.png" type="image/x-icon">

            <button aria-expanded="false" class="navbar-toggle collapsed"
            data-target="#bs-example-navbar-collapse-1" data-toggle="collapse"
            type="button">Toggle navigation

            </button> Rodrigo's Webpage

                Home (current)

                About Me

                Contact

                Projects

                More

Rodrigo Delgado

Web-Developer Student

Welcome! - Bienvenido! - Kia Ora!

Hello! My name is Rodrigo Delgado and I am a
          Web-Developer student from Chile living in New Zealand. I am
          currently studying through the Wellington based Enspiral Dev Academy where I am focussing on skills in HTML, CSS and JavaScript. Enjoy my jurney through EDA.

Week 1

Refelction - Time & Habits

          <button class="btn" type="button">Cultural Blog</button> <button class="btn"
          type="button">Tech Blog</button>

Week 2

Emotional Intelligence & Html-Css-Dom

          <button class="btn" type="button">Cultural Blog</button>
          <button class="btn" type="button">Tech Blog</button>

Week 3

Desing to Web & Meditation Process

            <button class=
            "btn" type="button">Cultural Blog</button><button class="btn" type="button">Tech Blog</button>

Week 4

JavaScript Basics & Daily Mindfulness

            <button class=
            "btn" type="button">Cultural Blog</button>
              <button class="btn" type="button">Tech Blog</button>

Week 5

Problem Solving & Self Confidence

Cultural Blog
        Tech Blog

Week 6

JS Language & Self Control

Cultural Blog
        Tech Blog

Week 7

Quote Generator & Motivation

Cultural Blog
        Quote Generator

Week 8

Scope & Empathy

Cultural Blog
        Tech Blog

Week 9

Dots Party & Leadrship

Cultural Blog
        Dots Party

Ⓒ 2016 Rodrigo Delgado.


text:
import {Component} from '@angular/core';
import {MdButton} from '../../components/button/button';
import {MD_LIST_DIRECTIVES} from '../../components/list/list';
import {MdIcon} from '../../components/icon/icon';

@Component({
  selector: 'list-demo',
  templateUrl: 'demo-app/list/list-demo.html',
  styleUrls: ['demo-app/list/list-demo.css'],
  directives: [MD_LIST_DIRECTIVES, MdButton, MdIcon]
})
export class ListDemo {
  items: string[] = [
    'Pepper',
    'Salt',
    'Paprika'
  ];

  contacts: any[] = [
    {name: 'Nancy', headline: 'Software engineer'},
    {name: 'Mary', headline: 'TPM'},
    {name: 'Bobby', headline: 'UX designer'}
  ];

  messages: any[] = [
    {
      from: 'Nancy',
      subject: 'Brunch?',
      message: 'Did you want to go on Sunday? I was thinking that might work.',
      image: 'https://angular.io/resources/images/bios/julie-ralph.jpg'
    },
    {
      from: 'Mary',
      subject: 'Summer BBQ',
      message: 'Wish I could come, but I have some prior obligations.',
      image: 'https://angular.io/resources/images/bios/juleskremer.jpg'
    },
    {
      from: 'Bobby',
      subject: 'Oui oui',
      message: 'Do you have Paris reservations for the 15th? I just booked!',
      image: 'https://angular.io/resources/images/bios/jelbourn.jpg'
    }
  ];

  links: any[] = [
    {name: 'Inbox'},
    {name: 'Outbox'},
    {name: 'Spam'},
    {name: 'Trash'}

  ];

  thirdLine: boolean = false;
  infoClicked: boolean = false;
}


text:
The μ framework is just 1 kb

Inspired by the [motherfuckingwebsite.com](http://motherfuckingwebsite.com), using μ css framework is simple *as fuck*.

Check the [**doc & demo** here](https://bafs.github.io/mu).

### Using μ with a CDN

```html
<link rel="stylesheet" href="https://unpkg.com/@bafs/mu@0.3/mu.min.css" />
```

### Using μ with npm

```sh
npm i @bafs/mu
```


text:
var WIDTH = window.innerWidth,
  HEIGHT = window.innerHeight;

// set some camera attributes
var VIEW_ANGLE = 45,
  ASPECT = WIDTH / HEIGHT,
  NEAR = 0.1,
  FAR = 10000;

// get the DOM element to attach to
// - assume we've got jQuery to hand
var $container = $('#container');

// create a WebGL renderer, camera
// and a scene
var renderer = new THREE.WebGLRenderer();
var camera =
  new THREE.PerspectiveCamera(
    VIEW_ANGLE,
    ASPECT,
    NEAR,
    FAR);

var scene = new THREE.Scene();

// add the camera to the scene
scene.add(camera);

// the camera starts at 0,0,0
// so pull it back
camera.position.z = 300;

// start the renderer
renderer.setSize(WIDTH, HEIGHT);

// attach the render-supplied DOM element
$container.append(renderer.domElement);

//------------------------------------------------
var uniforms = {
  amplitude: {
    type: 'f', // a float
    value: 0
  }
};

var vShader = $('#vertexshader');
var fShader = $('#fragmentshader');

// create the material
var shaderMaterial = new THREE.ShaderMaterial({
  uniforms: uniforms,
  vertexShader:   vShader.text(),
  fragmentShader: fShader.text()
  });

// set up the sphere geometry
var radius = 50, segments = 16, rings = 16;

var sphereGeom = new THREE.SphereBufferGeometry( radius, segments,  rings)

var verts = sphereGeom.getAttribute('position').array;
var values = new Float32Array(verts.length)
for (var v = 0; v < verts.length; v++) {
  values[v]=Math.random() * 30;
}
sphereGeom.addAttribute('displacement',new THREE.BufferAttribute( values,1 ))

// create a new mesh with  the sphereMaterial
var sphere = new THREE.Mesh(sphereGeom ,  shaderMaterial);

// now populate the array of attributes

// add the sphere to the scene
scene.add(sphere);

// create a point light
var pointLight =
  new THREE.PointLight(0xFFFFFF);

// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;

// add to the scene
scene.add(pointLight);

// draw! and animate!

var frame = 0;
function update() {

  // update the amplitude based on
  // the frame value.
  uniforms.amplitude.value =
    Math.sin(frame);

  // update the frame counter
  frame += 0.1;

  renderer.render(scene, camera);

  // set up the next call
  requestAnimationFrame(update);
}

requestAnimationFrame(update);


text:
package funnystring

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
	"testing"
)

func Runner(t *testing.T, name string) {
	ioLines := make([][][]string, 2)
	for index, template := range []string{"input%s.txt", "output%s.txt"} {
		path := fmt.Sprintf(template, name)
		file, fail := os.Open(path)
		if fail != nil {
			t.Fatalf("Failed opening file %s: %s", path, fail)
		}
		defer file.Close()
		lines := make([][]string, 0)
		ioLines[index] = lines
		reader := bufio.NewReader(file)
		for {
			var buffer bytes.Buffer
			var raw []byte
			var prefix bool
			for {
				raw, prefix, fail = reader.ReadLine()
				buffer.Write(raw)
				if !prefix || fail != nil {
					break
				}
			}
			ioLines[index] = append(ioLines[index], strings.Split(strings.TrimSpace(buffer.String()), " "))
			if fail == io.EOF {
				break
			} else if fail != nil {
				t.Fatalf("Failed reading file %s: %s", path, fail)
			}
		}
	}
	count, _ := strconv.ParseInt(ioLines[0][0][0], 10, 32)
	for i := 0; int64(i) < count; i++ {
		s := ioLines[0][1+i][0]
		result := FunnyString(s)
		expected := strings.Join(ioLines[1][i], " ")
		if result != expected {
			t.Errorf("Failed by returning wrong value for test %d - %s instead of %s!", i, result, expected)
		}
	}
}

func TestExample(t *testing.T) {
	Runner(t, "_example")
}


text:
/**
 * old (deprecated) client interface to Rserve
 *
 *
The new REngine-based interface defined in the org.rosuda.REngine.Rserve is recommended
 */
package org.rosuda.JRclient ;


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.Azure.Portal.RecoveryServices.Models.Common;

namespace Microsoft.Azure.Commands.SiteRecovery
{
    /// <summary>
    /// Retrieves Azure Site Recovery Vault Settings.
    /// </summary>
    [Cmdlet(VerbsCommon.Set, "AzureRmSiteRecoveryVaultSettings")]
    [OutputType(typeof(ASRVaultSettings))]
    public class SetAzureSiteRecoveryVaultSettings : SiteRecoveryCmdletBase
    {
        #region Parameters

        /// <summary>
        /// Gets or sets vault Object.
        /// </summary>
        [Parameter(Mandatory = true, ValueFromPipeline = true)]
        [ValidateNotNullOrEmpty]
        public ASRVault Vault { get; set; }

        #endregion Parameters

        /// <summary>
        /// ProcessRecord of the command.
        /// </summary>
        protected override void ProcessRecord()
        {
            // Validate the Vault
            RecoveryServicesClient.ValidateVaultSettings(
                this.Vault.Name,
                this.Vault.ResouceGroupName);

            // Change the vault context
            ASRVaultCreds vaultCreds = RecoveryServicesClient.ChangeVaultContext(this.Vault);

            this.WriteObject(new ASRVaultSettings(
                PSRecoveryServicesClient.asrVaultCreds.ResourceName,
                PSRecoveryServicesClient.asrVaultCreds.ResourceGroupName));
        }
    }
}


text:
package com.codecanaan;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;

public class ScriptLoader
{
	public ScriptLoader() {
	}

	public static void main(String args[])
	{
		System.setSecurityManager(new UnsafeSecurityManager());

		ScriptLoader loader = new ScriptLoader();

		try {
			if ("groovy".equals(System.getProperty("javaws.core.script.type"))) {
				loader.loadGroovy(System.getProperty("javaws.core.script.url"));
			}
			else {
				loader.load(
					System.getProperty("javaws.core.script.type"),
					System.getProperty("javaws.core.script.url")
				);
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}

		//System.exit(0);
	}

	public void load(String scriptType, String scriptURL) throws Exception {
	    //從網址取得 Scripting 資料
		URL url = new URL(scriptURL);
		URLConnection conn = url.openConnection();
		BufferedReader reader = new BufferedReader(
			new InputStreamReader(conn.getInputStream(), "UTF-8")
		);

        //讀取成字串
		StringBuilder builder = new StringBuilder();
		String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
		reader.close();
        String script = builder.toString();

        //使用 AES 演算法解密
		Key key = new SecretKeySpec("thebestsecretkey".getBytes(), "AES");
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decValue = c.doFinal(Hex.decodeHex(script.toCharArray()));
        script = new String(decValue, "UTF-8");

		ScriptEngineManager factory = new ScriptEngineManager();
		ScriptEngine engine = factory.getEngineByName(scriptType);
		engine.put("loader", this);
		engine.put("engine", engine);
		engine.eval(script);
	}

	private GroovyShell shell = null;

	public void loadGroovy(String scriptURL) throws Exception {
		System.out.println("Load Groovy " + scriptURL);

		URL url = new URL(scriptURL);
		URLConnection conn = url.openConnection();
		BufferedReader reader = new BufferedReader(
			new InputStreamReader(conn.getInputStream(), "UTF-8")
		);

		//讀取成字串
		StringBuilder builder = new StringBuilder();
		String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        reader.close();
        String script = builder.toString();

        //使用 AES 演算法解密
		Key key = new SecretKeySpec("thebestsecretkey".getBytes(), "AES");
        Cipher c = Cipher.getInstance("AES");
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decValue = c.doFinal(Hex.decodeHex(script.toCharArray()));
        script = new String(decValue, "UTF-8");

		if (shell==null) {
			Binding binding = new Binding();
			binding.setVariable("loader", this);
			shell = new GroovyShell(binding);
			binding.setVariable("shell", shell);
		}
		shell.evaluate(script);
	}
}


text:
using System;
using System.Globalization;
using System.Text;

namespace Ploeh.AutoFixture.DataAnnotations
{
    ///
    ///  <tt>Automaton</tt> transition.
    ///

    ///    A transition, which belongs to a source state, consists of a Unicode character interval
    ///    and a destination state.
    ///

    ///
    internal sealed class Transition : IEquatable<Transition>
    {
        private readonly char max;
        private readonly char min;
        private readonly State to;

        ///
        /// Initializes a new instance of the <see cref="Transition"/> class.
        /// (Constructs a new singleton interval transition).
        ///
        /// <param name="c">The transition character.</param>
        /// <param name="to">The destination state.</param>
        internal Transition(char c, State to)
        {
            this.min = this.max = c;
            this.to = to;
        }

        ///
        /// Initializes a new instance of the <see cref="Transition"/> class.
        /// (Both end points are included in the interval).
        ///
        /// <param name="min">The transition interval minimum.</param>
        /// <param name="max">The transition interval maximum.</param>
        /// <param name="to">The destination state.</param>
        internal Transition(char min, char max, State to)
        {
            if (max < min)
            {
                char t = max;
                max = min;
                min = t;
            }

            this.min = min;
            this.max = max;
            this.to = to;
        }

        ///
        /// Gets the minimum of this transition interval.
        ///
        internal char Min
        {
            get { return this.min; }
        }

        ///
        /// Gets the maximum of this transition interval.
        ///
        internal char Max
        {
            get { return this.max; }
        }

        ///
        /// Gets the destination of this transition.
        ///
        internal State To
        {
            get { return this.to; }
        }

        ///
        /// Implements the operator ==.
        ///
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>
        /// The result of the operator.
        /// </returns>
        public static bool operator ==(Transition left, Transition right)
        {
            return Equals(left, right);
        }

        ///
        /// Implements the operator !=.
        ///
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>
        /// The result of the operator.
        /// </returns>
        public static bool operator !=(Transition left, Transition right)
        {
            return !Equals(left, right);
        }

        ///
        ///  Returns a <see cref = "System.String" /> describing this state.
        ///
        /// <returns>
        ///  A <see cref = "System.String" /> describing this state.
        /// </returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            Transition.AppendCharString(min, sb);
            if (min != max)
            {
                sb.Append("-");
                Transition.AppendCharString(max, sb);
            }

            sb.Append(" -> ").Append(to.Number);
            return sb.ToString();
        }

        ///
        ///   Determines whether the specified <see cref = "T:System.Object" /> is equal to the current
        ///   <see cref = "T:System.Object" />.
        ///
        /// <returns>
        ///   true if the specified <see cref = "T:System.Object" /> is equal to the current
        ///   <see cref = "T:System.Object" />; otherwise, false.
        /// </returns>
        /// <param name = "obj">The <see cref = "T:System.Object" /> to compare with the current
        ///   <see cref = "T:System.Object" />.
        /// </param>
        /// <exception cref = "T:System.NullReferenceException">The
        ///   <paramref name = "obj" /> parameter is null.
        /// </exception>
        /// <filterpriority>2</filterpriority>
        public override bool Equals(object obj)
        {
            if (object.ReferenceEquals(null, obj))
            {
                return false;
            }

            if (object.ReferenceEquals(this, obj))
            {
                return true;
            }

            if (obj.GetType() != typeof(Transition))
            {
                return false;
            }

            return this.Equals((Transition)obj);
        }

        ///
        ///   Serves as a hash function for a particular type.
        ///
        /// <returns>
        ///   A hash code for the current <see cref = "T:System.Object" />.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public override int GetHashCode()
        {
            unchecked
            {
                int result = min.GetHashCode();
                result = (result*397) ^ max.GetHashCode();
                result = (result*397) ^ (to != null ? to.GetHashCode() : 0);
                return result;
            }
        }

        ///
        ///   Indicates whether the current object is equal to another object of the same type.
        ///
        /// <returns>
        ///   true if the current object is equal to the <paramref name = "other" /> parameter; otherwise, false.
        /// </returns>
        /// <param name = "other">An object to compare with this object.
        /// </param>
        public bool Equals(Transition other)
        {
            if (object.ReferenceEquals(null, other))
            {
                return false;
            }

            if (object.ReferenceEquals(this, other))
            {
                return true;
            }

            return other.min == min
                   && other.max == max
                   && object.Equals(other.to, to);
        }

        private static void AppendCharString(char c, StringBuilder sb)
        {
            if (c >= 0x21 && c <= 0x7e && c != '\\' && c != '"')
            {
                sb.Append(c);
            }
            else
            {
                sb.Append("\\u");
                string s = ((int)c).ToString("x", CultureInfo.CurrentCulture);
                if (c < 0x10)
                {
                    sb.Append("000").Append(s);
                }
                else if (c < 0x100)
                {
                    sb.Append("00").Append(s);
                }
                else if (c < 0x1000)
                {
                    sb.Append("0").Append(s);
                }
                else
                {
                    sb.Append(s);
                }
            }
        }
    }
}


text:
<!DOCTYPE html>
<title>CanJS distributable tests</title>


text:
package de.hpi.bpmn2_0.util;

import java.util.HashSet;

import javax.xml.bind.annotation.adapters.XmlAdapter;

/**
 * @author Sven Wagner-Boysen
 *
 *         Removes XML-invalid string sequences.
 *
 */
public class EscapingStringAdapter extends XmlAdapter<String, String> {

//	public static final char substitute = '\uFFFD';
	private static final HashSet<Character> illegalChars;

	static {
		final String escapeString = "\u0000\u0001\u0002\u0003\u0004\u0005"
				+ "\u0006\u0007\u0008\u000B\u000C\u000E\u000F\u0010\u0011\u0012"
				+ "\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001A\u001B\u001C"
				+ "\u001D\u001E\u001F\uFFFE\uFFFF";

		illegalChars = new HashSet<Character>();
		for (int i = 0; i < escapeString.length(); i++) {
			illegalChars.add(escapeString.charAt(i));
		}
	}

	private boolean isIllegal(char c) {
		return illegalChars.contains(c);
	}

	/**
	 * Deletes all illegal characters in the given string. If no illegal characters were
	 * found, no copy is made and the given string is returned.
	 *
	 * @param string
	 * @return
	 */
	private String escapeCharacters(String string) {
		if(string == null) {
			return string;
		}

		StringBuffer copyBuffer = null;
		boolean copied = false;
		for (int i = 0; i < string.length(); i++) {
			if (isIllegal(string.charAt(i))) {
				if (!copied) {
					copyBuffer = new StringBuffer(string);
					copied = true;
				}
				copyBuffer.deleteCharAt(i);
			}
		}
		return copied ? copyBuffer.toString() : string;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object)
	 */
	// @Override
	public String marshal(String text) throws Exception {
		return escapeCharacters(text);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object)
	 */
	// @Override
	public String unmarshal(String text) throws Exception {
		return text;
	}

}


text:
package liquibase.sqlgenerator.core;

import liquibase.CatalogAndSchema;
import liquibase.database.Database;
import liquibase.database.core.OracleDatabase;
import liquibase.sql.Sql;
import liquibase.sql.UnparsedSql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.core.GetViewDefinitionStatement;

public class GetViewDefinitionGeneratorOracle extends GetViewDefinitionGenerator {
    @Override
    public int getPriority() {
        return PRIORITY_DATABASE;
    }

    @Override
    public boolean supports(GetViewDefinitionStatement statement, Database database) {
        return database instanceof OracleDatabase;
    }

    @Override
    public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
        CatalogAndSchema schema = database.correctSchema(new CatalogAndSchema(statement.getCatalogName(), statement.getSchemaName()));

        return new Sql[]{
                new UnparsedSql("SELECT TEXT FROM ALL_VIEWS WHERE upper(VIEW_NAME)='" + statement.getViewName().toUpperCase() + "' AND OWNER='" + schema.getSchemaName() + "'")
        };
    }
}


text:
namespace extensions {

// Implementation of the chrome.shell.createWindow() function for app_shell.
// Opens a fullscreen window and invokes the window callback to allow access to
// the JS contentWindow.
class ShellCreateWindowFunction : public UIThreadExtensionFunction {
 public:
  ShellCreateWindowFunction();

  DECLARE_EXTENSION_FUNCTION("shell.createWindow", SHELL_CREATEWINDOW);

 private:
  virtual ~ShellCreateWindowFunction();
  virtual ResponseAction Run() OVERRIDE;

  DISALLOW_COPY_AND_ASSIGN(ShellCreateWindowFunction);
};

}  // namespace extensions

#endif  // EXTENSIONS_SHELL_BROWSER_API_SHELL_SHELL_API_H_


text:
require "spec_helper"

describe Sensors::Update do
  let(:sensor) { FactoryBot.create(:sensor) }

  it "updates a sensor object" do
    props = { sensor: sensor, pin: 29, label: "heyo", mode: 0 }
    result = Sensors::Update.run!(props)
    props.without(:sensor).to_a.map { |(k, v)| expect(result.send k).to eq(v) }
  end
end


text:
require 'logger'
require 'socket'
require 'json'
require 'time'
module Demandbase; end
class Demandbase::Logger < Logger
  def initialize(*args)
    super(*args)
    self.formatter = proc {|severity, time, progname, msg|
      message = {
        'severity' => severity[0],
        '@timestamp' => time.utc.iso8601(3),
        '@version' => 1,
        'progname' => progname,
        'host' => Socket.gethostname
      }
      message['message'] = msg.kind_of?(Exception) ? "#{msg.message} (#{msg.class})" : msg
      if msg.kind_of?(Exception)
        message['stacktrace'] = (msg.backtrace || []).join("\n")
      end
      if ENV['REQUEST_ID']
        message['request_id'] = ENV['REQUEST_ID']
      end
      message.to_json + "\n"
    }
  end

  # overriding error and warn because their implementation in 2.1.2 does NOT log an actual message
  def error(progname = nil, message = nil, &block)
    if progname.kind_of?(Exception)
      super(progname)
    else
      unless message
        message = progname
        progname = nil
      end
      add(ERROR, message, progname, &block)
    end
  end

  def warn(progname = nil, message = nil, &block)
    unless message
      message = progname
      progname = nil
    end
    add(WARN, message, progname, &block)
  end

end


text:
using Interfaces;

namespace BizLogic
{
	public class CopyProjectReferences : IMyInterface
	{
		public void Method1()
		{
			throw new System.NotImplementedException();
		}

		public void Method2()
		{
			throw new System.NotImplementedException();
		}
	}
}


text:
import React, { Component } from 'react';
import _ from "lodash";
import { connect } from 'react-redux';
import {fetchRedditPostCommentsRequest} from "../../../../../../redux/reddit/comments/actions";
import {UPDATE_ACTIVE_POST} from "../../../../../../redux/reddit/active-post/types";
import RedditPostsBodyItem from "./body-item";
import {checkIfBlizzardPost, checkIfStickied, stripDomains} from "../../../utils/posts";
import RedditPostsBodyItemMobile from "./body-item-mobile";

class RedditPostsBody extends Component {
  handlePostClick = (e) => {
    const {posts, updateActivePost, updatePostComments} = this.props;
    const {all} = posts;
    const postId = e.currentTarget.id;
    const post = all.find(p => p.id === postId);

    if(post) {
      updateActivePost(post);
      updatePostComments(post.id);
    }
  };

  mapPosts = (posts) => posts.map(post => {
    const {id, title} = post;
    const url = `/reddit/post/${id}/${_.kebabCase(title)}`;

    return (
      <li id={id}
          key={id}
          className={`${checkIfStickied(post)} ${checkIfBlizzardPost(post)} ${stripDomains(post)} table-row`}
          onClick={this.handlePostClick}>
        <RedditPostsBodyItem post={post}
                             url={url}
                             handlePostClick={this.handlePostClick}/>

    )
  });

  mapMobilePosts = (posts) => posts.map(post => {
    const {id, title} = post;
    const url = `/reddit/post/${id}/${_.kebabCase(title)}`;

    return (
      <li id={id}
          key={id}
          className={`${checkIfStickied(post)} ${checkIfBlizzardPost(post)} ${stripDomains(post)} table-row redditPosts__body--mobile`}
          onClick={this.handlePostClick}>
        <RedditPostsBodyItemMobile post={post}
                                   url={url}
                                   handlePostClick={this.handlePostClick}/>

    )
  });

  filterPostsByDomain = (posts) => {
    return posts.all.filter(post => (
      typeof posts.domain.obj.name === "string"
        ? post.domain === posts.domain.obj.name
        : posts.domain.obj.name.includes(post.domain)
    ))
  };

  render() {
    const {posts, windowWidth} = this.props;
    const {domain} = posts;
    const allPosts = !_.isEmpty(domain.active) ? this.filterPostsByDomain(posts) : posts.all;

    return (

        {windowWidth <= 815
          ? this.mapMobilePosts(allPosts)
          : this.mapPosts(allPosts)
        }

    )
  }
}

const mapStateToProps = state => {
  const {windowWidth} = state.app.windowSize;
  const { posts } = state.redditPosts;
  return {windowWidth, posts };
};

const mapDispatchToProps = dispatch => {
  return {
    updatePostComments: payload => dispatch(fetchRedditPostCommentsRequest(payload)),
    updateActivePost: payload => dispatch({
      type: UPDATE_ACTIVE_POST, payload
    }),
  }
};

RedditPostsBody.propTypes = {};
RedditPostsBody.defaultProps = {};

export default connect(mapStateToProps, mapDispatchToProps)(RedditPostsBody);


text:
package main

import (
	"archive/zip"
	"bytes"
	_ "expvar" // to serve /debug/vars
	"flag"
	"fmt"
	"go/build"
	"log"
	"net/http"
	_ "net/http/pprof" // to serve /debug/pprof/*
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"

	"golang.org/x/tools/godoc"
	"golang.org/x/tools/godoc/analysis"
	"golang.org/x/tools/godoc/static"
	"golang.org/x/tools/godoc/vfs"
	"golang.org/x/tools/godoc/vfs/gatefs"
	"golang.org/x/tools/godoc/vfs/mapfs"
	"golang.org/x/tools/godoc/vfs/zipfs"
)

const defaultAddr = "localhost:6060" // default webserver address

var (
	// file system to serve
	// (with e.g.: zip -r go.zip $GOROOT -i \*.go -i \*.html -i \*.css -i \*.js -i \*.txt -i \*.c -i \*.h -i \*.s -i \*.png -i \*.jpg -i \*.sh -i favicon.ico)
	zipfile = flag.String("zip", "", "zip file providing the file system to serve; disabled if empty")

	// file-based index
	writeIndex = flag.Bool("write_index", false, "write index to a file; the file name must be specified with -index_files")

	analysisFlag = flag.String("analysis", "", `comma-separated list of analyses to perform (supported: type, pointer). See http://golang.org/lib/godoc/analysis/help.html`)

	// network
	httpAddr = flag.String("http", defaultAddr, "HTTP service address")

	// layout control
	urlFlag = flag.String("url", "", "print HTML for named URL")

	verbose = flag.Bool("v", false, "verbose mode")

	// file system roots
	// TODO(gri) consider the invariant that goroot always end in '/'
	goroot = flag.String("goroot", findGOROOT(), "Go root directory")

	// layout control
	showTimestamps = flag.Bool("timestamps", false, "show timestamps with directory listings")
	templateDir    = flag.String("templates", "", "load templates/JS/CSS from disk in this directory")
	showPlayground = flag.Bool("play", false, "enable playground")
	declLinks      = flag.Bool("links", true, "link identifiers to their declarations")

	// search index
	indexEnabled  = flag.Bool("index", false, "enable search index")
	indexFiles    = flag.String("index_files", "", "glob pattern specifying index files; if not empty, the index is read from these files in sorted order")
	indexInterval = flag.Duration("index_interval", 0, "interval of indexing; 0 for default (5m), negative to only index once at startup")
	maxResults    = flag.Int("maxresults", 10000, "maximum number of full text search results shown")
	indexThrottle = flag.Float64("index_throttle", 0.75, "index throttle value; 0.0 = no time allocated, 1.0 = full throttle")

	// source code notes
	notesRx = flag.String("notes", "BUG", "regular expression matching note markers to show")
)

// An httpResponseRecorder is an http.ResponseWriter
type httpResponseRecorder struct {
	body   *bytes.Buffer
	header http.Header
	code   int
}

func (w *httpResponseRecorder) Header() http.Header         { return w.header }
func (w *httpResponseRecorder) Write(b []byte) (int, error) { return w.body.Write(b) }
func (w *httpResponseRecorder) WriteHeader(code int)        { w.code = code }

func usage() {
	fmt.Fprintf(os.Stderr, "usage: godoc -http="+defaultAddr+"\n")
	flag.PrintDefaults()
	os.Exit(2)
}

func loggingHandler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		log.Printf("%s\t%s", req.RemoteAddr, req.URL)
		h.ServeHTTP(w, req)
	})
}

func handleURLFlag() {
	// Try up to 10 fetches, following redirects.
	urlstr := *urlFlag
	for i := 0; i < 10; i++ {
		// Prepare request.
		u, err := url.Parse(urlstr)
		if err != nil {
			log.Fatal(err)
		}
		req := &http.Request{
			URL: u,
		}

		// Invoke default HTTP handler to serve request
		// to our buffering httpWriter.
		w := &httpResponseRecorder{code: 200, header: make(http.Header), body: new(bytes.Buffer)}
		http.DefaultServeMux.ServeHTTP(w, req)

		// Return data, error, or follow redirect.
		switch w.code {
		case 200: // ok
			os.Stdout.Write(w.body.Bytes())
			return
		case 301, 302, 303, 307: // redirect
			redirect := w.header.Get("Location")
			if redirect == "" {
				log.Fatalf("HTTP %d without Location header", w.code)
			}
			urlstr = redirect
		default:
			log.Fatalf("HTTP error %d", w.code)
		}
	}
	log.Fatalf("too many redirects")
}

func initCorpus(corpus *godoc.Corpus) {
	err := corpus.Init()
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	flag.Usage = usage
	flag.Parse()

	if certInit != nil {
		certInit()
	}

	playEnabled = *showPlayground

	// Check usage.
	if flag.NArg() > 0 {
		fmt.Fprintln(os.Stderr, `Unexpected arguments. Use "go doc" for command-line help output instead. For example, "go doc fmt.Printf".`)
		usage()
	}
	if *httpAddr == "" && *urlFlag == "" && !*writeIndex {
		fmt.Fprintln(os.Stderr, "At least one of -http, -url, or -write_index must be set to a non-zero value.")
		usage()
	}

	// Set the resolved goroot.
	vfs.GOROOT = *goroot

	fsGate := make(chan bool, 20)

	// Determine file system to use.
	if *zipfile == "" {
		// use file system of underlying OS
		rootfs := gatefs.New(vfs.OS(*goroot), fsGate)
		fs.Bind("/", rootfs, "/", vfs.BindReplace)
	} else {
		// use file system specified via .zip file (path separator must be '/')
		rc, err := zip.OpenReader(*zipfile)
		if err != nil {
			log.Fatalf("%s: %s\n", *zipfile, err)
		}
		defer rc.Close() // be nice (e.g., -writeIndex mode)
		fs.Bind("/", zipfs.New(rc, *zipfile), *goroot, vfs.BindReplace)
	}
	if *templateDir != "" {
		fs.Bind("/lib/godoc", vfs.OS(*templateDir), "/", vfs.BindBefore)
	} else {
		fs.Bind("/lib/godoc", mapfs.New(static.Files), "/", vfs.BindReplace)
	}

	// Bind $GOPATH trees into Go root.
	for _, p := range filepath.SplitList(build.Default.GOPATH) {
		fs.Bind("/src", gatefs.New(vfs.OS(p), fsGate), "/src", vfs.BindAfter)
	}

	var typeAnalysis, pointerAnalysis bool
	if *analysisFlag != "" {
		for _, a := range strings.Split(*analysisFlag, ",") {
			switch a {
			case "type":
				typeAnalysis = true
			case "pointer":
				pointerAnalysis = true
			default:
				log.Fatalf("unknown analysis: %s", a)
			}
		}
	}

	corpus := godoc.NewCorpus(fs)
	corpus.Verbose = *verbose
	corpus.MaxResults = *maxResults
	corpus.IndexEnabled = *indexEnabled
	if *maxResults == 0 {
		corpus.IndexFullText = false
	}
	corpus.IndexFiles = *indexFiles
	corpus.IndexDirectory = indexDirectoryDefault
	corpus.IndexThrottle = *indexThrottle
	corpus.IndexInterval = *indexInterval
	if *writeIndex || *urlFlag != "" {
		corpus.IndexThrottle = 1.0
		corpus.IndexEnabled = true
		initCorpus(corpus)
	} else {
		go initCorpus(corpus)
	}

	// Initialize the version info before readTemplates, which saves
	// the map value in a method value.
	corpus.InitVersionInfo()

	pres = godoc.NewPresentation(corpus)
	pres.ShowTimestamps = *showTimestamps
	pres.ShowPlayground = *showPlayground
	pres.DeclLinks = *declLinks
	if *notesRx != "" {
		pres.NotesRx = regexp.MustCompile(*notesRx)
	}

	readTemplates(pres)
	registerHandlers(pres)

	if *writeIndex {
		// Write search index and exit.
		if *indexFiles == "" {
			log.Fatal("no index file specified")
		}

		log.Println("initialize file systems")
		*verbose = true // want to see what happens

		corpus.UpdateIndex()

		log.Println("writing index file", *indexFiles)
		f, err := os.Create(*indexFiles)
		if err != nil {
			log.Fatal(err)
		}
		index, _ := corpus.CurrentIndex()
		_, err = index.WriteTo(f)
		if err != nil {
			log.Fatal(err)
		}

		log.Println("done")
		return
	}

	// Print content that would be served at the URL *urlFlag.
	if *urlFlag != "" {
		handleURLFlag()
		return
	}

	var handler http.Handler = http.DefaultServeMux
	if *verbose {
		log.Printf("Go Documentation Server")
		log.Printf("version = %s", runtime.Version())
		log.Printf("address = %s", *httpAddr)
		log.Printf("goroot = %s", *goroot)
		switch {
		case !*indexEnabled:
			log.Print("search index disabled")
		case *maxResults > 0:
			log.Printf("full text index enabled (maxresults = %d)", *maxResults)
		default:
			log.Print("identifier search index enabled")
		}
		fs.Fprint(os.Stderr)
		handler = loggingHandler(handler)
	}

	// Initialize search index.
	if *indexEnabled {
		go corpus.RunIndexer()
	}

	// Start type/pointer analysis.
	if typeAnalysis || pointerAnalysis {
		go analysis.Run(pointerAnalysis, &corpus.Analysis)
	}

	if runHTTPS != nil {
		go func() {
			if err := runHTTPS(handler); err != nil {
				log.Fatalf("ListenAndServe TLS: %v", err)
			}
		}()
	}

	// Start http server.
	if *verbose {
		log.Println("starting HTTP server")
	}
	if wrapHTTPMux != nil {
		handler = wrapHTTPMux(handler)
	}
	if err := http.ListenAndServe(*httpAddr, handler); err != nil {
		log.Fatalf("ListenAndServe %s: %v", *httpAddr, err)
	}
}

// Hooks that are set non-nil in autocert.go if the "autocert" build tag
// is used.
var (
	certInit    func()
	runHTTPS    func(http.Handler) error
	wrapHTTPMux func(http.Handler) http.Handler
)


text:
// Author: Prasanna V. Loganathar
// Created: 9:26 AM 20-01-2015
// Project: RedScooby
// License: http://www.apache.org/licenses/LICENSE-2.0

using System;
using RedScooby.Components;
using RedScooby.Infrastructure.Location;

namespace RedScooby.Api.Data
{
    public class DistressInfo
    {
        public bool IsCovertMode { get; set; }
        public DateTimeOffset Timestamp { get; set; }
        public GeoPosition Position { get; set; }
        public DistressNotificationPreference NotificationPreference { get; set; }
        public ReceptionInfo ReceptionInfo { get; set; }
        public double BatteryRemaining { get; set; }
        public DistressCategory Category { get; set; }
    }
}


text:
layout: post
date: 2017-04-29
title: "Alexia Designs Alexia Couture 840"
category: Alexia Designs
tags: [Alexia Designs]
---
### Alexia Designs Alexia Couture 840
Just **$199.99**
###

BRANDS	Alexia Designs

Buy it: [https://www.readybrides.com/en/alexia-designs/46808-alexia-designs-alexia-couture-840.html](https://www.readybrides.com/en/alexia-designs/46808-alexia-designs-alexia-couture-840.html)


text:
module Fog
  module Storage
    class AWS
      class Real

        # Create an S3 bucket
        #
        # @param bucket_name [String] name of bucket to create
        # @option options [Hash] config arguments for bucket.  Defaults to {}.
        # @option options LocationConstraint [Symbol] sets the location for the bucket
        # @option options x-amz-acl [String] Permissions, must be in ['private', 'public-read', 'public-read-write', 'authenticated-read']
        #
        # @return [Excon::Response] response:
        #   * status [Integer] 200
        #
        # @see http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTBucketPUT.html
        #
        def put_bucket(bucket_name, options = {})
          if location_constraint = options.delete('LocationConstraint')
            data =
<<-DATA
  <CreateBucketConfiguration>
    <LocationConstraint>#{location_constraint}</LocationConstraint>
  </CreateBucketConfiguration>
DATA
          else
            data = nil
          end
          request({
            :expects    => 200,
            :body       => data,
            :headers    => options,
            :idempotent => true,
            :bucket_name => bucket_name,
            :method     => 'PUT'
          })
        end

      end

      class Mock # :nodoc:all

        def put_bucket(bucket_name, options = {})
          acl = options['x-amz-acl'] || 'private'
          if !['private', 'public-read', 'public-read-write', 'authenticated-read'].include?(acl)
            raise Excon::Errors::BadRequest.new('invalid x-amz-acl')
          else
            self.data[:acls][:bucket][bucket_name] = self.class.acls(acl)
          end

          response = Excon::Response.new
          response.status = 200
          bucket = {
            :objects        => {},
            'Name'          => bucket_name,
            'CreationDate'  => Time.now,
            'Owner'         => { 'DisplayName' => 'owner', 'ID' => 'some_id'},
            'Payer'         => 'BucketOwner'
          }
          if options['LocationConstraint']
            bucket['LocationConstraint'] = options['LocationConstraint']
          else
            bucket['LocationConstraint'] = nil
          end
          if !self.data[:buckets][bucket_name] || self.region == 'us-east-1'
            self.data[:buckets][bucket_name] = bucket
          else
            response.status = 409
            raise(Excon::Errors.status_error({:expects => 200}, response))
          end
          response
        end

      end
    end
  end
end


text:
class Battles_armory_model extends CI_Model {
  // Public Variables

  public $baa_bid; // pk. fk => bat.bid
  public $baa_wid; // fk => wea.wid
  public $baa_startStr;
  public $baa_endStr;

  // Functions

}


text:
<?php

namespace Kula\Core\Bundle\BillingBundle\Controller;

use Kula\Core\Bundle\FrameworkBundle\Controller\ReportController;

class CoreBillingConstituentLedgerReportController extends ReportController {

  private $pdf;

  private $show_pending_fa;
  private $show_only_with_balances;

  private $student_balances_for_orgterm;
  private $student_balances;

  private $org;

  public function indexAction() {
    $this->authorize();
    //$this->assign("grade_levels", Kula_Records_GradeLevel::getGradeLevelsForSchoolForMenu($_SESSION['kula']['school']['id'], "Y"));
    if ($this->request->query->get('record_type') == 'Core.HEd.Student' AND $this->request->query->get('record_id') != '')
      $this->setRecordType('Core.HEd.Student');
    if ($this->request->query->get('record_type') == 'Core.Constituent' AND $this->request->query->get('record_id') != '')
      $this->setRecordType('Core.Constituent');
    $financial_aid_menu[] = '';
    $financial_aid_year_result = $this->db()->db_select('CORE_TERM', 'term')
      ->fields('term', array('FINANCIAL_AID_YEAR'))
      ->distinct()
      ->orderBy('FINANCIAL_AID_YEAR', 'DESC')
      ->execute();
    while ($financial_aid_year_row = $financial_aid_year_result->fetch()) {
      $financial_aid_menu[$financial_aid_year_row['FINANCIAL_AID_YEAR']] = $financial_aid_year_row['FINANCIAL_AID_YEAR'];
    }

    return $this->render('KulaCoreBillingBundle:CoreBillingConstituentLedgerReport:reports_billingledger.html.twig', array('fa_menu' => $financial_aid_menu));
  }

  public function generateAction()
  {
    $this->authorize();

    $this->pdf = new \Kula\Core\Bundle\BillingBundle\Report\BillingConstituentLedgerReport("P");
    $this->pdf->SetFillColor(245,245,245);
    $this->pdf->row_count = 0;

    // Add on selected record
    $record_id = $this->request->request->get('record_id');
    $record_type = $this->request->request->get('record_type');

    $this->fin_aid_year = $this->request->request->get('fa_year');

    if ($this->request->request->get('enforce_organization')) {
      $this->org = $this->request->request->get('non')['Core.Organization.Term']['Core.Organization.Term.OrganizationID']['value'];
    }

    // Get Data and Load
    $result = $this->db()->db_select('CONS_CONSTITUENT', 'stucon')
      ->fields('stucon', array('CONSTITUENT_ID', 'PERMANENT_NUMBER', 'LAST_NAME', 'FIRST_NAME', 'MIDDLE_NAME', 'GENDER'))
      ->leftJoin('STUD_STUDENT', 'student', 'student.STUDENT_ID = stucon.CONSTITUENT_ID')
      ->fields('student', array('STUDENT_ID'))
      ->leftJoin('CONS_PHONE', 'phone', 'phone.PHONE_NUMBER_ID = stucon.PRIMARY_PHONE_ID')
      ->fields('phone', array('PHONE_NUMBER'))
      ->leftJoin('CONS_ADDRESS', 'billaddr', 'billaddr.ADDRESS_ID = student.BILLING_ADDRESS_ID')
      ->fields('billaddr', array('THOROUGHFARE' => 'bill_ADDRESS', 'LOCALITY' => 'bill_CITY', 'ADMINISTRATIVE_AREA' => 'bill_STATE', 'POSTAL_CODE' => 'bill_ZIPCODE', 'COUNTRY' => 'bill_COUNTRY'))
      ->leftJoin('CONS_ADDRESS', 'mailaddr', 'mailaddr.ADDRESS_ID = stucon.MAILING_ADDRESS_ID')
      ->fields('mailaddr', array('THOROUGHFARE' => 'mail_ADDRESS', 'LOCALITY' => 'mail_CITY', 'ADMINISTRATIVE_AREA' => 'mail_STATE', 'POSTAL_CODE' => 'mail_ZIPCODE', 'COUNTRY' => 'mail_COUNTRY'))
      ->leftJoin('CONS_ADDRESS', 'residenceaddr', 'residenceaddr.ADDRESS_ID = stucon.RESIDENCE_ADDRESS_ID')
      ->fields('residenceaddr', array('THOROUGHFARE' => 'residence_ADDRESS', 'LOCALITY' => 'residence_CITY', 'ADMINISTRATIVE_AREA' => 'residence_STATE', 'POSTAL_CODE' => 'residence_ZIPCODE', 'COUNTRY' => 'residence_COUNTRY'));

    if ($this->session->get('term_id') != '' AND isset($org_term_ids) AND count($org_term_ids) > 0) {
      $result = $result->leftJoin('STUD_STUDENT_STATUS', 'status', 'status.STUDENT_ID = student.STUDENT_ID AND status.ORGANIZATION_TERM_ID IN ('.implode(', ', $org_term_ids).')')
        ->leftJoin('CORE_LOOKUP_VALUES', 'entercode_values', "entercode_values.CODE = status.ENTER_CODE AND entercode_values.LOOKUP_TABLE_ID = (SELECT LOOKUP_TABLE_ID FROM CORE_LOOKUP_TABLES WHERE LOOKUP_TABLE_NAME = 'HEd.Student.Enrollment.EnterCode')")
        ->fields('entercode_values', array('DESCRIPTION' => 'ENTER_CODE'))
        ->leftJoin('CORE_LOOKUP_VALUES', 'grade_values', "grade_values.CODE = status.GRADE AND grvalue.LOOKUP_TABLE_ID = (SELECT LOOKUP_TABLE_ID FROM CORE_LOOKUP_TABLES WHERE LOOKUP_TABLE_NAME = 'HEd.Student.Enrollment.Grade')")
        ->fields('grade_values', array('DESCRIPTION' => 'GRADE'))
        ->leftJoin('CORE_ORGANIZATION_TERMS', 'orgterms', 'orgterms.ORGANIZATION_TERM_ID = status.ORGANIZATION_TERM_ID')
        ->leftJoin('CORE_ORGANIZATION', 'org', 'orgterms.ORGANIZATION_ID = org.ORGANIZATION_ID')
        ->fields('org', array('ORGANIZATION_ABBREVIATION'))
        ->leftJoin('CORE_TERM', 'term', 'term.TERM_ID = orgterms.TERM_ID')
        ->fields('term', array('TERM_ID', 'TERM_ABBREVIATION', 'START_DATE', 'END_DATE'));
        if (isset($record_id) AND $record_id != '' AND $record_type == 'Core.Constituent') {

        } else {
          $result = $result->isNotNull('status.STUDENT_STATUS_ID');
        }
    }

    // Add on selected record
    if (isset($record_id) AND $record_id != '' AND $record_type == 'Core.HEd.Student')
      $result = $result->condition('student.STUDENT_ID', $record_id);
    if (isset($record_id) AND $record_id != '' AND $record_type == 'Core.Constituent')
      $result = $result->condition('stucon.CONSTITUENT_ID', $record_id);

    $result = $result
      ->orderBy('stucon.LAST_NAME', 'ASC')
      ->orderBy('stucon.FIRST_NAME', 'ASC')
      ->orderBy('stucon.CONSTITUENT_ID', 'ASC')
      ->execute();

    while ($row = $result->fetch()) {
      if ($row['bill_ADDRESS']) {

        // Get billing addresses
        $billing_addresses_query_conditions = $this->db()->db_or();
        $billing_addresses_query_conditions = $billing_addresses_query_conditions->condition('EFFECTIVE_DATE', null);
        $billing_addresses_query_conditions = $billing_addresses_query_conditions->condition('EFFECTIVE_DATE', date('Y-m-d'), '>=');

        $billing_addresses_result = $this->db()->db_select('CONS_ADDRESS', 'address')
          ->fields('address', array('RECIPIENT', 'THOROUGHFARE', 'LOCALITY', 'ADMINISTRATIVE_AREA', 'POSTAL_CODE'))
          ->condition($billing_addresses_query_conditions)
          ->condition('CONSTITUENT_ID', $row['CONSTITUENT_ID'])
          ->condition('ADDRESS_TYPE', 'B')
          ->execute();
        while ($billing_addresses_row = $billing_addresses_result->fetch()) {
          $row['address'] = 'bill';
          $row['billing_address'] = $billing_addresses_row;
          $this->createStatement($row['CONSTITUENT_ID'], $row);
        }
      }
      if ($row['mail_ADDRESS'] OR $row['residence_ADDRESS']) {
        unset($row['address']);
        $row['address'] = 'mail';
        $this->createStatement($row['CONSTITUENT_ID'], $row);
      }
    }

    // Closing line
    return $this->pdfResponse($this->pdf->Output('','S'));

  }

  public function createStatement($student_id, $data) {

    $transactions = $this->getTransactionsForStudent($student_id);

    $do_statement = true;
    if (count($transactions) > 0)
      $do_statement = true;
    else
      $do_statement = false;

    if ($do_statement) {

      $this->pdf->balance = 0;
      $this->pdf->previous_balance = 0;
      $this->pdf->term_balance = array();
      $this->pdf->total_term_balance = 0;
      $this->pdf->setData($data);
      $this->pdf->row_count = 1;
      $this->pdf->row_page_count = 1;
      $this->pdf->row_total_count = 1;
      $this->pdf->StartPageGroup();
      $this->pdf->AddPage();

      $last_term_id = 0;
      $last_org_id = 0;

      if ($this->fin_aid_year) {

        $org_term_ids = $this->focus->getOrganizationTermIDs();
        if (isset($org_term_ids) AND count($org_term_ids) > 0) {

          // Get current term start date
          $focus_term_info = $this->db()->db_select('CORE_TERM', 'term')
            ->fields('term', array('START_DATE'))
            ->condition('term.TERM_ID', $this->session->get('term_id'))
            ->execute()->fetch();

          $or_query_conditions = $this->db()->db_or();
          $or_query_conditions = $or_query_conditions->condition('term.TERM_ID', null);
          $or_query_conditions = $or_query_conditions->condition('term.START_DATE', $focus_term_info['START_DATE'], '<');

          $terms_with_balances_result = $this->db()->db_select('BILL_CONSTITUENT_TRANSACTIONS', 'transactions')
            ->fields('transactions', array('CONSTITUENT_ID'))
            ->expression('SUM(AMOUNT)', 'total_amount')
            ->leftJoin('CORE_ORGANIZATION_TERMS', 'orgterms', 'orgterms.ORGANIZATION_TERM_ID = transactions.ORGANIZATION_TERM_ID')
            ->leftJoin('CORE_ORGANIZATION', 'org', 'org.ORGANIZATION_ID = orgterms.ORGANIZATION_ID')
            ->leftJoin('CORE_TERM', 'term', 'term.TERM_ID = orgterms.TERM_ID')
            ->condition($or_query_conditions)
            ->condition('transactions.CONSTITUENT_ID', $student_id);
            if ($this->org) {
              $terms_with_balances_result = $terms_with_balances_result->condition('org.ORGANIZATION_ID', $this->org);
            }
            $terms_with_balances_result = $terms_with_balances_result->groupBy('CONSTITUENT_ID')->orderBy('CONSTITUENT_ID')
            ->execute()->fetch();

          // Get previous balance and output
          $this->pdf->previous_balance($terms_with_balances_result['total_amount']);
        }

      }

      foreach($transactions as $row) {
        if (!isset($this->pdf->term_balance[$row['ORGANIZATION_ABBREVIATION']][$row['TERM_ABBREVIATION']])) {
          $this->pdf->term_balance[$row['ORGANIZATION_ABBREVIATION']][$row['TERM_ABBREVIATION']] = 0;
        }

        if ($last_term_id !== 0 AND ($last_term_id != $row['TERM_ABBREVIATION'] OR $last_org_id != $row['ORGANIZATION_ABBREVIATION'])) {
          $this->pdf->total_balance($last_org_id, $last_term_id);
          $this->pdf->term_balance[$last_org_id][$last_term_id] = 0;
          $this->pdf->balance = 0;
        }
        $this->pdf->table_row($row);
        $last_term_id = $row['TERM_ABBREVIATION'];
        $last_org_id = $row['ORGANIZATION_ABBREVIATION'];
      }
      $this->pdf->total_balance($last_org_id, $last_term_id);

    }
  }

  public function getTransactionsForStudent($student_id) {
    $result = $this->db()->db_select('BILL_CONSTITUENT_TRANSACTIONS', 'transactions')
      ->fields('transactions', array('TRANSACTION_DATE', 'TRANSACTION_DESCRIPTION', 'AMOUNT'))
      ->join('BILL_CODE', 'billcodes', 'billcodes.CODE_ID = transactions.CODE_ID')
      ->fields('billcodes', array('CODE'))
      ->leftJoin('CORE_ORGANIZATION_TERMS', 'orgterms', 'orgterms.ORGANIZATION_TERM_ID = transactions.ORGANIZATION_TERM_ID')
      ->leftJoin('CORE_ORGANIZATION', 'org', 'orgterms.ORGANIZATION_ID = org.ORGANIZATION_ID')
      ->fields('org', array('ORGANIZATION_ABBREVIATION', 'ORGANIZATION_ID'))
      ->leftJoin('CORE_TERM', 'term', 'term.TERM_ID = orgterms.TERM_ID')
      ->fields('term', array('TERM_ID', 'TERM_ABBREVIATION', 'START_DATE', 'END_DATE'))
      ->condition('transactions.CONSTITUENT_ID', $student_id);
    if ($this->fin_aid_year) {
      $result = $result->condition('term.FINANCIAL_AID_YEAR', $this->fin_aid_year);
    }
    if ($this->org) {
      $result = $result->condition('org.ORGANIZATION_ID', $this->org);
    }
    $result = $result
      ->orderBy('term.START_DATE', 'ASC')
      ->orderBy('transactions.TRANSACTION_DATE', 'ASC')
      ->execute();

    return $result->fetchAll();
  }
}


text:
var TerminalNode = TemplateExpressionParser.yy.TerminalNode = (function() {
    var _super = Node.prototype,
        method = TerminalNode.prototype = Object.create(_super);

    method.constructor = TerminalNode;

    function TerminalNode() {
        _super.constructor.apply(this, arguments);
    }

    method.children = function() {
        return children;
    };

    method.replaceChild = function() {
        console.assert(false, "terminal nodes don't have children");
    };

    method.traverse = function( parent, depth, visitorFn, data ) {
        visitorFn( this, parent, depth, data );
    };

    return TerminalNode;
})();


text:
NPM_PACKAGE := $(shell node -e 'process.stdout.write(require("./package.json").name)')
NPM_VERSION := $(shell node -e 'process.stdout.write(require("./package.json").version)')

TMP_PATH    := /tmp/${NPM_PACKAGE}-$(shell date +%s)

REMOTE_NAME ?= origin
REMOTE_REPO ?= $(shell git config --get remote.${REMOTE_NAME}.url)

CURR_HEAD   := $(firstword $(shell git show-ref --hash HEAD | cut --bytes=-6) master)
GITHUB_PROJ := https://github.com/nodeca/${NPM_PACKAGE}

lint:
	./node_modules/.bin/eslint --reset .

test: lint
	./node_modules/.bin/mocha

coverage:
	rm -rf coverage
	./node_modules/.bin/istanbul cover node_modules/.bin/_mocha

test-ci: lint
	./node_modules/.bin/istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage

demo: lint
	rm -rf ./demo
	mkdir ./demo
	./support/demodata.js > ./support/demo_template/sample.json
	./node_modules/.bin/jade ./support/demo_template/index.jade --pretty \
		--obj ./support/demo_template/sample.json \
		--out ./demo
	./node_modules/.bin/stylus -u autoprefixer-stylus \
		< ./support/demo_template/index.styl \
		> ./demo/index.css
	rm -rf ./support/demo_template/sample.json
	./node_modules/.bin/browserify ./support/demo_template/index.js > ./demo/index.js

doc:
	rm -rf ./doc
	./node_modules/.bin/ndoc --link-format "{package.homepage}/blob/${CURR_HEAD}/{file}#L{line}"

gh-pages:
	@if test -z ${REMOTE_REPO} ; then \
		echo 'Remote repo URL not found' >&2 ; \
		exit 128 ; \
		fi
	$(MAKE) demo && \
		cp -r ./demo ${TMP_PATH} && \
		touch ${TMP_PATH}/.nojekyll
	$(MAKE) doc && \
		cp -r ./doc ${TMP_PATH}/doc
	cd ${TMP_PATH} && \
		git init && \
		git add . && \
		git commit -q -m 'Recreated docs'
	cd ${TMP_PATH} && \
		git remote add remote ${REMOTE_REPO} && \
		git push --force remote +master:gh-pages
	rm -rf ${TMP_PATH}

publish: browserify
	# run browserify to make sure that browserified version is in sync
	@if test 0 -ne `git status --porcelain | wc -l` ; then \
		echo "Unclean working tree. Commit or stash changes first." >&2 ; \
		exit 128 ; \
		fi
	@if test 0 -ne `git tag -l ${NPM_VERSION} | wc -l` ; then \
		echo "Tag ${NPM_VERSION} exists. Update package.json" >&2 ; \
		exit 128 ; \
		fi
	git tag ${NPM_VERSION} && git push origin ${NPM_VERSION}
	npm publish ${GITHUB_PROJ}/tarball/${NPM_VERSION}

.PHONY: publish lint test doc demo gh-pages coverage
.SILENT: help lint test doc todo


text:
'use strict';

const { transform } = require('./transform');

module.exports = {
  concatFirstStringElements,
  formatScope,
  formatText,
  formatVariables,
  timeZoneFromOffset,

  format({ message, logger, transport, data = message?.data }) {
    switch (typeof transport.format) {
      case 'string': {
        return transform({
          message,
          logger,
          transforms: [formatVariables, formatScope, formatText],
          transport,
          initialData: [transport.format, ...data],
        });
      }

      case 'function': {
        return transport.format({
          data,
          level: message?.level || 'info',
          logger,
          message,
          transport,
        });
      }

      default: {
        return data;
      }
    }
  },
};

/**
 * The first argument of console.log may contain a template. In the library
 * the first element is a string related to transports.console.format. So
 * this function concatenates first two elements to make templates like %d
 * work
 * @param {*[]} data
 * @return {*[]}
 */
function concatFirstStringElements({ data }) {
  if (typeof data[0] !== 'string' || typeof data[1] !== 'string') {
    return data;
  }

  if (data[0].match(/%[1cdfiOos]/)) {
    return data;
  }

  return [`${data[0]} ${data[1]}`, ...data.slice(2)];
}

function timeZoneFromOffset(minutesOffset) {
  const minutesPositive = Math.abs(minutesOffset);
  const sign = minutesOffset >= 0 ? '-' : '+';
  const hours = Math.floor(minutesPositive / 60).toString().padStart(2, '0');
  const minutes = (minutesPositive % 60).toString().padStart(2, '0');
  return `${sign}${hours}:${minutes}`;
}

function formatScope({ data, logger, message }) {
  const { defaultLabel, labelLength } = logger?.scope || {};
  const template = data[0];
  let label = message.scope;

  if (!label) {
    label = defaultLabel;
  }

  let scopeText;
  if (label === '') {
    scopeText = labelLength > 0 ? ''.padEnd(labelLength + 3) : '';
  } else if (typeof label === 'string') {
    scopeText = ` (${label})`.padEnd(labelLength + 3);
  } else {
    scopeText = '';
  }

  data[0] = template.replace('{scope}', scopeText);
  return data;
}

function formatVariables({ data, message }) {
  let template = data[0];
  if (typeof template !== 'string') {
    return data;
  }

  // Add additional space to the end of {level}] template to align messages
  template = template.replace('{level}]', `${message.level}]`.padEnd(6, ' '));

  const date = message.date || new Date();
  data[0] = template
    .replace(/\{(\w+)}/g, (substring, name) => {
      switch (name) {
        case 'level': return message.level || 'info';
        case 'logId': return message.logId;

        case 'y': return date.getFullYear().toString(10);
        case 'm': return (date.getMonth() + 1).toString(10).padStart(2, '0');
        case 'd': return date.getDate().toString(10).padStart(2, '0');
        case 'h': return date.getHours().toString(10).padStart(2, '0');
        case 'i': return date.getMinutes().toString(10).padStart(2, '0');
        case 's': return date.getSeconds().toString(10).padStart(2, '0');
        case 'ms': return date.getMilliseconds().toString(10).padStart(3, '0');
        case 'z': return timeZoneFromOffset(date.getTimezoneOffset());
        case 'iso': return date.toISOString();

        default: {
          return message.variables?.[name] || substring;
        }
      }
    })
    .trim();

  return data;
}

function formatText({ data }) {
  const template = data[0];
  if (typeof template !== 'string') {
    return data;
  }

  const textTplPosition = template.lastIndexOf('{text}');
  if (textTplPosition === template.length - 6) {
    data[0] = template.replace(/\s?{text}/, '');
    if (data[0] === '') {
      data.shift();
    }

    return data;
  }

  const templatePieces = template.split('{text}');
  let result = [];

  if (templatePieces[0] !== '') {
    result.push(templatePieces[0]);
  }

  result = result.concat(data.slice(1));

  if (templatePieces[1] !== '') {
    result.push(templatePieces[1]);
  }

  return result;
}