text:
<?php
use Stikman\FileWatcher;
use org\bovigo\vfs;

/**
 * Test the watcher class understanding we can not build a
 * vitural filesystem that works with libc glob function. oh well. this will
 * have to do for now.
 *
 */
class WatcherTest extends \PHPUnit_Framework_TestCase
{
    private $dir;

    public function setup()
    {
        $tmp = sys_get_temp_dir();
        $this->dir = $tmp . "/watcher-test";

        if($this->dir === "/") {
            exit();
        }

        if(!is_dir($this->dir)) {
            mkdir($this->dir);
        }

        file_put_contents($this->dir . "/config.ini", "[]");
        file_put_contents($this->dir . "/test.php", "<?php ?>");
        file_put_contents($this->dir . "/my.js", "console.log('hello world'); ");
    }

    public function testFindFiles()
    {
        $watcher = new FileWatcher($this->dir);
        $result = $watcher->findFiles();

        $mock = array(
            $this->dir . "/config.ini",
            $this->dir . "/my.js",
            $this->dir . "/test.php"
        );

        $this->assertEquals($mock, $result);
    }

    public function testCustomPattern()
    {
        $watcher = new FileWatcher($this->dir, "*.php");
        $result = $watcher->findFiles();

        $mock = array(
            $this->dir . "/test.php"
        );

        $this->assertEquals($mock, $result);
    }

    public function testCreateEvent()
    {
        $watcher = new FileWatcher($this->dir);

        // just for simplicity we will set a reference variable to true if the event fires
        $value = false;
        $watcher->on(FileWatcher::CREATE, function() use (&$value) {
            $value = true;
        });

        // set the watcher to stop as soon as it starts
        $watcher->setIterations(1);
        $watcher->start();

        // now change the file system to add a file
        file_put_contents($this->dir . "/newfile.txt", "content");
        $watcher->start();

        $this->assertTrue($value);
    }

    public function testDeleteEvent()
    {
        $watcher = new FileWatcher($this->dir);

        // just for simplicity we will set a reference variable to true if the event fires
        $value = false;
        $watcher->on(FileWatcher::DELETE, function() use (&$value) {
                $value = true;
            });

        // set the watcher to stop as soon as it starts
        $watcher->setIterations(1);
        $watcher->start();

        // now change the file system to add a file
        unlink($this->dir . "/config.ini");
        $watcher->start();

        $this->assertTrue($value);
    }

    public function testModifiedEvent()
    {
        $watcher = new FileWatcher($this->dir);

        // just for simplicity we will set a reference variable to true if the event fires
        $value = false;
        $watcher->on(FileWatcher::MODIFIED, function() use (&$value) {
                $value = true;
            });

        // set the watcher to stop as soon as it starts
        $watcher->setIterations(1);
        $watcher->start();

        // now change the file system to add a file
        file_put_contents($this->dir . "/config.ini", "[this is new]");
        $watcher->start();

        $this->assertTrue($value);
    }

    public function teardown()
    {
        $tmp = sys_get_temp_dir();
        $files = glob($tmp . "/watcher-test/*");
        foreach ($files as $file) {
            @unlink($file);
        }

        rmdir($tmp . "/watcher-test");
    }

}


text:
class PythonMICallbacks : public MI::Callbacks
{
private:
    PyObject* m_indicationResult = NULL;
public:
    PythonMICallbacks(PyObject* indicationResult);
    bool WriteError(std::shared_ptr<MI::Operation> operation, std::shared_ptr<const MI::Instance> instance);
    void IndicationResult(std::shared_ptr<MI::Operation> operation, std::shared_ptr<const MI::Instance> instance,
        const std::wstring& bookmark, const std::wstring& machineID, bool moreResults, MI_Result resultCode,
        const std::wstring& errorString, std::shared_ptr<const MI::Instance> errorDetails);
    ~PythonMICallbacks();
};

redpajama_set_name: RedPajamaGithub


text:
@interface NSXSideViewHeader : UIView

@property (strong, nonatomic) UIImageView *avatarImageView;
@property (strong, nonatomic) UIButton *loginBtn;
@property (strong, nonatomic) UIButton *collectionBtn;
@property (strong, nonatomic) UIButton *messageBtn;
@property (strong, nonatomic) UIButton *settingBtn;

@end


text:
package com.sun.xml.internal.ws.encoding.xml;

public class XMLConstants {

     public static final String OUTPUT_XML_CHARACTER_ENCODING = "com.sun.jaxws.rest.contenttype";
}


text:
package com.mapr.synth.distributions;

import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
import com.google.common.io.Resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Emulates an infinite list of words, a prefix of which are taken from lists of plausible words.  The first words are
 * taken from a resource that has frequencies in it.  These frequencies can be used to initialize term generators to a
 * common language.  The next batch of words are taken from a long list of words with no frequencies. After that, words
 * are coined by using an integer count.
 */
public class WordGenerator {
    private final Logger log = LoggerFactory.getLogger(WordGenerator.class);

    private BufferedReader wordReader;
    private final List<String> words = Lists.newArrayList();
    private final Map<String, Integer> baseWeights = Maps.newLinkedHashMap();

    public WordGenerator(String seed, String others) {
        // read the common words
        if (seed != null) {
            try {
                //noinspection UnstableApiUsage
                Resources.readLines(Resources.getResource(seed), Charsets.UTF_8,
                        new LineProcessor<>() {
                            private boolean header = true;
                            private final Splitter onTabs = Splitter.on("\t");

                            public boolean processLine(String s) {
                                if (!s.startsWith("#")) {
                                    if (!header) {
                                        Iterator<String> fields = onTabs.split(s).iterator();
                                        fields.next();
                                        String word = fields.next();
                                        words.add(word);
                                        int count = (int) Math.rint(Double.parseDouble(fields.next()));
                                        baseWeights.put(word, count);
                                    } else {
                                        header = false;
                                    }
                                }
                                return true;
                            }

                            public Object getResult() {
                                return null;
                            }
                        });
            } catch (IOException e) {
                log.error("Can't read resource \"{}\", will continue without realistic words", seed);
            }
        }

        InputStream s = this.getClass().getResourceAsStream(others);
        if (s == null) {
            s = this.getClass().getResourceAsStream("/" + others);
        }
        if (s == null) {
            log.error("Can't read resource \"{}\", will continue without realistic words", others);
            wordReader = null;
        } else {
            wordReader = new BufferedReader(new InputStreamReader(s, Charsets.UTF_8));
        }
    }

    public String getString(int n) {
        if (n >= words.size()) {
            synchronized (this) {
                while (n >= words.size()) {
                    try {
                        String w = wordReader != null ? wordReader.readLine() : null;
                        if (w != null) {
                            words.add(w);
                        } else {
                            words.add("w-" + n);
                        }
                    } catch (IOException e) {
                        log.error("Error reading other words resource", e);
                        words.add("w-" + n);
                    }
                }
            }
        }
        return words.get(n);
    }

    public Map<String, Integer> getBaseWeights() {
        return baseWeights;
    }

    public int size() {
        return words.size();
    }
}


text:
import sys
from subprocess import Popen, PIPE, STDOUT

MODEL = sys.argv[1]

try:
    INPUT = open(sys.argv[2], 'r')
except:
    INPUT = sys.stdin

for line in INPUT:
    # p = Popen(['./crf_test_filter.sh', MODEL], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    p = Popen(['./crf_test_filter.sh', MODEL], stdin=PIPE, stdout=PIPE)
    # fails to put newline between each output
    # p.communicate(input=line.strip()+'\n')
    f_stdout = p.communicate(input=line.strip()+'\n')[0]
    print f_stdout

try:
    close(INPUT)
except:
    pass

# adapted from example http://stackoverflow.com/a/165662/2077242
# from subprocess import Popen, PIPE, STDOUT
# p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
# grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
# print(grep_stdout.decode())


text:
body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

* {
  font-size: 1.5rem;
  margin-left: 10px;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\Test\PostOrder\Types;

use DTS\eBaySDK\PostOrder\Types\SendReturnShippingLabelRestRequest;

class SendReturnShippingLabelRestRequestTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new SendReturnShippingLabelRestRequest();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\PostOrder\Types\SendReturnShippingLabelRestRequest', $this->obj);
    }

    public function testExtendsBaseType()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj);
    }
}


text:
require File.dirname(__FILE__) + '/../test_helper'
require 'locations_controller'

# Re-raise errors caught by the controller.
class LocationsController; def rescue_action(e) raise e end; end

class LocationsControllerTest < Test::Unit::TestCase
  fixtures :locations

  def setup
    @controller = LocationsController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
  end

  def test_should_get_index
    get :index
    assert_response :success
    assert assigns(:locations)
  end

  def test_should_get_new
    get :new
    assert_response :success
  end

  def test_should_create_location
    old_count = Location.count
    post :create, :location => {:name => 'Home'}
    assert_equal old_count+1, Location.count

    assert_redirected_to locations_path
  end

  def test_should_show_location
    get :show, :id => locations(:conference)
    assert_response :success
  end

  def test_should_get_edit
    get :edit, :id => locations(:conference)
    assert_response :success
  end

  def test_should_update_location
    put :update, :id => locations(:conference), :location => { }
    assert_redirected_to locations_path
  end

  def test_should_destroy_location
    old_count = Location.count
    delete :destroy, :id => locations(:conference).id
    assert_equal old_count-1, Location.count

    assert_redirected_to locations_path
  end
end


text:
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoFramework.Infrastructure;
using MongoFramework.Infrastructure.Commands;

namespace MongoFramework.Tests.Infrastructure.Commands
{
	[TestClass]
	public class UpdateEntityCommandTests : TestBase
	{
		public class TestModel
		{
			public string Id { get; set; }
			public string Title { get; set; }
		}

		public class TestValidationModel
		{
			public string Id { get; set; }

			[Required]
			public string RequiredField { get; set; }
			public bool BooleanField { get; set; }
		}

		[TestMethod]
		public void UpdateEntity()
		{
			var connection = TestConfiguration.GetConnection();
			var context = new MongoDbContext(connection);

			var entity = new TestModel
			{
				Title = "UpdateEntityCommandTests.UpdateEntity"
			};

			context.CommandStaging.Add(new AddEntityCommand<TestModel>(new EntityEntry(entity, EntityEntryState.Added)));
			context.SaveChanges();

			var updatedEntity = new TestModel
			{
				Id = entity.Id,
				Title = "UpdateEntityCommandTests.UpdateEntity-Updated"
			};

			context.CommandStaging.Add(new UpdateEntityCommand<TestModel>(new EntityEntry(updatedEntity, EntityEntryState.Updated)));
			context.SaveChanges();

			var dbEntity = context.Query<TestModel>().Where(e => e.Id == entity.Id).FirstOrDefault();
			Assert.AreEqual("UpdateEntityCommandTests.UpdateEntity-Updated", dbEntity.Title);
		}

