text:
#include <ruby.h>

void rb_objspace_each_objects(
    int (*callback)(void *start, void *end, size_t stride, void *data),
    void *data);

struct os_heap_inspector_struct {
    size_t num;
    VALUE data;
};

static int
os_heap_mark_inspector(void *vstart, void *vend, size_t stride, void *data)
{
    struct os_heap_inspector_struct *ohis = (struct os_heap_inspector_struct *)data;
    struct RBasic *p = (struct RBasic *)vstart, *pend = (struct RBasic *)vend;
    volatile VALUE v;

    for (; p != pend; p = (size_t)p + stride) {
        if (p->flags) {
            if (p->flags & FL_MARK) {
                rb_ary_store(ohis->data, ohis->num, Qtrue);
            }
            else {
                rb_ary_store(ohis->data, ohis->num, Qfalse);
            }
        }
        else {
            rb_ary_store(ohis->data, ohis->num, Qnil);
        }
        ohis->num++;
    }

    return 0;
}

/*
 *  call-seq:
 *     HeapInspector.mark_inspect!(array) -> 100
 *
 *  Inspect for Heap.
 *
 *  It args a array as:
 *  [true, false, ... nil, ..., 0]
 *
 *  It return value is heap objects count.
 *
 *  Element:
 *  True is marked. Flase is not marked. FREE RVALUE is nil.
 *  0(zero) is sentry.
 *
 */

VALUE
heap_inspector_mark_inspect(VALUE self, VALUE ary)
{
    struct os_heap_inspector_struct ohis;
    ohis.num = 0;
    ohis.data = ary;
    rb_objspace_each_objects(os_heap_mark_inspector, &ohis);
    rb_ary_store(ohis.data, ohis.num, SIZET2NUM(0));
    return SIZET2NUM(ohis.num);
}

void
Init_heap_inspector(void)
{
  VALUE rb_cHeapInspector;

  rb_cHeapInspector = rb_define_class("HeapInspector", rb_cObject);
  rb_define_singleton_method(rb_cHeapInspector, "mark_inspect!", heap_inspector_mark_inspect, 1);
}


text:
YUI.add("yuidoc-meta", function(Y) {
   Y.YUIDoc = { meta: {
    "classes": [
        "MockDataRetriever",
        "StreamChannels",
        "TwitterStreamChannels",
        "TwitterStreamChannelsMock"
    ],
    "modules": [
        "twitter-stream-channels"
    ],
    "allModules": [
        {
            "displayName": "twitter-stream-channels",
            "name": "twitter-stream-channels",
            "description": "With the Twitter stream API, you can only open one stream at a time. So, if you have multiple filters, the tweets in result will be mixed up, you'll need to do some post-processing.\n\nThis module lets you open multiple channels with there own filters, on the same stream. And then, you can add events to each of them individually, to listen to there results, like if you had open multiple streams.\n\ntwitter-stream-channels handles all the post-processing, the connexion layer (OAuth, etc ...) is handled by [twit](https://github.com/ttezel/twit). See the [FAQ](https://github.com/topheman/twitter-stream-channels#faq) about both topics."
        }
    ],
    "elements": []
} };
});

redpajama_set_name: RedPajamaGithub


text:
package format

import (
	"github.com/trivago/gollum/core"
	"os"
)

// Hostname formatter plugin
// Hostname is a formatter that prefixes a message with the hostname.
// Configuration example
//
//  - "stream.Broadcast":
//    Formatter: "format.Hostname"
//    HostnameFormatter: "format.Envelope"
//    HostnameSeparator: " "
//
// HostnameDataFormatter defines the formatter for the data transferred as
// message. By default this is set to "format.Envelope"
//
// HostnameSeparator sets the separator character placed after the hostname.
// This is set to " " by default.
type Hostname struct {
	core.SimpleFormatter `gollumdoc:"embed_type"`
	separator            []byte
}

func init() {
	core.TypeRegistry.Register(Hostname{})
}

// Configure initializes this formatter with values from a plugin config.
func (format *Hostname) Configure(conf core.PluginConfigReader) error {
	format.SimpleFormatter.Configure(conf)

	format.separator = []byte(conf.GetString("Separator", ":"))
	return conf.Errors.OrNil()
}

// ApplyFormatter update message payload
func (format *Hostname) ApplyFormatter(msg *core.Message) error {
	content := format.getFinalContent(format.GetAppliedContent(msg))
	format.SetAppliedContent(msg, content)

	return nil
}

func (format *Hostname) getFinalContent(content []byte) []byte {
	hostname, err := os.Hostname()
	if err != nil {
		format.Log.Error.Print(err)
		hostname = "unknown host"
	}

	dataSize := len(hostname) + len(format.separator) + len(content)
	payload := core.MessageDataPool.Get(dataSize)

	offset := copy(payload, []byte(hostname))
	offset += copy(payload[offset:], format.separator)
	copy(payload[offset:], content)

	return payload
}


text:
#include <znc/User.h>
#include <znc/IRCNetwork.h>

using std::vector;
using std::map;

class CSendRaw_Mod : public CModule {
    void SendClient(const CString& sLine) {
        CUser* pUser = CZNC::Get().FindUser(sLine.Token(1));

        if (pUser) {
            CIRCNetwork* pNetwork = pUser->FindNetwork(sLine.Token(2));

            if (pNetwork) {
                pNetwork->PutUser(sLine.Token(3, true));
                PutModule(t_f("Sent [{1}] to {2}/{3}")(sLine.Token(3, true),
                                                       pUser->GetUsername(),
                                                       pNetwork->GetName()));
            } else {
                PutModule(t_f("Network {1} not found for user {2}")(
                    sLine.Token(2), sLine.Token(1)));
            }
        } else {
            PutModule(t_f("User {1} not found")(sLine.Token(1)));
        }
    }

    void SendServer(const CString& sLine) {
        CUser* pUser = CZNC::Get().FindUser(sLine.Token(1));

        if (pUser) {
            CIRCNetwork* pNetwork = pUser->FindNetwork(sLine.Token(2));

            if (pNetwork) {
                pNetwork->PutIRC(sLine.Token(3, true));
                PutModule(t_f("Sent [{1}] to IRC server of {2}/{3}")(
                    sLine.Token(3, true), pUser->GetUsername(),
                    pNetwork->GetName()));
            } else {
                PutModule(t_f("Network {1} not found for user {2}")(
                    sLine.Token(2), sLine.Token(1)));
            }
        } else {
            PutModule(t_f("User {1} not found")(sLine.Token(1)));
        }
    }

    void CurrentClient(const CString& sLine) {
        CString sData = sLine.Token(1, true);
        GetClient()->PutClient(sData);
    }

  public:
    ~CSendRaw_Mod() override {}

    bool OnLoad(const CString& sArgs, CString& sErrorMsg) override {
        if (!GetUser()->IsAdmin()) {
            sErrorMsg =
                t_s("You must have admin privileges to load this module");
            return false;
        }

        return true;
    }

    CString GetWebMenuTitle() override { return t_s("Send Raw"); }
    bool WebRequiresAdmin() override { return true; }

    bool OnWebRequest(CWebSock& WebSock, const CString& sPageName,
                      CTemplate& Tmpl) override {
        if (sPageName == "index") {
            if (WebSock.IsPost()) {
                CUser* pUser = CZNC::Get().FindUser(
                    WebSock.GetParam("network").Token(0, false, "/"));
                if (!pUser) {
                    WebSock.GetSession()->AddError(t_s("User not found"));
                    return true;
                }

                CIRCNetwork* pNetwork = pUser->FindNetwork(
                    WebSock.GetParam("network").Token(1, false, "/"));
                if (!pNetwork) {
                    WebSock.GetSession()->AddError(t_s("Network not found"));
                    return true;
                }

                bool bToServer = WebSock.GetParam("send_to") == "server";
                const CString sLine = WebSock.GetParam("line");

                Tmpl["user"] = pUser->GetUsername();
                Tmpl[bToServer ? "to_server" : "to_client"] = "true";
                Tmpl["line"] = sLine;

                if (bToServer) {
                    pNetwork->PutIRC(sLine);
                } else {
                    pNetwork->PutUser(sLine);
                }

                WebSock.GetSession()->AddSuccess(t_s("Line sent"));
            }

            const map<CString, CUser*>& msUsers = CZNC::Get().GetUserMap();
            for (const auto& it : msUsers) {
                CTemplate& l = Tmpl.AddRow("UserLoop");
                l["Username"] = it.second->GetUsername();

                vector<CIRCNetwork*> vNetworks = it.second->GetNetworks();
                for (const CIRCNetwork* pNetwork : vNetworks) {
                    CTemplate& NetworkLoop = l.AddRow("NetworkLoop");
                    NetworkLoop["Username"] = it.second->GetUsername();
                    NetworkLoop["Network"] = pNetwork->GetName();
                }
            }

            return true;
        }

        return false;
    }

    MODCONSTRUCTOR(CSendRaw_Mod) {
        AddHelpCommand();
        AddCommand("Client", t_d("[user] [network] [data to send]"),
                   t_d("The data will be sent to the user's IRC client(s)"),
                   [=](const CString& sLine) { SendClient(sLine); });
        AddCommand("Server", t_d("[user] [network] [data to send]"),
                   t_d("The data will be sent to the IRC server the user is "
                       "connected to"),
                   [=](const CString& sLine) { SendServer(sLine); });
        AddCommand("Current", t_d("[data to send]"),
                   t_d("The data will be sent to your current client"),
                   [=](const CString& sLine) { CurrentClient(sLine); });
    }
};

template <>
void TModInfo<CSendRaw_Mod>(CModInfo& Info) {
    Info.SetWikiPage("send_raw");
}

USERMODULEDEFS(CSendRaw_Mod,
               t_s("Lets you send some raw IRC lines as/to someone else"))


text:
/*	Table OF Contents
	==========================
	Carousel
	Ajax Tab
	List view , Grid view  and compact view
	Global Plugins
	Customs Script
	responsive cat-collapse for homepage
	*/

