text:
#include "tensorflow/lite/toco/graph_transformations/lstm_utils.h"

#include <string>

namespace toco {

void CreateOptionalArray(Model* model, std::string* input_array_buffer,
                         const std::string& array_name) {
  *input_array_buffer = array_name;
  model->CreateOptionalArray(array_name);
}

void CopyArrayData(const Buffer<ArrayDataType::kFloat>& src_buffer,
                   int src_stride, int src_start_idx1, int src_start_idx2,
                   Buffer<ArrayDataType::kFloat>* dst_buffer, int dst_stride,
                   int dst_start_idx1, int dst_start_idx2, int dim1_copy_size,
                   int dim2_copy_size) {
  int src_offset = src_start_idx1 * src_stride + src_start_idx2;
  int dst_offset = dst_start_idx1 * dst_stride + dst_start_idx2;
  for (int i = 0; i < dim1_copy_size; i++) {
    for (int j = 0; j < dim2_copy_size; j++) {
      int idx_src = src_offset + i * src_stride + j;
      int idx_dst = dst_offset + i * dst_stride + j;
      dst_buffer->data[idx_dst] = src_buffer.data[idx_src];
    }
  }
}

Buffer<ArrayDataType::kFloat>* CreateFloatArrayBuffer(Model* model,
                                                      std::string* array_name,
                                                      const Shape& shape) {
  *array_name = AvailableArrayName(*model, *array_name);
  auto& array = model->GetOrCreateArray(*array_name);
  array.data_type = ArrayDataType::kFloat;
  array.copy_shape(shape);
  Buffer<ArrayDataType::kFloat>* buffer =
      &(array.GetMutableBuffer<ArrayDataType::kFloat>());
  buffer->data.resize(RequiredBufferSizeForShape(shape));
  return buffer;
}

void CopySubArrayToArray(Model* model, std::string* array_name,
                         const std::string& tensor_name, int dim1_size,
                         int dim2_size, const Array& original_array,
                         int start_idx1, int start_idx2) {
  // Determine whether it's bias or not, create shape, buffer.
  bool is_bias = dim2_size == 1;
  Shape shape = is_bias ? Shape({dim1_size}) : Shape({dim1_size, dim2_size});
  Buffer<ArrayDataType::kFloat>* buffer =
      CreateFloatArrayBuffer(model, array_name, shape);
  auto& orig_buffer = original_array.GetBuffer<ArrayDataType::kFloat>();

  // Copy data from big tensor.
  CopyArrayData(orig_buffer, is_bias ? 1 : original_array.shape().dims(1),
                start_idx1, start_idx2, buffer, dim2_size, 0, 0, dim1_size,
                dim2_size);
}

void CopyArrayToSubArray(Buffer<ArrayDataType::kFloat>& tensor_buffer,
                         int tensor_stride, const Array& sub_array,
                         int start_idx1, int start_idx2) {
  // Get tensor data.
  bool is_bias = sub_array.shape().dims().size() == 1;
  int dim1_copy_size = sub_array.shape().dims()[0];
  int dim2_copy_size = is_bias ? 1 : sub_array.shape().dims(1);
  auto& sub_buffer = sub_array.GetBuffer<ArrayDataType::kFloat>();

  // Copy data from sub tensor.
  CopyArrayData(sub_buffer, dim2_copy_size, 0, 0, &tensor_buffer,
                is_bias ? 1 : tensor_stride, start_idx1, start_idx2,
                dim1_copy_size, dim2_copy_size);
}

bool GetMatchingRnnArray(Model* model,
                         const std::string& back_edge_source_array,
                         std::string* rnn_array) {
  for (const auto& rnn_state : model->flags.rnn_states()) {
    if (rnn_state.back_edge_source_array() == back_edge_source_array) {
      *rnn_array = rnn_state.state_array();
      return true;
    }
  }
  return false;
}

}  // namespace toco


text:
package log

import (
	"github.com/lastbackend/monarch/pkg/log/logger"
)

var l *logger.Logger

const def = ""

// Initialize loggers map

func New(name string, level int) *logger.Logger {
	l = logger.New(name, level)
	return l
}

func Debug(args ...interface{}) {
	l.Debug(args...)
}

func Debugf(format string, args ...interface{}) {
	l.Debugf(format, args...)
}

func Info(args ...interface{}) {
	l.Info(args...)
}

func Infof(format string, args ...interface{}) {
	l.Infof(format, args...)
}

func Warn(args ...interface{}) {
	l.Warn(args...)
}

func Warnf(format string, args ...interface{}) {
	l.Warnf(format, args...)
}

func Error(args ...interface{}) {
	l.Error(args...)
}

func Errorf(format string, args ...interface{}) {
	l.Errorf(format, args...)
}

func Fatal(args ...interface{}) {
	l.Fatal(args...)
}

func Fatalf(format string, args ...interface{}) {
	l.Fatalf(format, args...)
}

func Panic(args ...interface{}) {
	l.Panic(args...)
}

func Panicf(format string, args ...interface{}) {
	l.Panicf(format, args...)
}

func V(level logger.Level) logger.Verbose {
	return l.V(level)
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare (strict_types=1);
namespace Ssch\TYPO3Rector\Rector\Extensions\solr\v8;

use PhpParser\Node;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Type\ObjectType;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
 * @changelog https://github.com/TYPO3-Solr/ext-solr/commit/523aff17187ecc25e4cad83e7d20af31329ecd6c#diff-563034ee193649001177d14f15ce4dcb24cbe39ecd0de99588fe2ec841b283fe
 * @see \Ssch\TYPO3Rector\Tests\Rector\Extensions\solr\v8\SolrConnectionAddDocumentsToWriteServiceAddDocumentsRector\SolrConnectionAddDocumentsToWriteServiceAddDocumentsTest
 */
final class SolrConnectionAddDocumentsToWriteServiceAddDocumentsRector extends \Rector\Core\Rector\AbstractRector
{
    /**
     * @codeCoverageIgnore
     */
    public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
    {
        return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Use method addDocuments from WriteService of SolrConnection class', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample(<<<'CODE_SAMPLE'
$this->solrConnection->addDocuments([]);
CODE_SAMPLE
, <<<'CODE_SAMPLE'
$this->solrConnection->getWriteService()->addDocuments([]);
CODE_SAMPLE
)]);
    }
    /**
     * @return array<class-string<Node>>
     */
    public function getNodeTypes() : array
    {
        return [\PhpParser\Node\Expr\MethodCall::class];
    }
    /**
     * @param MethodCall $node
     */
    public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
    {
        if (!$this->nodeTypeResolver->isMethodStaticCallOrClassMethodObjectType($node, new \PHPStan\Type\ObjectType('ApacheSolrForTypo3\\Solr\\System\\Solr\\SolrConnection'))) {
            return null;
        }
        if (!$this->isName($node->name, 'addDocuments')) {
            return null;
        }
        return $this->nodeFactory->createMethodCall($this->nodeFactory->createMethodCall($node->var, 'getWriteService'), 'addDocuments', $node->args);
    }
}


text:
<?php

namespace Es\View;

use Es\Mvc\ViewInterface;
use Es\Services\Provider;

/**
 * The accessors of View.
 */
trait ViewTrait
{
    /**
     * Sets the view.
     *
     * @param \Es\Mvc\ViewInterface $view The view
     */
    public function setView(ViewInterface $view)
    {
        Provider::getServices()->set('View', $view);
    }

    /**
     * Gets the view.
     *
     * @return \Es\Mvc\ViewInterface The view
     */
    public function getView()
    {
        return Provider::getServices()->get('View');
    }
}


text:
import {devModeEqual, looseIdentical} from '@angular/core/src/change_detection/change_detection_util';
import {ExpressionChangedAfterItHasBeenCheckedError} from '@angular/core/src/linker/errors';

export function createElementAndAppend(parent: any, name: string) {
  const el = document.createElement(name);
  parent.appendChild(el);
  return el;
}

export function createTextAndAppend(parent: any) {
  const txt = document.createTextNode('');
  parent.appendChild(txt);
  return txt;
}

export function createAnchorAndAppend(parent: any) {
  const txt = document.createComment('');
  parent.appendChild(txt);
  return txt;
}

export function checkBinding(throwOnChange: boolean, oldValue: any, newValue: any): boolean {
  if (throwOnChange) {
    if (!devModeEqual(oldValue, newValue)) {
      throw new ExpressionChangedAfterItHasBeenCheckedError(oldValue, newValue, false);
    }
    return false;
  } else {
    return !looseIdentical(oldValue, newValue);
  }
}


text:
class 'GUIAlienSensorBlips' (GUIScript)

GUIAlienSensorBlips.kBlipImageName = "ui/aura.dds"

GUIAlienSensorBlips.kFontName = Fonts.kArial_15

GUIAlienSensorBlips.kAlphaPerSecond = 0.8
GUIAlienSensorBlips.kImpulseIntervall = 2.5

GUIAlienSensorBlips.kRotationDuration = 5

function GUIAlienSensorBlips:Initialize()

    GUIAlienSensorBlips.kDefaultBlipSize = GUIScale(20)
    GUIAlienSensorBlips.kMaxBlipSize = GUIScale(80)

    self.updateInterval = 0

    self.activeBlipList = { }

    self.visible = true

end

function GUIAlienSensorBlips:SetIsVisible(state)

    self.visible = state
    for i=1, #self.activeBlipList do
        self.activeBlipList[i].GraphicsItem:SetIsVisible(state)
        self.activeBlipList[i].TextItem:SetIsVisible(state)
    end

end

function GUIAlienSensorBlips:GetIsVisible()

    return self.visible

end

function GUIAlienSensorBlips:Uninitialize()

    for i, blip in ipairs(self.activeBlipList) do
        GUI.DestroyItem(blip.GraphicsItem)
        GUI.DestroyItem(blip.TextItem)
    end
    self.activeBlipList = { }

end

function GUIAlienSensorBlips:Update(deltaTime)

    PROFILE("GUIAlienSensorBlips:Update")

    self:UpdateBlipList(AlienUI_GetSensorBlipInfo())

    self:UpdateAnimations(deltaTime)

end

