text:
// This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT

use Adjustment;
use ScrollablePolicy;
use ffi;
use glib::object::IsA;
use glib::translate::*;

glib_wrapper! {
    pub struct Scrollable(Object<ffi::GtkScrollable>);

    match fn {
        get_type => || ffi::gtk_scrollable_get_type(),
    }
}

pub trait ScrollableExt {
    //#[cfg(feature = "v3_16")]
    //fn get_border(&self, border: /*Ignored*/Border) -> bool;

    fn get_hadjustment(&self) -> Option<Adjustment>;

    fn get_hscroll_policy(&self) -> ScrollablePolicy;

    fn get_vadjustment(&self) -> Option<Adjustment>;

    fn get_vscroll_policy(&self) -> ScrollablePolicy;

    fn set_hadjustment(&self, hadjustment: Option<&Adjustment>);

    fn set_hscroll_policy(&self, policy: ScrollablePolicy);

    fn set_vadjustment(&self, vadjustment: Option<&Adjustment>);

    fn set_vscroll_policy(&self, policy: ScrollablePolicy);
}

impl<O: IsA<Scrollable>> ScrollableExt for O {
    //#[cfg(feature = "v3_16")]
    //fn get_border(&self, border: /*Ignored*/Border) -> bool {
    //    unsafe { TODO: call ffi::gtk_scrollable_get_border() }
    //}

    fn get_hadjustment(&self) -> Option<Adjustment> {
        unsafe {
            from_glib_none(ffi::gtk_scrollable_get_hadjustment(self.to_glib_none().0))
        }
    }

    fn get_hscroll_policy(&self) -> ScrollablePolicy {
        unsafe {
            from_glib(ffi::gtk_scrollable_get_hscroll_policy(self.to_glib_none().0))
        }
    }

    fn get_vadjustment(&self) -> Option<Adjustment> {
        unsafe {
            from_glib_none(ffi::gtk_scrollable_get_vadjustment(self.to_glib_none().0))
        }
    }

    fn get_vscroll_policy(&self) -> ScrollablePolicy {
        unsafe {
            from_glib(ffi::gtk_scrollable_get_vscroll_policy(self.to_glib_none().0))
        }
    }

    fn set_hadjustment(&self, hadjustment: Option<&Adjustment>) {
        unsafe {
            ffi::gtk_scrollable_set_hadjustment(self.to_glib_none().0, hadjustment.to_glib_none().0);
        }
    }

    fn set_hscroll_policy(&self, policy: ScrollablePolicy) {
        unsafe {
            ffi::gtk_scrollable_set_hscroll_policy(self.to_glib_none().0, policy.to_glib());
        }
    }

    fn set_vadjustment(&self, vadjustment: Option<&Adjustment>) {
        unsafe {
            ffi::gtk_scrollable_set_vadjustment(self.to_glib_none().0, vadjustment.to_glib_none().0);
        }
    }