		[TestMethod, ExpectedException(typeof(ValidationException))]
		public void ValidationExceptionOnInvalidModel()
		{
			var entity = new TestValidationModel { };
			var command = new UpdateEntityCommand<TestValidationModel>(new EntityEntry(entity, EntityEntryState.Updated));
			command.GetModel(WriteModelOptions.Default).FirstOrDefault();
		}
	}
}


text:
module io.fusionauth {
	exports io.fusionauth.jwt.hmac;
	exports io.fusionauth.jwt.json;
	exports io.fusionauth.pem.domain;
	exports io.fusionauth.jwks.domain;
	exports io.fusionauth.jwks;
	exports io.fusionauth.der;
	exports io.fusionauth.jwt.domain;
	exports io.fusionauth.jwt.ec;
	exports io.fusionauth.jwt.rsa;
	exports io.fusionauth.jwt;
	exports io.fusionauth.pem;
	exports io.fusionauth.security;

	requires com.fasterxml.jackson.annotation;
	requires com.fasterxml.jackson.core;
	requires com.fasterxml.jackson.databind;
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <parent>
	<groupId>net.anotheria</groupId>
	<artifactId>moskito</artifactId>
	<version>2.8.7-SNAPSHOT</version>
	<relativePath>../../pom.xml</relativePath>
  </parent>

  <modelVersion>4.0.0</modelVersion>
  <artifactId>moskito-additional-producers</artifactId>
  <version>2.8.7-SNAPSHOT</version>
  <name>additional producers</name>

  <dependencies>
      <dependency>
		<groupId>net.anotheria</groupId>
		<artifactId>moskito-core</artifactId>
		<version>${project.version}</version>
	</dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
      </dependency>
      <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <!--scope>test</scope-->
      </dependency>

      <dependency>
          <groupId>com.googlecode.concurrentlinkedhashmap</groupId>
          <artifactId>concurrentlinkedhashmap-lru</artifactId>
          <version>1.4</version>
      </dependency>
  </dependencies>
</project>


text:
package bootstrap

import "github.com/astaxie/beego"

// Logger initialization writes to ./logs directory and sets 5 different files,
// one for each of the following levels: critical, error, warning, info and debug
func SetupLogger()  {
	beego.SetLogger("multifile", `{"filename":"logs/app.log", "maxdays":30,
	"separate":["critical", "error", "warning", "info", "debug"]}`)
}


text:
package org.finra.herd.model.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * A notification type.
 */
@Table(name = "ntfcn_type_cd_lk")
@Entity
public class NotificationTypeEntity extends AuditableEntity
{
    /**
     * Notification type for business object data.
     */
    public static final String NOTIFICATION_TYPE_BDATA = "BUS_OBJCT_DATA";

    /**
     * Notification type for storage unit.
     */
    public static final String NOTIFICATION_TYPE_STORAGE_UNIT = "STRGE_UNIT";

    /**
     * The code column.
     */
    @Id
    @Column(name = "ntfcn_type_cd")
    private String code;

    @Column(name = "ntfcn_type_ds")
    private String description;