$(document).ready(function() {

    /*==================================
	 Carousel
	====================================*/

    // Featured Listings  carousel || HOME PAGE
    var owlitem = $(".item-carousel");

    owlitem.owlCarousel({
        //navigation : true, // Show next and prev buttons
        navigation: false,
        pagination: true,
        items: 5,
		itemsDesktopSmall: 	[979,3],
		itemsTablet: [768, 3],
        itemsTabletSmall: [660, 2],
		itemsMobile: [400,1]

    });

    // Custom Navigation Events
    $("#nextItem").click(function() {
        owlitem.trigger('owl.next');
    })
    $("#prevItem").click(function() {
        owlitem.trigger('owl.prev');
    })

    // Featured Listings  carousel || HOME PAGE
    var featuredListSlider = $(".featured-list-slider");

    featuredListSlider.owlCarousel({
        //navigation : true, // Show next and prev buttons
        navigation: false,
        pagination: false,
        items: 5,
        itemsDesktopSmall: 	[979,3],
        itemsTablet: [768, 3],
        itemsTabletSmall: [660, 2],
        itemsMobile: [400,1]

    });

    // Custom Navigation Events
    $(".featured-list-row .next").click(function() {
        featuredListSlider.trigger('owl.next');
    })
    $(".featured-list-row .prev").click(function() {
        featuredListSlider.trigger('owl.prev');
    })

    /*==================================
	 Ajax Tab || CATEGORY PAGE
	====================================*/

     $("#ajaxTabs li > a").click(function() {

        $("#allAds").empty().append("

");
        $("#ajaxTabs li").removeClass('active');
        $(this).parent('li').addClass('active');
        $.ajax({ url: this.href, success: function(html) {
            $("#allAds").empty().append(html);
            $('.tooltipHere').tooltip('hide');
            }
    });
    return false;
    });

    urls = $('#ajaxTabs li:first-child a').attr("href");
    //alert(urls);
    $("#allAds").empty().append("

");
    $.ajax({ url: urls, success: function(html) {
            $("#allAds").empty().append(html);
        $('.tooltipHere').tooltip('hide');
    }
    });

    /*==================================
	 List view clickable || CATEGORY
	====================================*/

    // List view , Grid view  and compact view

    $('.list-view,#ajaxTabs li a').click(function(e) { //use a class, since your ID gets mangled
        e.preventDefault();
        $('.grid-view,.compact-view').removeClass("active");
        $('.list-view').addClass("active");
        $('.item-list').addClass("make-list"); //add the class to the clicked element
        $('.item-list').removeClass("make-grid");
        $('.item-list').removeClass("make-compact");
        $('.item-list .add-desc-box').removeClass("col-sm-9");
        $('.item-list .add-desc-box').addClass("col-sm-7");

        $(function() {
            $('.item-list').matchHeight('remove');
        });
    });

    $('.grid-view').click(function(e) { //use a class, since your ID gets mangled
        e.preventDefault();
        $('.list-view,.compact-view').removeClass("active");
        $(this).addClass("active");
        $('.item-list').addClass("make-grid"); //add the class to the clicked element
        $('.item-list').removeClass("make-list");
        $('.item-list').removeClass("make-compact");
        $('.item-list .add-desc-box').removeClass("col-sm-9");
        $('.item-list .add-desc-box').addClass("col-sm-7");

        $(function() {
            $('.item-list').matchHeight();
            $.fn.matchHeight._apply('.item-list');
        });

    });

    $(function() {
        $('.row-featured .f-category').matchHeight();
        $.fn.matchHeight._apply('.row-featured .f-category');
    });

    $(function() {
        $('.has-equal-div > div').matchHeight();
        $.fn.matchHeight._apply('.row-featured .f-category');
    });

    $('.compact-view').click(function(e) { //use a class, since your ID gets mangled
        e.preventDefault();
        $('.list-view,.grid-view').removeClass("active");
        $(this).addClass("active");
        $('.item-list').addClass("make-compact"); //add the class to the clicked element
        $('.item-list').removeClass("make-list");
        $('.item-list').removeClass("make-grid");
        $('.item-list .add-desc-box').toggleClass("col-sm-9 col-sm-7");

        $(function() {
            $('.adds-wrapper .item-list').matchHeight('remove');
        });

    });

    /*==================================
	Global Plugins ||
	====================================*/

    $('.long-list').hideMaxListItems({
        'max': 8,
        'speed': 500,
        'moreText': 'View More ([COUNT])'
    });

    $('.long-list-user').hideMaxListItems({
        'max': 12,
        'speed': 500,
        'moreText': 'View More ([COUNT])'
    });

    $(function () {
        $('[data-toggle="tooltip"]').tooltip()
    })

    $(".scrollbar").scroller(); // custom scroll bar plugin

    $("select.selecter").selecter({ // custom scroll select plugin
        label: "Select An Item"
    });

    $(".selectpicker").selecter({ // category list Short by
        customClass: "select-short-by"
    });

    /*=======================================================================================
		cat-collapse Hmepage Category Responsive view
	========================================================================================*/

    $(window).bind('resize load', function() {

        if ($(this).width() < 767) {

        $('.cat-collapse').collapse('hide');

            $('.cat-collapse').on('shown.bs.collapse', function() {
                $(this).prev('.cat-title').find('.icon-down-open-big').addClass("active-panel");
                //$(this).prev('.cat-title').find('.icon-down-open-big').toggleClass('icon-down-open-big icon-up-open-big');
            });

            $('.cat-collapse').on('hidden.bs.collapse', function() {
                $(this).prev('.cat-title').find('.icon-down-open-big').removeClass("active-panel");
            })

        } else {

		$('.cat-collapse').removeClass('out').addClass('in').css('height', 'auto');

        }

    });

    // DEMO PREVIEW

    $(".tbtn").click(function() {
        $('.themeControll').toggleClass('active')
    })

    // jobs

    $("input:radio").click(function() {
        if($('input:radio#job-seeker:checked').length > 0){
            $('.forJobSeeker').removeClass('hide');
            $('.forJobFinder').addClass('hide');
        }else{
            $('.forJobFinder').removeClass('hide');
            $('.forJobSeeker').addClass('hide')

        }

    })

    $(".filter-toggle").click(function() {
        $('.mobile-filter-sidebar').prepend("
X
");
        $(".mobile-filter-sidebar" ).animate({"left": "0" }, 250, "linear",function() {
        });
        $('.menu-overly-mask').addClass('is-visible');
    })

    $(".menu-overly-mask").click(function() {
        $(".mobile-filter-sidebar" ).animate({"left": "-251px" }, 250, "linear",function() {
        });
        $('.menu-overly-mask').removeClass('is-visible');
    })

    $(document).on('click', '.closeFilter' , function() {
        $(".mobile-filter-sidebar" ).animate({"left": "-251px" }, 250, "linear",function() {
        });
        $('.menu-overly-mask').removeClass('is-visible');
    });

}); // end Ready


text:
import json
import urllib.parse
import urllib.request

def read_webhose_key():
    webhose_api_key = None
    try:
        with open('search.key', 'r') as f:
            webhose_api_key = f.readline().strip()
    except:
        raise IOError('search.key file not found')

    return webhose_api_key

def run_query(search_terms, size=10):
    webhose_api_key = read_webhose_key()

    if not webhose_api_key:
        raise KeyError('Webhose key not found')

    root_url = 'http://webhose.io/search'
    query_string = urllib.parse.quote(search_terms)
    search_url = f'{root_url}?token={webhose_api_key}&format=json&q={query_string}&sort=relevancy&size={size}'
    results = []
    try:
        response = urllib.request.urlopen(search_url).read().decode('utf-8')
        json_response = json.loads(response)
        for post in json_response['posts']:
            results.append({'title': post['title'],
                            'link': post['url'],
                            'summary': post['text'][:200]})
    except:
        print('Error when querying the webhose API')

    return results


text:
#ifndef __EFFEKSEERRENDERER_METAL_RENDERER_H__
#define __EFFEKSEERRENDERER_METAL_RENDERER_H__

#include "../../EffekseerRendererCommon/EffekseerRenderer.Renderer.h"
#include "EffekseerRendererMetal.Base.h"
#include <functional>

#import <MetalKit/MetalKit.h>

@class MTLRenderPassDescriptor;
@protocol MTLDevice, MTLCommandBuffer, MTLRenderCommandEncoder, MTLTexture;

namespace EffekseerRendererMetal
{

::Effekseer::MaterialLoaderRef CreateMaterialLoader(::Effekseer::Backend::GraphicsDeviceRef graphicsDevice, ::Effekseer::FileInterfaceRef fileInterface = NULL);

::Effekseer::Backend::GraphicsDeviceRef CreateDevice();

::EffekseerRenderer::RendererRef Create(
                                      ::Effekseer::Backend::GraphicsDeviceRef graphicsDevice,
                                      int32_t squareMaxCount,
                                      MTLPixelFormat renderTargetFormat,
                                      MTLPixelFormat depthStencilFormat,
									  bool isReversedDepth);

/**
@brief	Create an instance
@param	device	metal device
@param	isReversedDepth is depth reversed
@param squareMaxCount	the number of maximum sprites
@return	instance
*/
::EffekseerRenderer::RendererRef Create(int32_t squareMaxCount,
                                      MTLPixelFormat renderTargetFormat,
                                      MTLPixelFormat depthStencilFormat,
									  bool isReversedDepth);

Effekseer::Backend::TextureRef CreateTexture(::Effekseer::Backend::GraphicsDeviceRef graphicsDevice, id<MTLTexture> texture);

void BeginCommandList(Effekseer::RefPtr<EffekseerRenderer::CommandList> commandList, id<MTLRenderCommandEncoder> encoder);

void EndCommandList(Effekseer::RefPtr<EffekseerRenderer::CommandList> commandList);

} // namespace EffekseerRendererMetal

#endif


text:
chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('index.html', {
    'bounds': {
      'width': 1138,
      'height': 640
    }
  });
});


text:
from django.db import migrations
from django.db.models import F

class Migration(migrations.Migration):
    def move_to_vuln_id(apps, schema_editor):
        finding_model = apps.get_model('dojo', 'Finding')
        test_type_model = apps.get_model('dojo', 'Test_Type')
        anchore_scan, _ = test_type_model.objects.get_or_create(name='Anchore Engine Scan')
        # extra protection, only migrate for the findings that have a non-null unique_id_from_tool
        findings = finding_model.objects.filter(test__test_type=anchore_scan, unique_id_from_tool__isnull=False)

        # assign value from unique_id_from tool to vuln_id_from_tool
        findings.update(vuln_id_from_tool=F('unique_id_from_tool'))

        # reset unique_id_from_tool
        findings.update(unique_id_from_tool=None)

    def reverse_move_to_vuln_id(apps, schema_editor):
        finding_model = apps.get_model('dojo', 'Finding')
        test_type_model = apps.get_model('dojo', 'Test_Type')
        anchore_scan, _ = test_type_model.objects.get_or_create(name='Anchore Engine Scan')
        findings = finding_model.objects.filter(test__test_type=anchore_scan, vuln_id_from_tool__isnull=False)

        # assign value from vuln_id_from tool to unique_id_from_tool
        findings.update(unique_id_from_tool=F('vuln_id_from_tool'))

        # reset vuln_id_from_tool
        findings.update(vuln_id_from_tool=None)

    dependencies = [
        ('dojo', '0097_engagement_type'),
    ]

    operations = [migrations.RunPython(move_to_vuln_id, reverse_move_to_vuln_id)]


text:
namespace Avalonia.Data
{
    /// <summary>
    /// The priority of a binding.
    /// </summary>
    public enum BindingPriority
    {
        /// <summary>
        /// A value that comes from an animation.
        /// </summary>
        Animation = -1,

        /// <summary>
        /// A local value.
        /// </summary>
        LocalValue = 0,

        /// <summary>
        /// A triggered style binding.
        /// </summary>
        /// <remarks>
        /// A style trigger is a selector such as .class which overrides a
        /// <see cref="TemplatedParent"/> binding. In this way, a basic control can have
        /// for example a Background from the templated parent which changes when the
        /// control has the :pointerover class.
        /// </remarks>
        StyleTrigger,

        /// <summary>
        /// A binding to a property on the templated parent.
        /// </summary>
        TemplatedParent,

        /// <summary>
        /// A style binding.
        /// </summary>
        Style,

        /// <summary>
        /// The binding is uninitialized.
        /// </summary>
        Unset = int.MaxValue,
    }
}


text:
var assert = require("assert"),
    form = require("../index"),
    validate = form.validate;

module.exports = {
  'validate : isDate': function() {
    // Skip validating empty values
    var request = { body: {} };
    form(validate("field").isDate())(request, {});
    assert.equal(request.form.errors.length, 0);

    // Failure.
    var request = { body: { field: "fail" }};
    form(validate("field").isDate())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is not a date");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    form(validate("field").isDate("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "01/29/2012" }};
    form(validate("field").isDate())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : isEmail': function() {
    // Skip validating empty values
    var request = { body: {} };
    form(validate("field").isEmail())(request, {});
    assert.equal(request.form.errors.length, 0);

    // Failure.
    var request = { body: { field: "fail" }};
    form(validate("field").isEmail())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is not an email address");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    form(validate("field").isEmail("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "me@dandean.com" }};
    form(validate("field").isEmail())(request, {});
    assert.equal(request.form.errors.length, 0);

    var validEmails = [
      "user@host.com",
      "user@host.info",
      "user@host.co.uk",
      "user+service@host.co.uk",
      "user-ok.yes+tag@host.k12.mi.us",
      "FirstNameLastName2000@hotmail.com"
    ];

    for (var i in validEmails) {
      var request = { body: { field: validEmails[i] }};
      form(validate("field").isEmail())(request, {});
      assert.equal(request.form.errors.length, 0, 'failed to validate email: ' + validEmails[i]);
    }

    var badEmails = [
      "dontvalidateme",
      "nope@",
      "someUser",
      "<script@host.com",
      "userawesome*@host.com",
      "userawesom@ok.com?&vl=1"
    ];

    for (var i in badEmails) {
      var request = { body: { field: badEmails[i] }};
      form(validate("field").isEmail())(request, {});
      assert.equal(request.form.errors.length, 1, 'should not validate email: ' + badEmails[i]);
    }

  },

  'validate : isUrl': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    form(validate("field").isUrl())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is not a URL");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    form(validate("field").isUrl("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "http://www.google.com" }};
    form(validate("field").isUrl())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : isIP': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    form(validate("field").isIP())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is not an IP address");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    form(validate("field").isIP("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "0.0.0.0" }};
    form(validate("field").isIP())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : isAlpha': function() {
    // Failure.
    var request = { body: { field: "123456" }};
    form(validate("field").isAlpha())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field contains non-letter characters");

    // Failure w/ custom message.
    var request = { body: { field: "123456" }};
    form(validate("field").isAlpha("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "abcde" }};
    form(validate("field").isAlpha())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : isAlphanumeric': function() {
    // Failure.
    var request = { body: { field: "------" }};
    form(validate("field").isAlphanumeric())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field contains non alpha-numeric characters");

    // Failure w/ custom message.
    var request = { body: { field: "------" }};
    form(validate("field").isAlphanumeric("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "abc123" }};
    form(validate("field").isAlphanumeric())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : isNumeric': function() {
    // Failure.
    var request = { body: { field: "------" }};
    form(validate("field").isNumeric())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is not a number");

    // Failure w/ custom message.
    var request = { body: { field: "------" }};
    form(validate("field").isNumeric("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success Int
    var request = { body: {
      integer: "123456",
      floating: "123456.45",
      negative: "-123456.45",
      positive: "+123456.45",
      padded: "000045.343"
    }};
    form(
      validate("integer").isNumeric(),
      validate("floating").isNumeric(),
      validate("negative").isNumeric(),
      validate("positive").isNumeric(),
      validate("padded").isNumeric()
    )(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : isInt': function() {
    // Failure.
    var request = { body: { field: "------" }};
    form(validate("field").isInt())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is not an integer");

    // Failure w/ custom message.
    var request = { body: { field: "------" }};
    form(validate("field").isInt("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "50" }};
    form(validate("field").isInt())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : isLowercase': function() {
    // Failure.
    var request = { body: { field: "FAIL" }};
    form(validate("field").isLowercase())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field contains uppercase letters");

    // Failure w/ custom message.
    var request = { body: { field: "FAIL" }};
    form(validate("field").isInt("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "win" }};
    form(validate("field").isLowercase())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : isUppercase': function() {
    // Failure.
    var request = { body: { field: "fail" }};
    form(validate("field").isUppercase())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field contains lowercase letters");

    // Failure w/ custom message.
    var request = { body: { field: "fail" }};
    form(validate("field").isUppercase("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "WIN" }};
    form(validate("field").isUppercase())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : isFloat': function() {
    // Failure.
    var request = { body: { field: "5000" }};
    form(validate("field").isFloat())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is not a decimal");

    // Failure w/ custom message.
    var request = { body: { field: "5000" }};
    form(validate("field").isFloat("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "5000.00" }};
    form(validate("field").isFloat())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : notEmpty': function() {
    // Failure.
    var request = { body: { field: "  \t" }};
    form(validate("field").notEmpty())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field has no value or is only whitespace");

    // Failure w/ custom message.
    var request = { body: { field: "  \t" }};
    form(validate("field").notEmpty("!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "win" }};
    form(validate("field").notEmpty())(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : equals': function() {
    // Failure.
    var request = { body: { field: "value" }};
    form(validate("field").equals("other"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field does not equal other");

    // Failure w/ custom message.
    var request = { body: { field: "value" }};
    form(validate("field").equals("other", "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "value" }};
    form(validate("field").equals("value"))(request, {});
    assert.equal(request.form.errors.length, 0);

    // Failure
    var request = {
      body: {
        field1: "value1",
        field2: "value2"
      }
    };
    form(validate("field1").equals("field::field2"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field1 does not equal value2");

    // Success
    var request = {
      body: {
        field1: "value",
        field2: "value"
      }
    };
    form(validate("field1").equals("field::field2"))(request, {});
    assert.equal(request.form.errors.length, 0);

    // Failure with nested values
    var request = {
      body: {
        field1: { deep: "value1"},
        field2: { deeper: "value2"}
      }
    };
    form(validate("field1.deep").equals("field::field2[deeper]"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field1.deep does not equal value2");

    // Success with nested values
    var request = {
      body: {
        field1: { deep: "value"},
        field2: { deeper: "value"}
      }
    };
    form(validate("field1[deep]").equals("field::field2.deeper"))(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : contains': function() {
    // Failure.
    var request = { body: { field: "value" }};
    form(validate("field").contains("other"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field does not contain required characters");

    // Failure w/ custom message.
    var request = { body: { field: "value" }};
    form(validate("field").contains("other", "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "value" }};
    form(validate("field").contains("alu"))(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : notContains': function() {
    // Failure.
    var request = { body: { field: "value" }};
    form(validate("field").notContains("alu"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field contains invalid characters");

    // Failure w/ custom message.
    var request = { body: { field: "value" }};
    form(validate("field").notContains("alu", "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "value" }};
    form(validate("field").notContains("win"))(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : regex/is': function() {
    // regex(/pattern/)
    // regex(/pattern/, "message")
    // regex("pattern")
    // regex("pattern", "modifiers")
    // regex("pattern", "message")
    // regex("pattern", "modifiers", "message")

    // Failure: RegExp with default args
    var request = { body: { field: "value" }};
    form(validate("field").regex(/^\d+$/))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field has invalid characters");

    // Failure: RegExp with custom message.
    var request = { body: { field: "value" }};
    form(validate("field").regex(/^\d+$/, "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Failure: String with default args.
    var request = { body: { field: "value" }};
    form(validate("field").regex("^\d+$"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field has invalid characters");

    // Success: String with modifiers
    var request = { body: { field: "value" }};
    form(validate("field").regex("^VALUE$", "i"))(request, {});
    assert.equal(request.form.errors.length, 0);

    // Failure: String with custom message
    var request = { body: { field: "value" }};
    form(validate("field").regex("^\d+$", "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Failure: String with modifiers and custom message
    var request = { body: { field: "value" }};
    form(validate("field").regex("^\d+$", "i", "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "value" }};
    form(validate("field").regex(/^value$/))(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validate : notRegex/not': function() {
    // notRegex(/pattern/)
    // notRegex(/pattern/, "message")
    // notRegex("pattern")
    // notRegex("pattern", "modifiers")
    // notRegex("pattern", "message")
    // notRegex("pattern", "modifiers", "message")

    // Failure: RegExp with default args
    var request = { body: { field: "value" }};
    form(validate("field").notRegex(/^value$/))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field has invalid characters");

    // Failure: RegExp with custom message.
    var request = { body: { field: "value" }};
    form(validate("field").notRegex(/^value$/, "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Failure: String with default args.
    var request = { body: { field: "value" }};
    form(validate("field").notRegex("^value$"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field has invalid characters");

    // Success: String with modifiers
    var request = { body: { field: "value" }};
    form(validate("field").notRegex("^win$", "i"))(request, {});
    assert.equal(request.form.errors.length, 0);

    // Failure: String with custom message
    var request = { body: { field: "value" }};
    form(validate("field").notRegex("^value$", "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Failure: String with modifiers and custom message
    var request = { body: { field: "value" }};
    form(validate("field").notRegex("^value$", "i", "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "value" }};
    form(validate("field").notRegex(/^win$/))(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validation : minLength': function() {
    // Failure.
    var request = { body: { field: "value" }};
    form(validate("field").minLength(10))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is too short");

    // Failure w/ custom message.
    var request = { body: { field: "value" }};
    form(validate("field").minLength(10, "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "value" }};
    form(validate("field").minLength(1))(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validation : isString()': function() {
    var request = { body: { username: 'adasds@example.com', password: { 'somevalue': '1' } }};
    form(validate('password', 'Password')
      .required()
      .isString()
      .minLength(10, '%s must be a minimum of 10 characters')
      .maxLength(256, '%s must be a maximum of 256 characters'))(request, {});
    assert.ok(!request.form.isValid);
    assert.strictEqual(request.form.errors[0], 'Password is not a string');
  },

  'validation : maxLength': function() {
    // Failure.
    var request = { body: { field: "value" }};
    form(validate("field").maxLength(1))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is too long");

    // Failure w/ custom message.
    var request = { body: { field: "value" }};
    form(validate("field").maxLength(1, "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "value" }};
    form(validate("field").maxLength(5))(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validation : required': function() {
    // Failure.
    var request = { body: {} };
    form(validate("field").required())(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is required");

    // Failure w/ placeholder value and custom message.
    var request = { body: { field: "value" }};
    form(validate("field").required("value", "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Success
    var request = { body: { field: "5000.00" }};
    form(validate("field").required())(request, {});
    assert.equal(request.form.errors.length, 0);

    // Non-required fields with no value should not trigger errors
    // Success
    var request = { body: {
      fieldEmpty: "",
      fieldUndefined: undefined,
      fieldNull: null
    }};
    form(
      validate("fieldEmpty").is(/whatever/),
      validate("fieldUndefined").is(/whatever/),
      validate("fieldNull").is(/whatever/),
      validate("fieldMissing").is(/whatever/)
    )(request, {});
    assert.equal(request.form.errors.length, 0);
  },

  'validation : custom': function() {
    var request;

    // Failure.
    request = { body: { field: "value" }};
    form(validate("field").custom(function(value) {
      throw new Error();
    }))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "field is invalid");

    // Failure w/ custom message.
    request = { body: { field: "value" }};
    form(validate("field").custom(function(value) {
      throw new Error();
    }, "!!! %s !!!"))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "!!! field !!!");

    // Failure w/ custom message from internal error.
    request = { body: { field: "value" }};
    form(validate("field").custom(function(value) {
      throw new Error("Radical %s");
    }))(request, {});
    assert.equal(request.form.errors.length, 1);
    assert.equal(request.form.errors[0], "Radical field");

    // Success
    request = { body: { field: "value" }};
    form(validate("field").custom(function(value) {}))(request, {});
    assert.equal(request.form.errors.length, 0);

    // Pass form data as 2nd argument to custom validators
    request = { body: { field1: "value1", field2: "value2" }};
    form(validate("field1").custom(function(value, formData) {
      assert.equal("value1", value);
      assert.ok(formData);
      assert.equal("value1", formData.field1);
      assert.equal("value2", formData.field2);
      throw new Error("This is a custom error thrown for %s.");
    }))(request, {});
    assert.equal(request.form.errors.length, 1);
  },

  "validation: custom : async": function(done) {
    var request = { body: { field1: "value1", field2: "value2" }};
    var next = function next() {
      assert.strictEqual(request.form.isValid, false);
      assert.strictEqual(request.form.errors.length, 1);
      assert.strictEqual(request.form.errors[0], 'Invalid field1');
      done();
    };

    form(validate("field1").custom(function(value, source, callback) {
      process.nextTick(function() {
        assert.strictEqual(value, 'value1');
        callback(new Error("Invalid %s"));
      });
    }))(request, {}, next);
  },

  "validation : custom : async : success": function(done) {
    var request = { body: { field1: "value1", field2: "value2" }};
    var callbackCalled = false;
    var next = function next() {
      assert.strictEqual(callbackCalled, true);
      assert.strictEqual(request.form.isValid, true);
      assert.strictEqual(request.form.errors.length, 0);
      done();
    };
    form(validate("field1").custom(function(value, source, callback) {
      process.nextTick(function() {
        assert.strictEqual(value, 'value1');
        callbackCalled = true;
        callback(null);
      });
    }))(request, {}, next);
  },

  "validation : custom : async : chaining": function(done) {
    var request = { body: { field1: "value1", field2: "value2" }};
    var callbackCalled = 0;
    var next = function next() {
      assert.strictEqual(callbackCalled, 2);
      assert.strictEqual(request.form.isValid, false);
      assert.strictEqual(request.form.errors.length, 2);
      assert.strictEqual(request.form.errors[0], 'Fail! field1');
      assert.strictEqual(request.form.errors[1], 'yes sync custom funcs still work !! field1');
      done();
    };

    form(validate("field1")
      .custom(function(value, source, callback) {
        process.nextTick(function() {
          ++callbackCalled;
          callback(null);
        });
      })
      .custom(function(value, source, callback) {
        process.nextTick(function() {
          ++callbackCalled;
          callback(new Error('Fail! %s'));
        });
      })
      .custom(function(value, source) {
        throw new Error('yes sync custom funcs still work !! %s');
      })
    )(request, {}, next);
  },

  "validation : custom : async : multiple fields": function(done) {
    var request = { body: { field1: "value1", field2: "value2" }};
    var callbackCalled = 0;
    var next = function next() {
      assert.strictEqual(callbackCalled, 2);
      assert.strictEqual(request.form.isValid, false);
      assert.strictEqual(request.form.errors.length, 2);
      assert.strictEqual(request.form.errors[0], 'field1 error');
      assert.strictEqual(request.form.errors[1], 'field2 error');
      done();
    };
    form(
      validate("field1").custom(function(value, source, callback) {
        process.nextTick(function() {
          ++callbackCalled;
          assert.strictEqual(value, 'value1')
          callback(new Error('%s error'));
        });
      }),
      validate("field2").custom(function(value, source, callback) {
        process.nextTick(function() {
          ++callbackCalled;
          assert.strictEqual(value, 'value2');
          callback(new Error('%s error'));
        });
      })
    )(request, {}, next);
  },

  "validation : request.form property-pollution": function() {
    var request = { body: { }};
    form()(request, {});
    assert.equal(request.form.errors.length, 0);
    assert.equal('{}', JSON.stringify(request.form));
  },

  "validation : complex properties": function() {
    var request = { body: { field: { inner: "value", even: { more: { inner: "value" }}}}};
    form(
      validate("field[inner]").required().equals("value"),
      validate("field[inner]").required().equals("fail"),
      validate("field[even][more][inner]").required().equals("value"),
      validate("field[even][more][inner]").required().equals("fail")
    )(request, {});
    assert.equal(request.form.errors.length, 2);
  }
};


text:
<html>
<body>
Reports ternary conditional expressions that are nested inside other
conditional expressions.  Such nested conditionals may be very confusing.  "Elvis" expressions are counted as conditionals
for purpose of this inspection.
</body>
</html>


text:
CREATE TABLE album(
  id CHAR(10) NOT NULL PRIMARY KEY,
  title VARCHAR(100),
  artist VARCHAR(100)
);

CREATE TABLE track(
  album CHAR(10),
  dsk INTEGER,
  posn INTEGER,
  song VARCHAR(255),
  FOREIGN KEY (album) REFERENCES album(id)
);

ALTER TABLE album DROP ATTRIBUTE id;

drop class track;
drop class album;


text:
import os
import sys

CURRENT_DIR  = os.path.dirname(__file__)
NEWSBLUR_DIR = ''.join([CURRENT_DIR, '/../../'])
sys.path.insert(0, NEWSBLUR_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

import time
import s3
from django.conf import settings

filename = 'backup_redis_story_%s.rdb.gz' % time.strftime('%Y-%m-%d-%H-%M')
path = '/var/lib/redis/dump.rdb'
print 'Uploading %s (from %s) to S3...' % (filename, path)
s3.save_file_in_s3(path, name=filename)


text:
Noize Watcher

Connected:
* Sound Sensor on A0
* LCD on I2C-1
* Button on D3


text:
insert into DRAGON (ID, DRAGON_TYPE, NAME) values (1, 'BLUE', 'Saphira');
insert into DRAGON (ID, DRAGON_TYPE, NAME) values (2, 'GREEN', 'Puff');


text:
Per https://shapeshed.com/vim-templates/, it's possible to create template files
and have them autopopulate a new buffer.

Simply linking this folder to `~/.vim/templates` and adding this snippet below
is enough to activate this functionality.

```
if has("autocmd")
  augroup templates
    autocmd BufNewFile *.sh 0r ~/.vim/templates/skeleton.sh
    autocmd BufNewFile *.zsh 0r ~/.vim/templates/skeleton.zsh
  augroup END
endif
```


text:
require 'ripl'

module Ripl
  module ColorResult
    VERSION = '0.4.1'

    def before_loop
      super
      if Ripl.config[:color_result_engine] == :default
        require 'wirb' unless defined?(Wirb)
        Ripl.config[:color_result_default_schema].merge! Wirb.schema
      end
    end

    def format_result(result)
      return super if !config[:color_result_engine]

      @result_prompt + case config[:color_result_engine].to_sym
      when :coderay
        require 'coderay' unless defined?(CodeRay)
        CodeRay.scan( result.inspect, :ruby ).term
      when :ap, :awesome_print
        require 'ap' unless defined?(AwesomePrint)
        result.awesome_inspect( config[:color_result_ap_options] || {} )
      else # :default
        require 'wirb' unless defined?(Wirb)
        Wirb.start unless Wirb.running?
        Wirb.colorize_result result.inspect, Ripl.config[:color_result_default_schema]
      end
    end
  end
end

Ripl::Shell.include Ripl::ColorResult

Ripl.config[:color_result_engine] ||= :default
Ripl.config[:color_result_default_schema] = Hash.new{ |h,k| h[k] = {} }


text:
package client

import (
	"bytes"
	"crypto/tls"
	"io/ioutil"
	"net/http"

	"github.com/docker/engine-api/client/transport"
)

type mockClient struct {
	do func(*http.Request) (*http.Response, error)
}

// TLSConfig returns the TLS configuration.
func (m *mockClient) TLSConfig() *tls.Config {
	return &tls.Config{}
}

// Scheme returns protocol scheme to use.
func (m *mockClient) Scheme() string {
	return "http"
}

// Secure returns true if there is a TLS configuration.
func (m *mockClient) Secure() bool {
	return false
}

// NewMockClient returns a mocked client that runs the function supplied as `client.Do` call
func newMockClient(tlsConfig *tls.Config, doer func(*http.Request) (*http.Response, error)) transport.Client {
	if tlsConfig != nil {
		panic("this actually gets set!")
	}

	return &mockClient{
		do: doer,
	}
}

// Do executes the supplied function for the mock.
func (m mockClient) Do(req *http.Request) (*http.Response, error) {
	return m.do(req)
}

func errorMock(statusCode int, message string) func(req *http.Request) (*http.Response, error) {
	return func(req *http.Request) (*http.Response, error) {
		return &http.Response{
			StatusCode: statusCode,
			Body:       ioutil.NopCloser(bytes.NewReader([]byte(message))),
		}, nil
	}
}


text:
"""Helper object for transforming audio to spectra.

Handles transformations between waveforms, stfts, spectrograms,
mel-spectrograms, and instantaneous frequency (specgram).
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from magenta.models.gansynth.lib import spectral_ops
import numpy as np
import tensorflow as tf

class SpecgramsHelper(object):
  """Helper functions to compute specgrams."""

  def __init__(self, audio_length, spec_shape, overlap,
               sample_rate, mel_downscale, ifreq=True, discard_dc=True):
    self._audio_length = audio_length
    self._spec_shape = spec_shape
    self._overlap = overlap
    self._sample_rate = sample_rate
    self._mel_downscale = mel_downscale
    self._ifreq = ifreq
    self._discard_dc = discard_dc

    self._nfft, self._nhop = self._get_nfft_nhop()
    self._pad_l, self._pad_r = self._get_padding()

    self._eps = 1.0e-6

  def _safe_log(self, x):
    return tf.log(x + self._eps)

  def _get_nfft_nhop(self):
    n_freq_bins = self._spec_shape[1]
    # Power of two only has 1 nonzero in binary representation
    is_power_2 = bin(n_freq_bins).count('1') == 1
    if not is_power_2:
      raise ValueError('Wrong spec_shape. Number of frequency bins must be '
                       'a power of 2, not %d' % n_freq_bins)
    nfft = n_freq_bins * 2
    nhop = int((1. - self._overlap) * nfft)
    return (nfft, nhop)

  def _get_padding(self):
    """Infer left and right padding for STFT."""
    n_samps_inv = self._nhop * (self._spec_shape[0] - 1) + self._nfft
    if n_samps_inv < self._audio_length:
      raise ValueError('Wrong audio length. Number of ISTFT samples, %d, should'
                       ' be less than audio lengeth %d' % self._audio_length)

    # For Nsynth dataset, we are putting all padding in the front
    # This causes edge effects in the tail
    padding = n_samps_inv - self._audio_length
    padding_l = padding
    padding_r = padding - padding_l
    return padding_l, padding_r

  def waves_to_stfts(self, waves):
    """Convert from waves to complex stfts.

    Args:
      waves: Tensor of the waveform, shape [batch, time, 1].

    Returns:
      stfts: Complex64 tensor of stft, shape [batch, time, freq, 1].
    """
    waves_padded = tf.pad(waves, [[0, 0], [self._pad_l, self._pad_r], [0, 0]])
    stfts = tf.contrib.signal.stft(
        waves_padded[:, :, 0],
        frame_length=self._nfft,
        frame_step=self._nhop,
        fft_length=self._nfft,
        pad_end=False)[:, :, :, tf.newaxis]
    stfts = stfts[:, :, 1:] if self._discard_dc else stfts[:, :, :-1]
    stft_shape = stfts.get_shape().as_list()[1:3]
    if tuple(stft_shape) != tuple(self._spec_shape):
      raise ValueError(
          'Spectrogram returned the wrong shape {}, is not the same as the '
          'constructor spec_shape {}.'.format(stft_shape, self._spec_shape))
    return stfts

  def stfts_to_waves(self, stfts):
    """Convert from complex stfts to waves.

    Args:
      stfts: Complex64 tensor of stft, shape [batch, time, freq, 1].

    Returns:
      waves: Tensor of the waveform, shape [batch, time, 1].
    """
    dc = 1 if self._discard_dc else 0
    nyq = 1 - dc
    stfts = tf.pad(stfts, [[0, 0], [0, 0], [dc, nyq], [0, 0]])
    waves_resyn = tf.contrib.signal.inverse_stft(
        stfts=stfts[:, :, :, 0],
        frame_length=self._nfft,
        frame_step=self._nhop,
        fft_length=self._nfft,
        window_fn=tf.contrib.signal.inverse_stft_window_fn(
            frame_step=self._nhop))[:, :, tf.newaxis]
    # Python does not allow rslice of -0
    if self._pad_r == 0:
      return waves_resyn[:, self._pad_l:]
    else:
      return waves_resyn[:, self._pad_l:-self._pad_r]

  def stfts_to_specgrams(self, stfts):
    """Converts stfts to specgrams.

    Args:
      stfts: Complex64 tensor of stft, shape [batch, time, freq, 1].

    Returns:
      specgrams: Tensor of log magnitudes and instantaneous frequencies,
        shape [batch, time, freq, 2].
    """
    stfts = stfts[:, :, :, 0]

    logmag = self._safe_log(tf.abs(stfts))

    phase_angle = tf.angle(stfts)
    if self._ifreq:
      p = spectral_ops.instantaneous_frequency(phase_angle)
    else:
      p = phase_angle / np.pi

    return tf.concat(
        [logmag[:, :, :, tf.newaxis], p[:, :, :, tf.newaxis]], axis=-1)

  def specgrams_to_stfts(self, specgrams):
    """Converts specgrams to stfts.

    Args:
      specgrams: Tensor of log magnitudes and instantaneous frequencies,
        shape [batch, time, freq, 2].

    Returns:
      stfts: Complex64 tensor of stft, shape [batch, time, freq, 1].
    """
    logmag = specgrams[:, :, :, 0]
    p = specgrams[:, :, :, 1]

    mag = tf.exp(logmag)

    if self._ifreq:
      phase_angle = tf.cumsum(p * np.pi, axis=-2)
    else:
      phase_angle = p * np.pi

    return spectral_ops.polar2rect(mag, phase_angle)[:, :, :, tf.newaxis]

  def _linear_to_mel_matrix(self):
    """Get the mel transformation matrix."""
    num_freq_bins = self._nfft // 2
    lower_edge_hertz = 0.0
    upper_edge_hertz = self._sample_rate / 2.0
    num_mel_bins = num_freq_bins // self._mel_downscale
    return spectral_ops.linear_to_mel_weight_matrix(
        num_mel_bins, num_freq_bins, self._sample_rate, lower_edge_hertz,
        upper_edge_hertz)

  def _mel_to_linear_matrix(self):
    """Get the inverse mel transformation matrix."""
    m = self._linear_to_mel_matrix()
    m_t = np.transpose(m)
    p = np.matmul(m, m_t)
    d = [1.0 / x if np.abs(x) > 1.0e-8 else x for x in np.sum(p, axis=0)]
    return np.matmul(m_t, np.diag(d))

  def specgrams_to_melspecgrams(self, specgrams):
    """Converts specgrams to melspecgrams.

    Args:
      specgrams: Tensor of log magnitudes and instantaneous frequencies,
        shape [batch, time, freq, 2].

    Returns:
      melspecgrams: Tensor of log magnitudes and instantaneous frequencies,
        shape [batch, time, freq, 2], mel scaling of frequencies.
    """
    if self._mel_downscale is None:
      return specgrams

    logmag = specgrams[:, :, :, 0]
    p = specgrams[:, :, :, 1]

    mag2 = tf.exp(2.0 * logmag)
    phase_angle = tf.cumsum(p * np.pi, axis=-2)

    l2mel = tf.to_float(self._linear_to_mel_matrix())
    logmelmag2 = self._safe_log(tf.tensordot(mag2, l2mel, 1))
    mel_phase_angle = tf.tensordot(phase_angle, l2mel, 1)
    mel_p = spectral_ops.instantaneous_frequency(mel_phase_angle)

    return tf.concat(
        [logmelmag2[:, :, :, tf.newaxis], mel_p[:, :, :, tf.newaxis]], axis=-1)

  def melspecgrams_to_specgrams(self, melspecgrams):
    """Converts melspecgrams to specgrams.

    Args:
      melspecgrams: Tensor of log magnitudes and instantaneous frequencies,
        shape [batch, time, freq, 2], mel scaling of frequencies.

    Returns:
      specgrams: Tensor of log magnitudes and instantaneous frequencies,
        shape [batch, time, freq, 2].
    """
    if self._mel_downscale is None:
      return melspecgrams

    logmelmag2 = melspecgrams[:, :, :, 0]
    mel_p = melspecgrams[:, :, :, 1]

    mel2l = tf.to_float(self._mel_to_linear_matrix())
    mag2 = tf.tensordot(tf.exp(logmelmag2), mel2l, 1)
    logmag = 0.5 * self._safe_log(mag2)
    mel_phase_angle = tf.cumsum(mel_p * np.pi, axis=-2)
    phase_angle = tf.tensordot(mel_phase_angle, mel2l, 1)
    p = spectral_ops.instantaneous_frequency(phase_angle)

    return tf.concat(
        [logmag[:, :, :, tf.newaxis], p[:, :, :, tf.newaxis]], axis=-1)

  def stfts_to_melspecgrams(self, stfts):
    """Converts stfts to mel-spectrograms."""
    return self.specgrams_to_melspecgrams(self.stfts_to_specgrams(stfts))

  def melspecgrams_to_stfts(self, melspecgrams):
    """Converts mel-spectrograms to stfts."""
    return self.specgrams_to_stfts(self.melspecgrams_to_specgrams(melspecgrams))

  def waves_to_specgrams(self, waves):
    """Converts waves to spectrograms."""
    return self.stfts_to_specgrams(self.waves_to_stfts(waves))

  def specgrams_to_waves(self, specgrams):
    """Converts spectrograms to stfts."""
    return self.stfts_to_waves(self.specgrams_to_stfts(specgrams))

  def waves_to_melspecgrams(self, waves):
    """Converts waves to mel-spectrograms."""
    return self.stfts_to_melspecgrams(self.waves_to_stfts(waves))

  def melspecgrams_to_waves(self, melspecgrams):
    """Converts mel-spectrograms to stfts."""
    return self.stfts_to_waves(self.melspecgrams_to_stfts(melspecgrams))


text:
<?php

declare(strict_types=1);

namespace sspat\ProfiRu\Contracts;

interface SIDGenerator
{
    public function generate() : string;
}


text:
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(non_camel_case_types)]

//! Validates all used crates and extern libraries and loads their metadata

use back::svh::Svh;
use session::{config, Session};
use session::search_paths::PathKind;
use metadata::cstore;
use metadata::cstore::{CStore, CrateSource, MetadataBlob};
use metadata::decoder;
use metadata::loader;
use metadata::loader::CratePaths;

use std::rc::Rc;
use syntax::ast;
use syntax::abi;
use syntax::attr;
use syntax::attr::AttrMetaMethods;
use syntax::codemap::{COMMAND_LINE_SP, Span, mk_sp};
use syntax::parse;
use syntax::parse::token::InternedString;
use syntax::parse::token;
use syntax::visit;
use util::fs;
use log;

pub struct CrateReader<'a> {
    sess: &'a Session,
    next_crate_num: ast::CrateNum,
}

impl<'a, 'v> visit::Visitor<'v> for CrateReader<'a> {
    fn visit_view_item(&mut self, a: &ast::ViewItem) {
        self.process_view_item(a);
        visit::walk_view_item(self, a);
    }
    fn visit_item(&mut self, a: &ast::Item) {
        self.process_item(a);
        visit::walk_item(self, a);
    }
}

fn dump_crates(cstore: &CStore) {
    debug!("resolved crates:");
    cstore.iter_crate_data_origins(|_, data, opt_source| {
        debug!("  name: {}", data.name());
        debug!("  cnum: {}", data.cnum);
        debug!("  hash: {}", data.hash());
        opt_source.map(|cs| {
            let CrateSource { dylib, rlib, cnum: _ } = cs;
            dylib.map(|dl| debug!("  dylib: {}", dl.0.display()));
            rlib.map(|rl|  debug!("   rlib: {}", rl.0.display()));
        });
    })
}

fn should_link(i: &ast::ViewItem) -> bool {
    !attr::contains_name(&i.attrs[], "no_link")

}

struct CrateInfo {
    ident: String,
    name: String,
    id: ast::NodeId,
    should_link: bool,
}

pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
    let err = |&: s: &str| {
        match (sp, sess) {
            (_, None) => panic!("{}", s),
            (Some(sp), Some(sess)) => sess.span_err(sp, s),
            (None, Some(sess)) => sess.err(s),
        }
    };
    if s.len() == 0 {
        err("crate name must not be empty");
    }
    for c in s.chars() {
        if c.is_alphanumeric() { continue }
        if c == '_' || c == '-' { continue }
        err(&format!("invalid character `{}` in crate name: `{}`", c, s)[]);
    }
    match sess {
        Some(sess) => sess.abort_if_errors(),
        None => {}
    }
}

fn register_native_lib(sess: &Session,
                       span: Option<Span>,
                       name: String,
                       kind: cstore::NativeLibraryKind) {
    if name.is_empty() {
        match span {
            Some(span) => {
                sess.span_err(span, "#[link(name = \"\")] given with \
                                     empty name");
            }
            None => {
                sess.err("empty library name given via `-l`");
            }
        }
        return
    }
    let is_osx = sess.target.target.options.is_like_osx;
    if kind == cstore::NativeFramework && !is_osx {
        let msg = "native frameworks are only available on OSX targets";
        match span {
            Some(span) => sess.span_err(span, msg),
            None => sess.err(msg),
        }
    }
    sess.cstore.add_used_library(name, kind);
}

pub struct PluginMetadata<'a> {
    sess: &'a Session,
    metadata: PMDSource,
    dylib: Option<Path>,
    info: CrateInfo,
    vi_span: Span,
    target_only: bool,
}

enum PMDSource {
    Registered(Rc<cstore::crate_metadata>),
    Owned(MetadataBlob),
}

impl PMDSource {
    pub fn as_slice<'a>(&'a self) -> &'a [u8] {
        match *self {
            PMDSource::Registered(ref cmd) => cmd.data(),
            PMDSource::Owned(ref mdb) => mdb.as_slice(),
        }
    }
}

impl<'a> CrateReader<'a> {
    pub fn new(sess: &'a Session) -> CrateReader<'a> {
        CrateReader {
            sess: sess,
            next_crate_num: sess.cstore.next_crate_num(),
        }
    }

    // Traverses an AST, reading all the information about use'd crates and extern
    // libraries necessary for later resolving, typechecking, linking, etc.
    pub fn read_crates(&mut self, krate: &ast::Crate) {
        self.process_crate(krate);
        visit::walk_crate(self, krate);

        if log_enabled!(log::DEBUG) {
            dump_crates(&self.sess.cstore);
        }

        for &(ref name, kind) in self.sess.opts.libs.iter() {
            register_native_lib(self.sess, None, name.clone(), kind);
        }
    }

    fn process_crate(&self, c: &ast::Crate) {
        for a in c.attrs.iter().filter(|m| m.name() == "link_args") {
            match a.value_str() {
                Some(ref linkarg) => self.sess.cstore.add_used_link_args(linkarg.get()),
                None => { /* fallthrough */ }
            }
        }
    }

    fn process_view_item(&mut self, i: &ast::ViewItem) {
        if !should_link(i) {
            return;
        }

        match self.extract_crate_info(i) {
            Some(info) => {
                let (cnum, _, _) = self.resolve_crate(&None,
                                                      &info.ident[],
                                                      &info.name[],
                                                      None,
                                                      i.span,
                                                      PathKind::Crate);
                self.sess.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
            }
            None => ()
        }
    }

    fn extract_crate_info(&self, i: &ast::ViewItem) -> Option<CrateInfo> {
        match i.node {
            ast::ViewItemExternCrate(ident, ref path_opt, id) => {
                let ident = token::get_ident(ident);
                debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
                       ident, path_opt);
                let name = match *path_opt {
                    Some((ref path_str, _)) => {
                        let name = path_str.get().to_string();
                        validate_crate_name(Some(self.sess), &name[],
                                            Some(i.span));
                        name
                    }
                    None => ident.get().to_string(),
                };
                Some(CrateInfo {
                    ident: ident.get().to_string(),
                    name: name,
                    id: id,
                    should_link: should_link(i),
                })
            }
            _ => None
        }
    }

    fn process_item(&self, i: &ast::Item) {
        match i.node {
            ast::ItemForeignMod(ref fm) => {
                if fm.abi == abi::Rust || fm.abi == abi::RustIntrinsic {
                    return;
                }

                // First, add all of the custom link_args attributes
                let link_args = i.attrs.iter()
                    .filter_map(|at| if at.name() == "link_args" {
                        Some(at)
                    } else {
                        None
                    })
                    .collect::<Vec<&ast::Attribute>>();
                for m in link_args.iter() {
                    match m.value_str() {
                        Some(linkarg) => self.sess.cstore.add_used_link_args(linkarg.get()),
                        None => { /* fallthrough */ }
                    }
                }

                // Next, process all of the #[link(..)]-style arguments
                let link_args = i.attrs.iter()
                    .filter_map(|at| if at.name() == "link" {
                        Some(at)
                    } else {
                        None
                    })
                    .collect::<Vec<&ast::Attribute>>();
                for m in link_args.iter() {
                    match m.meta_item_list() {
                        Some(items) => {
                            let kind = items.iter().find(|k| {
                                k.name() == "kind"
                            }).and_then(|a| a.value_str());
                            let kind = match kind {
                                Some(k) => {
                                    if k == "static" {
                                        cstore::NativeStatic
                                    } else if self.sess.target.target.options.is_like_osx
                                              && k == "framework" {
                                        cstore::NativeFramework
                                    } else if k == "framework" {
                                        cstore::NativeFramework
                                    } else if k == "dylib" {
                                        cstore::NativeUnknown
                                    } else {
                                        self.sess.span_err(m.span,
                                            &format!("unknown kind: `{}`",
                                                    k)[]);
                                        cstore::NativeUnknown
                                    }
                                }
                                None => cstore::NativeUnknown
                            };
                            let n = items.iter().find(|n| {
                                n.name() == "name"
                            }).and_then(|a| a.value_str());
                            let n = match n {
                                Some(n) => n,
                                None => {
                                    self.sess.span_err(m.span,
                                        "#[link(...)] specified without \
                                         `name = \"foo\"`");
                                    InternedString::new("foo")
                                }
                            };
                            register_native_lib(self.sess, Some(m.span),
                                                n.get().to_string(), kind);
                        }
                        None => {}
                    }
                }
            }
            _ => { }
        }
    }

    fn existing_match(&self, name: &str, hash: Option<&Svh>, kind: PathKind)
                      -> Option<ast::CrateNum> {
        let mut ret = None;
        self.sess.cstore.iter_crate_data(|cnum, data| {
            if data.name != name { return }

            match hash {
                Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
                Some(..) => return,
                None => {}
            }

            // When the hash is None we're dealing with a top-level dependency
            // in which case we may have a specification on the command line for
            // this library. Even though an upstream library may have loaded
            // something of the same name, we have to make sure it was loaded
            // from the exact same location as well.
            //
            // We're also sure to compare *paths*, not actual byte slices. The
            // `source` stores paths which are normalized which may be different
            // from the strings on the command line.
            let source = self.sess.cstore.get_used_crate_source(cnum).unwrap();
            if let Some(locs) = self.sess.opts.externs.get(name) {
                let found = locs.iter().any(|l| {
                    let l = fs::realpath(&Path::new(&l[])).ok();
                    source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
                    source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
                });
                if found {
                    ret = Some(cnum);
                }
            }

            // Alright, so we've gotten this far which means that `data` has the
            // right name, we don't have a hash, and we don't have a --extern
            // pointing for ourselves. We're still not quite yet done because we
            // have to make sure that this crate was found in the crate lookup
            // path (this is a top-level dependency) as we don't want to
            // implicitly load anything inside the dependency lookup path.
            let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
                                  .unwrap().1;
            if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
                ret = Some(cnum);
            }
        });
        return ret;
    }

    fn register_crate(&mut self,
                      root: &Option<CratePaths>,
                      ident: &str,
                      name: &str,
                      span: Span,
                      lib: loader::Library)
                      -> (ast::CrateNum, Rc<cstore::crate_metadata>,
                          cstore::CrateSource) {
        // Claim this crate number and cache it
        let cnum = self.next_crate_num;
        self.next_crate_num += 1;

        // Stash paths for top-most crate locally if necessary.
        let crate_paths = if root.is_none() {
            Some(CratePaths {
                ident: ident.to_string(),
                dylib: lib.dylib.clone().map(|p| p.0),
                rlib:  lib.rlib.clone().map(|p| p.0),
            })
        } else {
            None
        };
        // Maintain a reference to the top most crate.
        let root = if root.is_some() { root } else { &crate_paths };

        let cnum_map = self.resolve_crate_deps(root, lib.metadata.as_slice(), span);

        let loader::Library{ dylib, rlib, metadata } = lib;

        let cmeta = Rc::new( cstore::crate_metadata {
            name: name.to_string(),
            data: metadata,
            cnum_map: cnum_map,
            cnum: cnum,
            span: span,
        });

        let source = cstore::CrateSource {
            dylib: dylib,
            rlib: rlib,
            cnum: cnum,
        };

        self.sess.cstore.set_crate_data(cnum, cmeta.clone());
        self.sess.cstore.add_used_crate_source(source.clone());
        (cnum, cmeta, source)
    }

    fn resolve_crate(&mut self,
                     root: &Option<CratePaths>,
                     ident: &str,
                     name: &str,
                     hash: Option<&Svh>,
                     span: Span,
                     kind: PathKind)
                         -> (ast::CrateNum, Rc<cstore::crate_metadata>,
                             cstore::CrateSource) {
        match self.existing_match(name, hash, kind) {
            None => {
                let mut load_ctxt = loader::Context {
                    sess: self.sess,
                    span: span,
                    ident: ident,
                    crate_name: name,
                    hash: hash.map(|a| &*a),
                    filesearch: self.sess.target_filesearch(kind),
                    target: &self.sess.target.target,
                    triple: &self.sess.opts.target_triple[],
                    root: root,
                    rejected_via_hash: vec!(),
                    rejected_via_triple: vec!(),
                    should_match_name: true,
                };
                let library = load_ctxt.load_library_crate();
                self.register_crate(root, ident, name, span, library)
            }
            Some(cnum) => (cnum,
                           self.sess.cstore.get_crate_data(cnum),
                           self.sess.cstore.get_used_crate_source(cnum).unwrap())
        }
    }

    // Go through the crate metadata and load any crates that it references
    fn resolve_crate_deps(&mut self,
                          root: &Option<CratePaths>,
                          cdata: &[u8], span : Span)
                       -> cstore::cnum_map {
        debug!("resolving deps of external crate");
        // The map from crate numbers in the crate we're resolving to local crate
        // numbers
        decoder::get_crate_deps(cdata).iter().map(|dep| {
            debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
            let (local_cnum, _, _) = self.resolve_crate(root,
                                                   &dep.name[],
                                                   &dep.name[],
                                                   Some(&dep.hash),
                                                   span,
                                                   PathKind::Dependency);
            (dep.cnum, local_cnum)
        }).collect()
    }

    pub fn read_plugin_metadata<'b>(&'b mut self,
                                    krate: CrateOrString<'b>) -> PluginMetadata<'b> {
        let (info, span) = match krate {
            CrateOrString::Krate(c) => {
                (self.extract_crate_info(c).unwrap(), c.span)
            }
            CrateOrString::Str(s) => {
                (CrateInfo {
                     name: s.to_string(),
                     ident: s.to_string(),
                     id: ast::DUMMY_NODE_ID,
                     should_link: true,
                 }, COMMAND_LINE_SP)
            }
        };
        let target_triple = &self.sess.opts.target_triple[];
        let is_cross = target_triple != config::host_triple();
        let mut should_link = info.should_link && !is_cross;
        let mut target_only = false;
        let ident = info.ident.clone();
        let name = info.name.clone();
        let mut load_ctxt = loader::Context {
            sess: self.sess,
            span: span,
            ident: &ident[],
            crate_name: &name[],
            hash: None,
            filesearch: self.sess.host_filesearch(PathKind::Crate),
            target: &self.sess.host,
            triple: config::host_triple(),
            root: &None,
            rejected_via_hash: vec!(),
            rejected_via_triple: vec!(),
            should_match_name: true,
        };
        let library = match load_ctxt.maybe_load_library_crate() {
            Some(l) => l,
            None if is_cross => {
                // Try loading from target crates. This will abort later if we
                // try to load a plugin registrar function,
                target_only = true;
                should_link = info.should_link;

                load_ctxt.target = &self.sess.target.target;
                load_ctxt.triple = target_triple;
                load_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
                load_ctxt.load_library_crate()
            }
            None => { load_ctxt.report_load_errs(); unreachable!() },
        };

        let dylib = library.dylib.clone();
        let register = should_link && self.existing_match(info.name.as_slice(),
                                                          None,
                                                          PathKind::Crate).is_none();
        let metadata = if register {
            // Register crate now to avoid double-reading metadata
            let (_, cmd, _) = self.register_crate(&None, &info.ident[],
                                &info.name[], span, library);
            PMDSource::Registered(cmd)
        } else {
            // Not registering the crate; just hold on to the metadata
            PMDSource::Owned(library.metadata)
        };

        PluginMetadata {
            sess: self.sess,
            metadata: metadata,
            dylib: dylib.map(|p| p.0),
            info: info,
            vi_span: span,
            target_only: target_only,
        }
    }
}

#[derive(Copy)]
pub enum CrateOrString<'a> {
    Krate(&'a ast::ViewItem),
    Str(&'a str)
}

impl<'a> PluginMetadata<'a> {
    /// Read exported macros
    pub fn exported_macros(&self) -> Vec<ast::MacroDef> {
        let imported_from = Some(token::intern(&self.info.ident[]).ident());
        let source_name = format!("<{} macros>", &self.info.ident[]);
        let mut macros = vec![];
        decoder::each_exported_macro(self.metadata.as_slice(),
                                     &*self.sess.cstore.intr,
            |name, attrs, body| {
                // NB: Don't use parse::parse_tts_from_source_str because it parses with
                // quote_depth > 0.
                let mut p = parse::new_parser_from_source_str(&self.sess.parse_sess,
                                                              self.sess.opts.cfg.clone(),
                                                              source_name.clone(),
                                                              body);
                let lo = p.span.lo;
                let body = p.parse_all_token_trees();
                let span = mk_sp(lo, p.last_span.hi);
                p.abort_if_errors();
                macros.push(ast::MacroDef {
                    ident: name.ident(),
                    attrs: attrs,
                    id: ast::DUMMY_NODE_ID,
                    span: span,
                    imported_from: imported_from,
                    // overridden in plugin/load.rs
                    export: false,
                    use_locally: false,

                    body: body,
                });
                true
            }
        );
        macros
    }

    /// Look for a plugin registrar. Returns library path and symbol name.
    pub fn plugin_registrar(&self) -> Option<(Path, String)> {
        if self.target_only {
            // Need to abort before syntax expansion.
            let message = format!("plugin crate `{}` is not available for triple `{}` \
                                   (only found {})",
                                  self.info.ident,
                                  config::host_triple(),
                                  self.sess.opts.target_triple);
            self.sess.span_err(self.vi_span, &message[]);
            self.sess.abort_if_errors();
        }

        let registrar = decoder::get_plugin_registrar_fn(self.metadata.as_slice())
            .map(|id| decoder::get_symbol(self.metadata.as_slice(), id));

        match (self.dylib.as_ref(), registrar) {
            (Some(dylib), Some(reg)) => Some((dylib.clone(), reg)),
            (None, Some(_)) => {
                let message = format!("plugin crate `{}` only found in rlib format, \
                                       but must be available in dylib format",
                                       self.info.ident);
                self.sess.span_err(self.vi_span, &message[]);
                // No need to abort because the loading code will just ignore this
                // empty dylib.
                None
            }
            _ => None,
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<foxml:digitalObject PID="$pid$" VERSION="1.1"
  xmlns:foxml="info:fedora/fedora-system:def/foxml#"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="info:fedora/fedora-system:def/foxml# http://www.fedora.info/definitions/1/0/foxml1-1.xsd">
  <foxml:objectProperties>
    <foxml:property NAME="info:fedora/fedora-system:def/model#state" VALUE="Active"/>
    <foxml:property NAME="info:fedora/fedora-system:def/model#label" VALUE="$label$"/>
    <foxml:property NAME="info:fedora/fedora-system:def/model#ownerId" VALUE="fedoraAdmin"/>
    <foxml:property NAME="info:fedora/fedora-system:def/model#createdDate" VALUE="2008-07-02T05:09:42.015Z"/>
    <foxml:property NAME="info:fedora/fedora-system:def/view#lastModifiedDate" VALUE="2008-07-02T05:09:42.015Z"/>
  </foxml:objectProperties>
  <foxml:datastream CONTROL_GROUP="X" ID="DC" STATE="A" VERSIONABLE="true">
    <foxml:datastreamVersion CREATED="2008-07-02T05:09:42.921Z"
      FORMAT_URI="http://www.openarchives.org/OAI/2.0/oai_dc/" ID="DC.1"
      LABEL="$label$" MIMETYPE="text/xml">
      <foxml:xmlContent>
        <oai_dc:dc xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/">
          <dc:title>$label$</dc:title>
          <dc:description>$label$</dc:description>
          <dc:identifier>$pid$</dc:identifier>
        </oai_dc:dc>
      </foxml:xmlContent>
    </foxml:datastreamVersion>
  </foxml:datastream>
  <foxml:datastream CONTROL_GROUP="X" ID="RELS-EXT" STATE="A" VERSIONABLE="true">
    <foxml:datastreamVersion CREATED="2008-07-02T05:09:42.921Z"
      FORMAT_URI="info:fedora/fedora-system:FedoraRELSExt-1.0" ID="RELS-EXT.0"
      LABEL="$label$" MIMETYPE="application/rdf+xml">
      <foxml:xmlContent>
        <rdf:RDF xmlns:fedora-model="info:fedora/fedora-system:def/model#"
          xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:rel="info:fedora/fedora-system:def/relations-external#">
          <rdf:Description rdf:about="info:fedora/$pid$">
            <fedora-model:hasModel rdf:resource="info:fedora/$cmodel_pid$"/>
          </rdf:Description>
        </rdf:RDF>
      </foxml:xmlContent>
    </foxml:datastreamVersion>
  </foxml:datastream>
  <foxml:datastream CONTROL_GROUP="E" ID="MEDIUM_SIZE" STATE="A" VERSIONABLE="true">
    <foxml:datastreamVersion CREATED="2008-07-02T05:09:42.921Z"
      ID="MediumSize.jpg.0" LABEL="$label$" MIMETYPE="image/jpeg">
      <foxml:contentLocation
        REF="http://local.fedora.server/fedora-demo/image-collection-demo/SmileyBeerGlass-MediumSize.jpg" TYPE="URL"/>
    </foxml:datastreamVersion>
  </foxml:datastream>
  <foxml:datastream CONTROL_GROUP="E" ID="FULL_SIZE" STATE="A" VERSIONABLE="true">
    <foxml:datastreamVersion CREATED="2008-07-02T05:09:42.921Z"
      ID="FullSize.jpg.0" LABEL="$label$" MIMETYPE="image/jpeg">
      <foxml:contentLocation
        REF="http://local.fedora.server/fedora-demo/image-collection-demo/SmileyBeerGlass-FullSize.jpg" TYPE="URL"/>
    </foxml:datastreamVersion>
  </foxml:datastream>
</foxml:digitalObject>


text:
<?php

class Comprobante extends CI_Model{

    function __construct(){
        parent::__construct();
    }

    public function guardar($descripcion,$estatus){
        $response = false;
        $data = array(
            'nombre_doc' => $descripcion,
            'estatus' => $estatus
        );
        if($this->db->insert('documentos_emitir', $data)){
            $response = true;
        }
        return $response;
    }

    public function actualizar($cve,$datosActualizar){
        $resultado  = false;
        if($cve != NULL && !(empty($datosActualizar))){
            $SQL = "UPDATE documentos_emitir SET ";
            foreach ($datosActualizar as $key => $value){
                $SQL .= $key." = '".$value."',";
            }
            $SQL = trim($SQL,",");
            $SQL .= " WHERE id_tipo_doc = '".$cve."'";
            if($this->db->query($SQL)){
                $resultado = true;
            }
        }
        return $resultado;
    }

    public function obtener_todos(){
        $this->db->select('id_tipo_doc, nombre_doc, estatus');
        $this->db->from('documentos_emitir');
        $this->db->order_by('id_tipo_doc', 'asc');
        $consulta = $this->db->get();
        $resultado = $consulta->result();
        return $resultado;
    }

    public function obtener_todos_activos(){
        $this->db->select('id_tipo_doc, nombre_doc, estatus');
        $this->db->from('documentos_emitir');
        $this->db->where('estatus', '1');
        $this->db->order_by('id_tipo_doc', 'asc');
        $consulta = $this->db->get();
        $resultado = $consulta->result();
        return $resultado;
    }

    public function obtener_por_id($id_tipo){
        $this->db->select('id_tipo_doc, nombre_doc, estatus');
        $this->db->from('documentos_emitir');
        $this->db->where('id_tipo_doc', $id_tipo);
        $consulta = $this->db->get();
        $resultado = $consulta->row();
        return $resultado;
    }

    public function eliminar($id_doc){
        $response = false;
        $this->db->where('id_tipo_doc', $id_doc);
        if($this->db->delete('documentos_emitir')){
            $response = true;
        }
        return $response;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisualInstance3D" inherits="Node3D" version="4.0">
	<brief_description>
		Parent of all visual 3D nodes.
	</brief_description>
	<description>
		The [VisualInstance3D] is used to connect a resource to a visual representation. All visual 3D nodes inherit from the [VisualInstance3D]. In general, you should not access the [VisualInstance3D] properties directly as they are accessed and managed by the nodes that inherit from [VisualInstance3D]. [VisualInstance3D] is the node representation of the [RenderingServer] instance.
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="get_aabb" qualifiers="const">
			<return type="AABB">
			</return>
			<description>
				Returns the [AABB] (also known as the bounding box) for this [VisualInstance3D]. See also [method get_transformed_aabb].
			</description>
		</method>
		<method name="get_base" qualifiers="const">
			<return type="RID">
			</return>
			<description>
				Returns the RID of the resource associated with this [VisualInstance3D]. For example, if the Node is a [MeshInstance3D], this will return the RID of the associated [Mesh].
			</description>
		</method>
		<method name="get_instance" qualifiers="const">
			<return type="RID">
			</return>
			<description>
				Returns the RID of this instance. This RID is the same as the RID returned by [method RenderingServer.instance_create]. This RID is needed if you want to call [RenderingServer] functions directly on this [VisualInstance3D].
			</description>
		</method>
		<method name="get_layer_mask_bit" qualifiers="const">
			<return type="bool">
			</return>
			<argument index="0" name="layer" type="int">
			</argument>
			<description>
				Returns [code]true[/code] when the specified layer is enabled in [member layers] and [code]false[/code] otherwise.
			</description>
		</method>
		<method name="get_transformed_aabb" qualifiers="const">
			<return type="AABB">
			</return>
			<description>
				Returns the transformed [AABB] (also known as the bounding box) for this [VisualInstance3D].
				Transformed in this case means the [AABB] plus the position, rotation, and scale of the [Node3D]'s [Transform]. See also [method get_aabb].
			</description>
		</method>
		<method name="set_base">
			<return type="void">
			</return>
			<argument index="0" name="base" type="RID">
			</argument>
			<description>
				Sets the resource that is instantiated by this [VisualInstance3D], which changes how the engine handles the [VisualInstance3D] under the hood. Equivalent to [method RenderingServer.instance_set_base].
			</description>
		</method>
		<method name="set_layer_mask_bit">
			<return type="void">
			</return>
			<argument index="0" name="layer" type="int">
			</argument>
			<argument index="1" name="enabled" type="bool">
			</argument>
			<description>
				Enables a particular layer in [member layers].
			</description>
		</method>
	</methods>
	<members>
		<member name="layers" type="int" setter="set_layer_mask" getter="get_layer_mask" default="1">
			The render layer(s) this [VisualInstance3D] is drawn on.
			This object will only be visible for [Camera3D]s whose cull mask includes the render object this [VisualInstance3D] is set to.
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
using System;
using System.Collections.Generic;
using System.Threading;
using GitHub.Models;
using GitHub.Services;
using GitHub.StartPage;
using Microsoft.VisualStudio.Shell.CodeContainerManagement;
using NSubstitute;
using NUnit.Framework;
using Task = System.Threading.Tasks.Task;
using ServiceProgressData = Microsoft.VisualStudio.Shell.ServiceProgressData;

public class GitHubContainerProviderTests
{
    public class TheAcquireCodeContainerAsyncMethod
    {
        [Test]
        public async Task CloneOrOpenRepository_CloneDialogResult_Returned_By_ShowCloneDialog()
        {
            var downloadProgress = Substitute.For<IProgress<ServiceProgressData>>();
            var cancellationToken = CancellationToken.None;
            var dialogService = Substitute.For<IDialogService>();
            var result = new CloneDialogResult(@"x:\repo", "https://github.com/owner/repo");
            dialogService.ShowCloneDialog(null).ReturnsForAnyArgs(result);
            var cloneService = Substitute.For<IRepositoryCloneService>();
            var target = CreateGitHubContainerProvider(dialogService: dialogService, cloneService: cloneService);

            await target.AcquireCodeContainerAsync(downloadProgress, cancellationToken);

            await cloneService.Received(1).CloneOrOpenRepository(result, downloadProgress, cancellationToken);
        }

        [Test]
        public async Task Pass_DisplayUrl_To_ShowCloneDialog()
        {
            var displayUrl = "https://github.com/owner/displayUrl";
            var browseOnlineUrl = "https://github.com/owner/browseOnlineUrl";
            var remoteCodeContainer = new RemoteCodeContainer("Name", Guid.NewGuid(), new Uri(displayUrl), new Uri(browseOnlineUrl),
                DateTimeOffset.Now, new Dictionary<string, string>());
            var downloadProgress = Substitute.For<IProgress<ServiceProgressData>>();
            var cancellationToken = CancellationToken.None;
            var dialogService = Substitute.For<IDialogService>();
            var result = new CloneDialogResult(@"x:\repo", "https://github.com/owner/repo");
            dialogService.ShowCloneDialog(null).ReturnsForAnyArgs(result);
            var cloneService = Substitute.For<IRepositoryCloneService>();
            var target = CreateGitHubContainerProvider(dialogService: dialogService, cloneService: cloneService);

            await target.AcquireCodeContainerAsync(remoteCodeContainer, downloadProgress, cancellationToken);

            await dialogService.Received(1).ShowCloneDialog(Arg.Any<IConnection>(), displayUrl);
        }

        [Test]
        public async Task Completes_When_Returning_CodeContainer()
        {
            var downloadProgress = Substitute.For<IProgress<ServiceProgressData>>();
            var cancellationToken = CancellationToken.None;
            var dialogService = Substitute.For<IDialogService>();
            var result = new CloneDialogResult(@"x:\repo", "https://github.com/owner/repo");
            dialogService.ShowCloneDialog(null).ReturnsForAnyArgs(result);
            var cloneService = Substitute.For<IRepositoryCloneService>();
            var target = CreateGitHubContainerProvider(dialogService: dialogService, cloneService: cloneService);

            var codeContainer = await target.AcquireCodeContainerAsync(downloadProgress, cancellationToken);

            Assert.That(codeContainer, Is.Not.Null);
            downloadProgress.Received(1).Report(
                Arg.Is<ServiceProgressData>(x => x.TotalSteps > 0 && x.CurrentStep == x.TotalSteps));
        }

        [Test]
        public async Task Does_Not_Complete_When_CloneDialog_Canceled()
        {
            var downloadProgress = Substitute.For<IProgress<ServiceProgressData>>();
            var cancellationToken = CancellationToken.None;
            var dialogService = Substitute.For<IDialogService>();
            var result = (CloneDialogResult)null;
            dialogService.ShowCloneDialog(null).ReturnsForAnyArgs(result);
            var cloneService = Substitute.For<IRepositoryCloneService>();
            var target = CreateGitHubContainerProvider(dialogService: dialogService, cloneService: cloneService);

            var codeContainer = await target.AcquireCodeContainerAsync(downloadProgress, cancellationToken);

            await cloneService.ReceivedWithAnyArgs(0).CloneOrOpenRepository(null, null, null);
            downloadProgress.ReceivedWithAnyArgs(0).Report(null);
            Assert.That(codeContainer, Is.Null);
        }

        static GitHubContainerProvider CreateGitHubContainerProvider(IDialogService dialogService = null,
            IRepositoryCloneService cloneService = null, IUsageTracker usageTracker = null)
        {
            dialogService = dialogService ?? Substitute.For<IDialogService>();
            cloneService = cloneService ?? Substitute.For<IRepositoryCloneService>();
            usageTracker = usageTracker ?? Substitute.For<IUsageTracker>();

            var sp = Substitute.For<IGitHubServiceProvider>();
            sp.GetService<IDialogService>().Returns(dialogService);
            sp.GetService<IRepositoryCloneService>().Returns(cloneService);
            sp.GetService<IUsageTracker>().Returns(usageTracker);

            var gitHubServiceProvider = new Lazy<IGitHubServiceProvider>(() => sp);
            return new GitHubContainerProvider(gitHubServiceProvider);
        }
    }
}