    fn set_vscroll_policy(&self, policy: ScrollablePolicy) {
        unsafe {
            ffi::gtk_scrollable_set_vscroll_policy(self.to_glib_none().0, policy.to_glib());
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using DiscUtils.Streams;

namespace DiscUtils.Vhd
{
    /// <summary>
    /// Provides read access to detailed information about a VHD file.
    /// </summary>
    public class DiskImageFileInfo
    {
        private readonly Footer _footer;
        private readonly DynamicHeader _header;
        private readonly Stream _vhdStream;

        internal DiskImageFileInfo(Footer footer, DynamicHeader header, Stream vhdStream)
        {
            _footer = footer;
            _header = header;
            _vhdStream = vhdStream;
        }

        /// <summary>
        /// Gets the cookie indicating this is a VHD file (should be "conectix").
        /// </summary>
        public string Cookie
        {
            get { return _footer.Cookie; }
        }

        /// <summary>
        /// Gets the time the file was created (note: this is not the modification time).
        /// </summary>
        public DateTime CreationTimestamp
        {
            get { return _footer.Timestamp; }
        }

        /// <summary>
        /// Gets the application used to create the file.
        /// </summary>
        public string CreatorApp
        {
            get { return _footer.CreatorApp; }
        }

        /// <summary>
        /// Gets the host operating system of the application used to create the file.
        /// </summary>
        public string CreatorHostOS
        {
            get { return _footer.CreatorHostOS; }
        }

        /// <summary>
        /// Gets the version of the application used to create the file, packed as an integer.
        /// </summary>
        public int CreatorVersion
        {
            get { return (int)_footer.CreatorVersion; }
        }

        /// <summary>
        /// Gets the current size of the disk (in bytes).
        /// </summary>
        public long CurrentSize
        {
            get { return _footer.CurrentSize; }
        }

        /// <summary>
        /// Gets the type of the disk.
        /// </summary>
        public FileType DiskType
        {
            get { return _footer.DiskType; }
        }

        /// <summary>
        /// Gets the number of sparse blocks the file is divided into.
        /// </summary>
        public long DynamicBlockCount
        {
            get { return _header.MaxTableEntries; }
        }

        /// <summary>
        /// Gets the size of a sparse allocation block, in bytes.
        /// </summary>
        public long DynamicBlockSize
        {
            get { return _header.BlockSize; }
        }

        /// <summary>
        /// Gets the checksum value of the dynamic header structure.
        /// </summary>
        public int DynamicChecksum
        {
            get { return (int)_header.Checksum; }
        }

        /// <summary>
        /// Gets the cookie indicating a dynamic disk header (should be "cxsparse").
        /// </summary>
        public string DynamicCookie
        {
            get { return _header.Cookie; }
        }

        /// <summary>
        /// Gets the version of the dynamic header structure, packed as an integer.
        /// </summary>
        public int DynamicHeaderVersion
        {
            get { return (int)_header.HeaderVersion; }
        }

        /// <summary>
        /// Gets the stored paths to the parent file (for differencing disks).
        /// </summary>
        public IEnumerable<string> DynamicParentLocators
        {
            get
            {
                List<string> vals = new List<string>(8);
                foreach (ParentLocator pl in _header.ParentLocators)
                {
                    if (pl.PlatformCode == ParentLocator.PlatformCodeWindowsAbsoluteUnicode
                        || pl.PlatformCode == ParentLocator.PlatformCodeWindowsRelativeUnicode)
                    {
                        _vhdStream.Position = pl.PlatformDataOffset;
                        byte[] buffer = StreamUtilities.ReadExact(_vhdStream, pl.PlatformDataLength);
                        vals.Add(Encoding.Unicode.GetString(buffer));
                    }
                }

                return vals;
            }
        }

        /// <summary>
        /// Gets the modification timestamp of the parent file (for differencing disks).
        /// </summary>
        public DateTime DynamicParentTimestamp
        {
            get { return _header.ParentTimestamp; }
        }

        /// <summary>
        /// Gets the unicode name of the parent file (for differencing disks).
        /// </summary>
        public string DynamicParentUnicodeName
        {
            get { return _header.ParentUnicodeName; }
        }

        /// <summary>
        /// Gets the unique id of the parent file (for differencing disks).
        /// </summary>
        public Guid DynamicParentUniqueId
        {
            get { return _header.ParentUniqueId; }
        }

        /// <summary>
        /// Gets the Features bit field.
        /// </summary>
        public int Features
        {
            get { return (int)_footer.Features; }
        }

        /// <summary>
        /// Gets the file format version packed as an integer.
        /// </summary>
        public int FileFormatVersion
        {
            get { return (int)_footer.FileFormatVersion; }
        }

        /// <summary>
        /// Gets the checksum of the file's 'footer'.
        /// </summary>
        public int FooterChecksum
        {
            get { return (int)_footer.Checksum; }
        }

        /// <summary>
        /// Gets the geometry of the disk.
        /// </summary>
        public Geometry Geometry
        {
            get { return _footer.Geometry; }
        }

        /// <summary>
        /// Gets the original size of the disk (in bytes).
        /// </summary>
        public long OriginalSize
        {
            get { return _footer.OriginalSize; }
        }

        /// <summary>
        /// Gets a flag indicating if the disk has associated saved VM memory state.
        /// </summary>
        public byte SavedState
        {
            get { return _footer.SavedState; }
        }

        /// <summary>
        /// Gets the unique identity of this disk.
        /// </summary>
        public Guid UniqueId
        {
            get { return _footer.UniqueId; }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<component name="libraryTable">
  <library name="AnimatedCircleLoadingView-1.1.4">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.jlmd/AnimatedCircleLoadingView/1.1.4/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.github.jlmd/AnimatedCircleLoadingView/1.1.4/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/com.github.jlmd/AnimatedCircleLoadingView/1.1.4/fd8d18f38e26e3e6b0efc995d700ae9edb16f198/AnimatedCircleLoadingView-1.1.4-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
##### Atividade
# Como a Internet Funciona
Atividade de Inquérito

### Princípios de Ciências da Computação: Objetivos de Aprendizagem:

- [LO 6.1.1] Explique as abstrações na Internet e como a Internet funciona. [P3]
- [LO 6.2.1]Explique as características da Internet e os sistemas construídos nela. [P5]
- [LO 6.2.2] Explique como as características da Internet influenciam os sistemas construídos sobre ela. [P4]

## Como a Internet Funciona?

Comece dando aos alunos de 3 a 5 minutos para escrever como eles acham que a internet funciona. Peça a dois ou três alunos que compartilhem seus pensamentos. Por enquanto, não se concentre em informar se eles estão certos ou errados. Em vez disso, permita que eles simplesmente compartilhem suas diferentes opiniões com a turma.

## Endereço do Protocolo da Internet (IP)

Pergunte aos alunos que já ouviram falar de um endereço IP antes. Sinta-se à vontade para permitir que os alunos discutam rapidamente o que eles acham que é um endereço IP. Compartilhe a seguinte definição escrevendo-a no quadro ou projetando um slide:

Um endereço IP (Internet Protocol) é um endereço de identificação exclusivo para cada dispositivo na Internet.

Peça aos alunos que pensem em algumas analogias com um endereço IP. As respostas apropriadas incluiriam um endereço para correspondência, um número de telefone, um número do seguro social e um endereço de e-mail.

Peça aos alunos que usem um dispositivo (computador, tablet ou smartphone) e visitem o site https://whatismyipaddress.com/. Peça a alguns alunos que compartilhem seus endereços IP com a turma. Observe que cada endereço IP tem o mesmo formato, #. #. #. #., Em que cada # é um número no intervalo de 0 a 255.

Além disso, muitos alunos da turma podem ter endereços IP semelhantes, principalmente no primeiro semestre. Se este for o caso, pergunte aos alunos por que eles acham que é assim. Levar a discussão para o esquema de nomenclatura de endereços IP. A parte inicial do endereço IP identifica a rede à qual o dispositivo está conectado. A parte final do endereço identifica o dispositivo real. Essa hierarquia é o que permite que sites como https://whatismyipaddress.com/ identifiquem onde um dispositivo é de seu endereço IP.

Com base no formato dos endereços IP, pergunte à classe quantos endereços IP possíveis existem. Eles devem descobrir que existem mais de 4 bilhões de endereços possíveis (calculando 256 * 256 * 256 * 256 ou 256 ^ 4). Pergunte aos alunos se eles acham que esses endereços são suficientes para acomodar o dispositivo de todos no mundo.

Na verdade, devido à ascensão de dispositivos móveis e ao número de endereços IP reservados para determinadas organizações, há uma escassez de endereços IP. Para acomodar isso, um novo protocolo, chamado IPv6, foi estabelecido para lidar com muito mais dispositivos.

Endereços IP são atribuídos a dispositivos pelo Protocolo de Configuração Dinâmica de Hosts (DHCP). O servidor DHCP mantém um conjunto de endereços IP que ele atribui aos dispositivos por um período de tempo limitado. Cada dispositivo na rede recebe seu próprio endereço IP. Quando um endereço IP não está sendo usado, ele é colocado de volta no pool para ser alocado novamente.

Uma analogia para a atribuição de endereços IP por DHCP é obter números na fila em uma lanchonete. Cada cliente obtém seu próprio número e, embora seja possível obter o mesmo número repetidamente, não é garantido.

## Servidores de Nome de Domínio (DNS)

Um componente adicional da Internet é o Servidor de Nomes de Domínio (DNS). Um DNS traduz os URLs de sites, ou nomes de domínio, para endereços IP. O DNS é necessário porque os dispositivos acessam sites com base em endereços IP, mas os humanos os acessam por meio de nomes de domínio.

Uma analogia para o DNS é um catálogo telefônico. A maioria das pessoas não memoriza os números de telefone um do outro, mas pode procurar o nome de uma pessoa para obter o seu número de telefone. Isso é semelhante a digitar um URL, que é então traduzido para um endereço IP para o qual o dispositivo pode navegar.

Diga aos alunos para navegar para uma página da Web comum, como www.nytimes.com. Peça-lhes para clicar em vários links no site e anote o URL após cada clique. Pergunte aos alunos o que eles notam sobre os URLs. Eles devem ver que todos os URLs começam com nytimes.com. Isso é chamado de nome de domínio.

Os nomes de domínio fazem parte da hierarquia de nomes do DNS. Um nível de hierarquia inclui os sufixos, como .com, .edu e .org. Outro nível inclui o nome do site, como facebook, nytimes e codecombat. Os períodos separam cada parte do nome, permitindo que o DNS execute a pesquisa e navegue até o site correto.

## Transmissão de Dados

A Internet move informações computadorizadas de um lugar para outro. Uma analogia para a Internet é o serviço postal dos Estados Unidos. A informação é passada entre os dispositivos, sem considerar o que é a informação ou por que ela está sendo enviada. Por causa dos protocolos e servidores padrão, a Internet pode ser usada para transmitir muitos tipos diferentes de informações. Além disso, podem ser criados aplicativos que simplesmente precisam se comunicar com a Internet para serem executados na rede.

A informação é transmitida na Internet via comutação de pacotes. Em vez de enviar informações de uma só vez, as informações são divididas em partes menores, chamadas de pacotes. Cada pacote é então enviado separadamente para o destino, onde todos são remontados. Como isso é feito é padronizado com o protocolo de controle de transmissão, ou TCP.

No final da lição, peça aos alunos que escrevam como a Internet funciona de uma maneira que as crianças possam entender. Instrua-os a explicar as abstrações da Internet em sua escrita. Eles podem revisitar sua escrita desde o início da aula e comparar seus pensamentos no início da aula com a realidade de como a Internet funciona.

### Questões de Discussões:
- Quais problemas podem surgir se dois dispositivos receberem o mesmo endereço IP em uma rede?
- O que você acha que acontecerá quando ficarmos sem endereços IP válidos?
- Por que precisamos de DHCP?
- Por que precisamos de DNS?
- Por que os endereços IP e os nomes de domínio são hierárquicos?
- Por que você acha que a comutação de pacotes é útil?
- Quais conexões existem entre as abstrações da Internet e as abstrações na programação?
- Compare e contraste a compressão de dados e a comutação de pacotes.
- Descrever como a comutação de pacotes pode ajudar a manter os dados mais seguros.

### Questões de Avaliação:
- Defina a internet [EK 6.1.1A]
- Como um dispositivo conectado à Internet é identificado por outro dispositivo? [EK 6.1.1E, EK 6.1.1G]
- Como os nomes de domínio e os endereços IP são organizados?? [EK 6.2.1B, EK 6.2.1C]
- O que torna a internet tolerante a falhas? [EK 6.2.2B]
- Quais são alguns protocolos que sustentam a internet? [EK 6.1.1E, EK 6.2.2G]


text:
package com.sao.spring.learning.hibernate.domain;

/**
 * Created by saopr on 7/15/2017.
 */
public class Trader {
}


text:
@implementation ViewController {
	IBOutlet NSManagedObjectContext *_managedObjectContext;
	GFFetchedResultsController *_fetchedResultsController;
}

- (void)viewDidLoad
{
	[super viewDidLoad];

	NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DemoModel" withExtension:@"momd"];
	NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

	NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption: @YES,
							  NSInferMappingModelAutomaticallyOption: @YES};

	NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
	NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"fetched_demo.storedata"]];
	NSError *error;
	[psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:options error:&error];

	_managedObjectContext.persistentStoreCoordinator = psc;

	NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"DemoObject"];
	_fetchedResultsController = [[GFFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext];

	NSError *fetchError;
	if (![_fetchedResultsController performFetch:&fetchError]) {
		NSLog(@"%@", fetchError);
	}
}

- (void)setRepresentedObject:(id)representedObject {
	[super setRepresentedObject:representedObject];

	// Update the view, if already loaded.
}

@end


text:
layout: default
title: Getting started
slug: getting-started
lead: "An overview of Jasny Bootstrap, how to download and use, basic templates and examples, and more."
base_url: "../"
---

Jasny Bootstrap

Jasny Bootstrap is an extension to vanilla Bootstrap, adding a number of features and components.

The aim of Jasny Bootstrap is to provide all the required features for building highly interactive web applications for desktop and mobile.

Delivered as extension only

As of version 3.1.0 Jasny Bootstrap is no longer bundled with vanilla Bootstrap. You should load vanilla Bootstrap's CSS before this extension.

Download

Jasny Bootstrap has a few easy ways to quickly get started, each one appealing to a different skill level and use case. Read through to see what suits your particular needs.

Compiled CSS and JS

The fastest way to get Jasny Bootstrap is to download the compiled and minified versions of our CSS and JavaScript. No documentation or original source files are included.

Download Jasny Bootstrap

Additional downloads

        Download source code

Get the latest Jasny Bootstrap LESS and JavaScript source code by downloading it directly from GitHub.

        Clone or fork via GitHub

Visit us on GitHub to clone or fork the Jasny Bootstrap project.

Jasny Bootstrap @ cdnjs

CDNJS is a community driven CDN hosted by CloudFlare, supporting over a hundred projects. To use this CDN, swap your local instances for the CDN links listed below.

{% highlight html %}

<link rel="stylesheet" href="{{ site.cdn.css }}">

{% endhighlight %}

Compiling Jasny Bootstrap's LESS files

If you work with Jasny Bootstrap's uncompiled source code, you need to compile the LESS files to produce usable CSS files. For compiling LESS files into CSS, we only officially support Recess, which is Twitter's CSS hinter based on less.js.

What's included

Within the download you'll find the following directories and files, logically grouping common resources and providing both compiled and minified variations.

Once downloaded, unzip the compressed folder to see the structure of (the compiled) Jasny Bootstrap. You'll see something like this:

{% highlight bash %}
jasny-bootstrap/
├── css/
│   ├── jasny-bootstrap.css
│   ├── jasny-bootstrap.min.css
└── js/
    ├── jasny-bootstrap.js
    └── jasny-bootstrap.min.js

{% endhighlight %}

This is the most basic form of Jasny Bootstrap. We provide compiled CSS and JS (jasny-bootstrap.*), as well as compiled and minified CSS and JS (jasny-bootstrap.min.*).

The jasny-bootstrap.* files should be loaded in conjunction with the original vanilla Bootstrap files.

jQuery required

Please note that all JavaScript plugins require jQuery to be included, as shown in the starter template.

Basic template

Start with this basic HTML template, or modify these examples. We hope you'll customize our templates and examples, adapting them to suit your needs.

Copy the HTML below to begin working with a minimal Bootstrap document.

{% highlight html %}
<!DOCTYPE html>

    <title>Bootstrap 101 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="css/jasny-bootstrap.min.css" rel="stylesheet" media="screen">

Hello, world!

{% endhighlight %}

Plugins

Individual or compiled

Plugins can be included individually (using Jasny Bootstrap's individual *.js files), or all at once (using jasny-bootstrap.js or the minified jasny-bootstrap.min.js).

The Jasny Bootstrap plugins work with or without loading vanilla Bootstrap's bootstrap.js.

Do not attempt to include both.

Both jasny-bootstrap.js and jasny-bootstrap.min.js contain all plugins in a single file.

Data attributes

You can use all Jasny Bootstrap plugins purely through the markup API without writing a single line of JavaScript. This is Bootstrap's first-class API and should be your first consideration when using a plugin.

That said, in some situations it may be desirable to turn this functionality off. Therefore, we also provide the ability to disable the data attribute API by unbinding all events on the document namespaced with data-api. This looks like this:
{% highlight js %}
$(document).off('.data-api')
{% endhighlight %}

Alternatively, to target a specific plugin, just include the plugin's name as a namespace along with the data-api namespace like this:

{% highlight js %}
$(document).off('.alert.data-api')
{% endhighlight %}

Programmatic API

We also believe you should be able to use all Bootstrap plugins purely through the JavaScript API. All public APIs are single, chainable methods, and return the collection acted upon.

{% highlight js %}
$(".fileinput").fileinput().addClass("fat")
{% endhighlight %}

All methods should accept an optional options object, a string which targets a particular method, or nothing (which initiates a plugin with default behavior):

{% highlight js %}
$("#myMenu").offcanvas()                      // initialized with defaults
$("#myMenu").offcanvas({ autohide: false })   // initialized with no autohide
$("#myMenu").offcanvas('show')                // initializes and invokes show immediately

{% endhighlight %}

Each plugin also exposes its raw constructor on a Constructor property: $.fn.popover.Offcanvas. If you'd like to get a particular plugin instance, retrieve it directly from an element: $('.navmenu').data('offcanvas').

No conflict

Sometimes it is necessary to use Bootstrap plugins with other UI frameworks. In these circumstances, namespace collisions can occasionally occur. If this happens, you may call .noConflict on the plugin you wish to revert the value of.

{% highlight js %}
var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton            // give $().bootstrapBtn the Bootstrap functionality
{% endhighlight %}

Events

Bootstrap provides custom events for most plugin's unique actions. Generally, these come in an infinitive and past participle form - where the infinitive (ex. show) is triggered at the start of an event, and its past participle form (ex. shown) is trigger on the completion of an action.

As of 3.1.2, all Bootstrap events are namespaced.

All infinitive events provide preventDefault functionality. This provides the ability to stop the execution of an action before it starts.

{% highlight js %}
$('#myMenu').on('show.bs.offcanvas', function (e) {
  if (!data) return e.preventDefault() // stops menu from being shown
})
{% endhighlight %}

Containers

Added .container-smooth a container to use the same max-width for all viewport sizes. This means that the container size won't jump at media query breakpoints.

Examples

Create diverse and advanced user interfaces using Jasny's Bootstrap components.

Starter template

Nothing but the basics: compiled CSS and JavaScript along with a container.

Navmenu

A basic template showing the navmenu element and demonstrates usage of the offcanvas plugin.

Off Canvas Push Menu

A template demonstrating a push effect for the off canvas navmenu.

Off Canvas Reveal Menu

A template demonstrating a reveal effect by placing the navmenu under the content.

Off canvas navbar

A template using offcanvas for mobile view of the navbar.

Migrating from 3.x to 4.0

There are not many changes in this migration, as it mostly deals with moving to Bootstrap 4 support.

Major class changes

Bootsrtap 4 release introduced some new classes, so we also switched to using them. There're no other new classes in this version of Jasny Bootstrap.

Introduced .nav-item, .nav-link, .flex-column classes, that are used in nav-menu.

.navbar-fixed-top is changed to .fixed-top.

What's removed

Starting from this version Jasny Bootstrap is no longer published on Bower.

Inputmask plugin has been removed.

Removed variables customization page in documentation.

By default file icon is removed from file input, though it can be easily added. See Fielinput examples.

As Glyphicons were excluded from Bootstrap 4 bundle, icons now should be explicitly loaded to be used. For button labels we switched to Font Awasome icons. For them to work, you should include the link to them on the page, like the following: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Migrating from 2.x to 3.0

Folks looking to upgrade to v3 should use this section as a general upgrade guide. We've outlined some of the major changes and provided tables that highlight key changes.

Major class changes

This table shows the style changes between v2.x and v3.0.

            Bootstrap 2.x
            Bootstrap 3.0

            .container-semifluid
            .container-smooth

            .fileupload .fileupload-*
            .fileinput .fileinput-*

What's new

We've added new elements and changed some existing ones. Here are the new or updated styles.

            Element
            Description

            Navmenu
            .navmenu .navmenu-default .navmenu .navmenu-inverse .navmenu-fixed-left .navmenu-fixed-right .navmenu-brand .navmenu-nav

            Fixed alerts
            .alert-fixed-top .alert-fixed-bottom

            Off canvas
            .offcanvas .offcanvas-*

What's removed

The following elements have been dropped or changed in v3.0.

            Element
            Removed from 2.x
            3.0 Equivalent

            Header actions
            .header-actions
            N/A

            Table actions
            .table-actions
            N/A

            Desktop rows
            .row-desktop
            .row > .col-md-*

            Action links
            .act-*
            N/A

            Page alerts
            .pagealert
            .alert-fixed-top

            Iconic icons
            .iconic-*
            N/A

            Editor textarea
            .editor
            N/A

Additional notes

Other changes in v3.0 are not immediately apparent. Base classes, key styles, and behaviors have been adjusted for flexibility and our mobile first approach. Here's a partial list:

The fileupload plugin has been renamed to fileinput. File upload was poorly chosen, since the plugin allows the creation of a styled file input element. It has nothing to do with how the file is uploaded.

Tab alignments are still supported in this fork (while dropped in vanilla Bootstrap).

Typeahead has been dropped, in favor of using Selectize.js.

Iconic icons are still available from P.J. Onori.

For more information on upgrading to v3.0, and code snippets from the community, see Bootply.


text:
Puppet::Type.type(:aem_crx_package).provide :ruby, parent: Puppet::Provider do

  mk_resource_methods

  confine feature: :xmlsimple
  confine feature: :crx_packmgr_api_client

  def self.require_libs
    require 'crx_packmgr_api_client'
    require 'xmlsimple'
  end

  def initialize(resource = nil)
    super(resource)
    @aem_root = nil
    @property_flush = {}
  end

  def upload
    @property_flush[:ensure] = :present
    Puppet.debug('aem_crx_package::ruby - Upload requested.')
  end

  def install
    @property_flush[:ensure] = :installed
    Puppet.debug('aem_crx_package::ruby - Install requested.')
  end

  def remove
    @property_flush[:ensure] = :absent
    Puppet.debug('aem_crx_package::ruby - Remove requested.')
  end

  def purge
    @property_flush[:ensure] = :purged
    Puppet.debug('aem_crx_package::ruby - Purge requested.')
  end

  def retrieve
    check_aem
    self.class.require_libs
    find_package
    Puppet.debug("aem_crx_package::ruby - Retrieve - Property Hash: #{@property_hash}")
    @property_hash[:ensure]
  end

  def flush
    return unless @property_flush[:ensure]

    Puppet.debug('aem_crx_package::ruby - Flushing out to AEM.')
    self.class.require_libs
    case @property_flush[:ensure]
    when :purged
      if @property_hash[:ensure] == :installed
        result = uninstall_package
        raise_on_failure(result)
      end
      result = remove_package
    when :absent
      result = remove_package
    when :present
      result = @property_hash[:ensure] == :absent ? upload_package : uninstall_package
    when :installed
      result = @property_hash[:ensure] == :absent ? upload_package(true) : install_package
    else
      raise(Puppet::ResourceError, "Unknown property flush value: #{@property_flush[:ensure]}")
    end
    raise_on_failure(result)
    find_package
    @property_flush.clear
  end

  private

  def aem_root
    return @aem_root if @aem_root

    port = nil
    context_root = nil

    File.foreach(File.join(resource[:home], 'crx-quickstart', 'bin', 'start-env')) do |line|
      match = line.match(/^PORT=(\S+)/) || nil
      port = match.captures[0] if match

      match = line.match(/^CONTEXT_ROOT='(\S+)'/) || nil
      context_root = match.captures[0] if match
    end

    uri = "http://localhost:#{port}"
    uri = "#{uri}/#{context_root}" if context_root
    @aem_root = uri
    @aem_root
  end

  def build_cfg(port = nil, context_root = nil)
    config = CrxPackageManager::Configuration.new
    config.configure do |c|
      c.username = @resource[:username]
      c.password = @resource[:password]
      c.timeout = @resource[:timeout]
      c.host = "localhost:#{port}" if port
      c.base_path = "#{context_root}#{c.base_path}" if context_root
    end
    config
  end

  def build_client

    return @client if @client

    port = nil
    context_root = nil

    File.foreach(File.join(@resource[:home], 'crx-quickstart', 'bin', 'start-env')) do |line|
      match = line.match(/^PORT=(\S+)/) || nil
      port = match.captures[0] if match

      match = line.match(/^CONTEXT_ROOT='(\S+)'/) || nil
      context_root = match.captures[0] if match
    end

    config = build_cfg(port, context_root)

    @client = CrxPackageManager::DefaultApi.new(CrxPackageManager::ApiClient.new(config))
    @client
  end

  def check_aem
    uri = URI("#{aem_root}/system/console/bundles.json")
    http = Net::HTTP.new(uri.host, uri.port)
    http.set_debug_output($stdout) if Puppet[:debug]
    req = Net::HTTP::Get.new(uri.request_uri)
    req.basic_auth resource[:username], resource[:password]
    Timeout.timeout(@resource[:timeout]) do
      Kernel.loop do
        begin
          res = http.request(req)
          jsn = JSON.parse(res.body) if res.is_a?(Net::HTTPSuccess)

          # s is a status array -
          #   0 -> Total Bundles
          #   1 -> Running Bundles
          #   2 -> Running Fragments
          return true if jsn['s'][0] == jsn['s'][1] + jsn['s'][2]

          raise StopIteration
        rescue Net::HTTPServerError, Net::HTTPClientError, Net::HTTPFatalError, StopIteration
          Puppet.debug('Unable to determine AEM state, waiting for AEM to start...')
          sleep 10
        end
      end
    end
  end

  def find_package
    client = build_client

    path = "/etc/packages/#{@resource[:group]}/#{@resource[:pkg]}-.zip"
    begin
      retries ||= @resource[:retries]
      retry_timeout = @resource[:retry_timeout]
      data = client.list(path: path, include_versions: true)
    rescue CrxPackageManager::ApiError => e
      Puppet.info("Unable to find package for Aem_crx_package[#{@resource[:pkg]}]: #{e}")
      will_retry = (retries -= 1) >= 0
      if will_retry
        Puppet.debug("Waiting #{retry_timeout} seconds before retrying package lookup")
        sleep retry_timeout
        Puppet.debug("Retrying package lookup; remaining retries: #{retries}")
        retry
      end
      raise
    end

    found_pkg = find_version(data.results)
    Puppet.debug("aem_crx_package::ruby - Found package: #{found_pkg}")
    if found_pkg
      @property_hash[:pkg] = found_pkg.name
      @property_hash[:group] = found_pkg.group
      @property_hash[:version] = found_pkg.version
      @property_hash[:ensure] = found_pkg.last_unpacked ? :installed : :present
    else
      @property_hash[:ensure] = :absent
    end
  end

  def find_version(ary)
    found_pkg = nil
    ary&.each do |p|
      found_pkg = p if p.version == @resource[:version]
      break if found_pkg
    end
    found_pkg
  end

  def upload_package(install = false)
    client = build_client
    file = File.new(@resource[:source])
    client.service_post(file, install: install)
  end

  def install_package
    client = build_client
    client.service_exec('install', @resource[:pkg], @resource[:group], @resource[:version])
  end

  def uninstall_package
    client = build_client
    client.service_exec('uninstall', @resource[:pkg], @resource[:group], @resource[:version])
  end

  def remove_package
    client = build_client
    client.service_exec('delete', @resource[:pkg], @resource[:group], @resource[:version])
  end

  def raise_on_failure(api_response)
    if api_response.is_a?(CrxPackageManager::ServiceExecResponse)
      raise(api_response.msg) unless api_response.success
    else
      hash = XmlSimple.xml_in(api_response, ForceArray: false, KeyToSymbol: true, AttrToSymbol: true)
      response = CrxPackageManager::ServiceResponse.new
      response.build_from_hash(hash)
      raise(response.response.status[:content]) unless response.response.status[:code].to_i == 200
    end
  end
end


text:
/**
 * Module dependencies.
 */

var express = require('express');
var MongoStore = require('connect-mongo')(express);
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');

/**
 * Load controllers.
 */

var homeController = require('./controllers/home');
var userController = require('./controllers/user');

/**
 * API keys + Passport configuration.
 */

var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Create Express server.
 */

var app = express();

/**
 * Mongoose configuration.
 */

mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('✗ MongoDB Connection Error. Please make sure MongoDB is running.');
});

/**
 * Express configuration.
 */

var hour = 3600000;
var day = (hour * 24);
var week = (day * 7);
var month = (day * 30);

app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(require('connect-assets')({
  src: 'public',
  helperContext: app.locals
}));
app.use(express.compress());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(expressValidator());
app.use(express.methodOverride());
app.use(express.session({
  secret: secrets.sessionSecret,
  store: new MongoStore({
    db: mongoose.connection.db,
    auto_reconnect: true
  })
}));
app.use(express.csrf());
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
  res.locals.user = req.user;
  res.locals.token = req.csrfToken();
  res.locals.secrets = secrets;
  next();
});
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public'), { maxAge: week }));
app.use(function(req, res) {
  res.status(404);
  res.render('404');
});
app.use(express.errorHandler());