    public String getCode()
    {
        return code;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    public String getDescription()
    {
        return description;
    }

    public void setDescription(String description)
    {
        this.description = description;
    }
}


text:
layout: post
title: DNE 14 - Carreira Front-end
cast: 220195311-devnaestrada-devnaestrada-14-carreira-front-end.mp3
cast-length: "88840245"
cast-time: "00:37:00"
description: "@femontanha, @Ojaviani e Erick Bessa batem um papo sobre carreira front-end. Como está o mercado? O que você precisa saber?"
soundcloud-id: "220195311"
soundcloud-post-image: "000135763399-nxbys1"
---

No cast de hoje, [@femontanha](http://twitter.com/femontanha), [@Ojaviani](http://twitter.com/Ojaviani) e Erick Bessa batem um papo sobre carreira front-end. Como está o mercado? O que você precisa saber? Preciso aprender milhares de frameworks? Aumente o som e descubra as alegrias e mazelas dessa profissão.

## Conheça a plataforma Alura
[Alura - Aprenda, crie e desenvolva](http://www.alura.com.br)

## Formulário Curso Alura
[Formulário do presente Alura](http://devnaestrada.typeform.com/to/QUBAdE)

### Eventos

- [Caipira Ágil - caipiraagil.com](http://www.caipiraagil.com)

- [DNE2015 - eventick.com.br/devnaestrada2015](http://www.eventick.com.br/devnaestrada2015)

- [Frontinsampa 2015 - frontinsampa.com.br](http://www.frontinsampa.com.br)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2016 Martin W. Kirst
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<!DOCTYPE module PUBLIC "//gwt-module/" "http://google-web-toolkit.googlecode.com/svn/tags/2.0.0/distro-source/core/src/gwt-module.dtd">
<module>
    <source path=""/>
    <inherits name="com.google.gwt.user.User"/>
</module>


text:
import solumdashboard.applications.views as views
from solumdashboard.utils import importutils

urls = importutils.import_any('django.conf.urls.defaults',
                              'django.conf.urls')

patterns = urls.patterns
url = urls.url

urlpatterns = patterns('',
                       url(r'^$', views.IndexView.as_view(),
                           name='index'),
                       url(r'^$', views.IndexView.as_view(),
                           name='applications'),
                       url(r'^create$',
                           views.CreateView.as_view(),
                           name='create'),
                       url(r'^(?P<application_id>[^/]+)$',
                           views.DetailView.as_view(),
                           name='detail'))


text:
namespace raytracer {

using math3d::V3D;

namespace netproto {
// Wire format is the following:
// 4 bytes Tag
// 8 bytes Sender/Destination ID (8-byte string)
// 4 bytes Length (excluding Tag, ID and Length)
// N bytes Data
// The wire format of each class is known only to the class itself.
// The Tag, ID and Length are automatically sent; there is no need for the class
// to add them manually to the bytes vector, however the Sender/Destination ID
// field must be filled. Worker puts its own ID in the Sender ID fields. Master
// puts the Destination ID there.
// All values are LE.

enum class kCommunicationSide {
  kMaster,
  kWorker
};

class NetworkProto {
 public:
  virtual ~NetworkProto() { };
  virtual std::string GetTag() const = 0;
  std::vector<uint8_t> bytes;
  std::string id;  // Sender/Destination ID.
};

// Worker->Master: Worker ready to receive the scene.
class WorkerReady : public NetworkProto {
 public:
  static WorkerReady* Make(const std::string &sender_id);
  std::string GetTag() const override {
    return "RDY!";
  };
};

// Master->Worker: Serialized scene (primitives, textures, lights).
class MasterScene : public NetworkProto {
 public:
  static MasterScene* Make(const std::string &destination_id, Scene *scene);
  std::string GetTag() const override {
    return "SCNE";
  };
};

// TODO(gynvael): Perhaps merge this with WORK?
// Master->Worker: Serialized Camera.
class MasterSetCamera : public NetworkProto {
 public:
  static MasterSetCamera* Make(
      const std::string &destination_id, Camera *camera);
  std::string GetTag() const override {
    return "CAMR";
  };
};

// Master->Worker: Serialized WorkChunk.
class MasterRenderOrder : public NetworkProto {
 public:
  static MasterRenderOrder* Make(
      const std::string &destination_id, WorkChunk *chunk);
  std::string GetTag() const override {
    return "WORK";
  };
};

// Worker->Master: Bitmap and logs/stats.
class WorkerRenderResult : public NetworkProto {
 public:
  // Uses only the output_* part of WorkChunk.
  static WorkerRenderResult* Make(
      const std::string &sender_id, WorkChunk *chunk);

  std::string GetTag() const override {
    return "PXLS";
  };
};

bool SendPacket(NetSock *s, NetworkProto *packet);
NetworkProto* ReceivePacket(NetSock *s, kCommunicationSide side);

}  // namespace netproto

}  // namespace raytracer


text:
//===- SDBMExpr.h - MLIR SDBM Expression ------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// A striped difference-bound matrix (SDBM) expression is a constant expression,
// an identifier, a binary expression with constant RHS and +, stripe operators
// or a difference expression between two identifiers.
//
//===----------------------------------------------------------------------===//

#ifndef MLIR_DIALECT_SDBM_SDBMEXPR_H
#define MLIR_DIALECT_SDBM_SDBMEXPR_H

#include "mlir/Support/LLVM.h"
#include "llvm/ADT/DenseMapInfo.h"

namespace mlir {

class AffineExpr;
class MLIRContext;

enum class SDBMExprKind { Add, Stripe, Diff, Constant, DimId, SymbolId, Neg };

namespace detail {
struct SDBMExprStorage;
struct SDBMBinaryExprStorage;
struct SDBMDiffExprStorage;
struct SDBMTermExprStorage;
struct SDBMConstantExprStorage;
struct SDBMNegExprStorage;
} // namespace detail

class SDBMConstantExpr;
class SDBMDialect;
class SDBMDimExpr;
class SDBMSymbolExpr;
class SDBMTermExpr;

/// Striped Difference-Bounded Matrix (SDBM) expression is a base left-hand side
/// expression for the SDBM framework.  SDBM expressions are a subset of affine
/// expressions supporting low-complexity algorithms for the operations used in
/// loop transformations.  In particular, are supported:
///   - constant expressions;
///   - single variables (dimensions and symbols) with +1 or -1 coefficient;
///   - stripe expressions: "x # C", where "x" is a single variable or another
///     stripe expression, "#" is the stripe operator, and "C" is a constant
///     expression; "#" is defined as x - x mod C.
///   - sum expressions between single variable/stripe expressions and constant
///     expressions;
///   - difference expressions between single variable/stripe expressions.
/// `SDBMExpr` class hierarchy provides a type-safe interface to constructing
/// and operating on SDBM expressions.  For example, it requires the LHS of a
/// sum expression to be a single variable or a stripe expression.  These
/// restrictions are intended to force the caller to perform the necessary
/// simplifications to stay within the SDBM domain, because SDBM expressions do
/// not combine in more cases than they do.  This choice may be reconsidered in
/// the future.
///
/// SDBM expressions are grouped into the following structure
/// - expression
///   - varying
///     - direct
///       - sum <- (term, constant)
///       - term
///         - symbol
///         - dimension
///         - stripe <- (direct, constant)
///     - negation <- (direct)
///     - difference <- (direct, term)
///   - constant
/// The notation <- (...) denotes the types of subexpressions a compound
/// expression can combine.  The tree of subexpressions essentially imposes the
/// following canonicalization rules:
///   - constants are always folded;
///   - constants can only appear on the RHS of an expression;
///   - double negation must be elided;
///   - an additive constant term is only allowed in a sum expression, and
///     should be sunk into the nearest such expression in the tree;
///   - zero constant expression can only appear at the top level.
///
/// `SDBMExpr` and derived classes are thin wrappers around a pointer owned by
/// an MLIRContext, and should be used by-value.  They are uniqued in the
/// MLIRContext and immortal.
class SDBMExpr {
public:
  using ImplType = detail::SDBMExprStorage;
  SDBMExpr() : impl(nullptr) {}
  /* implicit */ SDBMExpr(ImplType *expr) : impl(expr) {}

  /// SDBM expressions are thin wrappers around a unique'ed immutable pointer,
  /// which makes them trivially assignable and trivially copyable.
  SDBMExpr(const SDBMExpr &) = default;
  SDBMExpr &operator=(const SDBMExpr &) = default;

  /// SDBM expressions can be compared straight-forwardly.
  bool operator==(const SDBMExpr &other) const { return impl == other.impl; }
  bool operator!=(const SDBMExpr &other) const { return !(*this == other); }

  /// SDBM expressions are convertible to `bool`: null expressions are converted
  /// to false, non-null expressions are converted to true.
  explicit operator bool() const { return impl != nullptr; }
  bool operator!() const { return !static_cast<bool>(*this); }

  /// Negate the given SDBM expression.
  SDBMExpr operator-();

  /// Prints the SDBM expression.
  void print(raw_ostream &os) const;
  void dump() const;

  /// LLVM-style casts.
  template <typename U> bool isa() const { return U::isClassFor(*this); }
  template <typename U> U dyn_cast() const {
    if (!isa<U>())
      return {};
    return U(const_cast<SDBMExpr *>(this)->impl);
  }
  template <typename U> U cast() const {
    assert(isa<U>() && "cast to incorrect subtype");
    return U(const_cast<SDBMExpr *>(this)->impl);
  }

  /// Support for LLVM hashing.
  ::llvm::hash_code hash_value() const { return ::llvm::hash_value(impl); }

  /// Returns the kind of the SDBM expression.
  SDBMExprKind getKind() const;

  /// Returns the MLIR context in which this expression lives.
  MLIRContext *getContext() const;

  /// Returns the SDBM dialect instance.
  SDBMDialect *getDialect() const;

  /// Convert the SDBM expression into an Affine expression.  This always
  /// succeeds because SDBM are a subset of affine.
  AffineExpr getAsAffineExpr() const;

  /// Try constructing an SDBM expression from the given affine expression.
  /// This may fail if the affine expression is not representable as SDBM, in
  /// which case llvm::None is returned.  The conversion procedure recognizes
  /// (nested) multiplicative ((x floordiv B) * B) and additive (x - x mod B)
  /// patterns for the stripe expression.
  static Optional<SDBMExpr> tryConvertAffineExpr(AffineExpr affine);

protected:
  ImplType *impl;
};

/// SDBM constant expression, wraps a 64-bit integer.
class SDBMConstantExpr : public SDBMExpr {
public:
  using ImplType = detail::SDBMConstantExprStorage;

  using SDBMExpr::SDBMExpr;

  /// Obtain or create a constant expression unique'ed in the given dialect
  /// (which belongs to a context).
  static SDBMConstantExpr get(SDBMDialect *dialect, int64_t value);

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::Constant;
  }

  int64_t getValue() const;
};

/// SDBM varying expression can be one of:
///   - input variable expression;
///   - stripe expression;
///   - negation (product with -1) of either of the above.
///   - sum of a varying and a constant expression
///   - difference between varying expressions
class SDBMVaryingExpr : public SDBMExpr {
public:
  using ImplType = detail::SDBMExprStorage;
  using SDBMExpr::SDBMExpr;

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::DimId ||
           expr.getKind() == SDBMExprKind::SymbolId ||
           expr.getKind() == SDBMExprKind::Neg ||
           expr.getKind() == SDBMExprKind::Stripe ||
           expr.getKind() == SDBMExprKind::Add ||
           expr.getKind() == SDBMExprKind::Diff;
  }
};

/// SDBM direct expression includes exactly one variable (symbol or dimension),
/// which is not negated in the expression.  It can be one of:
///   - term expression;
///   - sum expression.
class SDBMDirectExpr : public SDBMVaryingExpr {
public:
  using SDBMVaryingExpr::SDBMVaryingExpr;

  /// If this is a sum expression, return its variable part, otherwise return
  /// self.
  SDBMTermExpr getTerm();

  /// If this is a sum expression, return its constant part, otherwise return 0.
  int64_t getConstant();

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::DimId ||
           expr.getKind() == SDBMExprKind::SymbolId ||
           expr.getKind() == SDBMExprKind::Stripe ||
           expr.getKind() == SDBMExprKind::Add;
  }
};

/// SDBM term expression can be one of:
///  - single variable expression;
///  - stripe expression.
/// Stripe expressions are treated as terms since, in the SDBM domain, they are
/// attached to temporary variables and can appear anywhere a variable can.
class SDBMTermExpr : public SDBMDirectExpr {
public:
  using SDBMDirectExpr::SDBMDirectExpr;

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::DimId ||
           expr.getKind() == SDBMExprKind::SymbolId ||
           expr.getKind() == SDBMExprKind::Stripe;
  }
};

/// SDBM sum expression.  LHS is a term expression and RHS is a constant.
class SDBMSumExpr : public SDBMDirectExpr {
public:
  using ImplType = detail::SDBMBinaryExprStorage;
  using SDBMDirectExpr::SDBMDirectExpr;

  /// Obtain or create a sum expression unique'ed in the given context.
  static SDBMSumExpr get(SDBMTermExpr lhs, SDBMConstantExpr rhs);

  static bool isClassFor(const SDBMExpr &expr) {
    SDBMExprKind kind = expr.getKind();
    return kind == SDBMExprKind::Add;
  }

  SDBMTermExpr getLHS() const;
  SDBMConstantExpr getRHS() const;
};

/// SDBM difference expression.  LHS is a direct expression, i.e. it may be a
/// sum of a term and a constant.  RHS is a term expression.  Thus the
/// expression (t1 - t2 + C) with term expressions t1,t2 is represented as
///   diff(sum(t1, C), t2)
/// and it is possible to extract the constant factor without negating it.
class SDBMDiffExpr : public SDBMVaryingExpr {
public:
  using ImplType = detail::SDBMDiffExprStorage;
  using SDBMVaryingExpr::SDBMVaryingExpr;

  /// Obtain or create a difference expression unique'ed in the given context.
  static SDBMDiffExpr get(SDBMDirectExpr lhs, SDBMTermExpr rhs);

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::Diff;
  }

  SDBMDirectExpr getLHS() const;
  SDBMTermExpr getRHS() const;
};

/// SDBM stripe expression "x # C" where "x" is a term expression, "C" is a
/// constant expression and "#" is the stripe operator defined as:
///   x # C = x - x mod C.
class SDBMStripeExpr : public SDBMTermExpr {
public:
  using ImplType = detail::SDBMBinaryExprStorage;
  using SDBMTermExpr::SDBMTermExpr;

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::Stripe;
  }

  static SDBMStripeExpr get(SDBMDirectExpr var, SDBMConstantExpr stripeFactor);

  SDBMDirectExpr getLHS() const;
  SDBMConstantExpr getStripeFactor() const;
};

/// SDBM "input" variable expression can be either a dimension identifier or
/// a symbol identifier.  When used to define SDBM functions, dimensions are
/// interpreted as function arguments while symbols are treated as unknown but
/// constant values, hence the name.
class SDBMInputExpr : public SDBMTermExpr {
public:
  using ImplType = detail::SDBMTermExprStorage;
  using SDBMTermExpr::SDBMTermExpr;

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::DimId ||
           expr.getKind() == SDBMExprKind::SymbolId;
  }

  unsigned getPosition() const;
};

/// SDBM dimension expression.  Dimensions correspond to function arguments
/// when defining functions using SDBM expressions.
class SDBMDimExpr : public SDBMInputExpr {
public:
  using ImplType = detail::SDBMTermExprStorage;
  using SDBMInputExpr::SDBMInputExpr;

  /// Obtain or create a dimension expression unique'ed in the given dialect
  /// (which belongs to a context).
  static SDBMDimExpr get(SDBMDialect *dialect, unsigned position);

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::DimId;
  }
};

/// SDBM symbol expression.  Symbols correspond to symbolic constants when
/// defining functions using SDBM expressions.
class SDBMSymbolExpr : public SDBMInputExpr {
public:
  using ImplType = detail::SDBMTermExprStorage;
  using SDBMInputExpr::SDBMInputExpr;

  /// Obtain or create a symbol expression unique'ed in the given dialect (which
  /// belongs to a context).
  static SDBMSymbolExpr get(SDBMDialect *dialect, unsigned position);

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::SymbolId;
  }
};

/// Negation of an SDBM variable expression.  Equivalent to multiplying the
/// expression with -1 (SDBM does not support other coefficients that 1 and -1).
class SDBMNegExpr : public SDBMVaryingExpr {
public:
  using ImplType = detail::SDBMNegExprStorage;
  using SDBMVaryingExpr::SDBMVaryingExpr;

  /// Obtain or create a negation expression unique'ed in the given context.
  static SDBMNegExpr get(SDBMDirectExpr var);

  static bool isClassFor(const SDBMExpr &expr) {
    return expr.getKind() == SDBMExprKind::Neg;
  }

  SDBMDirectExpr getVar() const;
};