function GUIAlienSensorBlips:UpdateAnimations(deltaTime)

    PROFILE("GUIAlienSensorBlips:UpdateAnimations")

    local baseRotationPercentage = (Shared.GetTime() % GUIAlienSensorBlips.kRotationDuration) / GUIAlienSensorBlips.kRotationDuration

    if not self.timeLastImpulse then
        self.timeLastImpulse = Shared.GetTime()
    end

    if self.timeLastImpulse + GUIAlienSensorBlips.kImpulseIntervall < Shared.GetTime() then
        self.timeLastImpulse = Shared.GetTime()
    end

    local destAlpha = math.max(0, 1 - (Shared.GetTime() - self.timeLastImpulse) * GUIAlienSensorBlips.kAlphaPerSecond)

    for i, blip in ipairs(self.activeBlipList) do
        local size = math.min(blip.Radius * GUIAlienSensorBlips.kDefaultBlipSize, GUIAlienSensorBlips.kMaxBlipSize)
        blip.GraphicsItem:SetSize(Vector(size, size, 0))

        -- Offset by size / 2 so the blip is centered.
        local newPosition = Vector(blip.ScreenX - size / 2, blip.ScreenY - size / 2, 0)
        blip.GraphicsItem:SetPosition(newPosition)

        -- rotate the blip
        blip.GraphicsItem:SetRotation(Vector(0, 0, 2 * math.pi * (baseRotationPercentage + (i / #self.activeBlipList))))

        -- Draw blips as barely visible when in view, to communicate their purpose. Animate color towards final value.
        local currentColor = blip.GraphicsItem:GetColor()
        destAlpha = ConditionalValue(blip.Obstructed, destAlpha * blip.Radius, currentColor.a - GUIAlienSensorBlips.kAlphaPerSecond * deltaTime)

        currentColor.a = destAlpha
        blip.GraphicsItem:SetColor(currentColor)
        blip.TextItem:SetColor(currentColor)

    end

end

function GUIAlienSensorBlips:UpdateBlipList(activeBlips)

    PROFILE("GUIAlienSensorBlips:UpdateBlipList")

    local numElementsPerBlip = 5
    local numBlips = table.icount(activeBlips) / numElementsPerBlip

    while numBlips > table.icount(self.activeBlipList) do
        local newBlipItem = self:CreateBlipItem()
        table.insert(self.activeBlipList, newBlipItem)
    end

    while numBlips < table.icount(self.activeBlipList) do
        GUI.DestroyItem(self.activeBlipList[#self.activeBlipList].GraphicsItem)
        table.remove(self.activeBlipList, #self.activeBlipList)
    end

    -- Update current blip state.
    local currentIndex = 1
    while numBlips > 0 do
        local updateBlip = self.activeBlipList[numBlips]
        updateBlip.ScreenX = activeBlips[currentIndex]
        updateBlip.ScreenY = activeBlips[currentIndex + 1]
        updateBlip.Radius = activeBlips[currentIndex + 2]
        updateBlip.Obstructed = activeBlips[currentIndex + 3]
        updateBlip.name = activeBlips[currentIndex + 4]

        --updateBlip.TextItem:SetText( activeBlips[currentIndex + 4] )

        numBlips = numBlips - 1
        currentIndex = currentIndex + numElementsPerBlip
    end

end

function GUIAlienSensorBlips:OnResolutionChanged(oldX, oldY, newX, newY)
    self:Uninitialize()
    self:Initialize()
end

function GUIAlienSensorBlips:CreateBlipItem()

    local newBlip = { ScreenX = 0, ScreenY = 0, Radius = 0, Type = 0 }
    newBlip.GraphicsItem = GUIManager:CreateGraphicItem()
    newBlip.GraphicsItem:SetAnchor(GUIItem.Left, GUIItem.Top)
    newBlip.GraphicsItem:SetTexture(GUIAlienSensorBlips.kBlipImageName)
    newBlip.GraphicsItem:SetBlendTechnique(GUIItem.Add)
    newBlip.GraphicsItem:SetIsVisible(self.visible)
    newBlip.GraphicsItem:SetColor(Color(1, 0.9, 0.4, 1))

    newBlip.TextItem = GUIManager:CreateTextItem()
    newBlip.TextItem:SetAnchor(GUIItem.Middle, GUIItem.Top)
    newBlip.TextItem:SetFontName(GUIAlienSensorBlips.kFontName)
    newBlip.TextItem:SetScale(GetScaledVector())
    newBlip.TextItem:SetTextAlignmentX(GUIItem.Align_Center)
    newBlip.TextItem:SetTextAlignmentY(GUIItem.Align_Min)
    newBlip.TextItem:SetColor(Color(1, 0.9, 0.4, 1))
    newBlip.TextItem:SetIsVisible(self.visible)
    GUIMakeFontScale(newBlip.TextItem)

    newBlip.GraphicsItem:AddChild(newBlip.TextItem)

    return newBlip

end


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

namespace EqualsVerifier.Util
{
    public class SupportedAttributes : IAttribute
    {
        /// <summary>
        /// If a class is marked [Immutable], EqualsVerifier will not
        /// complain about fields not being readonly.
        public static readonly SupportedAttributes IMMUTABLE = new SupportedAttributes(false, "Immutable");

        ///<summary>
        /// If a field is marked [NonNull] or [NotNull],
        /// <see cref="EqualsVerifier"/> will not complain about potential
        /// NullPointerExceptions being thrown if this field is null.
        /// </summary>
        public static readonly SupportedAttributes NONNULL = new SupportedAttributes(false, "Nonnull", "NonNull", "NotNull");

        public static readonly IEnumerable<IAttribute> Values = new IAttribute[] {
            IMMUTABLE,
            NONNULL
        };

        public SupportedAttributes(bool inherits, params string[] descriptors)
        {
            _inherits = inherits;
            _descriptors = descriptors ?? Enumerable.Empty<string>();
        }

        public IEnumerable<string> Descriptors { get { return _descriptors; } }

        readonly IEnumerable<string> _descriptors;

        public bool Inherits { get { return _inherits; } }

        readonly bool _inherits;
    }
}


text:
'use strict';
var TYPE_RE = /\.(\w{3,4})(\?.*)?$/i,
    extend = require('extend-object');

function parseSource(el) {

   var src = el.attr("src"),
      type = el.attr("type") || "",
      suffix = src.split(TYPE_RE)[1];
   type = type.toLowerCase();
   return extend(el.data(), { src: src, suffix: suffix || type, type: type || suffix });
}

function getType(typ) {
  if (/mpegurl/i.test(typ)) return 'application/x-mpegurl';
  return 'video/' + typ;
}

/* Resolves video object from initial configuration and from load() method */
module.exports = function URLResolver() {
  var self = this;

  self.sourcesFromVideoTag = function(videoTag, $) {
    var sources = [];
    // initial sources
    $("source", videoTag).each(function() {
      sources.push(parseSource($(this)));
    });

    if (!sources.length && videoTag.length) sources.push(parseSource(videoTag));

    return sources;
  };

  self.resolve = function(video, sources) {
    if (!video) return { sources: sources };

    if (typeof video == 'string') {
      video = { src: video, sources: [] };
      video.sources = (sources || []).map(function(source) {
        var suffix = source.src.split(TYPE_RE)[1];
        return {type: source.type, src: video.src.replace(TYPE_RE, '.' + suffix + "$2")};
      });
    }

    if (video instanceof Array) {
      video = {
        sources: video.map(function(src) {
          if (src.type && src.src) return src;
          return Object.keys(src).reduce(function(m, typ) {
            return extend(m, {
              type: getType(typ),
              src: src[typ]
            });
          }, {});
        })
      };
    }

    return video;
  };
};

module.exports.TYPE_RE = TYPE_RE;


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%-5level  %msg%n</pattern>
        </encoder>
    </appender>

    <!-- quiet, jetty -->
    <logger name="org.eclipse.jetty" level="WARN" />

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>


text:
<!DOCTYPE html>

	<title>
		Philippines
	</title>

	<link rel="stylesheet" type="text/css" href="JamCss/Main.css">
	<link rel="stylesheet" type="text/css" href="JamCss/phil_home.css">

Home

About Us

Wander To...

Romania

Ireland

Oman

Pakistan

Philippines

Gallery

Travel Resources

Calendar

External Sites

  Philippines

  "The Philippines is defined by its emerald rice fields, teeming megacities, graffiti-splashed jeepneys,

smouldering volcanoes, bug- eyed tarsiers, fuzzy water buffalo and smiling, happy- go-lucky people."

-The Lonely Planet

  Where is it?

The Philippines, officially known as the Republic of the Philippines, is a sovereign island country in Southeast Asia situated in the western Pacific Ocean.
It consists of 7,107 islands that are categorized broadly under three main geographical divisions: Luzon, Visayas, and Mindanao. Its capital city is Manila
while its most populous city is Quezon City; both are part of Metro Manila.

  What is it like?

 Philippines has one of the most diverse wildlife in the world.

Philippines is home of a diverse range of birds, plants, animals and sea creatures. There are nearly 200 mammal species in the Philippines.
The Philippine Tarsier is one of the smallest species of monkeys in the world. You will find more than 600 species of birds, over 300 species of
reptiles and amphibians and at least 400 coral species. From the giant whale shark to the world's smallest fish, everything you can dream of
is united in the beautiful islands of the Philippines.

Philippines has some stunning surroundings, the fantastic Chocolate Hills in Bohol, the Rice Terraces in Banaue, the incredible Archipelago of El Nido.
You can climb one of the 37 volcanoes, for example the Mount Pinatubo, or see the world's smallest volcano of Taal. You can discover caves, lakes and
waterfalls. If you love nature, you will love the Philippines.

If you want the bright and sunny, tropical glory of the Philippines, plan your trip between the summer months of March and May.
It will be hot and dry, but that is what beaches, sunblock and straw hats are for!
Want things a little bit cooler? Then November to February are best for you.
We would say avoid the rainy season from June to October, but a good traveller knows that off-peak season means lower rates in airfares, hotels, resorts
and maybe the beer too. Just be forewarned that the months between July and September are characterized by typhoons.

  Who we are?

Wherever you choose to go in the Philippines, it's the Filipinos that will make your holiday unforgettable. Lonely Planet calls us,
"among the most ebullient and easy going people anywhere."
Don't be shy about coming up to a Filipino and starting a conversation. We're not just fun, we're officially friendly too.
Forbes.com ranked us the friendliest country in Asia - eight in the world!

We have two official languages: Filipino and English.

Filipino is based on Tagalog, the predominant dialect from the Luzon mainland, and is used nationally to communicate among the ethnic groups.
There are seven other widely used languages: Cebuano, Ilocano, Hiligaynon or Ilonggo, Bicolano, Waray, Pampango, and Pangasinense.
Apart from these, there are more than 176 local dialects!

  Know More:

		 ⓒ DIT Travel 2014
		|
		FAQs
		|
		Feedback
		|
		Contact Us
		|
		 D.I.T


text:
namespace YAF.Controls
{
    #region Using

    using System;
    using System.Collections.Generic;
    using System.Linq;

    using YAF.Classes;
    using YAF.Core;
    using YAF.Core.Model;
    using YAF.Types;
    using YAF.Types.Extensions;
    using YAF.Types.Interfaces;
    using YAF.Types.Models;
    using YAF.Utilities;
    using YAF.Utils;

    #endregion

    /// <summary>
    /// The Attachments Upload Dialog.
    /// </summary>
    public partial class AttachmentsUploadDialog : BaseUserControl
    {
        /// <summary>
        /// Gets the file exentsions.
        /// </summary>
        /// <value>
        /// The file exentsions.
        /// </value>
        private IList<FileExtension> FileExentsions
        {
            get
            {
                return this.GetRepository<FileExtension>().ListTyped();
            }
        }

        #region Methods

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnInit([NotNull] EventArgs e)
        {
            this.PreRender += this.AttachmentsUploadDialog_PreRender;
            base.OnInit(e);
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
        {
            // show disallowed or allowed localized text depending on the Board Setting
            this.ExtensionTitle.LocalizedTag = this.Get<YafBoardSettings>().FileExtensionAreAllowed
                                                   ? "ALLOWED_EXTENSIONS"
                                                   : "DISALLOWED_EXTENSIONS";

            var types = string.Empty;
            var first = true;

            foreach (var extension in this.FileExentsions)
            {
                types += "{1}*.{0}".FormatWith(extension.Extension, first ? string.Empty : ", ");

                if (first)
                {
                    first = false;
                }
            }

            if (types.IsSet())
            {
                this.ExtensionsList.Text = types;
            }

            if (this.Get<YafBoardSettings>().MaxFileSize > 0)
            {
                this.UploadNodePlaceHold.Visible = true;
                this.UploadNote.Text = this.GetTextFormatted(
                    "UPLOAD_NOTE",
                    (this.Get<YafBoardSettings>().MaxFileSize / 1024).ToString());
            }
            else
            {
                this.UploadNodePlaceHold.Visible = false;
            }
        }

        /// <summary>
        /// Handles the PreRender event of the AttachmentsUploadDialog control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void AttachmentsUploadDialog_PreRender([NotNull] object sender, [NotNull] EventArgs e)
        {
            // Setup Hover Card JS
            YafContext.Current.PageElements.RegisterJsBlockStartup(
                "fileUploadjs",
                JavaScriptBlocks.FileUploadLoadJs(
                    string.Join("|", this.FileExentsions.Select(ext => ext.Extension)),
                    this.Get<YafBoardSettings>().MaxFileSize,
                    "{0}YafUploader.ashx".FormatWith(YafForumInfo.ForumClientFileRoot),
                    this.PageContext.PageForumID));
        }

        #endregion
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Roux & Triebel, Bull. Soc. linn. Provence 45: 515 (1994)

#### Original name
Stigmidium placynthii Cl. Roux & Nav.-Ros.

### Remarks
null


text:
<template name="loading">

</template>


text:
function hand = quiver3(Q, x, y, z, varargin)
% Overloads the quiver3 function to automatically calculate the electric
% field at the given points generated by the charges Q

% Input validation
num = length(x);

% E-Field Calculation

%
hand = quiver3(x, y, z, u, v, w, varargin{:});
if nargout == 0
    clear hand
end
end


text:
{% extends "cradmin_legacy/viewhelpers/update.django.html" %}
{% load i18n %}
{% load cradmin_legacy_tags %}
{% load cradmin_legacy_icon_tags %}

{% block pageheader-outer-extraclasses %}
    {{ block.super }}
    devilry-page-header-with-backlink
{% endblock %}

{% block pageheader-inner %}

            {% trans "Back to semester overview" %}

    {{ block.super }}
{% endblock pageheader-inner %}


text:
"""
Module with tests for templateexporter.py
"""

#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from traitlets.config import Config

from .base import ExportersTestsBase
from .cheese import CheesePreprocessor
from ..templateexporter import TemplateExporter

#-----------------------------------------------------------------------------
# Class
#-----------------------------------------------------------------------------

class TestExporter(ExportersTestsBase):
    """Contains test functions for exporter.py"""

    def test_constructor(self):
        """
        Can a TemplateExporter be constructed?
        """
        TemplateExporter()

    def test_export(self):
        """
        Can a TemplateExporter export something?
        """
        exporter = self._make_exporter()
        (output, resources) = exporter.from_filename(self._get_notebook())
        assert len(output) > 0

    def test_extract_outputs(self):
        """
        If the ExtractOutputPreprocessor is enabled, are outputs extracted?
        """
        config = Config({'ExtractOutputPreprocessor': {'enabled': True}})
        exporter = self._make_exporter(config=config)
        (output, resources) = exporter.from_filename(self._get_notebook())
        assert resources is not None
        assert isinstance(resources['outputs'], dict)
        assert len(resources['outputs']) > 0

    def test_preprocessor_class(self):
        """
        Can a preprocessor be added to the preprocessors list by class type?
        """
        config = Config({'Exporter': {'preprocessors': [CheesePreprocessor]}})
        exporter = self._make_exporter(config=config)
        (output, resources) = exporter.from_filename(self._get_notebook())
        assert resources is not None
        assert resources['cheese'] == 'real'

    def test_preprocessor_instance(self):
        """
        Can a preprocessor be added to the preprocessors list by instance?
        """
        config = Config({'Exporter': {'preprocessors': [CheesePreprocessor()]}})
        exporter = self._make_exporter(config=config)
        (output, resources) = exporter.from_filename(self._get_notebook())
        assert resources is not None
        assert resources['cheese'] == 'real'

    def test_preprocessor_dottedobjectname(self):
        """
        Can a preprocessor be added to the preprocessors list by dotted object name?
        """
        config = Config({'Exporter': {'preprocessors': ['nbconvert.exporters.tests.cheese.CheesePreprocessor']}})
        exporter = self._make_exporter(config=config)
        (output, resources) = exporter.from_filename(self._get_notebook())
        assert resources is not None
        assert resources['cheese'] == 'real'

    def test_preprocessor_via_method(self):
        """
        Can a preprocessor be added via the Exporter convenience method?
        """
        exporter = self._make_exporter()
        exporter.register_preprocessor(CheesePreprocessor, enabled=True)
        (output, resources) = exporter.from_filename(self._get_notebook())
        assert resources is not None
        assert resources['cheese'] == 'real'

    def _make_exporter(self, config=None):
        # Create the exporter instance, make sure to set a template name since
        # the base TemplateExporter doesn't have a template associated with it.
        exporter = TemplateExporter(config=config, template_file='python')
        return exporter


text:
package org.apache.flink.table.expressions

import org.apache.flink.table.`type`.{InternalType, InternalTypes, TimestampType}
import org.apache.flink.table.calcite.FlinkRelBuilder.NamedWindowProperty

import java.util
import java.util.Collections

trait WindowProperty {

  def toNamedWindowProperty(name: String): NamedWindowProperty

  def resultType: InternalType

}

abstract class AbstractWindowProperty(child: Expression)
  extends Expression
  with WindowProperty {

  override def toString = s"WindowProperty($child)"

  override def accept[T](exprVisitor: ExpressionVisitor[T]): T =
    exprVisitor.visit(this)

  override def getChildren: util.List[Expression] = Collections.emptyList()

  def toNamedWindowProperty(name: String): NamedWindowProperty = NamedWindowProperty(name, this)
}

case class WindowStart(child: Expression) extends AbstractWindowProperty(child) {

  override def resultType: TimestampType = InternalTypes.TIMESTAMP

  override def toString: String = s"start($child)"
}

case class WindowEnd(child: Expression) extends AbstractWindowProperty(child) {

  override def resultType: TimestampType = InternalTypes.TIMESTAMP

  override def toString: String = s"end($child)"
}


text:
=begin
#===============================================================================
 Title: Actor Inventory Scenes
 Author: Hime
 Date: Mar 10, 2014
--------------------------------------------------------------------------------
 ** Change log
 Mar 10, 2014
   - key item list is pulled from the leader
 Jul 27, 2013
   - Initial release
--------------------------------------------------------------------------------
 ** Terms of Use
 * Free to use in non-commercial projects
 * Contact me for commercial use
 * No real support. The script is provided as-is
 * Will do bug fixes, but no compatibility patches
 * Features may be requested but no guarantees, especially if it is non-trivial
 * Credits to Hime Works in your project
 * Preserve this header
--------------------------------------------------------------------------------
 ** Description

 This script provides scenes and windows to complement the Actor Inventory
 system. It is based on the default scenes and windows.

--------------------------------------------------------------------------------
 ** Required

 Actor Inventory
 (http://himeworks.com/2013/07/27/actor-inventory/)

--------------------------------------------------------------------------------
 ** Installation

 Place this script below Actor Inventory and above Main

--------------------------------------------------------------------------------
 ** Usage

 Plug and play.

#===============================================================================
=end
$imported = {} if $imported.nil?
$imported["TH_ActorInventoryScenes"] = true
#===============================================================================
# ** Rest of script
#===============================================================================
#-------------------------------------------------------------------------------
# Basic actor inventory scene and windows. Change it so that you first select
# an actor before opening the item menu. The item windows must obtain the data
# from the actor's inventory
#-------------------------------------------------------------------------------
class Window_ItemList < Window_Selectable

  alias :th_actor_inventory_initialize :initialize
  def initialize(x, y, width, height)
    th_actor_inventory_initialize(x, y, width, height)
    @actor ||= $game_party.leader
  end

  def actor=(actor)
    return if @actor == actor
    @actor = actor
    refresh
  end

  def make_item_list
    @data = @actor.all_items.select {|item| include?(item) }
    @data.push(nil) if include?(nil)
  end

  def enable?(item)
    @actor.usable?(item)
  end

  def select_last
    select(@data.index(@actor.last_item.object) || 0)
  end

  def draw_item_number(rect, item)
    draw_text(rect, sprintf(":%2d", @actor.item_number(item)), 2)
  end
end

class Scene_Item < Scene_ItemBase

  alias :th_actor_inventory_create_category_window :create_category_window
  def create_category_window
    th_actor_inventory_create_category_window
    @category_window.set_handler(:pagedown, method(:next_actor))
    @category_window.set_handler(:pageup,   method(:prev_actor))
  end

  alias :th_actor_inventory_create_item_window :create_item_window
  def create_item_window
    th_actor_inventory_create_item_window
    @item_window.actor = @actor
    @item_window.set_handler(:pagedown, method(:next_actor))
    @item_window.set_handler(:pageup,   method(:prev_actor))
  end

  #-----------------------------------------------------------------------------
  # Replace
  #-----------------------------------------------------------------------------
  def user
    @actor
  end

  #-----------------------------------------------------------------------------
  # Replace
  #-----------------------------------------------------------------------------
  def on_item_ok
    @actor.last_item.object = item
    determine_item
  end

  def on_actor_change
    @item_window.actor = @actor
    activate_current_window
  end

  #-----------------------------------------------------------------------------
  # Activate the appropriate window depending on which window is currently
  # active
  #-----------------------------------------------------------------------------
  def activate_current_window
    if @item_window.index > -1
      @item_window.activate
    else
      @category_window.activate
    end
  end
end

#-------------------------------------------------------------------------------
# Need to change these as well
#-------------------------------------------------------------------------------
class Scene_Menu < Scene_MenuBase
  def command_item
    command_personal
  end

  alias :th_actor_inventory_on_personal_ok :on_personal_ok
  def on_personal_ok
    return SceneManager.call(Scene_Item) if @command_window.current_symbol == :item
    th_actor_inventory_on_personal_ok
  end
end
#-------------------------------------------------------------------------------
# Need to change these as well
#-------------------------------------------------------------------------------
class Window_BattleItem < Window_ItemList

  #--------------------------------------------------------------------------
  # * Include in Item List?
  #--------------------------------------------------------------------------
  def include?(item)
    @actor ? @actor.usable?(item) : false
  end
end

class Scene_Battle < Scene_Base

  alias :th_actor_inventory_command_item :command_item
  def command_item
    @item_window.actor = BattleManager.actor
    th_actor_inventory_command_item
  end

  alias :th_actor_inventory_on_item_ok :on_item_ok
  def on_item_ok
    th_actor_inventory_on_item_ok
    BattleManager.actor.last_item.object = @item
  end
end
#-------------------------------------------------------------------------------
# You must first choose who is going to buy
#-------------------------------------------------------------------------------
class Window_ShopStatus < Window_Base

  alias :th_actor_inventory_initialize :initialize
  def initialize(x, y, width, height)
    @actor = nil
    th_actor_inventory_initialize(x, y, width, height)
  end

  def actor=(actor)
    return if @actor == actor
    @actor = actor
    refresh
  end

  def draw_current_actor(x, y)
    rect = Rect.new(x, y, contents.width - 4 - x, line_height)
    change_color(system_color)
    draw_text(rect, @actor.name)
  end

  alias :th_actor_inventory_draw_possession :draw_possession
  def draw_possession(x, y)
    if @actor
      draw_current_actor(x, y)
      rect = Rect.new(x, y + line_height, contents.width - 4 - x, line_height)
      change_color(system_color)
      draw_text(rect, Vocab::Possession)
      change_color(normal_color)
      draw_text(rect, @actor.item_number(@item), 2)
    end
  end
end

class Window_ShopBuy < Window_Selectable

  def actor=(actor)
    return if @actor == actor
    @actor = actor
    refresh
  end

  def enable?(item)
    item && price(item) <= @money && @actor && !@actor.item_max?(item)
  end
end

class Window_ShopSell < Window_ItemList
  def actor=(actor)
    return if @actor == actor
    @actor = actor
    refresh
  end
end

class Scene_Shop < Scene_MenuBase

  alias :th_actor_inventory_start :start
  def start
    th_actor_inventory_start
    @actor = $game_party.leader
  end

  alias :th_actor_inventory_create_status_window :create_status_window
  def create_status_window
    th_actor_inventory_create_status_window
    @status_window.actor = @actor
  end

  alias :th_actor_inventory_create_buy_window :create_buy_window
  def create_buy_window
    th_actor_inventory_create_buy_window
    @buy_window.set_handler(:pagedown, method(:next_actor))
    @buy_window.set_handler(:pageup,   method(:prev_actor))
    @buy_window.actor = @actor
  end

  alias :th_actor_inventory_create_sell_window :create_sell_window
  def create_sell_window
    th_actor_inventory_create_sell_window
    @sell_window.set_handler(:pagedown, method(:next_actor))
    @sell_window.set_handler(:pageup,   method(:prev_actor))
    @sell_window.actor = @actor
  end

  #-----------------------------------------------------------------------------
  # Overwrite
  #-----------------------------------------------------------------------------
  def max_buy
    max = @actor.max_item_number(@item) - @actor.item_number(@item)
    buying_price == 0 ? max : [max, money / buying_price].min
  end

  #-----------------------------------------------------------------------------
  # Overwrite
  #-----------------------------------------------------------------------------
  def max_sell
    @actor.item_number(@item)
  end

  #-----------------------------------------------------------------------------
  # Overwrite
  #-----------------------------------------------------------------------------
  def do_buy(number)
    $game_party.lose_gold(number * buying_price)
    @actor.gain_item(@item, number)
  end

  #-----------------------------------------------------------------------------
  # Overwrite
  #-----------------------------------------------------------------------------
  def do_sell(number)
    $game_party.gain_gold(number * selling_price)
    @actor.lose_item(@item, number)
  end

  def on_actor_change
    @status_window.actor = @actor
    @buy_window.actor = @actor
    @sell_window.actor = @actor
    activate_current_window
  end

  def activate_current_window
    case @command_window.current_symbol
    when :buy
      @buy_window.activate
    when :sell
      @sell_window.activate
    end
  end
end


text:
/**
 * This file contains all error messages intended to be used by sails-mysql-transactions
 * @module transaction-errors
 */
var util = require('./util'),
    AdapterError; // constructor
/**
 * @constructor
 * @inherits Error
 */
AdapterError = function (message) {
    if (!(this instanceof AdapterError)) {
        return new AdapterError(message);
    }
    Error.captureStackTrace(this, this.constructor);
    arguments.length && (this.message = message);
    this.name = 'AdapterError';
};

AdapterError.prototype = new Error();
AdapterError.prototype.constructor = AdapterError;

util.extend(AdapterError, {
    MEDIATOR_INVALID_MODEL: 'Invalid model forwarded to transaction.',
    MEDIATOR_INVALID_TXN: 'Invalid transaction parameters.',

    TRANSACTION_NOT_SETUP: 'Transaction.setup() has not been called. Missing ORM registration?',
    TRANSACTION_CONNECTION_OVERLAP: 'Multiple connections got associated with a single transaction. Nasty!',
    TRANSACTION_UNINITIATED: 'Transaction was used without doing Transaction.start();',
    TRANSACTION_UNINITIATED_COMM: 'Transaction commit failed since transaction has either expired or not started',
    TRANSACTION_UNINITIATED_ROLL: 'Transaction rollback failed since transaction has either expired or not started',
    TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED: 'Transaction attempted for multiple databases',
    TRANSACTION_NOT_IDENTIFIED: 'Unable to locate the connection for which to transact',
    TRANSACTION_CONFIG_NOT_FOUND: 'Database has no transaction configuration',
    TRANSACTION_ID_NOT_FOUND: 'No transaction id was associated',
    TRANSACTION_NOT_ASSOCIATED: 'No associated transaction found with the connection',
    TRANSACTION_ID_INTEGRITY_FAILURE: 'Transaction id integrity mismatch (report issue.)',

    NO_SOURCE: 'Connection source not found',
    UNKNOWN_CONNECTION: 'The connection was not found during multiplexing'
});

module.exports = AdapterError;


text:
use std;

///Error what occurs on start_recording, stop_recording, read methods of AudioDevice
#[derive(Debug)]
pub enum Error{
    Gen,
    NotOpen,
    Wave,
    Unknown,
}

impl From<i32> for Error {
    fn from(n:i32) -> Error {
        match n {
            -1 => Error::Gen,
            -2 => Error::NotOpen,
            -3 => Error::Wave,
            _ => Error::Unknown,
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "Sphinx audio device error:{}",
            match *self {
                Error::Gen => "Gen",
                Error::NotOpen => "NotOpen",
                Error::Wave => "Wave",
                Error::Unknown => "Unknown",
            }
        )
    }
}

impl std::error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::Gen => "Gen",
            Error::NotOpen => "NotOpen",
            Error::Wave => "Wave",
            Error::Unknown => "Unknown",
        }
    }
    fn cause(&self) -> Option<&std::error::Error> { None }
}


text:
var express = require('../')
  , request = require('supertest');

describe('app', function(){
  describe('.request', function(){
    it('should extend the request prototype', function(done){
      var app = express();

      app.request.querystring = function(){
        return require('url').parse(this.url).query;
      };

      app.use(function(req, res){
        res.end(req.querystring());
      });

      request(app)
      .get('/foo?name=tobi')
      .expect('name=tobi', done);
    })
  })
})


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/net_log.h"

#include "base/bind.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "net/base/net_errors.h"

namespace net {

namespace {

// Returns parameters for logging data transferred events. Includes number of
// bytes transferred and, if the log level indicates bytes should be logged and
// |byte_count| > 0, the bytes themselves.  The bytes are hex-encoded, since
// base::StringValue only supports UTF-8.
Value* BytesTransferredCallback(int byte_count,
                                const char* bytes,
                                NetLog::LogLevel log_level) {
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger("byte_count", byte_count);
  if (NetLog::IsLoggingBytes(log_level) && byte_count > 0)
    dict->SetString("hex_encoded_bytes", base::HexEncode(bytes, byte_count));
  return dict;
}

Value* SourceEventParametersCallback(const NetLog::Source source,
                                     NetLog::LogLevel /* log_level */) {
  if (!source.is_valid())
    return NULL;
  DictionaryValue* event_params = new DictionaryValue();
  source.AddToEventParameters(event_params);
  return event_params;
}

Value* NetLogIntegerCallback(const char* name,
                             int value,
                             NetLog::LogLevel /* log_level */) {
  DictionaryValue* event_params = new DictionaryValue();
  event_params->SetInteger(name, value);
  return event_params;
}

Value* NetLogInt64Callback(const char* name,
                           int64 value,
                           NetLog::LogLevel /* log_level */) {
  DictionaryValue* event_params = new DictionaryValue();
  event_params->SetString(name, base::Int64ToString(value));
  return event_params;
}

Value* NetLogStringCallback(const char* name,
                            const std::string* value,
                            NetLog::LogLevel /* log_level */) {
  DictionaryValue* event_params = new DictionaryValue();
  event_params->SetString(name, *value);
  return event_params;
}

Value* NetLogString16Callback(const char* name,
                              const string16* value,
                              NetLog::LogLevel /* log_level */) {
  DictionaryValue* event_params = new DictionaryValue();
  event_params->SetString(name, *value);
  return event_params;
}

}  // namespace

void NetLog::Source::AddToEventParameters(DictionaryValue* event_params) const {
  DictionaryValue* dict = new DictionaryValue();
  dict->SetInteger("type", static_cast<int>(type));
  dict->SetInteger("id", static_cast<int>(id));
  event_params->Set("source_dependency", dict);
}

NetLog::ParametersCallback NetLog::Source::ToEventParametersCallback() const {
  return base::Bind(&SourceEventParametersCallback, *this);
}

// static
bool NetLog::Source::FromEventParameters(Value* event_params, Source* source) {
  DictionaryValue* dict;
  DictionaryValue* source_dict;
  int source_id;
  int source_type;
  if (!event_params ||
      !event_params->GetAsDictionary(&dict) ||
      !dict->GetDictionary("source_dependency", &source_dict) ||
      !source_dict->GetInteger("id", &source_id) ||
      !source_dict->GetInteger("type", &source_type)) {
    *source = Source();
    return false;
  }

  DCHECK_LE(0, source_id);
  DCHECK_LT(source_type, NetLog::SOURCE_COUNT);
  *source = Source(static_cast<SourceType>(source_type), source_id);
  return true;
}

Value* NetLog::Entry::ToValue() const {
  DictionaryValue* entry_dict(new DictionaryValue());

  entry_dict->SetString("time", TickCountToString(base::TimeTicks::Now()));

  // Set the entry source.
  DictionaryValue* source_dict = new DictionaryValue();
  source_dict->SetInteger("id", source_.id);
  source_dict->SetInteger("type", static_cast<int>(source_.type));
  entry_dict->Set("source", source_dict);

  // Set the event info.
  entry_dict->SetInteger("type", static_cast<int>(type_));
  entry_dict->SetInteger("phase", static_cast<int>(phase_));

  // Set the event-specific parameters.
  if (parameters_callback_) {
    Value* value = parameters_callback_->Run(log_level_);
    if (value)
      entry_dict->Set("params", value);
  }

  return entry_dict;
}

Value* NetLog::Entry::ParametersToValue() const {
  if (parameters_callback_)
    return parameters_callback_->Run(log_level_);
  return NULL;
}

NetLog::Entry::Entry(
    EventType type,
    Source source,
    EventPhase phase,
    const ParametersCallback* parameters_callback,
    LogLevel log_level)
    : type_(type),
      source_(source),
      phase_(phase),
      parameters_callback_(parameters_callback),
      log_level_(log_level) {
};

NetLog::Entry::~Entry() {
}

NetLog::ThreadSafeObserver::ThreadSafeObserver() : log_level_(LOG_BASIC),
                                                   net_log_(NULL) {
}

NetLog::ThreadSafeObserver::~ThreadSafeObserver() {
  // Make sure we aren't watching a NetLog on destruction.  Because the NetLog
  // may pass events to each observer on multiple threads, we cannot safely
  // stop watching a NetLog automatically from a parent class.
  DCHECK(!net_log_);
}

NetLog::LogLevel NetLog::ThreadSafeObserver::log_level() const {
  DCHECK(net_log_);
  return log_level_;
}

NetLog* NetLog::ThreadSafeObserver::net_log() const {
  return net_log_;
}

void NetLog::AddGlobalEntry(EventType type) {
  AddEntry(type,
           Source(net::NetLog::SOURCE_NONE, NextID()),
           net::NetLog::PHASE_NONE,
           NULL);
}

void NetLog::AddGlobalEntry(
    EventType type,
    const NetLog::ParametersCallback& parameters_callback) {
  AddEntry(type,
           Source(net::NetLog::SOURCE_NONE, NextID()),
           net::NetLog::PHASE_NONE,
           &parameters_callback);
}

// static
std::string NetLog::TickCountToString(const base::TimeTicks& time) {
  int64 delta_time = (time - base::TimeTicks()).InMilliseconds();
  return base::Int64ToString(delta_time);
}

// static
const char* NetLog::EventTypeToString(EventType event) {
  switch (event) {
#define EVENT_TYPE(label) case TYPE_ ## label: return #label;
#include "net/base/net_log_event_type_list.h"
#undef EVENT_TYPE
    default:
      NOTREACHED();
      return NULL;
  }
}

// static
base::Value* NetLog::GetEventTypesAsValue() {
  DictionaryValue* dict = new DictionaryValue();
  for (int i = 0; i < EVENT_COUNT; ++i) {
    dict->SetInteger(EventTypeToString(static_cast<EventType>(i)), i);
  }
  return dict;
}

// static
const char* NetLog::SourceTypeToString(SourceType source) {
  switch (source) {
#define SOURCE_TYPE(label) case SOURCE_ ## label: return #label;
#include "net/base/net_log_source_type_list.h"
#undef SOURCE_TYPE
    default:
      NOTREACHED();
      return NULL;
  }
}

// static
base::Value* NetLog::GetSourceTypesAsValue() {
  DictionaryValue* dict = new DictionaryValue();
  for (int i = 0; i < SOURCE_COUNT; ++i) {
    dict->SetInteger(SourceTypeToString(static_cast<SourceType>(i)), i);
  }
  return dict;
}

// static
const char* NetLog::EventPhaseToString(EventPhase phase) {
  switch (phase) {
    case PHASE_BEGIN:
      return "PHASE_BEGIN";
    case PHASE_END:
      return "PHASE_END";
    case PHASE_NONE:
      return "PHASE_NONE";
  }
  NOTREACHED();
  return NULL;
}

// static
bool NetLog::IsLoggingBytes(LogLevel log_level) {
  return log_level == NetLog::LOG_ALL;
}

// static
bool NetLog::IsLoggingAllEvents(LogLevel log_level) {
  return log_level <= NetLog::LOG_ALL_BUT_BYTES;
}

// static
NetLog::ParametersCallback NetLog::IntegerCallback(const char* name,
                                                   int value) {
  return base::Bind(&NetLogIntegerCallback, name, value);
}

// static
NetLog::ParametersCallback NetLog::Int64Callback(const char* name,
                                                 int64 value) {
  return base::Bind(&NetLogInt64Callback, name, value);
}

// static
NetLog::ParametersCallback NetLog::StringCallback(const char* name,
                                                  const std::string* value) {
  DCHECK(value);
  return base::Bind(&NetLogStringCallback, name, value);
}

// static
NetLog::ParametersCallback NetLog::StringCallback(const char* name,
                                                  const string16* value) {
  DCHECK(value);
  return base::Bind(&NetLogString16Callback, name, value);
}

void NetLog::OnAddObserver(ThreadSafeObserver* observer, LogLevel log_level) {
  DCHECK(!observer->net_log_);
  observer->net_log_ = this;
  observer->log_level_ = log_level;
}

void NetLog::OnSetObserverLogLevel(ThreadSafeObserver* observer,
                                   LogLevel log_level) {
  DCHECK_EQ(this, observer->net_log_);
  observer->log_level_ = log_level;
}

void NetLog::OnRemoveObserver(ThreadSafeObserver* observer) {
  DCHECK_EQ(this, observer->net_log_);
  observer->net_log_ = NULL;
}

void NetLog::AddEntry(EventType type,
                      const Source& source,
                      EventPhase phase,
                      const NetLog::ParametersCallback* parameters_callback) {
  Entry entry(type, source, phase, parameters_callback, GetLogLevel());
  OnAddEntry(entry);
}

void BoundNetLog::AddEntry(NetLog::EventType type,
                           NetLog::EventPhase phase) const {
  if (!net_log_)
    return;
  net_log_->AddEntry(type, source_, phase, NULL);
}

void BoundNetLog::AddEntry(
    NetLog::EventType type,
    NetLog::EventPhase phase,
    const NetLog::ParametersCallback& get_parameters) const {
  if (!net_log_)
    return;
  net_log_->AddEntry(type, source_, phase, &get_parameters);
}

void BoundNetLog::AddEvent(NetLog::EventType type) const {
  AddEntry(type, NetLog::PHASE_NONE);
}

void BoundNetLog::AddEvent(
    NetLog::EventType type,
    const NetLog::ParametersCallback& get_parameters) const {
  AddEntry(type, NetLog::PHASE_NONE, get_parameters);
}

void BoundNetLog::BeginEvent(NetLog::EventType type) const {
  AddEntry(type, NetLog::PHASE_BEGIN);
}

void BoundNetLog::BeginEvent(
    NetLog::EventType type,
    const NetLog::ParametersCallback& get_parameters) const {
  AddEntry(type, NetLog::PHASE_BEGIN, get_parameters);
}

void BoundNetLog::EndEvent(NetLog::EventType type) const {
  AddEntry(type, NetLog::PHASE_END);
}

void BoundNetLog::EndEvent(
    NetLog::EventType type,
    const NetLog::ParametersCallback& get_parameters) const {
  AddEntry(type, NetLog::PHASE_END, get_parameters);
}

void BoundNetLog::AddEventWithNetErrorCode(NetLog::EventType event_type,
                                           int net_error) const {
  DCHECK_NE(ERR_IO_PENDING, net_error);
  if (net_error >= 0) {
    AddEvent(event_type);
  } else {
    AddEvent(event_type, NetLog::IntegerCallback("net_error", net_error));
  }
}

void BoundNetLog::EndEventWithNetErrorCode(NetLog::EventType event_type,
                                           int net_error) const {
  DCHECK_NE(ERR_IO_PENDING, net_error);
  if (net_error >= 0) {
    EndEvent(event_type);
  } else {
    EndEvent(event_type, NetLog::IntegerCallback("net_error", net_error));
  }
}

void BoundNetLog::AddByteTransferEvent(NetLog::EventType event_type,
                                       int byte_count,
                                       const char* bytes) const {
  AddEvent(event_type, base::Bind(BytesTransferredCallback, byte_count, bytes));
}

NetLog::LogLevel BoundNetLog::GetLogLevel() const {
  if (net_log_)
    return net_log_->GetLogLevel();
  return NetLog::LOG_BASIC;
}

bool BoundNetLog::IsLoggingBytes() const {
  return NetLog::IsLoggingBytes(GetLogLevel());
}

bool BoundNetLog::IsLoggingAllEvents() const {
  return NetLog::IsLoggingAllEvents(GetLogLevel());
}

// static
BoundNetLog BoundNetLog::Make(NetLog* net_log,
                              NetLog::SourceType source_type) {
  if (!net_log)
    return BoundNetLog();

  NetLog::Source source(source_type, net_log->NextID());
  return BoundNetLog(source, net_log);
}

}  // namespace net


text:
<?php
namespace Seven\FEBundle\Entity\Utilities;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Seven\FEBundle\Entity\Partial\BasicInfo;

/**
 * @ORM\Entity
 * @ORM\Table(name="images")
 * @ORM\HasLifecycleCallbacks
 */
class Image
{
    use BasicInfo;

    /**
     * @ORM\ManyToOne(targetEntity="ImageContainer", inversedBy="images")
     */
    protected $container;

    protected $cat_dir = "";
    protected $thumb_dir = null;

    protected $thumb_h = 100;
    protected $thumb_w = 150;

    /**
     * @Assert\Image
     */
    protected $image_file;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    protected $image_name;

    protected $crop_coordinates;

    protected $temp_img_size;

    public function getUploadDir()
    {
        return 'uploads'."/".'images'."/".$this->cat_dir;
    }

    public function getThumbUploadDir()
    {
        return $this->getUploadDir()."/".$this->thumb_dir;
    }

    public function getRootUploadDir()
    {
//        return $_SERVER['DOCUMENT_ROOT']."/SymfonyFP/finding_projects/web/".$this->getUploadDir();
        return $_SERVER['DOCUMENT_ROOT']."/".$this->getUploadDir();
    }

    public function getThumbRootUploadDir()
    {
//        return $_SERVER['DOCUMENT_ROOT']."/SymfonyFP/finding_projects/web/".$this->getThumbUploadDir();
        return $_SERVER['DOCUMENT_ROOT']."/".$this->getThumbUploadDir();
    }

    public function getWebPath()
    {
        return $this->image_name === null ? null : $this->getUploadDir()."/".$this->image_name;
    }

    public function getThumbWebPath()
    {
        return $this->image_name === null ? null : $this->getThumbUploadDir()."/".$this->image_name;
    }

    public function getAbsolutePath()
    {
        return $this->image_name === null ? null : $this->getRootUploadDir()."/".$this->image_name;
    }

    public function getThumbAbsolutePath()
    {
        return $this->image_name === null ? null : $this->getThumbRootUploadDir()."/".$this->image_name;

    }

    /**
     * WARNING!! PreUpdate no fired since $file is not managed by Doctrine.
     * SOLUTION: use PostLoad() Event.
     * @ORM\PostLoad()
     */
    public function postLoad()
    {
        $this->setUpdatedAt(new \DateTime());
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if($this->image_file != null)
        {
            if($this->image_name != null)
            {
                if(file_exists($this->getAbsolutePath()))
                {
                    unlink($this->getAbsolutePath());
                }
            }
            $this->image_name = uniqid().".jpeg";
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if($this->image_file === null)
        {
            return;
        }

        if(!file_exists($this->getUploadDir()))
        {
            $old_umask = umask(0);
            mkdir($this->getUploadDir(),0777, true);
            umask($old_umask);
        }

        if($this->thumb_dir)
        {
            if(!file_exists($this->getThumbUploadDir()))
            {
                $old_umask = umask(0);
                mkdir($this->getThumbUploadDir(),0775, true);
                umask($old_umask);
            }
        }

        $this->image_file->move($this->getUploadDir(), $this->image_name);

        if(isset($this->crop_coordinates))
        {
            list($original_width, $original_height, $img_type) = getimagesize($this->getAbsolutePath());
            $src = null;
            switch($img_type)
            {
                case IMAGETYPE_JPEG:
                    $src = \imagecreatefromjpeg($this->getAbsolutePath());
                    break;
                case IMAGETYPE_PNG:
                    $src = \imagecreatefrompng($this->getAbsolutePath());
                    break;
                case IMAGETYPE_GIF:
                    $src = \imagecreatefromgif($this->getAbsolutePath());
                    break;
                default:
                    $src = null;
                    break;
            }

            if($src)
            {
                $dst = imagecreatetruecolor($this->crop_coordinates["width"], $this->crop_coordinates["height"]);

                if($this->temp_img_size["temp_width"] == 0)
                {
                    \imagecopyresampled($dst, $src, 0, 0, 0, 0, $this->crop_coordinates["width"], $this->crop_coordinates["height"], $original_width, $original_height);
                }
                else
                {
                    $tmp_org = imagecreatetruecolor($this->temp_img_size["temp_width"], $this->temp_img_size["temp_height"]);
                    $white = imagecolorallocate($tmp_org,  255, 255, 255);
                    imagefilledrectangle($tmp_org, 0, 0, $original_width, $original_height, $white);
                    \imagecopyresampled($tmp_org, $src, 0, 0, 0, 0, $this->temp_img_size["temp_width"], $this->temp_img_size["temp_height"], $original_width, $original_height);
                    \imagecopy($dst, $tmp_org, 0, 0, $this->crop_coordinates["x"], $this->crop_coordinates["y"], $this->temp_img_size["temp_width"], $this->temp_img_size["temp_height"]);
                }
                \imageinterlace($dst, true);
                \imagejpeg($dst, $this->getAbsolutePath(), 80);
            }
        }
        else
        {
            list($original_width, $original_height, $img_type) = getimagesize($this->getAbsolutePath());
            $src = null;
            switch($img_type)
            {
                case IMAGETYPE_JPEG:
                    $src = \imagecreatefromjpeg($this->getAbsolutePath());
                    break;
                case IMAGETYPE_PNG:
                    $src = \imagecreatefrompng($this->getAbsolutePath());
                    break;
                case IMAGETYPE_GIF:
                    $src = \imagecreatefromgif($this->getAbsolutePath());
                    break;
                default:
                    $src = null;
                    break;
            }

            if($src)
            {
                $dst = imagecreatetruecolor($original_width, $original_height);
                $white = imagecolorallocate($dst,  255, 255, 255);
                imagefilledrectangle($dst, 0, 0, $original_width, $original_height, $white);
                \imagecopy($dst, $src, 0, 0, 0, 0, $original_width, $original_height);
                \imageinterlace($dst, true);
                \imagejpeg($dst, $this->getAbsolutePath(), 80);
            }
        }

        if($this->thumb_dir)
        {
            list($original_width, $original_height, $img_type) = getimagesize($this->getAbsolutePath());
            $src = null;
            switch($img_type)
            {
                case IMAGETYPE_JPEG:
                    $src = \imagecreatefromjpeg($this->getAbsolutePath());
                    break;
                case IMAGETYPE_PNG:
                    $src = \imagecreatefrompng($this->getAbsolutePath());
                    break;
                case IMAGETYPE_GIF:
                    $src = \imagecreatefromgif($this->getAbsolutePath());
                    break;
                default:
                    $src = null;
                    break;
            }

            $sourceRatio = $original_width / $original_height;
            $targetRatio = $this->thumb_w / $this->thumb_h;

            if ( $sourceRatio < $targetRatio ) {
                $scale = $original_width/ $this->thumb_w;
            } else {
                $scale = $original_height / $this->thumb_h;
            }

            $resizeWidth = (int)($original_width / $scale);
            $resizeHeight = (int)($original_height / $scale);

            $cropLeft = (int)(($resizeWidth - $this->thumb_w) / 2);
            $cropTop = (int)(($resizeHeight - $this->thumb_h) / 2);

            $dst = imagecreatetruecolor($this->thumb_w, $this->thumb_h);
            $white = imagecolorallocate($dst,  255, 255, 255);
            imagefilledrectangle($dst, 0, 0, $original_width, $original_height, $white);
            \imagecopyresampled($dst, $src, 0, 0, $cropLeft, $cropTop, $resizeWidth, $resizeHeight, $original_width, $original_height);
            \imageinterlace($dst, true);
            \imagejpeg($dst, $this->getThumbAbsolutePath(), 80);
        }

        unset($this->image_file);
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        if($this->getAbsolutePath() !== null){
            if(file_exists($this->getAbsolutePath()))
            {
                unlink($this->getAbsolutePath());
            }

            if($this->thumb_dir)
            {
                if(file_exists($this->getThumbAbsolutePath()))
                {
                    unlink($this->getThumbAbsolutePath());
                }
            }
        }
    }

    public function setImageFile($img_file)
    {
        $this->image_file = $img_file;
        return $this;
    }

    public function getImageFile()
    {
        return $this->image_file;
    }

    public function setImageName($img_name)
    {
        $this->image_name = $img_name;
        return $this;
    }

    public function getImageName()
    {
        return $this->image_name;
    }

    public function getTempImgSize()
    {
        return $this->temp_img_size;
    }

    public function setTempImgSize($img_size)
    {
        $this->temp_img_size = $img_size;
        return $this;
    }

    public function getCropCoordinates()
    {
        return $this->crop_coordinates;
    }

    public function setCropCoordinates($coordinates)
    {
        $this->crop_coordinates = $coordinates;
        return $this;
    }

    /**
     * Set container
     *
     * @param \Seven\FEBundle\Entity\Utilities\ImageContainer $container
     * @return Image
     */
    public function setContainer(\Seven\FEBundle\Entity\Utilities\ImageContainer $container = null)
    {
        $this->container = $container;

        return $this;
    }

    /**
     * Get container
     *
     * @return \Seven\FEBundle\Entity\Utilities\ImageContainer
     */
    public function getContainer()
    {
        return $this->container;
    }
}


text:
/* ChangeLog:
 *
 */

#ifndef _IAS_AS_Lang_Export_Text_Exception_ProcessorLinkedException_H_
#define _IAS_AS_Lang_Export_Text_Exception_ProcessorLinkedException_H_

#include <commonlib/commonlib.h>

#include "ProcessorException.h"
#include <lang/tools/parser/SourceLocation.h>
#include <lang/model/Node.h>

namespace IAS {
namespace Lang {
namespace Export{
namespace Text {

/*************************************************************************/
/** The class. */
 class ProcessorLinkedException : public ProcessorException {

public:

	ProcessorLinkedException(::IAS::Exception& e,
							 const Tools::Parser::SourceLocation& sourceLocation,
							 const Model::Node *pNode);

	virtual ~ProcessorLinkedException() throw();

	const Tools::Parser::SourceLocation&  getSourceLocation(){
		return sourceLocation;
	}

    const Model::Node* getNode(){
			return pNode;
		}

	virtual const char*  getName();

protected:

	const Model::Node *pNode;
	Tools::Parser::SourceLocation sourceLocation;
};
/*************************************************************************/

}
}
}
}

#endif /*_IAS_AS_Lang_Exception_ProcessorLinkedException_H_*/


text:
layout: page
title:
permalink: /about/
---

arg min blog: a blog of minimum value

Musings on systems, information, learning, and optimization by [Ben Recht](http://www.eecs.berkeley.edu/~brecht). With intermittent ramblings about music.

Follow Ben on Twitter: [@beenwrekt](https://twitter.com/beenwrekt)

Subscribe to the  RSS Feed.

Banners contributed by [Isaac Sparks](http://www.isaacsparks.com/).


text:
const path = require('path')
const buble = require('rollup-plugin-buble')
const alias = require('rollup-plugin-alias')
const replace = require('rollup-plugin-replace')
const flow = require('rollup-plugin-flow-no-whitespace')
const version = process.env.VERSION || require('../package.json').version
const weexVersion = process.env.WEEX_VERSION || require('../packages/weex-vue-framework/package.json').version

const banner =
  '/*!\n' +
  ' * Vue.js v' + version + '\n' +
  ' * (c) 2014-' + new Date().getFullYear() + ' Evan You\n' +
  ' * Released under the MIT License.\n' +
  ' */'

const weexFactoryPlugin = {
  intro () {
    return 'module.exports = function weexFactory (exports, renderer) {'
  },
  outro () {
    return '}'
  }
}

const aliases = require('./alias')
const resolve = p => {
  const base = p.split('/')[0]
  if (aliases[base]) {
    return path.resolve(aliases[base], p.slice(base.length + 1))
  } else {
    return path.resolve(__dirname, '../', p)
  }
}

const builds = {
  // Runtime only (CommonJS). Used by bundlers e.g. Webpack & Browserify
  'web-runtime-cjs': {
    entry: resolve('web/entry-runtime.js'),
    dest: resolve('dist/vue.runtime.common.js'),
    format: 'cjs',
    banner
  },
  // Runtime+compiler CommonJS build (CommonJS)
  'web-full-cjs': {
    entry: resolve('web/entry-runtime-with-compiler.js'),
    dest: resolve('dist/vue.common.js'),
    format: 'cjs',
    alias: { he: './entity-decoder' },
    banner
  },
  // Runtime only (ES Modules). Used by bundlers that support ES Modules,
  // e.g. Rollup & Webpack 2
  'web-runtime-esm': {
    entry: resolve('web/entry-runtime.js'),
    dest: resolve('dist/vue.runtime.esm.js'),
    format: 'es',
    banner
  },
  // Runtime+compiler CommonJS build (ES Modules)
  'web-full-esm': {
    entry: resolve('web/entry-runtime-with-compiler.js'),
    dest: resolve('dist/vue.esm.js'),
    format: 'es',
    alias: { he: './entity-decoder' },
    banner
  },
  // runtime-only build (Browser)
  'web-runtime-dev': {
    entry: resolve('web/entry-runtime.js'),
    dest: resolve('dist/vue.runtime.js'),
    format: 'umd',
    env: 'development',
    banner
  },
  // runtime-only production build (Browser)
  'web-runtime-prod': {
    entry: resolve('web/entry-runtime.js'),
    dest: resolve('dist/vue.runtime.min.js'),
    format: 'umd',
    env: 'production',
    banner
  },
  // Runtime+compiler development build (Browser)
  'web-full-dev': {
    entry: resolve('web/entry-runtime-with-compiler.js'),
    dest: resolve('dist/vue.js'),
    format: 'umd',
    env: 'development',
    alias: { he: './entity-decoder' },
    banner
  },
  // Runtime+compiler production build  (Browser)
  'web-full-prod': {
    entry: resolve('web/entry-runtime-with-compiler.js'),
    dest: resolve('dist/vue.min.js'),
    format: 'umd',
    env: 'production',
    alias: { he: './entity-decoder' },
    banner
  },
  // Web compiler (CommonJS).
  'web-compiler': {
    entry: resolve('web/entry-compiler.js'),
    dest: resolve('packages/vue-template-compiler/build.js'),
    format: 'cjs',
    external: Object.keys(require('../packages/vue-template-compiler/package.json').dependencies)
  },
  // Web server renderer (CommonJS).
  'web-server-renderer': {
    entry: resolve('web/entry-server-renderer.js'),
    dest: resolve('packages/vue-server-renderer/build.js'),
    format: 'cjs',
    external: Object.keys(require('../packages/vue-server-renderer/package.json').dependencies)
  },
  'web-server-renderer-webpack-server-plugin': {
    entry: resolve('server/webpack-plugin/server.js'),
    dest: resolve('packages/vue-server-renderer/server-plugin.js'),
    format: 'cjs',
    external: Object.keys(require('../packages/vue-server-renderer/package.json').dependencies)
  },
  'web-server-renderer-webpack-client-plugin': {
    entry: resolve('server/webpack-plugin/client.js'),
    dest: resolve('packages/vue-server-renderer/client-plugin.js'),
    format: 'cjs',
    external: Object.keys(require('../packages/vue-server-renderer/package.json').dependencies)
  },
  // Weex runtime factory
  'weex-factory': {
    weex: true,
    entry: resolve('weex/entry-runtime-factory.js'),
    dest: resolve('packages/weex-vue-framework/factory.js'),
    format: 'cjs',
    plugins: [weexFactoryPlugin]
  },
  // Weex runtime framework (CommonJS).
  'weex-framework': {
    weex: true,
    entry: resolve('weex/entry-framework.js'),
    dest: resolve('packages/weex-vue-framework/index.js'),
    format: 'cjs'
  },
  // Weex compiler (CommonJS). Used by Weex's Webpack loader.
  'weex-compiler': {
    weex: true,
    entry: resolve('weex/entry-compiler.js'),
    dest: resolve('packages/weex-template-compiler/build.js'),
    format: 'cjs',
    external: Object.keys(require('../packages/weex-template-compiler/package.json').dependencies)
  }
}

function genConfig (opts) {
  const config = {
    entry: opts.entry,
    dest: opts.dest,
    external: opts.external,
    format: opts.format,
    banner: opts.banner,
    moduleName: 'Vue',
    plugins: [
      replace({
        __WEEX__: !!opts.weex,
        __WEEX_VERSION__: weexVersion,
        __VERSION__: version
      }),
      flow(),
      buble(),
      alias(Object.assign({}, aliases, opts.alias))
    ].concat(opts.plugins || [])
  }

  if (opts.env) {
    config.plugins.push(replace({
      'process.env.NODE_ENV': JSON.stringify(opts.env)
    }))
  }

  return config
}

if (process.env.TARGET) {
  module.exports = genConfig(builds[process.env.TARGET])
} else {
  exports.getBuild = name => genConfig(builds[name])
  exports.getAllBuilds = () => Object.keys(builds).map(name => genConfig(builds[name]))
}


text:
require 'easy_management/builders/class_builder'

module EasyManagement
  module Builders

    class ManagerBuilder < ClassBuilder

      protected

      def class_full_name
        "#{model_helper.namespace}::#{model_helper.manager_class}"
      end

      def superclass
        EasyManagement::Managers::BaseManager
      end

      def setup_class
        model_class = model_helper.model_constant
        model_class_sym = model_helper.model_symbol

        model_method = Proc.new { model_class }
        model_name_method = Proc.new { model_class_sym }

        self.klass.send :define_method, :model, &model_method
        self.klass.send :define_method, :model_name, &model_name_method
      end

    end

  end
end


text:
from TASSELpy.java.lang.Object import Object
from TASSELpy.java.lang.Integer import metaInteger
from TASSELpy.utils.Overloading import javaConstructorOverload,javaOverload
from TASSELpy.utils.helper import make_sig

java_imports = {'Object':'java/lang/Object',
                'ProgressListener':'net/maizegenetics/util/ProgressListener'}
class ProgressListener(Object):
    _java_name = java_imports['ProgressListener']
    @javaConstructorOverload(java_imports['ProgressListener'])
    def __init__(self, *args, **kwargs):
        pass
    ## Returns the progress of execution
    # @param percent percent complete
    # @param meta meta data
    @javaOverload("progress",
                (make_sig(['int',java_imports['Object']],'void'),(metaInteger,Object),None))
    def progress(self, *args):
        """
        Returns the progress of execution

        Signatures:

        void progress(int percent, Object meta)

        Arguments:

        percent -- percent complete
        meta -- meta data
        """
        pass


text:
package test.giphy.com.giphytest.model.data.entity;

import com.google.gson.annotations.SerializedName;

/**
 * Created by Anton on 31.03.2016.
 */
public class GifData {

    @SerializedName("url")
    private String sourceUrl;
    @SerializedName("images")
    private GifImageData gifImageData;

    public GifData() {
    }

    public GifData(String sourceUrl, GifImageData gifImageData) {
        this.sourceUrl = sourceUrl;
        this.gifImageData = gifImageData;
    }

    public String getSourceUrl() {
        return sourceUrl;
    }

    public GifData setSourceUrl(String sourceUrl) {
        this.sourceUrl = sourceUrl;
        return this;
    }

    public GifImageData getGifImageData() {
        return gifImageData;
    }

    public GifData setGifImageData(GifImageData gifImageData) {
        this.gifImageData = gifImageData;
        return this;
    }
}


text: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">


text:
class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new # guest user (not logged in)

    alias_action :create, :read, :update, :destroy, to: :crud

    if user.roles.any? # зарегистрированные пользователи хотя бы с одной ролью могут:
      can :read, User # видеть подробности о других пользователях
      cannot :edit_document_place, Document
      cannot :edit_place, Contract

      if user.role? :user
        can :view_document, Document # просматривать файл с документомu.
      end

      if user.role? :author
        can :create, Document
        can %i[update destroy clone], Document, owner_id: user.id # документ владельца
        can :manage, [Directive, Term]
        can :view_document, Document # просматривать файл с документом
        can :edit_document, [Document] # может брать исходник документа
        can [:read], [Agent, Contract]
        can %i[create_user update], Letter # назначать исполнителей писем
        can [:create], [Task] # создавать Задачи
      end

      if user.role? :keeper
        can :edit_contract_place, Contract  # может изменять место хранения договора
        can :edit_document_place, Document  # может изменять место хранения документа
      end

      if user.role? :owner # владелец процесса
        can %i[update create clone], Document
        can :manage, [Directive, Term]
        can :crud, [BproceBapp, BproceIresource]
        can :update, Bproce, user_id: user.id # процесс владельца
        can :crud, BusinessRole # роли в процессе владельца
        can :crud, Metric
        can :crud, [Contract, Agent, ContractScan]
        can :crud, [Task, Requirement]
      end

      if user.role? :analitic
        can %i[update create clone], Document
        can :crud, [Bproce, Bapp, BusinessRole, BproceBapp, Term, Contract, Agent, ContractScan]
        can :manage_tag, [Bproce] # может редактировать теги процессов
        can :edit_document, [Document] # может брать исходник документа
        can :crud, Metric
        can :crud, [Task, Requirement]
      end

      if user.role? :secretar
        can %i[create_user create update], Letter # назначать исполнителей писем, создать, изменить письмо
        can :registr, Letter # регистрирует корреспонденцию
        can :create_outgoing, Letter # создает исходящее по входящему
      end

      if user.role? :admin
        can :assign_roles, User # администратор может изменять роли доступа пользователям
        can :manage, [User, Workplace, Bapp, Iresource, Term]
        can :crud, [MetricValue]
        can :manage_tag, [Bproce, Bapp] # может редактировать теги процессов, приложений
      end

      if user.role? :security
        can :assign_roles, User # администратор доступа может изменять роли доступа пользователям
      end
    else
      can :read, :all # for guest without roles
      cannot :show, User
    end
  end
end


text:
@implementation NSString (FOS)

- (NSString *)sentenceCapitalizedString {

    NSString *result = self;

    if (self.length > 0) {

        NSString *firstChar = [[self substringToIndex:1] uppercaseString];

        if (self.length > 1) {

            NSString *endString = [[self substringFromIndex:1] lowercaseString];

            result = [firstChar stringByAppendingString:endString];
        } else {

            result = firstChar;
        }
    }

    return result;
}

- (NSString *)lowercaseFirstCharString {
    NSString *result = self;

    if (self.length > 0) {

        NSString *firstChar = [[self substringToIndex:1] lowercaseString];

        if (self.length > 1) {

            NSString *endString = [self substringFromIndex:1];

            result = [firstChar stringByAppendingString:endString];
        } else {

            result = firstChar;
        }
    }

    return result;
}

- (NSString *)toUnderscore {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=[a-z])([A-Z])|([A-Z])(?=[a-z])"
                                                                           options:0 error:nil];
    NSString *result = [[regex stringByReplacingMatchesInString:self
                                                        options:0
                                                          range:NSMakeRange(0, self.length)
                                                   withTemplate:@"_$1$2"] lowercaseString];

    return result;
}

- (BOOL)containsString:(NSString *)otherString {
    NSRange range = [self rangeOfString:otherString];

    return range.location != NSNotFound;
}

@end


text:
'use strict'

var React = require('react')
var window = require('global/window')
var r = require('r-dom')
var SVGOverlay = require('../../react-map-gl/src/overlays/svg.react')
var assign = require('object-assign')

module.exports = React.createClass({

  displayName: 'ExampleOverlay',

  propTypes: {
    locations: React.PropTypes.array.isRequired,
    width: React.PropTypes.number.isRequired,
    height: React.PropTypes.number.isRequired,
    longitude: React.PropTypes.number.isRequired,
    latitude: React.PropTypes.number.isRequired,
    zoom: React.PropTypes.number.isRequired,
    isDragging: React.PropTypes.bool.isRequired
  },

  render: function render () {
    return r(SVGOverlay, assign({}, this.props, { style: {'zIndex': 900},
      redraw: function redraw (opt) {
        return r.g(this.props.locations.map(function map (location) {
          var pixel = opt.project([location.longitude, location.latitude])
          return r.circle({
            cx: pixel[0],
            cy: pixel[1],
            r: 10,
            style: {
              fill: 'rgba(231, 76, 60, 0.4)',
              pointerEvents: 'all',
              cursor: 'pointer'
            },
            onClick: function onClick () {
              window.location.href = 'https://en.wikipedia.org' + location.wiki
            }
          })
        }))
      }.bind(this)
    }))
  }
})


text:
var mongoose = require('mongoose');

var courseSchema = new mongoose.Schema({
  name: String,
  department_code: String,
  course_code: String

}, { timestamps: true });

var Course = mongoose.model('Course', courseSchema);
module.exports = Course;

//SEEDS
Course.create(
  {
    name: 'Frameworks',
    department_code: 'CS',
    course_code: '390P'
  },
  {
    name: 'Computer Science 1',
    department_code: 'CS',
    course_code: '1050'
  },
  {
    name: 'Computer Science 2',
    department_code: 'CS',
    course_code: '2050'
  },
  {
    name: 'Databases',
    department_code: 'CS',
    course_code: '3020'
  },
  {
    name: 'Operating Systems',
    department_code: 'CS',
    course_code: '3600'
  },
  {
    name: 'Software Engineering 1',
    department_code: 'CS',
    course_code: '4250'
  },
  {
    name: 'Software Engineering 2',
    department_code: 'CS',
    course_code: '4260'
  },
  {
    name: 'Embedded Systems',
    department_code: 'CS',
    course_code: '3410'
  },
  {
    name: 'Principles Of Programming Languages',
    department_code: 'CS',
    course_code: '3210'
  }
);


text:
package golib

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/gotoeveryone/golib/config"
)

func TestLoadConfigNoSuchFile(t *testing.T) {
	current, _ := filepath.Abs(".")

	if err := os.Remove(filepath.Join(current, "config.json")); err != nil {
		if !os.IsNotExist(err) {
			t.Errorf("Remove log error: %s", err)
		}
	}

	var config config.Config
	if err := LoadConfig(&config, ""); err != nil {
		if !strings.Contains(err.Error(), "Read file Error") {
			t.Error(err)
		}
	}
}

func TestLoadConfigParseError(t *testing.T) {
	current, _ := filepath.Abs(".")
	dir := filepath.Join(current, "tmp")

	if err := os.MkdirAll(dir, 0755); err != nil {
		t.Error(err)
	}

	if err := ioutil.WriteFile(filepath.Join(dir, "config.json"), []byte("hoge"), 0755); err != nil {
		t.Error(err)
	}

	var config config.Config
	if err := LoadConfig(&config, dir); err != nil {
		if !strings.Contains(err.Error(), "Unmarshal error") {
			t.Error(err)
		}
	}
}

func TestLoadConfig(t *testing.T) {
	current, _ := filepath.Abs(".")

	f, err := ioutil.ReadFile(filepath.Join(current, "config.json.example"))
	if err != nil {
		t.Error(err)
	}

	if err := ioutil.WriteFile(filepath.Join(current, "config.json"), f, 0755); err != nil {
		t.Error(err)
	}

	var config config.Config
	if err := LoadConfig(&config, current); err != nil {
		t.Error(err)
	}
}

func TestLoadConfigCustomPath(t *testing.T) {
	current, _ := filepath.Abs(".")

	f, err := ioutil.ReadFile(filepath.Join(current, "config.json.example"))
	if err != nil {
		t.Error(err)
	}

	if err := ioutil.WriteFile(filepath.Join(current, "tmp", "config.json"), f, 0755); err != nil {
		t.Error(err)
	}

	var config config.Config
	if err := LoadConfig(&config, filepath.Join(current, "tmp")); err != nil {
		t.Error(err)
	}
}


text:
@extends('admin::layout.main')

@section('title')
	Add Event Category
@stop

@section('page_title')
	Add Event Category
@stop

@section('breadcrumbs')
	@parent

 Event Categories

 New Event Category

@stop

@section('sidebar')
	@parent
	@include('admin::event_categories.sidebar')
@stop

@section('content')
	<form method="post" action="{{route('admin-event_categories-add')}}" role="form" accept-charset="UTF-8" enctype="multipart/form-data">

has('title') ? ' has-error':'' !!}">
					Title
					<input type="text" class="form-control" id="title" name="title" placeholder="Enter title"{!! ((old('title')) ? ' value="'.old('title').'"' : '') !!}>
					{!! $errors->has('title') ? ''.$errors->first('title').'' : '' !!}

has('description') ? ' has-error':'' !!}">
					Description
					<input type="text" class="form-control" id="description" name="description" placeholder="Enter description"{!! ((old('description')) ? ' value="'.old('description').'"' : '') !!}>
					{!! $errors->has('description') ? ''.$errors->first('description').'' : '' !!}

		<input type="hidden" name="_token" value="{{csrf_token()}}">
		<button type="submit" class="btn btn-primary">  Save</button>
	</form>
@stop

@section('styles')

@stop
@section('scripts_top')

@stop

@section('scripts_bottom')

@stop


text:
// Copyright (c) 2019 Google LLC
//
// 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.

#include "source/fuzz/transformation_add_type_pointer.h"

#include "source/fuzz/fuzzer_util.h"

namespace spvtools {
namespace fuzz {

TransformationAddTypePointer::TransformationAddTypePointer(
    const spvtools::fuzz::protobufs::TransformationAddTypePointer& message)
    : message_(message) {}

TransformationAddTypePointer::TransformationAddTypePointer(
    uint32_t fresh_id, SpvStorageClass storage_class, uint32_t base_type_id) {
  message_.set_fresh_id(fresh_id);
  message_.set_storage_class(storage_class);
  message_.set_base_type_id(base_type_id);
}

bool TransformationAddTypePointer::IsApplicable(
    opt::IRContext* ir_context, const TransformationContext& /*unused*/) const {
  // The id must be fresh.
  if (!fuzzerutil::IsFreshId(ir_context, message_.fresh_id())) {
    return false;
  }
  // The base type must be known.
  return ir_context->get_type_mgr()->GetType(message_.base_type_id()) !=
         nullptr;
}

void TransformationAddTypePointer::Apply(
    opt::IRContext* ir_context, TransformationContext* /*unused*/) const {
  // Add the pointer type.
  opt::Instruction::OperandList in_operands = {
      {SPV_OPERAND_TYPE_STORAGE_CLASS, {message_.storage_class()}},
      {SPV_OPERAND_TYPE_ID, {message_.base_type_id()}}};
  ir_context->module()->AddType(MakeUnique<opt::Instruction>(
      ir_context, SpvOpTypePointer, 0, message_.fresh_id(), in_operands));
  fuzzerutil::UpdateModuleIdBound(ir_context, message_.fresh_id());
  // We have added an instruction to the module, so need to be careful about the
  // validity of existing analyses.
  ir_context->InvalidateAnalysesExceptFor(
      opt::IRContext::Analysis::kAnalysisNone);
}

protobufs::Transformation TransformationAddTypePointer::ToMessage() const {
  protobufs::Transformation result;
  *result.mutable_add_type_pointer() = message_;
  return result;
}

}  // namespace fuzz
}  // namespace spvtools


text:
// <auto-generated>
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
//
// For documentation on code generator please visit
//   https://aka.ms/nrp-code-generation
// Please contact wanrpdev@microsoft.com if you need to make changes to this file.
// </auto-generated>

using Microsoft.Azure.Management.Network.Models;
using Microsoft.WindowsAzure.Commands.Common.Attributes;
using Newtonsoft.Json;

namespace Microsoft.Azure.Commands.Network.Models
{
    public partial class PSConnectionSharedKey : PSChildResource
    {
        [JsonProperty(Order = 1)]
        [Ps1Xml(Target = ViewControl.Table)]
        public string Value { get; set; }
    }
}


text:
namespace DB
{

namespace TEST
{

class DBHandlerHelper : public SERVICES::DBHandler
{
public:
  using SERVICES::DBHandler::getInstanceForTestsDemand; // UWAGA
};

} // namespace TEST

} // namespace DB

#endif // DBHANDLERHELPER_H


text:
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using UnitTestingWebAPI.Domain;
using UnitTestingWebAPI.Service;

namespace UnitTestingWebAPI.API.Core.Controllers
{
    public class ArticlesController : ApiController
    {
        private IArticleService _articleService;

        public ArticlesController(IArticleService articleService)
        {
            _articleService = articleService;
        }

        // GET: api/Articles
        public IEnumerable<Article> GetArticles()
        {
            return _articleService.GetArticles();
        }

        // GET: api/Articles/5
        [ResponseType(typeof(Article))]
        public IHttpActionResult GetArticle(int id)
        {
            Article article = _articleService.GetArticle(id);
            if (article == null)
            {
                return NotFound();
            }

            return Ok(article);
        }

        // PUT: api/Articles/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutArticle(int id, Article article)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != article.ID)
            {
                return BadRequest();
            }

            _articleService.UpdateArticle(article);

            try
            {
                _articleService.SaveArticle();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ArticleExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Articles
        [ResponseType(typeof(Article))]
        public IHttpActionResult PostArticle(Article article)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _articleService.CreateArticle(article);

            return CreatedAtRoute("DefaultApi", new { id = article.ID }, article);
        }

        // DELETE: api/Articles/5
        [ResponseType(typeof(Article))]
        public IHttpActionResult DeleteArticle(int id)
        {
            Article article = _articleService.GetArticle(id);
            if (article == null)
            {
                return NotFound();
            }

            _articleService.DeleteArticle(article);

            return Ok(article);
        }

        private bool ArticleExists(int id)
        {
            return _articleService.GetArticle(id) != null;
        }
    }
}


text:
<?php

namespace Balance\ScrapyBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class SpiderControllerTest extends WebTestCase
{
}