/**
 * Application routes.
 */

app.get('/', homeController.index);
app.get('/logout', userController.logout);

/**
 * OAuth routes for sign-in.
 */

app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'read_stream'] }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/login' }));

/**
 * Start Express server.
 */

app.listen(app.get('port'), function() {
  console.log("✔ Express server listening on port %d in %s mode", app.get('port'), app.settings.env);
});


text:
import React from 'react';
import PropTypes from 'prop-types';
import type { ClientOpts, ClientState, _ClientImpl } from './client';
declare type WrappedBoardDelegates = 'matchID' | 'playerID' | 'credentials';
export declare type WrappedBoardProps = Pick<ClientOpts, WrappedBoardDelegates | 'debug'>;
declare type ExposedClientProps<G extends any = any> = Pick<_ClientImpl<G>, 'log' | 'moves' | 'events' | 'reset' | 'undo' | 'redo' | 'playerID' | 'matchID' | 'matchData' | 'sendChatMessage'>;
export declare type BoardProps<G extends any = any> = ClientState<G> & Omit<WrappedBoardProps, keyof ExposedClientProps<G>> & ExposedClientProps<G> & {
    isMultiplayer: boolean;
};
declare type ReactClientOpts<G extends any = any, P extends BoardProps<G> = BoardProps<G>> = Omit<ClientOpts<G>, WrappedBoardDelegates> & {
    board?: React.ComponentType<P>;
    loading?: React.ComponentType;
};
/**
 * Client
 *
 * boardgame.io React client.
 *
 * @param {...object} game - The return value of `Game`.
 * @param {...object} numPlayers - The number of players.
 * @param {...object} board - The React component for the game.
 * @param {...object} loading - (optional) The React component for the loading state.
 * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
 * @param {...object} debug - Enables the Debug UI.
 * @param {...object} enhancer - Optional enhancer to send to the Redux store
 *
 * Returns:
 *   A React component that wraps board and provides an
 *   API through props for it to interact with the framework
 *   and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET,
 *   UNDO and REDO.
 */