/// A visitor class for SDBM expressions.  Calls the kind-specific function
/// depending on the kind of expression it visits.
template <typename Derived, typename Result = void> class SDBMVisitor {
public:
  /// Visit the given SDBM expression, dispatching to kind-specific functions.
  Result visit(SDBMExpr expr) {
    auto *derived = static_cast<Derived *>(this);
    switch (expr.getKind()) {
    case SDBMExprKind::Add:
    case SDBMExprKind::Diff:
    case SDBMExprKind::DimId:
    case SDBMExprKind::SymbolId:
    case SDBMExprKind::Neg:
    case SDBMExprKind::Stripe:
      return derived->visitVarying(expr.cast<SDBMVaryingExpr>());
    case SDBMExprKind::Constant:
      return derived->visitConstant(expr.cast<SDBMConstantExpr>());
    }

    llvm_unreachable("unsupported SDBM expression kind");
  }

  /// Traverse the SDBM expression tree calling `visit` on each node
  /// in depth-first preorder.
  void walkPreorder(SDBMExpr expr) { return walk</*isPreorder=*/true>(expr); }

  /// Traverse the SDBM expression tree calling `visit` on each node in
  /// depth-first postorder.
  void walkPostorder(SDBMExpr expr) { return walk</*isPreorder=*/false>(expr); }

protected:
  /// Default visitors do nothing.
  void visitSum(SDBMSumExpr) {}
  void visitDiff(SDBMDiffExpr) {}
  void visitStripe(SDBMStripeExpr) {}
  void visitDim(SDBMDimExpr) {}
  void visitSymbol(SDBMSymbolExpr) {}
  void visitNeg(SDBMNegExpr) {}
  void visitConstant(SDBMConstantExpr) {}

  /// Default implementation of visitDirect dispatches to the dedicated for sums
  /// or delegates to visitTerm for the other expression kinds.  Concrete
  /// visitors can overload it.
  Result visitDirect(SDBMDirectExpr expr) {
    auto *derived = static_cast<Derived *>(this);
    if (auto sum = expr.dyn_cast<SDBMSumExpr>())
      return derived->visitSum(sum);
    else
      return derived->visitTerm(expr.cast<SDBMTermExpr>());
  }

  /// Default implementation of visitTerm dispatches to the special functions
  /// for stripes and other variables.  Concrete visitors can override it.
  Result visitTerm(SDBMTermExpr expr) {
    auto *derived = static_cast<Derived *>(this);
    if (expr.getKind() == SDBMExprKind::Stripe)
      return derived->visitStripe(expr.cast<SDBMStripeExpr>());
    else
      return derived->visitInput(expr.cast<SDBMInputExpr>());
  }

  /// Default implementation of visitInput dispatches to the special
  /// functions for dimensions or symbols.  Concrete visitors can override it to
  /// visit all variables instead.
  Result visitInput(SDBMInputExpr expr) {
    auto *derived = static_cast<Derived *>(this);
    if (expr.getKind() == SDBMExprKind::DimId)
      return derived->visitDim(expr.cast<SDBMDimExpr>());
    else
      return derived->visitSymbol(expr.cast<SDBMSymbolExpr>());
  }

  /// Default implementation of visitVarying dispatches to the special
  /// functions for variables and negations thereof.  Concrete visitors can
  /// override it to visit all variables and negations instead.
  Result visitVarying(SDBMVaryingExpr expr) {
    auto *derived = static_cast<Derived *>(this);
    if (auto var = expr.dyn_cast<SDBMDirectExpr>())
      return derived->visitDirect(var);
    else if (auto neg = expr.dyn_cast<SDBMNegExpr>())
      return derived->visitNeg(neg);
    else if (auto diff = expr.dyn_cast<SDBMDiffExpr>())
      return derived->visitDiff(diff);

    llvm_unreachable("unhandled subtype of varying SDBM expression");
  }

  template <bool isPreorder> void walk(SDBMExpr expr) {
    if (isPreorder)
      visit(expr);
    if (auto sumExpr = expr.dyn_cast<SDBMSumExpr>()) {
      walk<isPreorder>(sumExpr.getLHS());
      walk<isPreorder>(sumExpr.getRHS());
    } else if (auto diffExpr = expr.dyn_cast<SDBMDiffExpr>()) {
      walk<isPreorder>(diffExpr.getLHS());
      walk<isPreorder>(diffExpr.getRHS());
    } else if (auto stripeExpr = expr.dyn_cast<SDBMStripeExpr>()) {
      walk<isPreorder>(stripeExpr.getLHS());
      walk<isPreorder>(stripeExpr.getStripeFactor());
    } else if (auto negExpr = expr.dyn_cast<SDBMNegExpr>()) {
      walk<isPreorder>(negExpr.getVar());
    }
    if (!isPreorder)
      visit(expr);
  }
};

/// Overloaded arithmetic operators for SDBM expressions asserting that their
/// arguments have the proper SDBM expression subtype.  Perform canonicalization
/// and constant folding on these expressions.
namespace ops_assertions {

/// Add two SDBM expressions.  At least one of the expressions must be a
/// constant or a negation, but both expressions cannot be negations
/// simultaneously.
SDBMExpr operator+(SDBMExpr lhs, SDBMExpr rhs);
inline SDBMExpr operator+(SDBMExpr lhs, int64_t rhs) {
  return lhs + SDBMConstantExpr::get(lhs.getDialect(), rhs);
}
inline SDBMExpr operator+(int64_t lhs, SDBMExpr rhs) {
  return SDBMConstantExpr::get(rhs.getDialect(), lhs) + rhs;
}

/// Subtract an SDBM expression from another SDBM expression.  Both expressions
/// must not be difference expressions.
SDBMExpr operator-(SDBMExpr lhs, SDBMExpr rhs);
inline SDBMExpr operator-(SDBMExpr lhs, int64_t rhs) {
  return lhs - SDBMConstantExpr::get(lhs.getDialect(), rhs);
}
inline SDBMExpr operator-(int64_t lhs, SDBMExpr rhs) {
  return SDBMConstantExpr::get(rhs.getDialect(), lhs) - rhs;
}

/// Construct a stripe expression from a positive expression and a positive
/// constant stripe factor.
SDBMExpr stripe(SDBMExpr expr, SDBMExpr factor);
inline SDBMExpr stripe(SDBMExpr expr, int64_t factor) {
  return stripe(expr, SDBMConstantExpr::get(expr.getDialect(), factor));
}
} // namespace ops_assertions

} // end namespace mlir

namespace llvm {
// SDBMExpr hash just like pointers.
template <> struct DenseMapInfo<mlir::SDBMExpr> {
  static mlir::SDBMExpr getEmptyKey() {
    auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
    return mlir::SDBMExpr(static_cast<mlir::SDBMExpr::ImplType *>(pointer));
  }
  static mlir::SDBMExpr getTombstoneKey() {
    auto *pointer = llvm::DenseMapInfo<void *>::getTombstoneKey();
    return mlir::SDBMExpr(static_cast<mlir::SDBMExpr::ImplType *>(pointer));
  }
  static unsigned getHashValue(mlir::SDBMExpr expr) {
    return expr.hash_value();
  }
  static bool isEqual(mlir::SDBMExpr lhs, mlir::SDBMExpr rhs) {
    return lhs == rhs;
  }
};

// SDBMDirectExpr hash just like pointers.
template <> struct DenseMapInfo<mlir::SDBMDirectExpr> {
  static mlir::SDBMDirectExpr getEmptyKey() {
    auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
    return mlir::SDBMDirectExpr(
        static_cast<mlir::SDBMExpr::ImplType *>(pointer));
  }
  static mlir::SDBMDirectExpr getTombstoneKey() {
    auto *pointer = llvm::DenseMapInfo<void *>::getTombstoneKey();
    return mlir::SDBMDirectExpr(
        static_cast<mlir::SDBMExpr::ImplType *>(pointer));
  }
  static unsigned getHashValue(mlir::SDBMDirectExpr expr) {
    return expr.hash_value();
  }
  static bool isEqual(mlir::SDBMDirectExpr lhs, mlir::SDBMDirectExpr rhs) {
    return lhs == rhs;
  }
};

// SDBMTermExpr hash just like pointers.
template <> struct DenseMapInfo<mlir::SDBMTermExpr> {
  static mlir::SDBMTermExpr getEmptyKey() {
    auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
    return mlir::SDBMTermExpr(static_cast<mlir::SDBMExpr::ImplType *>(pointer));
  }
  static mlir::SDBMTermExpr getTombstoneKey() {
    auto *pointer = llvm::DenseMapInfo<void *>::getTombstoneKey();
    return mlir::SDBMTermExpr(static_cast<mlir::SDBMExpr::ImplType *>(pointer));
  }
  static unsigned getHashValue(mlir::SDBMTermExpr expr) {
    return expr.hash_value();
  }
  static bool isEqual(mlir::SDBMTermExpr lhs, mlir::SDBMTermExpr rhs) {
    return lhs == rhs;
  }
};

// SDBMConstantExpr hash just like pointers.
template <> struct DenseMapInfo<mlir::SDBMConstantExpr> {
  static mlir::SDBMConstantExpr getEmptyKey() {
    auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
    return mlir::SDBMConstantExpr(
        static_cast<mlir::SDBMExpr::ImplType *>(pointer));
  }
  static mlir::SDBMConstantExpr getTombstoneKey() {
    auto *pointer = llvm::DenseMapInfo<void *>::getTombstoneKey();
    return mlir::SDBMConstantExpr(
        static_cast<mlir::SDBMExpr::ImplType *>(pointer));
  }
  static unsigned getHashValue(mlir::SDBMConstantExpr expr) {
    return expr.hash_value();
  }
  static bool isEqual(mlir::SDBMConstantExpr lhs, mlir::SDBMConstantExpr rhs) {
    return lhs == rhs;
  }
};
} // namespace llvm

#endif // MLIR_DIALECT_SDBM_SDBMEXPR_H


text:
require 'rails_helper'

RSpec.describe ActiveAdmin::Views::StatusTag do

  describe "#status_tag" do

    # Helper method to build StatusTag objects in an Arbre context
    def status_tag(*args)
      render_arbre_component(status_tag_args: args) do
        status_tag(*assigns[:status_tag_args])
      end
    end

    subject { status_tag(nil) }

    describe '#tag_name' do
      subject { super().tag_name }
      it      { is_expected.to eq 'span' }
    end

    describe '#class_list' do
      subject { super().class_list }
      it      { is_expected.to include('status_tag') }
    end

    context "when status is 'completed'" do
      subject { status_tag('completed') }

      describe '#tag_name' do
        subject { super().tag_name }
        it      { is_expected.to eq 'span' }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('status_tag') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('completed') }
      end

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq 'Completed' }
      end
    end

    context "when status is 'in_progress'" do
      subject { status_tag('in_progress') }

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('in_progress') }
      end

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq 'In Progress' }
      end
    end

    context "when status is 'In progress'" do
      subject { status_tag('In progress') }

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('in_progress') }
      end

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq 'In Progress' }
      end
    end

    context "when status is an empty string" do
      subject { status_tag('') }

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('status_tag') }
      end

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq '' }
      end
    end

    context "when status is 'false'" do
      subject { status_tag('false') }

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('status_tag') }
      end

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq('No') }
      end
    end

    context "when status is false" do
      subject { status_tag(false) }

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('status_tag') }
      end

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq('No') }
      end
    end

    context "when status is nil" do
      subject { status_tag(nil) }

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('status_tag') }
      end

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq('No') }
      end
    end

    context "when status is 'Active' and type is :ok" do
      subject { status_tag('Active', :ok) }

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('status_tag') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('active') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('ok') }
      end
    end

    context "when status is 'Active' and class is 'ok'" do
      subject { status_tag('Active', class: 'ok') }

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('status_tag') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('active') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('ok') }
      end
    end

    context "when status is 'Active' and label is 'on'" do
      subject { status_tag('Active', label: 'on') }

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq 'on' }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('status_tag') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('active') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.not_to include('on') }
      end
    end

    context "when status is 'So useless', type is :ok, class is 'woot awesome' and id is 'useless'" do
      subject { status_tag('So useless', :ok, class: 'woot awesome', id: 'useless') }

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq 'So Useless' }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('status_tag') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('ok') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('so_useless') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('woot') }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.to include('awesome') }
      end

      describe '#id' do
        subject { super().id }
        it      { is_expected.to eq 'useless' }
      end
    end

    context "when status is set to a Fixnum" do
      subject { status_tag(42) }

      describe '#content' do
        subject { super().content }
        it      { is_expected.to eq '42' }
      end

      describe '#class_list' do
        subject { super().class_list }
        it      { is_expected.not_to include('42') }
      end
    end
  end
end


text:
<?php

/**
 * @namespace
 */
namespace Zend\Search\Lucene\Search\Weight;
use Zend\Search\Lucene\Search\Query;
use Zend\Search\Lucene;

/**
 * @uses       \Zend\Search\Lucene\Search\Weight\AbstractWeight
 * @uses       \Zend\Search\Lucene\Search\Query\AbstractQuery
 * @uses       \Zend\Search\Lucene\SearchIndex
 * @category   Zend
 * @package    Zend_Search_Lucene
 * @subpackage Search
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class MultiTerm extends AbstractWeight
{
    /**
     * IndexReader.
     *
     * @var \Zend\Search\Lucene\SearchIndex
     */
    private $_reader;

    /**
     * The query that this concerns.
     *
     * @var \Zend\Search\Lucene\Search\Query\AbstractQuery
     */
    private $_query;

    /**
     * Query terms weights
     * Array of Zend_Search_Lucene_Search_Weight_Term
     *
     * @var array
     */
    private $_weights;

    /**
     * Zend_Search_Lucene_Search_Weight_MultiTerm constructor
     * query - the query that this concerns.
     * reader - index reader
     *
     * @param \Zend\Search\Lucene\Search\Query\AbstractQuery $query
     * @param \Zend\Search\Lucene\SearchIndex             $reader
     */
    public function __construct(Query\AbstractQuery $query, Lucene\SearchIndex $reader)
    {
        $this->_query   = $query;
        $this->_reader  = $reader;
        $this->_weights = array();

        $signs = $query->getSigns();

        foreach ($query->getTerms() as $id => $term) {
            if ($signs === null || $signs[$id] === null || $signs[$id]) {
                $this->_weights[$id] = new Term($term, $query, $reader);
                $query->setWeight($id, $this->_weights[$id]);
            }
        }
    }

    /**
     * The weight for this query
     * Standard Weight::$_value is not used for boolean queries
     *
     * @return float
     */
    public function getValue()
    {
        return $this->_query->getBoost();
    }

    /**
     * The sum of squared weights of contained query clauses.
     *
     * @return float
     */
    public function sumOfSquaredWeights()
    {
        $sum = 0;
        foreach ($this->_weights as $weight) {
            // sum sub weights
            $sum += $weight->sumOfSquaredWeights();
        }

        // boost each sub-weight
        $sum *= $this->_query->getBoost() * $this->_query->getBoost();

        // check for empty query (like '-something -another')
        if ($sum == 0) {
            $sum = 1.0;
        }
        return $sum;
    }

    /**
     * Assigns the query normalization factor to this.
     *
     * @param float $queryNorm
     */
    public function normalize($queryNorm)
    {
        // incorporate boost
        $queryNorm *= $this->_query->getBoost();

        foreach ($this->_weights as $weight) {
            $weight->normalize($queryNorm);
        }
    }
}


text:
module Mocha

  module ParameterMatchers

    # :call-seq: has_value(value) -> parameter_matcher
    #
    # Matches +Hash+ containing +value+.
    #   object = mock()
    #   object.expects(:method_1).with(has_value(1))
    #   object.method_1('key_1' => 1, 'key_2' => 2)
    #   # no error raised
    #
    #   object = mock()
    #   object.expects(:method_1).with(has_value(1))
    #   object.method_1('key_2' => 2)
    #   # error raised, because method_1 was not called with Hash containing value: 1
    def has_value(value)
      HasValue.new(value)
    end

    class HasValue # :nodoc:

      def initialize(value)
        @value = value
      end

      def ==(parameter)
        parameter.values.include?(@value)
      end

      def mocha_inspect
        "has_value(#{@value.mocha_inspect})"
      end

    end

  end

end


text:
import threading

class NyanUser:

    def __init__(self, id):
        self.id = id
        self.searches = 0
        self.banned = False

    def PerformedSearch(self):
        self.searches += 1

        # If they do a bunch of searches all at once, block them for half an hour.
        if self.searches >= 8:
            threading.Timer(1800.0, self.ResetSearches).start()
        # Otherwise, the search counter will decay 5 minutes after their search
        else:
            threading.Timer(600.0, self.DecrementSearches).start()

    def DecrementSearches(self):
        # We don't want to decrement if they've spammed so much that they're
        # temporarily blocked.
        if (self.searches > 0 and self.searches < 8):
            self.searches -= 1

    def ResetSearches(self):
        self.searches = 0


text:
//
//  JEFuture.h
//  JustPromises
//
//  Created by Marek Rogosz on 26/11/2014.
//  Copyright (c) 2014 JUST EAT. All rights reserved.
//

#import <Foundation/Foundation.h>

@class JEFuture;

typedef void (^JEContinuation)(JEFuture *fut);

typedef JEFuture* (^JETask)(JEFuture *fut);
typedef JEFuture* (^JESuccessTask)(id val);

typedef NS_ENUM(NSUInteger, JEFutureState) {
    JEFutureStateUnresolved = 0,
    JEFutureStateResolvedWithResult,
    JEFutureStateResolvedWithError,
    JEFutureStateResolvedWithCancellation
};

/**
 *  This class represents the future value of an asynchronous task.
 */
@interface JEFuture : NSObject

/**
 *  Handy factory methods.
 */
+ (instancetype)futureWithResult:(id)result;
+ (instancetype)futureWithError:(NSError *)error;
+ (instancetype)cancelledFuture;
+ (instancetype)futureWithResolutionOfFuture:(JEFuture *)src;

/**
 *  Check if the receiver is resolved.
 *
 *  @return YES if the future is resolved, NO otherwise.
 */
- (BOOL)isResolved;

/**
 *  This method returns the receiver state as an enumeration.
 *
 *  @return The future state enum.
 */
- (JEFutureState)state;

/**
 *  Check if the receiver has a result. You should call this method prior to call -result to avoid an undesired blocking call.
 *
 *  @return YES if the receiver has a result, NO otherwise.
 */
- (BOOL)hasResult;

/**
 *  Check if the receiver has an error. You should call this method prior to call -error to avoid an undesired blocking call.
 *
 *  @return YES if the receiver has an error, NO otherwise.
 */
- (BOOL)hasError;

/**
 *  Check if the receiver is cancelled.
 *
 *  @return YES if the receiver is cancelled, NO otherwise.
 */
- (BOOL)isCancelled;

/**
 *  Explicitly wait until the receiver is resolved.
 */
- (void)wait;

/**
 *  Explicitly wait with a timeout until the receiver is resolved.
 */
- (BOOL)waitUntilDate:(NSDate *)timeout;

/**
 *  This method hangs until the future is resolved.
 *
 *  @return The result of the receiver if it succeeded, nil otherwise.
 */
- (id)result;

/**
 *  This method hangs until the future is resolved.
 *
 *  @return The error of the receiver if it failed, nil otherwise.
 */
- (NSError *)error;

/**
 *  Set the continuation on the receiver. If the receiver is already resolved, the continuation block will execute immediately.
 *
 *  @param continuation The continuation block.
*/
- (void)setContinuation:(JEContinuation)continuation;

/**
 *  Set the continuation on the receiver executing it on a specific queue. If the receiver is already resolved, the continuation block will execute immediately.
 *
 *  @param queue        The queue on which the continuation block is executed.
 *  @param continuation The continuation block.
 */
- (void)onQueue:(dispatch_queue_t)queue setContinuation:(JEContinuation)continuation;

/**
 *  Set the continuation on the receiver providing a block and return the subsequent future.
 *  This method should be used for asynchronous operations that return a future straightaway.
 *
 *  @param task The task block.
 *
 *  @return The subsequent future.
 */
- (JEFuture *)continueWithTask:(JETask)task;

/**
 *  Set the continuation on the receiver providing a block and a queue and return the subsequent future.
 *  This method should be used for asynchronous operations that return a future straightaway.
 *
 *  @param queue The queue on which the task block is executed.
 *  @param task The task block
 *
 *  @return The subsequent future.
 */
- (JEFuture *)continueOnQueue:(dispatch_queue_t)queue withTask:(JETask)task;

/**
 *  Set the continuation on the receiver providing a block and return the subsequent future.
 *  This method should be used for asynchronous operations that return a future straightaway.
 *
 *  @param successTask The task block to execute for the continuation if the future passed in suceeded.
 *
 *  @return The subsequent future.
 */
- (JEFuture *)continueWithSuccessTask:(JESuccessTask)successTask;

/**
 *  Set the continuation on the receiver providing a block and a queue and return the subsequent future.
 *  This method should be used for asynchronous operations that return a future straightaway.
 *
 *  @param queue The queue on which the task block is executed.
 *  @param successTask The task block to execute for the continuation if the future passed in suceeded.
 *
 *  @return The subsequent future.
 */
- (JEFuture *)continueOnQueue:(dispatch_queue_t)queue withSuccessTask:(JESuccessTask)successTask;

/**
 *  Return a future that is resolved only when all the passed in futures are resolved.
 *  Once this method is called, it's not possible to add further continuations to the futures passed in.
 *
 *  @param futures The futures the received checks for resolution.
 *
 *  @return A future that is resolved only when all the futures passed in are resolved.
 */
+ (instancetype)whenAll:(NSArray *)futures;

@end

/**
 *  This class wraps a future object representing the future value of an asynchronous task.
 */
@interface JEPromise : NSObject

/**
 *  The future wrapped in the receiver.
 *
 *  @return The future.
 */
- (JEFuture *)future;

/**
 *  Make the wrapped future succeeded.
 *
 *  @param result The result.
 */
- (void)setResult:(id)result;

/**
 *  Make the wrapped future fail with an error.
 *
 *  @param error The error.
 */
- (void)setError:(NSError *)error;