export declare function Client<G extends any = any, P extends BoardProps<G> = BoardProps<G>>(opts: ReactClientOpts<G, P>): {
    new (props: Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>): {
        client: _ClientImpl<G>;
        unsubscribe?: () => void;
        componentDidMount(): void;
        componentWillUnmount(): void;
        componentDidUpdate(prevProps: Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>): void;
        render(): JSX.Element;
        context: any;
        setState<K extends never>(state: {} | ((prevState: Readonly<{}>, props: Readonly<Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>>) => {} | Pick<{}, K>) | Pick<{}, K>, callback?: () => void): void;
        forceUpdate(callback?: () => void): void;
        readonly props: Readonly<Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>> & Readonly<{
            children?: React.ReactNode;
        }>;
        state: Readonly<{}>;
        refs: {
            [key: string]: React.ReactInstance;
        };
        shouldComponentUpdate?(nextProps: Readonly<Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>>, nextState: Readonly<{}>, nextContext: any): boolean;
        componentDidCatch?(error: Error, errorInfo: React.ErrorInfo): void;
        getSnapshotBeforeUpdate?(prevProps: Readonly<Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>>, prevState: Readonly<{}>): any;
        componentWillMount?(): void;
        UNSAFE_componentWillMount?(): void;
        componentWillReceiveProps?(nextProps: Readonly<Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>>, nextContext: any): void;
        UNSAFE_componentWillReceiveProps?(nextProps: Readonly<Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>>, nextContext: any): void;
        componentWillUpdate?(nextProps: Readonly<Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>>, nextState: Readonly<{}>, nextContext: any): void;
        UNSAFE_componentWillUpdate?(nextProps: Readonly<Pick<ClientOpts<any, import("../types").Ctx>, "matchID" | "playerID" | "credentials" | "debug"> & Pick<P, Exclude<keyof P, "matchID" | "playerID" | "credentials" | "debug" | "log" | "moves" | "events" | "reset" | "undo" | "redo" | "matchData" | "sendChatMessage" | "plugins" | "deltalog" | "G" | "ctx" | "_undo" | "_redo" | "_stateID" | "isActive" | "isConnected" | "isMultiplayer">>>, nextState: Readonly<{}>, nextContext: any): void;
    };
    propTypes: {
        matchID: PropTypes.Requireable<string>;
        playerID: PropTypes.Requireable<string>;
        credentials: PropTypes.Requireable<string>;
        debug: PropTypes.Requireable<any>;
    };
    defaultProps: {
        matchID: string;
        playerID: any;
        credentials: any;
        debug: boolean;
    };
    contextType?: React.Context<any>;
};
export {};


text:
<?php

namespace Symfony\Component\Form\Extension\Core\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\ReversedTransformer;
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer;
use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer;
use Symfony\Component\Form\FormView;