/**
 *  Cancel the wrapped future.
 */
- (void)setCancelled;

/**
 *  Provides a future with the same resolution of the one passed as a parameter.
 *
 *  @param future The source future.
 */
- (void)setResolutionOfFuture:(JEFuture *)future;

@end


text:
project_path: /web/fundamentals/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: I gestori di input sono una potenziale causa di problemi di prestazioni nelle tue app poiché possono bloccare il completamento dei frame e possono causare lavori di layout aggiuntivi e non necessari.

{# wf_updated_on: 2017-12-07 #}
{# wf_published_on: 2015-03-20 #}

# Ridurre i rimbalzi dei gestori di input {: .page-title}

{% include "web/_shared/contributors/paullewis.html" %}

I gestori di input sono una potenziale causa di problemi di prestazioni nelle
tue app, poiché possono bloccare il completamento dei frame e possono causare
operazioni di layout aggiuntive non necessarie.

### TL;DR {: .hide-from-toc }

- Evita gestori di input a esecuzione prolungata; possono bloccare lo scrolling.
- Non apportare modifiche di stile nei gestori di input.
- Riduci i rimbalzi dei tuoi gestori; archivia i valori degli eventi e
gestisci le modifiche di stile nella richiesta callback successiva di
requestAnimationFrame.

## Evita gestori di input a esecuzione prolungata

Il caso più veloce possibile è quando un utente interagisce con la pagina.  Il
thread di composizione pagina può prendere l'input touch dell'utente e
semplicemente spostarne il contenuto. Ciò non richiede alcun intervento da parte
del thread principale dove vengono eseguiti JavaScript, layout, stili o paint.

Se tuttavia alleghi un gestore di input, come `touchstart` , `touchmove` o
`touchend` il thread di composizione deve attendere che questo gestore termini
l'esecuzione perché potresti voler chiamare `preventDefault()` e
interrompere lo scorrimento del tocco. Anche se non si chiama `preventDefault()`
il compositore deve attendere e pertanto lo scroll dell'utente viene bloccato, il
che può causare rallentamenti e frame persi.

In breve dovresti assicurarti che qualsiasi gestore di input esegui venga
elaborato rapidamente e consentire al compositore di svolgere il proprio lavoro.

## Evita i cambiamenti di stile nei gestori di input

I gestori di input come quelli per lo scroll e il touch sono programmati per
essere eseguiti prima di ogni callback `requestAnimationFrame`.

Se apporti una modifica visiva all'interno di uno di questi gestori all'inizio
della `requestAnimationFrame` ci saranno cambiamenti di stile in sospeso. Se
leggi *quindi* le proprietà visive all'inizio della callback
`requestAnimationFrame`, come suggerito in "[Evita layout grandi,
complessi e thrashing](avoid-large-complex-layouts-and-layout-thrashing) ",
attiverai una richiesta di layout sincrono forzato!

##  Riduci i rimbalzi dei gestori di scorrimento

La soluzione ad entrambi i problemi di cui sopra è la stessa: devi sempre
eseguire il rimbalzo delle modifiche visive alla prossima callback
`requestAnimationFrame`:

```
function onScroll (evt) {

  // Store the scroll value for laterz.
  lastScrollY = window.scrollY;

  // Prevent multiple rAF callbacks.
  if (scheduledAnimationFrame)
    return;

  scheduledAnimationFrame = true;
  requestAnimationFrame(readAndUpdatePage);
}

window.addEventListener('scroll', onScroll);
```

In questo modo hai anche il vantaggio di mantenere i gestori di input leggeri,
che è fantastico, perché non blocca attività come lo scrolling o
il touch di codice computazionalmente costoso!

Translated by
{% include "web/_shared/contributors/lucaberton.html" %}


text:
package "mailutils"

remote_file "/etc/postfix/main.cf"

service "postfix" do
  action :restart
end


text:
<?php
namespace qtil\Collection {
    use qtil;

    class Iterator implements \ArrayAccess,\Countable,\Iterator {
        use qtil\ArrayAccess,qtil\Countable,qtil\Iterator;

        function __construct(array $data = []) {
            $property = defined('static::$DOMAIN_PROPERTY') ? static::$DOMAIN_PROPERTY : 'data';

            $this->{$property} = $data;
        }
    }
}


text:
data = node[cookbook_name][recipe_name]

cookbook_file "#{data['wk_dir']}\\#{data['file']}" do
  source data['file']
end

data['paths'].each do |key, dir|
  powershell_script "#{key}_rcon" do
    architecture :x86_64
    cwd data['wk_dir']
    code <<-EOS
      Copy-Item -Force -Path .\\#{data['file']} -Destination #{dir}
    EOS
  end
end


text:
package org.aplikator.client.local.widgets.fileupload;

import org.gwtbootstrap3.client.ui.Icon;
import org.gwtbootstrap3.client.ui.constants.ButtonType;
import org.gwtbootstrap3.client.ui.constants.IconType;
import org.gwtbootstrap3.client.ui.constants.Styles;
import org.gwtbootstrap3.client.ui.html.Span;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;

/*
 * Copied from https://groups.google.com/forum/#!msg/gwtbootstrap3/3Yd5fxfEHYA/RF2CpbwToXsJ
 * USAGE

 FileInputButton one = new FileInputButton(ButtonType.PRIMARY, false);
 one.setText("Select ONE");
 one.setIcon(IconType.UPLOAD);

 FileInputButton two = new FileInputButton(ButtonType.DANGER, true);
 two.setIcon(IconType.PLUS);
 two.setText("Select MANY");

 InputGroup ig = new InputGroup();

 final TextBox tb = new TextBox();

 tb.setEnabled(false);

 FileInputButton three = new FileInputButton(ButtonType.DEFAULT, false);
 three.setText("Browse...");
 three.addValueChangeHandler(new ValueChangeHandler<JsArray<UploadFile>>() {

@Override
public void onValueChange(ValueChangeEvent<JsArray<UploadFile>> event) {

tb.setText("");

if( event.getValue() != null && event.getValue().length() > 0 ){

tb.setText(event.getValue().get(0).getName());

}

}

});

 ig.add(new FileInputGroupButton(three));
 ig.add(tb);

 RootPanel.get().add(one);
 RootPanel.get().add(two);
 RootPanel.get().add(ig);
 */

public class FileInputButton extends Composite implements HasValueChangeHandlers<JsArray<UploadFile>> {

    public interface FileInputButtonResources extends ClientBundle {
        public static final FileInputButtonResources INSTANCE = GWT.create(FileInputButtonResources.class);

        @Source("FileInputButton.css")
        public FileInputButtonCss css();
    }

    public interface FileInputButtonCss extends CssResource {
        @ClassName("btn-file")
        public String btnFile();

    }

    static {
        FileInputButtonResources.INSTANCE.css().ensureInjected();
    }

    private Span wrapper;

    private Span textSpan;

    private FileUpload upload;

    private Icon icon;

    public FileInputButton(boolean isMultiple) {

        this(null, isMultiple);

    }

    public FileInputButton(ButtonType additionalStyle, boolean isMultiple) {

        wrapper = new Span();

        wrapper.addStyleName(Styles.BTN);

        if (additionalStyle != null) {

            wrapper.addStyleName(additionalStyle.getCssName());

        }

        //wrapper.addStyleName("btn-file");
        wrapper.addStyleName(FileInputButtonResources.INSTANCE.css().btnFile());

        initWidget(wrapper);

        upload = new FileUpload();

        if (isMultiple) {

            upload.getElement().setPropertyBoolean("multiple", true);

        }

        upload.addChangeHandler(new ChangeHandler() {

            @Override

            public void onChange(ChangeEvent event) {

                fireChanged();

            }

        });

        wrapper.add(upload);

    }

    public void setText(String text) {

        if (textSpan == null) {

            textSpan = new Span(text);

            wrapper.add(textSpan);

        } else {

            textSpan.setText(text);

        }

    }

    public void setIcon(IconType type) {

        if (icon == null) {

            icon = new Icon(type);

            wrapper.add(icon);

        } else {

            icon.setType(type);

        }

    }

    private void fireChanged() {

        ValueChangeEvent.fire(this, getFiles(upload.getElement()));

    }

    private native JsArray<UploadFile> getFiles(Element el) /*-{

        if (el.files) {

            return el.files;

        } else {

            return null;

        }

    }-*/;

    @Override

    public HandlerRegistration addValueChangeHandler(ValueChangeHandler<JsArray<UploadFile>> handler) {

        return super.addHandler(handler, ValueChangeEvent.getType());

    }
}


text:
package com.qozix.tileview.paths;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;

import java.util.HashSet;

public class CompositePathView extends View {

  private static final int DEFAULT_STROKE_COLOR = 0xFF000000;
  private static final int DEFAULT_STROKE_WIDTH = 10;

  private float mScale = 1;

  private boolean mShouldDraw = true;

  private Path mRecyclerPath = new Path();
  private Matrix mMatrix = new Matrix();

  private HashSet<DrawablePath> mDrawablePaths = new HashSet<DrawablePath>();

  private Paint mDefaultPaint = new Paint();

  {
    mDefaultPaint.setStyle( Paint.Style.STROKE );
    mDefaultPaint.setColor( DEFAULT_STROKE_COLOR );
    mDefaultPaint.setStrokeWidth( DEFAULT_STROKE_WIDTH );
    mDefaultPaint.setAntiAlias( true );
  }

  public CompositePathView( Context context ) {
    super( context );
    setWillNotDraw( false );
  }

  public float getScale() {
    return mScale;
  }

  public void setScale( float scale ) {
    mScale = scale;
    mMatrix.setScale( mScale, mScale );
    invalidate();
  }

  public Paint getDefaultPaint() {
    return mDefaultPaint;
  }

  public DrawablePath addPath( Path path, Paint paint ) {
    if( paint == null ) {
      paint = mDefaultPaint;
    }
    DrawablePath DrawablePath = new DrawablePath();
    DrawablePath.path = path;
    DrawablePath.paint = paint;
    return addPath( DrawablePath );
  }

  public DrawablePath addPath( DrawablePath DrawablePath ) {
    mDrawablePaths.add( DrawablePath );
    invalidate();
    return DrawablePath;
  }

  public void removePath( DrawablePath path ) {
    mDrawablePaths.remove( path );
    invalidate();
  }

  public void clear() {
    mDrawablePaths.clear();
    invalidate();
  }

  public void setShouldDraw( boolean shouldDraw ) {
    mShouldDraw = shouldDraw;
    invalidate();
  }

  @Override
  public void onDraw( Canvas canvas ) {
    if( mShouldDraw ) {
      for( DrawablePath drawablePath : mDrawablePaths ) {
        mRecyclerPath.set( drawablePath.path );
        mRecyclerPath.transform( mMatrix );
        canvas.drawPath( mRecyclerPath, drawablePath.paint );
      }
    }
    super.onDraw( canvas );
  }

  public static class DrawablePath {

    /**
     * The path that this drawable will follow.
     */
    public Path path;

    /**
     * The paint to be used for this path.
     */
    public Paint paint;

  }
}


text:
FROM tomcat:7

RUN apt-get update && apt-get install -y wget maven default-jdk

# Build notifier and example webapp
ENV ROOT_SRC /tmp/sources
ENV WEBAPP $ROOT_SRC/examples/example-webapp

ADD sources $ROOT_SRC

RUN mvn clean package -DskipTests -f $ROOT_SRC/pom.xml -Denv.TRAVIS \
    && mvn clean package -DskipTests -f $WEBAPP/pom.xml -Denv.TRAVIS \
    && cp $WEBAPP/target/example-webapp*.war $CATALINA_HOME/webapps \
    && mkdir -p $CATALINA_HOME/conf/Catalina/localhost \
    && cp $WEBAPP/src/tomcat/context.xml $CATALINA_HOME/conf/Catalina/localhost/example-webapp.xml \
    && cp $ROOT_SRC/tomcat-notifier/target/tomcat-notifier*.jar $CATALINA_HOME/lib \
    && wget -P $CATALINA_HOME/lib http://search.maven.org/remotecontent?filepath=org/slf4j/slf4j-simple/1.7.12/slf4j-simple-1.7.12.jar

ADD .send-notification /root/.send-notification

# Clean up APT when done.
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*


text:
function selectedSiteId = siteDialog(siteId, siteDesc)
%SITEDIALOG Displays a dialog prompting the user to select a Site.
%
% The user is able to choose from a list of site IDs retrieved from the deployment database.
% When the user confirms the dialog, the selected site is returned.
% If the user cancels the dialog, the siteId return values will be empty.
%
% Inputs:
%
%   siteId    - a cell array of site IDs.
%
%   siteDesc  - a cell array of description for each site ID.
%
% Outputs:
%
%   selectedSiteId    - a string of the selected site ID.
%
% Author: Guillaume Galibert <guillaume.galibert@utas.edu.au>
%

%
% Copyright (C) 2017, Australian Ocean Data Network (AODN) and Integrated
% Marine Observing System (IMOS).
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation version 3 of the License.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.

% You should have received a copy of the GNU General Public License
% along with this program.
% If not, see <https://www.gnu.org/licenses/gpl-3.0.en.html>.
%
  narginchk(2,2);

  % generate site labels
  nSites = length(siteId);
  siteLabel = cell(1, nSites);
  for i=1:nSites
      siteLabel{i} = [siteId{i} ' (' siteDesc{i} ')'];
  end

  % currently selected site
  siteIdx = 1;
  selectedSiteId  = siteId{siteIdx};

  %% Dialog creation
  %

  % dialog figure
  f = figure('Name',        'Select Deployment Site', ...
             'Visible',     'off', ...
             'MenuBar',     'none', ...
             'Resize',      'off', ...
             'WindowStyle', 'Modal', ...
             'NumberTitle', 'off');

  % create the widgets
  fidLabel      = uicontrol('Style',  'text',...
                            'String', 'Site ID');
  fidList       = uicontrol('Style',  'listbox', 'Min', 1, 'Max', 1,...
                            'String', siteLabel,...
                            'Value',  siteIdx);
  cancelButton  = uicontrol('Style', 'pushbutton', 'String', 'Cancel');
  confirmButton = uicontrol('Style', 'pushbutton', 'String', 'Ok');

  % labels and text are aligned to the left
  set(fidLabel, 'HorizontalAlignment', 'Left');

  % use normalised coordinates
  set(f,                                'Units', 'normalized');
  set([fidLabel,fidList],               'Units', 'normalized');
  set([cancelButton, confirmButton],    'Units', 'normalized');

  % position the widgets
  set(f,               'Position', [0.2,  0.35,  0.6,   0.3]);
  set(cancelButton,    'Position', [0.0,  0.0,   0.5,   0.1]);
  set(confirmButton,   'Position', [0.5,  0.0,   0.5,   0.1]);
  set(fidLabel,        'Position', [0.0,  0.1,   0.2,   0.9]);
  set(fidList,         'Position', [0.2,  0.1,   0.8,   0.9]);

  % reset back to pixels
  set(f,                                'Units', 'pixels');
  set([fidLabel,fidList],               'Units', 'pixels');
  set([cancelButton, confirmButton],    'Units', 'pixels');

  % set widget callbacks
  set(f,               'CloseRequestFcn', @cancelCallback);
  set(fidList,         'Callback',        @fidMenuCallback);
  set(cancelButton,    'Callback',        @cancelCallback);
  set(confirmButton,   'Callback',        @confirmCallback);

  % user can hit escape to quit dialog
  set(f, 'WindowKeyPressFcn', @keyPressCallback);

  % display the dialog and wait for user input
  uicontrol(fidList);
  set(f, 'Visible', 'on');
  uiwait(f);

  %% Callback functions
  %

  function keyPressCallback(source,ev)
  %KEYPRESSCALLBACK If the user pushes escape/return while the dialog has
  % focus, the dialog is cancelled/confirmed. This is done by delegating
  % to the cancelCallback/confirmCallback functions.
  %
    if     strcmp(ev.Key, 'escape'), cancelCallback( source,ev);
    elseif strcmp(ev.Key, 'return'), confirmCallback(source,ev);
    end
  end

  function fidMenuCallback(source,ev)
  % FIDMENUCALLBACK site ID popup menu callback. Saves the currently
  % selected site ID.
  %
    siteIdx = get(fidList, 'Value');
    selectedSiteId  = siteId{siteIdx};
  end

  function cancelCallback(source,ev)
  %CANCELCALLBACK Cancel button callback. Discards user input and closes the
  % dialog .
  %
    selectedSiteId = [];
    delete(f);
  end

  function confirmCallback(source,ev)
  % CONFIRMCALLBACK. Confirm button callback. Closes the dialog.
  %
    delete(f);
  end

  %% Input processing
  %

  % if user cancelled, return empty matrices
  if isempty(selectedSiteId), return; end

end


text:
<script type="text/javascript">

    Ext4.onReady(function(){
        var webpart = <%=webpartContext%>;
        Ext4.create('EHR_Billing.panel.DomainSettingsPanel', {
            moduleName: 'wnprc_billing'
        }).render(webpart.wrapperDivId);
    });

</script>


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/latter-day-figures/bennett-frances-marion-grant-1899-1995" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/bennett-frances-marion-grant-1899-1995</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Bennett, Frances Marion Grant 1899-1995</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/bennett-frances-marion-grant-1899-1995</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/bennett-frances-marion-grant-1899-1995</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
            <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbar-collapse">

            </button>
            Homepage

                    Logout

                    Login


text:
//
//  Player.h
//  CowboyScene
//
//  Created by NiTe Luo on 10/17/13.
//
//

#ifndef __CowboyScene__Player__
#define __CowboyScene__Player__

#include "cocos2d.h"
#include "cocos-ext.h"

USING_NS_CC;
USING_NS_CC_EXT;
using namespace std;

#define WALK_SPEED 10
#define WALK_LEFT 1
#define WALK_RIGHT -1

enum PlayerState {
    IDLE = 0,
    WALK,
    SHOOT,
    GRENADE
    };

class Player : public CCObject
{
    CCNode* playerNode;
    CCArmatureAnimation* animation;
    PlayerState currentState;
    PlayerState newState;
    int direction;
    bool lockState;

    void onAnimationEvent(CCArmature *pArmature, MovementEventType eventType, const char *animationID);

public:
    Player(CCNode* node);
    void update(float dt);
    void updateAnimation();
    void updateMovement();
    void play(string animName);
    bool isLockState();

    inline void setState(PlayerState state) {newState = state;}
    void setDirection(int newDirection);
};

#endif /* defined(__CowboyScene__Player__) */


text:
public class OverrideGetName {

    // Overrides the default getName class method, which causes TypeError
    // when OverrideGetName.getName() is called on Jython.
    public String getName() {
	return "xxx";
    }

    public void doNothing() {
    }
}


text:
/* global Log, Class, Loader, Class , MM */
/* exported Module */

/* Magic Mirror
 * Module Blueprint.
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

var Module = Class.extend({

	/*********************************************************
	 * All methods (and properties) below can be subclassed. *
	 *********************************************************/

	// Set the minimum MagicMirror module version for this module.
	requiresVersion: "2.0.0",

	// Module config defaults.
	defaults: {},

	// Timer reference used for showHide animation callbacks.
	showHideTimer: null,

	// Array to store lockStrings. These strings are used to lock
	// visibility when hiding and showing module.
	lockStrings: [],

	/* init()
	 * Is called when the module is instantiated.
	 */
	init: function () {
		//Log.log(this.defaults);
	},

	/* start()
	 * Is called when the module is started.
	 */
	start: function () {
		Log.info("Starting module: " + this.name);
	},

	/* getScripts()
	 * Returns a list of scripts the module requires to be loaded.
	 *
	 * return Array<String> - An array with filenames.
	 */
	getScripts: function () {
		return [];
	},

	/* getStyles()
	 * Returns a list of stylesheets the module requires to be loaded.
	 *
	 * return Array<String> - An array with filenames.
	 */
	getStyles: function () {
		return [];
	},

	/* getTranslations()
	 * Returns a map of translation files the module requires to be loaded.
	 *
	 * return Map<String, String> - A map with langKeys and filenames.
	 */
	getTranslations: function () {
		return false;
	},

	/* getDom()
	 * This method generates the dom which needs to be displayed. This method is called by the Magic Mirror core.
	 * This method needs to be subclassed if the module wants to display info on the mirror.
	 *
	 * return domobject - The dom to display.
	 */
	getDom: function () {
		var nameWrapper = document.createElement("div");
		var name = document.createTextNode(this.name);
		nameWrapper.appendChild(name);

		var identifierWrapper = document.createElement("div");
		var identifier = document.createTextNode(this.identifier);
		identifierWrapper.appendChild(identifier);
		identifierWrapper.className = "small dimmed";

		var div = document.createElement("div");
		div.appendChild(nameWrapper);
		div.appendChild(identifierWrapper);

		return div;
	},

	/* getHeader()
	 * This method generates the header string which needs to be displayed if a user has a header configured for this module.
	 * This method is called by the Magic Mirror core, but only if the user has configured a default header for the module.
	 * This method needs to be subclassed if the module wants to display modified headers on the mirror.
	 *
	 * return string - The header to display above the header.
	 */
	getHeader: function () {
		return this.data.header;
	},

	/* notificationReceived(notification, payload, sender)
	 * This method is called when a notification arrives.
	 * This method is called by the Magic Mirror core.
	 *
	 * argument notification string - The identifier of the notification.
	 * argument payload mixed - The payload of the notification.
	 * argument sender Module - The module that sent the notification.
	 */
	notificationReceived: function (notification, payload, sender) {
		if (sender) {
			Log.log(this.name + " received a module notification: " + notification + " from sender: " + sender.name);
		} else {
			Log.log(this.name + " received a system notification: " + notification);
		}
	},

	/* socketNotificationReceived(notification, payload)
	 * This method is called when a socket notification arrives.
	 *
	 * argument notification string - The identifier of the notification.
	 * argument payload mixed - The payload of the notification.
	 */
	socketNotificationReceived: function (notification, payload) {
		Log.log(this.name + " received a socket notification: " + notification + " - Payload: " + payload);
	},

	/* suspend()
	 * This method is called when a module is hidden.
	 */
	suspend: function () {
		Log.log(this.name + " is suspended.");
	},

	/* resume()
	 * This method is called when a module is shown.
	 */
	resume: function () {
		Log.log(this.name + " is resumed.");
	},

	/*********************************************
	 * The methods below don"t need subclassing. *
	 *********************************************/

	/* setData(data)
	 * Set the module data.
	 *
	 * argument data obejct - Module data.
	 */
	setData: function (data) {
		this.data = data;
		this.name = data.name;
		this.identifier = data.identifier;
		this.hidden = false;

		this.setConfig(data.config);
	},

	/* setConfig(config)
	 * Set the module config and combine it with the module defaults.
	 *
	 * argument config obejct - Module config.
	 */
	setConfig: function (config) {
		this.config = Object.assign({}, this.defaults, config);
	},

	/* socket()
	 * Returns a socket object. If it doesn"t exist, it"s created.
	 * It also registers the notification callback.
	 */
	socket: function () {
		if (typeof this._socket === "undefined") {
			this._socket = this._socket = new MMSocket(this.name);
		}

		var self = this;
		this._socket.setNotificationCallback(function (notification, payload) {
			self.socketNotificationReceived(notification, payload);
		});

		return this._socket;
	},

	/* file(file)
	 * Retrieve the path to a module file.
	 *
	 * argument file string - Filename.
	 *
	 * return string - File path.
	 */
	file: function (file) {
		return this.data.path + "/" + file;
	},

	/* loadStyles()
	 * Load all required stylesheets by requesting the MM object to load the files.
	 *
	 * argument callback function - Function called when done.
	 */
	loadStyles: function (callback) {
		this.loadDependencies("getStyles", callback);
	},

	/* loadScripts()
	 * Load all required scripts by requesting the MM object to load the files.
	 *
	 * argument callback function - Function called when done.
	 */
	loadScripts: function (callback) {
		this.loadDependencies("getScripts", callback);
	},

	/* loadDependencies(funcName, callback)
	 * Helper method to load all dependencies.
	 *
	 * argument funcName string - Function name to call to get scripts or styles.
	 * argument callback function - Function called when done.
	 */
	loadDependencies: function (funcName, callback) {
		var self = this;
		var dependencies = this[funcName]();

		var loadNextDependency = function () {
			if (dependencies.length > 0) {
				var nextDependency = dependencies[0];
				Loader.loadFile(nextDependency, self, function () {
					dependencies = dependencies.slice(1);
					loadNextDependency();
				});
			} else {
				callback();
			}
		};

		loadNextDependency();
	},

	/* loadScripts()
	 * Load all required scripts by requesting the MM object to load the files.
	 *
	 * argument callback function - Function called when done.
	 */
	loadTranslations: function (callback) {
		var self = this;
		var translations = this.getTranslations();
		var lang = config.language.toLowerCase();

		// The variable `first` will contain the first
		// defined translation after the following line.
		for (var first in translations) { break; }

		if (translations) {
			var translationFile = translations[lang] || undefined;
			var translationsFallbackFile = translations[first];

			// If a translation file is set, load it and then also load the fallback translation file.
			// Otherwise only load the fallback translation file.
			if (translationFile !== undefined && translationFile !== translationsFallbackFile) {
				Translator.load(self, translationFile, false, function () {
					Translator.load(self, translationsFallbackFile, true, callback);
				});
			} else {
				Translator.load(self, translationsFallbackFile, true, callback);
			}
		} else {
			callback();
		}
	},

	/* translate(key, defaultValue)
	 * Request the translation for a given key.
	 *
	 * argument key string - The key of the string to translage
   * argument defaultValue string - The default value if no translation was found. (Optional)
	 */
	translate: function (key, defaultValue) {
		return Translator.translate(this, key) || defaultValue || "";
	},

	/* updateDom(speed)
	 * Request an (animated) update of the module.
	 *
	 * argument speed Number - The speed of the animation. (Optional)
	 */
	updateDom: function (speed) {
		MM.updateDom(this, speed);
	},

	/* sendNotification(notification, payload)
	 * Send a notification to all modules.
	 *
	 * argument notification string - The identifier of the notification.
	 * argument payload mixed - The payload of the notification.
	 */
	sendNotification: function (notification, payload) {
		MM.sendNotification(notification, payload, this);
	},

	/* sendSocketNotification(notification, payload)
	 * Send a socket notification to the node helper.
	 *
	 * argument notification string - The identifier of the notification.
	 * argument payload mixed - The payload of the notification.
	 */
	sendSocketNotification: function (notification, payload) {
		this.socket().sendNotification(notification, payload);
	},

	/* hideModule(module, speed, callback)
	 * Hide this module.
	 *
	 * argument speed Number - The speed of the hide animation.
	 * argument callback function - Called when the animation is done.
	 * argument options object - Optional settings for the hide method.
	 */
	hide: function (speed, callback, options) {
		if (typeof callback === "object") {
			options = callback;
			callback = function () { };
		}

		callback = callback || function () { };
		options = options || {};

		var self = this;
		MM.hideModule(self, speed, function () {
			self.suspend();
			callback();
		}, options);
	},

	/* showModule(module, speed, callback)
	 * Show this module.
	 *
	 * argument speed Number - The speed of the show animation.
	 * argument callback function - Called when the animation is done.
	 * argument options object - Optional settings for the hide method.
	 */
	show: function (speed, callback, options) {
		if (typeof callback === "object") {
			options = callback;
			callback = function () { };
		}

		callback = callback || function () { };
		options = options || {};

		this.resume();
		MM.showModule(this, speed, callback, options);
	}
});