class TimeType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilder $builder, array $options)
    {
        $parts  = array('hour', 'minute');
        $format = 'H:i:00';
        if ($options['with_seconds']) {
            $format  = 'H:i:s';
            $parts[] = 'second';
        }

        if ('single_text' === $options['widget']) {
            $builder->appendClientTransformer(new DateTimeToStringTransformer($options['data_timezone'], $options['user_timezone'], $format));
        } else {
            $hourOptions = $minuteOptions = $secondOptions = array();

            if ('choice' === $options['widget']) {
                if (is_array($options['empty_value'])) {
                    $options['empty_value'] = array_merge(array('hour' => null, 'minute' => null, 'second' => null), $options['empty_value']);
                } else {
                    $options['empty_value'] = array('hour' => $options['empty_value'], 'minute' => $options['empty_value'], 'second' => $options['empty_value']);
                }

                $hours = $minutes = array();

                foreach ($options['hours'] as $hour) {
                    $hours[$hour] = str_pad($hour, 2, '0', STR_PAD_LEFT);
                }
                foreach ($options['minutes'] as $minute) {
                    $minutes[$minute] = str_pad($minute, 2, '0', STR_PAD_LEFT);
                }

                // Only pass a subset of the options to children
                $hourOptions = array(
                    'choices' => $hours,
                    'value_strategy' => ChoiceList::COPY_CHOICE,
                    'index_strategy' => ChoiceList::COPY_CHOICE,
                    'empty_value' => $options['empty_value']['hour'],
                );
                $minuteOptions = array(
                    'choices' => $minutes,
                    'value_strategy' => ChoiceList::COPY_CHOICE,
                    'index_strategy' => ChoiceList::COPY_CHOICE,
                    'empty_value' => $options['empty_value']['minute'],
                );

                if ($options['with_seconds']) {
                    $seconds = array();

                    foreach ($options['seconds'] as $second) {
                        $seconds[$second] = str_pad($second, 2, '0', STR_PAD_LEFT);
                    }

                    $secondOptions = array(
                        'choices' => $seconds,
                        'value_strategy' => ChoiceList::COPY_CHOICE,
                        'index_strategy' => ChoiceList::COPY_CHOICE,
                        'empty_value' => $options['empty_value']['second'],
                    );
                }

                // Append generic carry-along options
                foreach (array('required', 'translation_domain') as $passOpt) {
                    $hourOptions[$passOpt] = $minuteOptions[$passOpt] = $options[$passOpt];
                    if ($options['with_seconds']) {
                        $secondOptions[$passOpt] = $options[$passOpt];
                    }
                }
            }

            $builder
                ->add('hour', $options['widget'], $hourOptions)
                ->add('minute', $options['widget'], $minuteOptions)
            ;

            if ($options['with_seconds']) {
                $builder->add('second', $options['widget'], $secondOptions);
            }

            $builder->appendClientTransformer(new DateTimeToArrayTransformer($options['data_timezone'], $options['user_timezone'], $parts, 'text' === $options['widget']));
        }

        if ('string' === $options['input']) {
            $builder->appendNormTransformer(new ReversedTransformer(
                new DateTimeToStringTransformer($options['data_timezone'], $options['data_timezone'], $format)
            ));
        } elseif ('timestamp' === $options['input']) {
            $builder->appendNormTransformer(new ReversedTransformer(
                new DateTimeToTimestampTransformer($options['data_timezone'], $options['data_timezone'])
            ));
        } elseif ('array' === $options['input']) {
            $builder->appendNormTransformer(new ReversedTransformer(
                new DateTimeToArrayTransformer($options['data_timezone'], $options['data_timezone'], $parts)
            ));
        }

        $builder
            ->setAttribute('widget', $options['widget'])
            ->setAttribute('with_seconds', $options['with_seconds'])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form)
    {
        $view
            ->set('widget', $form->getAttribute('widget'))
            ->set('with_seconds', $form->getAttribute('with_seconds'))
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getDefaultOptions(array $options)
    {
        return array(
            'hours'          => range(0, 23),
            'minutes'        => range(0, 59),
            'seconds'        => range(0, 59),
            'widget'         => 'choice',
            'input'          => 'datetime',
            'with_seconds'   => false,
            'data_timezone'  => null,
            'user_timezone'  => null,
            'empty_value'    => null,
            // Don't modify \DateTime classes by reference, we treat
            // them like immutable value objects
            'by_reference'   => false,
            'error_bubbling' => false,
            // If initialized with a \DateTime object, FieldType initializes
            // this option to "\DateTime". Since the internal, normalized
            // representation is not \DateTime, but an array, we need to unset
            // this option.
            'data_class'     => null,
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getAllowedOptionValues(array $options)
    {
        return array(
            'input' => array(
                'datetime',
                'string',
                'timestamp',
                'array',
            ),
            'widget' => array(
                'single_text',
                'text',
                'choice',
            ),
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getParent(array $options)
    {
        return isset($options['widget']) && 'single_text' === $options['widget'] ? 'field' : 'form';
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'time';
    }
}


text:
package griffon.core;

import static griffon.util.GriffonNameUtils.getClassNameForLowerCaseHyphenSeparatedName;

/**
 * Defines all the events triggered by the application.
 *
 * @author Andres Almiray
 * @since 2.0.0
 */
public enum ApplicationEvent {
    UNCAUGHT_EXCEPTION_THROWN,
    LOAD_ADDONS_START, LOAD_ADDONS_END, LOAD_ADDON_START, LOAD_ADDON_END,
    BOOTSTRAP_START, BOOTSTRAP_END,
    STARTUP_START, STARTUP_END,
    READY_START, READY_END,
    STOP_START, STOP_END,
    SHUTDOWN_REQUESTED, SHUTDOWN_ABORTED, SHUTDOWN_START,
    NEW_INSTANCE, DESTROY_INSTANCE,
    INITIALIZE_MVC_GROUP("InitializeMVCGroup"), CREATE_MVC_GROUP("CreateMVCGroup"), DESTROY_MVC_GROUP("DestroyMVCGroup"),
    WINDOW_SHOWN, WINDOW_HIDDEN;

    /**
     * Display friendly name
     */
    private final String name;

    ApplicationEvent() {
        String name = name().toLowerCase().replaceAll("_", "-");
        this.name = getClassNameForLowerCaseHyphenSeparatedName(name);
    }

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

    /**
     * Returns the capitalized String representation of this Event object.
     *
     * @return a capitalized String
     */
    public String getName() {
        return this.name;
    }
}


text:
package client

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"sync"
	"time"
)

type APIKey struct {
	CallPerDay    int    `json:"call_per_day"`
	CallPerSecond int    `json:"call_per_second"`
	Key           string `json:"key"`

	leftForDay    int
	leftForSecond int

	lock *sync.Mutex

	secondTicker *time.Ticker
	dayTicker    *time.Ticker
	die          chan interface{}
}

func LoadAPIKeysFromFile(filename string) ([]APIKey, error) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("couldn't read file, %v", err)
	}
	var keys []APIKey
	err = json.Unmarshal(data, &keys)
	if err != nil {
		return nil, fmt.Errorf("unmarshalling failed, %v, payload `%s`", err, string(data))
	}
	for i := range keys {
		keys[i].init()
	}
	return keys, nil
}

func (a *APIKey) init() {
	a.leftForDay = a.CallPerDay
	a.leftForSecond = a.CallPerSecond
	a.lock = new(sync.Mutex)
	a.die = make(chan interface{})

	perDay := time.Hour * time.Duration(a.CallPerDay) * 24
	perSecond := time.Second * time.Duration(a.CallPerSecond)

	a.dayTicker = time.NewTicker(perDay)
	a.secondTicker = time.NewTicker(perSecond)

	go func() {
		for {
			select {
			case <-a.dayTicker.C:
				a.replenishDay()
			case <-a.secondTicker.C:
				a.replenishSecond()
			case <-a.die:
				return
			}
		}
	}()
}

func BuildKey(key string, callPerDay, callPerSecond int) *APIKey {
	a := APIKey{
		Key:           key,
		CallPerDay:    callPerDay,
		CallPerSecond: callPerSecond,
	}
	a.init()

	return &a
}

func (a *APIKey) Use() (string, error) {
	a.lock.Lock()
	defer a.lock.Unlock()
	if a.leftForSecond <= 0 {
		return "", errors.New("throttled for second usage")
	}

	if a.leftForDay <= 0 {
		return "", errors.New("throttled for day usage")
	}

	a.leftForDay--
	a.leftForSecond--

	return a.Key, nil
}

func (a *APIKey) LeftForDay() int {
	return a.leftForDay
}

func (a *APIKey) LeftForSecond() int {
	return a.leftForSecond
}

func (a *APIKey) HasLeft() bool {
	return a.LeftForDay() > 0 && a.LeftForSecond() > 0
}

func (a *APIKey) replenishDay() {
	a.lock.Lock()
	defer a.lock.Unlock()
	a.leftForDay = a.CallPerDay
}

func (a *APIKey) replenishSecond() {
	a.lock.Lock()
	defer a.lock.Unlock()
	a.leftForSecond = a.CallPerSecond
}

func (a *APIKey) Close() {
	a.dayTicker.Stop()
	a.secondTicker.Stop()
	a.die <- true
}


text:
#import <OfficeImport/WXFont.h>

@interface WXFont (WXInternal)
+ (void)readFrom:(struct _xmlNode *)arg1 to:(id)arg2;
@end


text:
require 'spec_helper'

describe DescriptiveStatistics::CentralTendency do
  describe '#sum' do
    it 'returns the amount attained by adding all numbers in the array' do
      DescriptiveStatistics::Stats.new([1,2,6]).sum.should == 9
    end

    it 'allows a block to be passed' do
      DescriptiveStatistics::Stats.new([1,2,6]).sum{ |x| x * 2 }.should == 18
    end

    it 'returns 0 if empty' do
      DescriptiveStatistics::Stats.new([]).sum.should == 0
    end
  end

  describe '#mean' do
    it 'returns the sum of the values over the count of the values' do
      DescriptiveStatistics::Stats.new([1,2,6]).mean.should == 3
    end

    it 'returns nil if empty' do
      DescriptiveStatistics::Stats.new([]).mean.should be_nil
    end
  end

  describe '#median' do
    it 'returns the value lying at the midpoint of the array' do
      DescriptiveStatistics::Stats.new([1,2,6]).median.should == 2
    end

    it 'returns the mean of the two midpoint values if the array length is even' do
      DescriptiveStatistics::Stats.new([1,2,3,6]).median.should == 2.5
    end

    it 'returns nil if empty' do
      DescriptiveStatistics::Stats.new([]).median.should be_nil
    end
  end

  describe '#mode' do
    it 'returns the most frequent value' do
      DescriptiveStatistics::Stats.new([1,1,2,46]).mode.should == 1
    end

    it 'returns nil if there is no most frequent value' do
      DescriptiveStatistics::Stats.new([1,2,3]).mode.should be_nil
    end

    it 'returns the first value if there is only one' do
      DescriptiveStatistics::Stats.new([3.5]).mode.should == 3.5
    end

    it 'returns nil if empty' do
      DescriptiveStatistics::Stats.new([]).mode.should be_nil
    end
  end
end


text:
import { combineReducers } from 'redux';
import messages from './messages';

const reducers = combineReducers({
  messages: messages
});

export default reducers;


text:
/*--------------------------------------------------------------------------------------------------
 */

var fs   = require('fs'),
    path = require('path'),
    lc   = require('../leapclient').client,
    la   = require('../leapclient').apply;

var client_stories_text = fs.readFileSync(
		path.resolve(__dirname, "./../../../test/stories/", "./client_stories.js"), "utf8");

var stories = JSON.parse(client_stories_text).client_stories;

var run_story = function(story, test) {
	"use strict";

	var content = story.content;
	var socket = { readyState : 1 };

	socket.close = function() {};

	// First send response should be the same doc, emulating creation
	socket.send = function(data) {
		var obj = JSON.parse(data);
		obj.body.document.id = "testdocument";
		obj.body.document.content = story.content;
		obj.body.document.version = 1;
		obj.type = "subscribe";
		socket.onmessage({ data : JSON.stringify(obj) });
	};

	var client = new lc();
	client.connect("", socket);

	client.on("error", function(err) {
		test.ok(false, "client error: " + JSON.stringify(err));
	});

	client.subscribe("testdocument");

	for ( var i = 0, l = story.epochs.length; i < l; i++ ) {
		var epoch_sends = story.epochs[i].send;
		var epoch_receives = story.epochs[i].receive;

		client.clear_handlers("transforms");
		client.on("transforms", function(body) {
			var tforms = body.transforms;
			for ( var tn = 0, ln = tforms.length; tn < ln; tn++ ) {
				content = la(tforms[tn], content);
			}
			if ( epoch_sends.length > 0 ) {
				var tform = epoch_sends.shift();
				content = la(tform, content);
				var err = client.send_transform("testdocument", tform);
				test.ok(err === undefined, "story '" + story.name + "' epoch " + i + ": " + err);
			} else if ( epoch_receives.length > 0 ) {
				let next = epoch_receives.shift();
				next.body.document = {
					id: "testdocument"
				};
				socket.onmessage({ data : JSON.stringify(next) });
			}
		});

		socket.send = function() {
			if ( epoch_receives.length > 0 ) {
				let next = epoch_receives.shift();
				next.body.document = {
					id: "testdocument"
				};
				socket.onmessage({ data : JSON.stringify(next) });
			}
		};

		if ( epoch_sends.length > 0 ) {
			var tmp = epoch_sends.shift();
			content = la(tmp, content);
			var err = client.send_transform("testdocument", tmp);
			test.ok(err === undefined, "story '" + story.name + "' epoch " + i + ": " + err);
		} else if ( epoch_receives.length > 0 ) {
			let next = epoch_receives.shift();
			next.body.document = {
				id: "testdocument"
			};
			socket.onmessage({ data : JSON.stringify(next) });
		}

		while ( epoch_receives.length > 0 ) {
			let next = epoch_receives.shift();
			next.body.document = {
				id: "testdocument"
			};
			socket.onmessage({ data : JSON.stringify(next) });
		}

		test.ok(epoch_sends.length === 0,
				"story '" + story.name + "' epoch " + i + ": epoch_sends (" + epoch_sends.length + ") != 0");

		test.ok(content === story.epochs[i].result,
				"story '" + story.name + "' epoch " + i + ": " + content + " != " + story.epochs[i].result);
	}

	client.close();
	test.ok(content === story.result,
			"story " + story.name + ": " + content + " != " + story.result);
};

module.exports = function(test) {
	"use strict";

	test.ok(stories.length > 0, "no stories found");

	// All stories are actually synchronous
	for ( var i = 0, l = stories.length; i < l; i++ ) {
		run_story(stories[i], test);
	}
	test.ok(stories !== undefined, "test for stories");
	test.done();
};

/*--------------------------------------------------------------------------------------------------
 */


text:
<?php
/*
Template Name: Producto
*/
?>

<?php get_template_part('templates/page', 'header'); ?>
<?php get_template_part('templates/content', 'page-productos'); ?>


text:
package cz.metacentrum.perun.ldapc.processor.impl;

import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.ldapc.processor.EventDispatcher.MessageBeans;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ldap.NamingException;

public class DeletionEventProcessor extends AbstractEventProcessor {

	private final static Logger log = LoggerFactory.getLogger(DeletionEventProcessor.class);

	@Override
	public void processEvent(String msg, MessageBeans beans) {
		for (int beanFlag : beans.getPresentBeansFlags()) {
			try {
				switch (beanFlag) {
					case MessageBeans.GROUP_F:
						log.debug("Removing group {}", beans.getGroup());
						perunGroup.removeGroup(beans.getGroup());
						break;

					case MessageBeans.RESOURCE_F:
						log.debug("Removing resource {}", beans.getResource());
						perunResource.deleteResource(beans.getResource());
						break;

					case MessageBeans.FACILITY_F:
						// skip if it is actually resource deletion
						if (beans.getResource() != null) break;
						// was facility deletion - proceed
						log.debug("Removing facility {}", beans.getFacility());
						perunFacility.deleteFacility(beans.getFacility());
						break;

					case MessageBeans.USER_F:
						log.debug("Removing user {}", beans.getUser());
						perunUser.deleteUser(beans.getUser());
						break;

					case MessageBeans.VO_F:
						log.debug("Removing VO {}", beans.getVo());
						perunVO.deleteVo(beans.getVo());
						break;

					default:
						break;
				}
			} catch (NamingException | InternalErrorException e) {
				log.error("Error removing entry: {}", e.getMessage());
			}
		}
	}

}


text:
use std::{fmt::Write, fs, path::PathBuf};

use codec::common::{base64, tracing};
use stencila_schema::*;

use super::{
    attr, attr_and_meta, attr_and_meta_opt, attr_id, attr_itemprop, attr_itemtype,
    attr_itemtype_str, attr_prop, attr_slot, concat, elem, elem_empty, elem_meta, elem_placeholder,
    json, nothing, EncodeContext, ToHtml,
};

impl ToHtml for InlineContent {
    fn to_html(&self, context: &EncodeContext) -> String {
        match self {
            InlineContent::AudioObject(node) => node.to_html(context),
            InlineContent::Boolean(node) => node.to_html(context),
            InlineContent::Cite(node) => node.to_html(context),
            InlineContent::CiteGroup(node) => node.to_html(context),
            InlineContent::CodeExpression(node) => node.to_html(context),
            InlineContent::CodeFragment(node) => node.to_html(context),
            InlineContent::Date(node) => node.to_html(context),
            InlineContent::DateTime(node) => node.to_html(context),
            InlineContent::Delete(node) => node.to_html(context),
            InlineContent::Duration(node) => node.to_html(context),
            InlineContent::Emphasis(node) => node.to_html(context),
            InlineContent::ImageObject(node) => node.to_html(context),
            InlineContent::Integer(node) => node.to_html(context),
            InlineContent::Link(node) => node.to_html(context),
            InlineContent::MathFragment(node) => node.to_html(context),
            InlineContent::NontextualAnnotation(node) => node.to_html(context),
            InlineContent::Note(node) => node.to_html(context),
            InlineContent::Null(node) => node.to_html(context),
            InlineContent::Number(node) => node.to_html(context),
            InlineContent::Parameter(node) => node.to_html(context),
            InlineContent::Quote(node) => node.to_html(context),
            // Unlike everything else, `String` instances are not wrapped in an element.
            // However, `InlineContent::String` (and `Node::String` instances) should be
            // because they are usually part of a vector (e.g. `Paragraph.content`).
            // Wrapping them indicates to the DOM patching algorithm that the container element
            // represents a vector and not a placeholder for an optional string property.
            // To reduce the size of the generated HTML a little, unlike for `Node::String`,
            // the `itemtype` attribute is not used.
            InlineContent::String(node) => elem("span", &[], &node.to_html(context)),
            InlineContent::Strikeout(node) => node.to_html(context),
            InlineContent::Strong(node) => node.to_html(context),
            InlineContent::Subscript(node) => node.to_html(context),
            InlineContent::Superscript(node) => node.to_html(context),
            InlineContent::Time(node) => node.to_html(context),
            InlineContent::Timestamp(node) => node.to_html(context),
            InlineContent::Underline(node) => node.to_html(context),
            InlineContent::VideoObject(node) => node.to_html(context),
        }
    }
}

macro_rules! mark_to_html {
    ($type:ident, $tag:literal) => {
        impl ToHtml for $type {
            fn to_html(&self, context: &EncodeContext) -> String {
                elem(
                    $tag,
                    &[attr_itemtype::<Self>(), attr_id(&self.id)],
                    &self.content.to_html(context),
                )
            }
        }
    };
}

mark_to_html!(Emphasis, "em");
mark_to_html!(Strikeout, "del");
mark_to_html!(Delete, "del");
mark_to_html!(Strong, "strong");
mark_to_html!(Subscript, "sub");
mark_to_html!(Superscript, "sup");
mark_to_html!(Underline, "u");
mark_to_html!(NontextualAnnotation, "u");

/// Convert a file:// URL to a data:// URI
///
/// Note that this function assumes that paths are absolute.
/// File URLs are usually resolves elsewhere e.g. in the `compile` method
/// before encoding to HTML.
fn file_uri_to_data_uri(url: &str) -> String {
    let path = if let Some(path) = url.strip_prefix("file://") {
        PathBuf::from(path)
    } else {
        return url.into();
    };

    // Read the file, convert it to a dataURI, and record it as a dependency
    match fs::read(&path) {
        Ok(bytes) => {
            let mime = match mime_guess::from_path(&path).first() {
                Some(mime) => mime.to_string(),
                None => "image/png".to_string(),
            };
            let data = base64::encode(bytes);
            ["data:", &mime, ";base64,", &data].concat()
        }
        Err(error) => {
            tracing::warn!("Unable to read media file {}: {}", path.display(), error);
            url.into()
        }
    }
}

fn content_url_to_src_attr(content_url: &str, context: &EncodeContext) -> String {
    let url = match context.bundle {
        true => file_uri_to_data_uri(content_url),
        false => content_url.to_string(),
    };
    attr("src", &url)
}

impl ToHtml for AudioObjectSimple {
    fn to_html(&self, context: &EncodeContext) -> String {
        elem(
            "audio",
            &[
                attr_itemtype_str("AudioObject"),
                attr_id(&self.id),
                "controls".to_string(),
                content_url_to_src_attr(&self.content_url, context),
            ],
            "",
        )
    }
}

impl ToHtml for ImageObjectSimple {
    fn to_html(&self, context: &EncodeContext) -> String {
        fn decode_base64(data: &str) -> String {
            match base64::decode(data) {
                Ok(data) => String::from_utf8_lossy(&data).to_string(),
                Err(error) => {
                    tracing::error!("While decoding base64 image data: {}", error);
                    format!("\"{}\"", error)
                }
            }
        }

        if let Some(data) = self
            .content_url
            .strip_prefix("data:application/vnd.plotly.")
        {
            let mut parts = data.split(";base64,");

            let version = parts.next().unwrap_or("1");
            let media_type = match &self.media_type {
                Some(value) => *value.clone(),
                None => ["application/vnd.plotly.", version].concat(),
            };

            let data = decode_base64(parts.next().unwrap_or_default());

            elem(
                "stencila-image-plotly",
                &[],
                &elem(
                    "picture",
                    &[],
                    &elem("script", &[attr("type", &media_type)], &data),
                ),
            )
        } else if let Some(data) = self.content_url.strip_prefix("data:application/vnd.vega") {
            let mut parts = data.split(";base64,");
            let data = decode_base64(parts.nth(1).unwrap_or_default());

            elem(
                "stencila-image-vega",
                &[],
                &elem(
                    "picture",
                    &[],
                    &elem(
                        "script",
                        &[attr("type", "application/vnd.vega+json")],
                        &data,
                    ),
                ),
            )
        } else {
            elem_empty(
                "img",
                &[
                    attr_itemtype_str("ImageObject"),
                    attr_id(&self.id),
                    content_url_to_src_attr(&self.content_url, context),
                ],
            )
        }
    }
}

impl ToHtml for VideoObjectSimple {
    fn to_html(&self, context: &EncodeContext) -> String {
        let src_attr = content_url_to_src_attr(&self.content_url, context);
        let type_attr = match &self.media_type {
            Some(media_type) => attr("type", media_type),
            None => "".to_string(),
        };
        elem(
            "video",
            &[
                attr_itemtype_str("VideoObject"),
                attr_id(&self.id),
                "controls".to_string(),
            ],
            &elem("source", &[src_attr, type_attr], ""),
        )
    }
}

impl ToHtml for Cite {
    fn to_html(&self, context: &EncodeContext) -> String {
        let content = match &self.content {
            Some(nodes) => nodes.to_html(context),
            None => {
                // Get the list of references from the root nodes
                let references = match context.root {
                    Node::Article(article) => article.references.clone(),
                    Node::CreativeWork(work) => work.references.clone(),
                    _ => {
                        tracing::warn!("Unhandled root document type");
                        None
                    }
                };
                if let Some(references) = references {
                    // Find the reference that matches the `target`
                    let reference = references
                        .iter()
                        .enumerate()
                        .find_map(|(index, reference)| match reference {
                            // A string reference so match against its index in the references list
                            CreativeWorkReferences::String(_) => {
                                if self.target == format!("ref{}", index + 1)
                                    || self.target == format!("ref{}", index + 1)
                                {
                                    Some((index, reference))
                                } else {
                                    None
                                }
                            }
                            // A `CreativeWork` reference so match against its `id`/
                            CreativeWorkReferences::CreativeWorkTypes(work) => match work {
                                CreativeWorkTypes::Article(Article { id, .. }) => {
                                    if let Some(id) = id.as_deref() {
                                        if self.target == *id {
                                            Some((index, reference))
                                        } else {
                                            None
                                        }
                                    } else {
                                        None
                                    }
                                }
                                _ => None,
                            },
                        });
                    // Create the content for the citation
                    match reference {
                        None => {
                            tracing::warn!("When encoding citation was unable to find reference '{}' in root document", self.target);
                            format!(r#"{}"#, self.target.clone())
                        }
                        Some((index, reference)) => {
                            // Always have a numeric citation
                            let mut content = format!(r#"{}"#, index + 1);
                            // If a `CreativeWorkType` then add authors and year
                            if let CreativeWorkReferences::CreativeWorkTypes(work) = reference {
                                let (authors, date) = match &work {
                                    CreativeWorkTypes::Article(article) => {
                                        (article.authors.clone(), article.date_published.clone())
                                    }
                                    CreativeWorkTypes::CreativeWork(work) => {
                                        (work.authors.clone(), work.date_published.clone())
                                    }
                                    _ => {
                                        tracing::warn!("Unhandled root document type");
                                        (None, None)
                                    }
                                };
                                if let Some(authors) = authors {
                                    let names: Vec<String> = authors
                                        .iter()
                                        .map(|author| match author {
                                            CreativeWorkAuthors::Person(person) => {
                                                match &person.family_names {
                                                    Some(family_names) => family_names.join(" "),
                                                    None => "Anonymous".to_string(),
                                                }
                                            }
                                            CreativeWorkAuthors::Organization(org) => {
                                                match &org.name {
                                                    Some(name) => *name.clone(),
                                                    None => "Anonymous".to_string(),
                                                }
                                            }
                                        })
                                        .collect();
                                    let names = if authors.len() == 1 {
                                        names.join("")
                                    } else if authors.len() == 2 {
                                        format!(r#"{} and {}"#, names[0], names[1])
                                    } else {
                                        format!(r#"{} et al"#, names[0])
                                    };
                                    write!(content, r#"{}"#, names)
                                        .expect("Unable to write to string")
                                }
                                if let Some(date) = date {
                                    if date.value.len() >= 4 {
                                        let year = date.value[..4].to_string();
                                        write!(content, r#"{}"#, year)
                                            .expect("Unable to write to string")
                                    }
                                }
                            }
                            content
                        }
                    }
                } else {
                    tracing::warn!("When encoding citation was unable to find references list in root document");
                    format!(r#"{}"#, self.target.clone())
                }
            }
        };
        elem(
            "cite",
            &[attr_itemtype::<Self>(), attr_id(&self.id)],
            &elem("a", &[attr("href", &self.target)], &content),
        )
    }
}

impl ToHtml for CiteGroup {
    fn to_html(&self, context: &EncodeContext) -> String {
        elem(
            "span",
            &[attr_itemtype::<Self>(), attr_id(&self.id)],
            &concat(&self.items, |cite| cite.to_html(context)),
        )
    }
}

impl ToHtml for CodeExpression {
    fn to_html(&self, context: &EncodeContext) -> String {
        let lang = attr_and_meta("programming_language", &self.programming_language);

        let compile_digest = attr_and_meta_opt(
            "compile_digest",
            self.compile_digest.as_ref().map(|cord| cord.0.to_string()),
        );

        let execute_digest = attr_and_meta_opt(
            "execute_digest",
            self.execute_digest.as_ref().map(|cord| cord.0.to_string()),
        );

        let execute_required = attr_and_meta_opt(
            "execute_required",
            self.execute_required
                .as_ref()
                .map(|required| (*required).as_ref().to_string()),
        );

        let execute_kernel = attr_and_meta_opt(
            "execute_kernel",
            self.execute_kernel
                .as_deref()
                .map(|kernel| kernel.to_string()),
        );

        let execute_status = attr_and_meta_opt(
            "execute_status",
            self.execute_status
                .as_ref()
                .map(|status| (*status).as_ref().to_string()),
        );

        let execute_ended = attr_and_meta_opt(
            "execute_ended",
            self.execute_ended
                .as_ref()
                .map(|date| (**date).value.to_string()),
        );

        let execute_duration = attr_and_meta_opt(
            "execute_duration",
            self.execute_duration
                .as_ref()
                .map(|seconds| seconds.to_string()),
        );

        let text = elem(
            "code",
            &[attr_prop("text"), attr_slot("text")],
            &self.text.to_html(context),
        );

        // For code_dependencies it is necessary to place the items in a  under
        // the custom element to avoid elements added by the Web Component interfering
        // with patch indexes.
        let dependencies = elem(
            "stencila-code-dependencies",
            &[attr_slot("code-dependencies")],
            &elem_placeholder(
                "span",
                &[attr_prop("code-dependencies")],
                &self.code_dependencies,
                context,
            ),
        );

        let output = elem_placeholder(
            "output",
            &[attr_prop("output"), attr_slot("output")],
            &self.output,
            &EncodeContext {
                inline: true,
                ..*context
            },
        );

        let errors = elem_placeholder(
            "span",
            &[attr_prop("errors"), attr_slot("errors")],
            &self.errors,
            context,
        );

        elem(
            "stencila-code-expression",
            &[
                attr_itemtype::<Self>(),
                attr_id(&self.id),
                lang.0,
                compile_digest.0,
                execute_digest.0,
                execute_required.0,
                execute_kernel.0,
                execute_status.0,
                execute_ended.0,
                execute_duration.0,
            ],
            &[
                lang.1,
                compile_digest.1,
                execute_digest.1,
                execute_required.1,
                execute_kernel.1,
                execute_status.1,
                execute_ended.1,
                execute_duration.1,
                text,
                dependencies,
                output,
                errors,
            ]
            .concat(),
        )
    }
}

impl ToHtml for CodeFragment {
    /// Encode a [`CodeFragment`] as HTML
    ///
    /// See `CodeBlock::to_html` for why `programming_language` is encoded
    /// as both a `class` attribute and a `<meta>` element.
    fn to_html(&self, context: &EncodeContext) -> String {
        let (lang_attr, lang_class, lang_meta) = match &self.programming_language {
            Some(programming_language) => (
                attr("programming-language", programming_language),
                attr("class", &["language-", programming_language].concat()),
                elem_meta("programmingLanguage", programming_language),
            ),
            None => (nothing(), nothing(), nothing()),
        };

        let text = elem(
            "code",
            &[attr_itemprop("text"), attr_slot("text"), lang_class],
            &self.text.to_html(context),
        );

        elem(
            "stencila-code-fragment",
            &[attr_itemtype::<Self>(), attr_id(&self.id), lang_attr],
            &[lang_meta, text].concat(),
        )
    }
}

impl ToHtml for Link {
    fn to_html(&self, context: &EncodeContext) -> String {
        elem(
            "a",
            &[
                attr_itemtype::<Self>(),
                attr_id(&self.id),
                attr("href", &self.target),
            ],
            &self.content.to_html(context),
        )
    }
}

impl ToHtml for Note {
    fn to_html(&self, _context: &EncodeContext) -> String {
        elem(
            "code",
            &[
                attr_itemtype::<Self>(),
                attr_id(&self.id),
                attr("class", "todo"),
            ],
            &json(self),
        )
    }
}

impl ToHtml for Quote {
    fn to_html(&self, context: &EncodeContext) -> String {
        elem(
            "q",
            &[attr_itemtype::<Self>(), attr_id(&self.id)],
            &self.content.to_html(context),
        )
    }
}


text:
package com.temple.model.access;

import com.temple.model.Resource;
import com.temple.util.Enumerable;
import com.temple.view.LocaleViewable;

/**
 * Enumeration of the different ways to access a {@link Resource}.
 *
 * @author Florent Pallaver
 * @version 1.0
 */
public interface AccessType extends LocaleViewable, Enumerable {}


text:
package org.broadinstitute.hellbender.metrics;

import htsjdk.samtools.metrics.MetricBase;
import htsjdk.samtools.metrics.MetricsFile;

/**
 *  PerRecordCollector - An interface for classes that collect data in order to generate one or more metrics.
 *      This process usually occurs in the following fashion:
 *      1. Loop through a data set (usually all records in a BAM file) and call collector.acceptRecord( data ),
 *         data in this step is usually added to metrics/Histogram objects
 *      2. Call collector.finish() - perform any final calculations necessary after ALL records have been accepted
 *      3. addMetricsToFile is then used to add any metric(s) or Histogram(s) to the given file
 *
 *      BEAN    - The Metric type we are generating
 *      HKEY    - The Key used in any Histograms, use a Wildcard(?) type if there are no Histograms
 *      ARGTYPE - Collectors are often used in groups of accumulation levels, in order to avoid recalculating
 *                any information needed by multiple collectors we allow different types of arguments that
 *                extend DefaultPerRecordCollectorArgs to accommodate any computed values
 */
public interface PerUnitMetricCollector<BEAN extends MetricBase, HKEY extends Comparable<HKEY>, ARGTYPE> {
    /**
     * Add a SAMRecord (with ReferenceSequence and Read Group info) to the metric(s) being calculated)
     * @param args Contains SAMRecord, SAMReadGroupRecord, ReferenceSequence of current record and any previously
     *             computed values that might be needed for this class
     */
    public void acceptRecord(final ARGTYPE args);

    /** When all records have been collected, compute any final values needed to finish constructing metrics/Histogram */
    public void finish();

    /**
     * Any metrics collected will be added to the metric file provided.
     * @param file MetricsFile to which all metrics created by this collector should be added
     */
    public void addMetricsToFile(final MetricsFile<BEAN, HKEY> file);
}


text: SIMPENDOS (SISTEM PENJADWALAN DOSEN) TEKNIK INFORMATIKA UNIVERSITAS MUHAMMADIYAH MALANG


text:
/* eslint-disable no-script-url */
import React from 'react'
import { connect } from 'cerebral/react'
import { signal, state } from 'cerebral/tags'
import translations from '../../common/compute/translations'

import LangSelector from '../LangSelector'

const TaglineRe = /^(.*)\[Cerebral](.*)$/

export default connect(
  {
    currentUser: state`user.$currentUser`,
    loading: state`app.$loading`,
    loggedIn: state`user.$loggedIn`,
    signOutClicked: signal`user.signOutClicked`,
    t: translations,
  },
  function Demo({ currentUser, loading, loggedIn, signOutClicked, t }) {
    const match = TaglineRe.exec(t.SiteTagLine)
    const tagline = match
      ?

          {match[1]}Cerebral{match[2]}

      :
{t.SiteTagLine}

    return (

                  {/* Wait until we have a logo that scales well in this place

                  */}

                {currentUser &&

                    {currentUser.email || t.Anonymous}

}
                {currentUser &&

                     signOutClicked()}>
                      {t.loginSignOut}

}

                  {loggedIn && <LangSelector />}

{t.CerebralDemo}

            {tagline}

    )
  }
)


text:
using System;
using System.IO;
using Castle.Core.Internal;
using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using Common.Logging;
using NCmdLiner;
using AdTools.Library.Infrastructure;
using AdTools.Library.ViewModels;
using AdTools.Library.Views;
using SingletonAttribute = AdTools.Library.Infrastructure.SingletonAttribute;

namespace AdTools.Infrastructure
{
    public class ContainerInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Component.For<IWindsorContainer>().Instance(container));
            container.AddFacility<TypedFactoryFacility>();
            container.Register(Component.For<ITypedFactoryComponentSelector>().ImplementedBy<CustomTypeFactoryComponentSelector>());

            //Configure logging
            ILoggingConfiguration loggingConfiguration = new LoggingConfiguration();
            log4net.GlobalContext.Properties["LogFile"] = Path.Combine(loggingConfiguration.LogDirectoryPath, loggingConfiguration.LogFileName);
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile));
            var applicationRootNameSpace = typeof (Program).Namespace;
            container.Kernel.Register(Component.For<ILog>().Instance(LogManager.GetLogger(applicationRootNameSpace))); //Default logger
            container.Kernel.Resolver.AddSubResolver(new LoggerSubDependencyResolver()); //Enable injection of class specific loggers

            //Manual registrations
            container.Register(Component.For<MainWindow>().Activator<StrictComponentActivator>());
            container.Register(Component.For<MainView>().Activator<StrictComponentActivator>());
            container.Register(Component.For<MainViewModel>().Activator<StrictComponentActivator>());

            //Factory registrations example:

            //container.Register(Component.For<ITeamProviderFactory>().AsFactory());
            //container.Register(
            //    Component.For<ITeamProvider>()
            //        .ImplementedBy<CsvTeamProvider>()
            //        .Named("CsvTeamProvider")
            //        .LifeStyle.Transient);
            //container.Register(
            //    Component.For<ITeamProvider>()
            //        .ImplementedBy<SqlTeamProvider>()
            //        .Named("SqlTeamProvider")
            //        .LifeStyle.Transient);

            container.Register(Component.For<IInvocationLogStringBuilder>().ImplementedBy<InvocationLogStringBuilder>().LifestyleSingleton());
            container.Register(Component.For<ILogFactory>().ImplementedBy<LogFactory>().LifestyleSingleton());
            ///////////////////////////////////////////////////////////////////
            //Automatic registrations
            ///////////////////////////////////////////////////////////////////
            //
            //   Register all interceptors
            //
            container.Register(Classes.FromAssemblyInThisApplication()
                .Pick().If(type => type.Name.EndsWith("Aspect")).LifestyleSingleton());
            //
            //   Register all command providers and attach logging interceptor
            //
            const string libraryRootNameSpace = "AdTools.Library";
            container.Register(Classes.FromAssemblyContaining<CommandProvider>()
                .InNamespace(libraryRootNameSpace, true)
                .If(type => type.Is<CommandProvider>())
                .Configure(registration => registration.Interceptors(new[] { typeof(InfoLogAspect) }))
                .WithService.DefaultInterfaces().LifestyleTransient()
            );
            //
            //   Register all command definitions
            //
            container.Register(
                Classes.FromAssemblyInThisApplication()
                .BasedOn<CommandDefinition>()
                .WithServiceBase()
                );
            //
            //   Register all singletons found in the library
            //
            container.Register(Classes.FromAssemblyContaining<CommandDefinition>()
                .InNamespace(libraryRootNameSpace, true)
                .If(type => Attribute.IsDefined(type, typeof(SingletonAttribute)))
                .WithService.DefaultInterfaces().LifestyleSingleton());
            //
            //   Register all transients found in the library
            //
            container.Register(Classes.FromAssemblyContaining<CommandDefinition>()
                .InNamespace(libraryRootNameSpace, true)
                .WithService.DefaultInterfaces().LifestyleTransient());

            IApplicationInfo applicationInfo = new ApplicationInfo();
            container.Register(Component.For<IApplicationInfo>().Instance(applicationInfo).LifestyleSingleton());
        }
    }
}


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [2.0.0.beta1] - 2017-05-12
### Added
- Convenience methods `RSpec::Scaffold.testify_file` and `RSpec::Scaffold.testify_text` which allow making scaffolds from within code.
- rspec-scaffold CLI

### Changed
- Scaffolds no longer produce the 'require spec/rails_helper' line - devs should keep it in .rspec file.
- Updates to Rails controller scaffolds
- Updates to Rails Model scaffolds

## [1.0.0] - 2016-08-05
Core functionality, `rake rspec:scaffold[app/models/ability.rb]`.


text:
(function (PIXI, lib) {

    var MovieClip = PIXI.animate.MovieClip;
    var Sprite = PIXI.Sprite;
    var fromFrame = PIXI.Texture.fromFrame;
    var Graphics = PIXI.Graphics;
    var shapes = PIXI.animate.ShapesCache;

    lib.bitmap_mask = MovieClip.extend(function () {
        MovieClip.call(this, {
            duration: 1,
            framerate: 24
        });
        var instance1 = new Sprite(fromFrame("Bitmap 1"))
            .setRenderable(false)
            .setTransform(2, 2, 0.5, 0.5);
        var instance2 = new Graphics()
            .drawCommands(shapes.bitmap_mask[0])
            .setMask(instance1);
        this.addChild(instance1, instance2);
    });

    lib.bitmap_mask.assets = {
        "Bitmap 1": "images/Bitmap 1.png",
        "bitmap_mask": "images/bitmap_mask.shapes.json"
    };
})(PIXI, lib = lib || {});
var lib;
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        stage: lib.bitmap_mask,
        background: 0xffffff,
        width: 32,
        height: 32,
        framerate: 24,
        totalFrames: 1,
        library: lib
    };
}


text:
<!DOCTYPE html>

    <title>OAuth 2 postMessage flow example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <link rel="StyleSheet" type="text/css" href="app.css" />

        <button class="auth-button" id="restart-auth-button"
                title="Check authorization…">Authorizing… ↻</button>
        <button class="auth-button" id="cancel-auth-button"
                title="Cancel">×</button>

        <button class="auth-button" id="auth-button">Authorize…</button>
        <button class="auth-button" id="auth-retry-button"
                title="Retry">↻</button>

          <button class="auth-button" id="auth-refresh-button">Authorized ↻</button>
          <button class="auth-button" id="auth-discard-button"
                  title="Discard">×</button>

          <button id="user-info" style="display: none;"></button>


text:
/**
 * @ngdoc service
 * @name $atajoUiTabsDelegate
 * @module atajoui
 *
 * @description
 * Delegate for controlling the {@link atajoui.directive:auiTabs} directive.
 *
 * Methods called directly on the $atajoUiTabsDelegate service will control all auiTabs
 * directives. Use the {@link atajoui.service:$atajoUiTabsDelegate#$getByHandle $getByHandle}
 * method to control specific auiTabs instances.
 *
 * @usage
 *
 * ```html
 * <body ng-controller="MyCtrl">
 *   <aui-tabs>
 *
 *     <aui-tab title="Tab 1">
 *       Hello tab 1!
 *       <button ng-click="selectTabWithIndex(1)">Select tab 2!</button>
 *     </aui-tab>
 *     <aui-tab title="Tab 2">Hello tab 2!</aui-tab>
 *
 *   </aui-tabs>
 * </body>
 * ```
 * ```js
 * function MyCtrl($scope, $atajoUiTabsDelegate) {
 *   $scope.selectTabWithIndex = function(index) {
 *     $atajoUiTabsDelegate.select(index);
 *   }
 * }
 * ```
 */
AtajoUiModule
.service('$atajoUiTabsDelegate', atajoui.DelegateService([
  /**
   * @ngdoc method
   * @name $atajoUiTabsDelegate#select
   * @description Select the tab matching the given index.
   *
   * @param {number} index Index of the tab to select.
   */
  'select',
  /**
   * @ngdoc method
   * @name $atajoUiTabsDelegate#selectedIndex
   * @returns `number` The index of the selected tab, or -1.
   */
  'selectedIndex',
  /**
   * @ngdoc method
   * @name $atajoUiTabsDelegate#showBar
   * @description
   * Set/get whether the {@link atajoui.directive:auiTabs} is shown
   * @param {boolean} show Whether to show the bar.
   * @returns {boolean} Whether the bar is shown.
   */
  'showBar'
  /**
   * @ngdoc method
   * @name $atajoUiTabsDelegate#$getByHandle
   * @param {string} handle
   * @returns `delegateInstance` A delegate instance that controls only the
   * {@link atajoui.directive:auiTabs} directives with `delegate-handle` matching
   * the given handle.
   *
   * Example: `$atajoUiTabsDelegate.$getByHandle('my-handle').select(0);`
   */
]));