Module.definitions = {};

Module.create = function (name) {

	// Make sure module definition is available.
	if (!Module.definitions[name]) {
		return;
	}

	var moduleDefinition = Module.definitions[name];
	var clonedDefinition = cloneObject(moduleDefinition);

	// Note that we clone the definition. Otherwise the objects are shared, which gives problems.
	var ModuleClass = Module.extend(clonedDefinition);

	return new ModuleClass();

};

/* cmpVersions(a,b)
* Compare two symantic version numbers and return the difference.
*
* argument a string - Version number a.
* argument a string - Version number b.
*/
function cmpVersions(a, b) {
	var i, diff;
	var regExStrip0 = /(\.0+)+$/;
	var segmentsA = a.replace(regExStrip0, "").split(".");
	var segmentsB = b.replace(regExStrip0, "").split(".");
	var l = Math.min(segmentsA.length, segmentsB.length);

	for (i = 0; i < l; i++) {
		diff = parseInt(segmentsA[i], 10) - parseInt(segmentsB[i], 10);
		if (diff) {
			return diff;
		}
	}
	return segmentsA.length - segmentsB.length;
}

Module.register = function (name, moduleDefinition) {

	if (moduleDefinition.requiresVersion) {
		Log.log("Check MagicMirror version for module '" + name + "' - Minimum version:  " + moduleDefinition.requiresVersion + " - Current version: " + version);
		if (cmpVersions(version, moduleDefinition.requiresVersion) >= 0) {
			Log.log("Version is ok!");
		} else {
			Log.log("Version is incorrect. Skip module: '" + name + "'");
			return;
		}
	}
	Log.log("Module registered: " + name);
	Module.definitions[name] = moduleDefinition;
};

if (typeof exports != "undefined") { // For testing purpose only
	// A good a idea move the function cmpversions a helper file.
	// It's used into other side.
	exports._test = {
		cmpVersions: cmpVersions
	}
}


text:
sensor_temp = require("sensor_temp")

sensor_temp.getTemps(1)

tmr.alarm(tmr.create(), 1000, tmr.ALARM_AUTO, function()
    sensor_temp.getTemps(1)

    for _sensorID, temp in pairs(temps) do
        print(">> " .. temp .. " C")
    end
end)


text:
using namespace std;

#include "Train.hpp"
using namespace Train;
using namespace Train::Font;

int main(int argc, char * const *argv)
{
	bool verbose = false;
	string file, action;

	Command cmd;
	cmd.description("An Example of Train command line args parser.");
	cmd.footer(("Visit ") + "http://libtrain.org/"_CYA + " for more information!");

	cmd << "Options:";
	cmd << Flags::Help;
	cmd << Option(verbose, "-v, --verbose", "Produce verbose output.");
	cmd << Option(file, "-f, --file PATH", "Perfom action on specified file.");

	cmd << "\nCommands:";
	cmd << Command(action, "read", "Read from the file.");
	cmd << Command(action, "write", "Print something to the file.");

	cmd.parse(argc, argv);

	cout << "verbose: " << boolalpha << verbose << endl;
	cout << "command: " << action << " " << file << endl;

	return 0;
}


text:
namespace network {
namespace {

template <typename MojoType, typename NativeType>
bool SerializeAndDeserializeEnum(NativeType in, NativeType* out) {
  MojoType intermediate = mojo::EnumTraits<MojoType, NativeType>::ToMojom(in);
  return mojo::EnumTraits<MojoType, NativeType>::FromMojom(intermediate, out);
}

TEST(DefaultCredentialsTraitsTest, Roundtrips_DefaultCredentials) {
  for (net::HttpAuthPreferences::DefaultCredentials default_credentials :
       {net::HttpAuthPreferences::ALLOW_DEFAULT_CREDENTIALS,
        net::HttpAuthPreferences::DISALLOW_DEFAULT_CREDENTIALS}) {
    net::HttpAuthPreferences::DefaultCredentials roundtrip;
    ASSERT_TRUE(SerializeAndDeserializeEnum<mojom::DefaultCredentials>(
        default_credentials, &roundtrip));
    EXPECT_EQ(default_credentials, roundtrip);
  }
}

}  // namespace
}  // namespace network