text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>NounClass</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

NounClass: noun class

  Values:
  Bantu1
  Bantu2
  Bantu3
  Bantu4
  Bantu5
  Bantu6
  Bantu7
  Bantu8
  Bantu9
  Bantu10

  Bantu11
  Bantu12
  Bantu13
  Bantu14
  Bantu15
  Bantu16
  Bantu17
  Bantu18
  Bantu19
  Bantu20

  Bantu21
  Bantu22
  Bantu23

  Wol1
  Wol2
  Wol3
  Wol4
  Wol5
  Wol6
  Wol7
  Wol8
  Wol9
  Wol10

  Wol11
  Wol12

NounClass is similar to Gender and Animacy because it is to a large part
a lexical category of nouns and other parts of speech inflect for it
to show agreement (pronouns, adjectives,
determiners, numerals, verbs).

The distinction between gender and noun class is not sharp and is partially
conditioned by the traditional terminology of a given language family. In general,
the feature is called gender if the number of possible values is relatively low
(typically 2-4) and the partition correlates with sex of people and animals.
In language families where the number of categories is high (10-20), the feature
is usually called noun class. No language family uses both the features.

In Bantu languages, the noun class also encodes Number; therefore it is
a lexical-inflectional feature of nouns. The words should be annotated with
the Number feature in addition to NounClass, despite the fact that people
who know Bantu could infer the number from the noun class. The lemma of the
noun should be its singular form.

The set of values of this feature is specific for a language family or group.
Within the group, it is possible to identify classes that have similar meaning
across languages (although some classes may have merged or disappeared in
some languages in the group). The value of the NounClass feature consists
of a short identifier of the language group (e.g., Bantu), and the number
of the class (there is a standardized class numbering system accepted by
scholars of the various Bantu languages; similar numbering systems should be
created for the other families that have noun classes).

List of noun classes in Swahili

(from https://en.wikipedia.org/wiki/Noun_class)

Class number
Prefix
Typical meaning

1
m-, mw-, mu-
singular: persons

2
wa-, w-
plural: persons (a plural counterpart of class 1)

3
m-, mw-, mu-
singular: plants

4
mi-, my-
plural: plants (a plural counterpart of class 3)

5
ji-, j-, Ø-
singular: fruits

6
ma-, m-
plural: fruits (a plural counterpart of class 5, 9, 11, seldom 1)

7
ki-, ch-
singular: things

8
vi-, vy-
plural: things (a plural counterpart of class 7)

9
n-, ny-, m-, Ø-
singular: animals, things

10
n-, ny-, m-, Ø-
plural: animals, things (a plural counterpart of class 9 and 11)

11
u-, w-, uw-
singular: no clear semantics

15
ku-, kw-
verbal nouns

16
pa-
locative meanings: close to something

17
ku-
indefinite locative or directive meaning

18
mu-, m-
locative meanings: inside something

Bantu1: singular, persons

The corresponding plural class is Bantu2.

Examples

[sw] mtoto "child"

Bantu2: plural, persons

The corresponding singular class is Bantu1.

Examples

[sw] watoto "children"

Bantu3: singular, plants, thin objects

The corresponding plural class is Bantu4.

Examples

[sw] mti "tree"

Bantu4: plural, plants, thin objects

The corresponding singular class is Bantu3.

Examples

[sw] miti "trees"

Bantu5: singular, fruits, round objects, paired things

The corresponding plural class is Bantu6.

Examples

[sw] jiwe "stone"

Bantu6: plural, fruits, round objects, paired things

The corresponding singular class is Bantu5, also Bantu9, Bantu11, seldomly Bantu1.

Examples

[sw] mawe "stones"

Bantu7: singular, things, diminutives

The corresponding plural class is Bantu8.

Examples

[sw] kitabu "book"

Bantu8: plural, things, diminutives

The corresponding singular class is Bantu7.

Examples

[sw] vitabu "books"

Bantu9: singular, animals, things

The corresponding plural class is Bantu10 or Bantu6.

Examples

[sw] ndege "bird"

Bantu10: plural, animals, things

The corresponding singular class is Bantu9.

Examples

[sw] ndege "birds" (plural of the noun is identical to singular; however, verbs agree with the zi- prefix in plural and with i- in singular)

Bantu11: long thin objects, natural phenomena, abstracts

Examples

[sw] utoto "childhood"

Bantu12: singular, small things, diminutives

The corresponding plural class is Bantu13 or Bantu14.

Examples

[lg] embwa "dog" → akabwa "puppy"

Bantu13: plural or mass, small amount of mass

Examples

[lg] mazzi "water" → otuzzi "drop of water"

Bantu14: plural, diminutives

In Ganda, this is the plural counterpart of Bantu12.

Examples

[lg] obubwa "puppies"

Bantu15: verbal nouns, infinitives

Examples

[sw] -soma "read" → kusoma "reading; to read"

Bantu16: definite location, close to something

Examples

[sw] pahali "place"

Bantu17: indefinite location, direction, movement

Examples

[sw] kule "there"

Bantu18: definite location, inside something

Examples

[sw] mule "in there"

Bantu19: little bit of, pejorative plural

Bantu class 19 may signify "a little bit of" or a plural with a pejorative nuance, as in Hunde.

Examples

[hke] hyùndù "a bit of porridge"

[hke] hìkátsì "frail females"

[hke] hyábánà "thin children"

Bantu20: singular, augmentatives

In Ganda, the corresponding plural class is Bantu6 or Bantu22.

Examples

[lg] musajja "man" → ogusajja "giant"

Bantu21: singular, augmentatives, derogatives

Examples

[ve] ḓinga "large lump of earth"

[ve] ḓanḓa "big clumsy hand"

Bantu22: plural, augmentatives

The corresponding singular class is Bantu20.

Examples

[lg] agasajja "giants"

Bantu23: location with place names

Examples

[lg] elugala "at Lugala"

Noun Classes in Wolof

Wolof is a non-Bantu Niger-Congo language. It has noun classes but their semantics
cannot be easily mapped on the Bantu classes. The class is morphologically unmarked
on nouns (although it is an inherent property of the lexeme) but determiners have
to show agreement with the class.

The Wolof noun class system lacks semantic coherence. One reason for this is that
in Wolof noun classification is sometimes based on other factors than semantics,
including phonology and morphology. And still these are just some tendencies, but in
most cases there is no clear semantics, phonology or morphology that can explain the
classification in Wolof.

Examples

The following table shows the forms of proximate demonstratives in the first ten noun classes;
classes 2 and 8 are plural, the rest are singular.

<tt>Wol1</tt>	<tt>Wol2</tt>	<tt>Wol3</tt>	<tt>Wol4</tt>	<tt>Wol5</tt>	<tt>Wol6</tt>	<tt>Wol7</tt>	<tt>Wol8</tt>	<tt>Wol9</tt>	<tt>Wol10</tt>	English

ki		gi	ji	bi	mi	li		si	wi	"this"

	ñi						yi			"these"

Wolof classes 11 and 12, although behaving like noun classes, have meanings that are adverbial rather than nominal:
class 11 is for location, class 12 for manner.

<tt>Wol11</tt>	<tt>Wol12</tt>

fi "here"	ni "so"

Wol1: Wolof noun class 1/k (singular human)

Examples

[wo] nitug Afrig ki

Wol2: Wolof noun class 2/ñ (plural human)

Examples

[wo] jigéen ñi

Wol3: Wolof noun class 3/g (singular)

Examples

[wo] dexug Gaambi gi

Wol4: Wolof noun class 4/j (singular)

Examples

[wo] jenn jamono ji

Wol5: Wolof noun class 5/b (singular)

For example, "dog" is in the b class.

Examples

[wo] xaj bi "this dog" (dog class-DEF.PROX)

[wo] xaj ba "that dog" (dog class-DEF.REMT)

[wo] buur bi

Wol6: Wolof noun class 6/m (singular)

For example, "sheep" is in the m class.

Examples

[wo] xar mi "this sheep" (sheep class-DEF.PROX)

[wo] at mi

Wol7: Wolof noun class 7/l (singular)

Examples

[wo] ndongo li

Wol8: Wolof noun class 8/y (plural non-human)

Examples

[wo] nguur yii

Wol9: Wolof noun class 9/s (singular)

Examples

[wo] sàmm si

Wol10: Wolof noun class 10/w (singular)

Examples

[wo] sama nag wa

Wol11: Wolof noun class 11/f (location)

Examples

[wo] fi "here"

[wo] fa "there"

Wol12: Wolof noun class 12/n (manner)

Examples

[wo] ni "so"

NounClass in other languages:

[u]

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
<?php

namespace cs\modules\Precincts;

use cs\Page;

$Page       = Page::instance();
$Violations = Violations::instance();
$number     = isset($_GET['number']) ? min((int)$_GET['number'], 100) : 10;
$number     = max($number, 0);
$last_id    = isset($_GET['last_id']) ? max((int)$_GET['last_id'], 0) : 0;
$search     = isset($_GET['search']) ? $_GET['search'] : '';
$Page->json(
	$Violations->last_violations($number, $last_id, $search) ?: []
);
header('Cache-Control: max-age=30, public');
header('Expires: access plus 30 seconds');

redpajama_set_name: RedPajamaGithub


text:
import { ViveController } from 'three_examples/vr/ViveController';

export default class ViveControls {
  constructor(body) {
    this.body = body;
    this.controller1 = new ViveController(0);
    this.controller2 = new ViveController(1);
    this.state = {
      forwards: false,
      backwards: false,
    };
    this.movementSpeed = 10.0;

    this.onRightTriggerDown = this.onRightTriggerDown.bind(this);
    this.onRightTriggerUp = this.onRightTriggerUp.bind(this);
    this.onLeftTriggerDown = this.onLeftTriggerDown.bind(this);
    this.onLeftTriggerUp = this.onLeftTriggerUp.bind(this);
  }

  onRightTriggerDown() {
    this.state.forwards = true;
  }
  onRightTriggerUp() {
    this.state.forwards = false;
  }
  onLeftTriggerDown() {
    this.state.backwards = true;
  }
  onLeftTriggerUp() {
    this.state.backwards = false;
  }

  connect() {
    this.controller1.addEventListener('triggerdown', this.onRightTriggerDown);
    this.controller1.addEventListener('triggerup', this.onRightTriggerUp);
    this.controller2.addEventListener('triggerdown', this.onLeftTriggerDown);
    this.controller2.addEventListener('triggerup', this.onLeftTriggerUp);
  }

  disconnect() {
    this.controller1.removeEventListener('triggerdown', this.onRightTriggerDown);
    this.controller1.removeEventListener('triggerup', this.onRightTriggerUp);
    this.controller2.removeEventListener('triggerdown', this.onLeftTriggerDown);
    this.controller2.removeEventListener('triggerup', this.onLeftTriggerUp);
  }

  update(delta) {
    this.controller1.update();
    this.controller2.update();

    const movement = this.movementSpeed * delta;
    if (this.state.forwards !== this.state.backwards) {
      const direction = this.body.camera.getWorldDirection();
      direction.normalize();
      direction.multiplyScalar(movement);

      if (this.state.backwards) {
        direction.multiplyScalar(-1);
      }
      this.body.position.add(direction);
    }
  }
}


text:
package org.apache.hyracks.tests.unit;

import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.dataflow.std.sort.AbstractSortRunGenerator;
import org.apache.hyracks.dataflow.std.sort.Algorithm;
import org.apache.hyracks.dataflow.std.sort.ExternalSortRunGenerator;

public class ExternalSortRunGeneratorTest extends AbstractRunGeneratorTest {

    @Override
    AbstractSortRunGenerator getSortRunGenerator(IHyracksTaskContext ctx, int frameLimit, int numOfInputRecord)
            throws HyracksDataException {
        return new ExternalSortRunGenerator(ctx, SortFields, null, ComparatorFactories, RecordDesc,
                Algorithm.MERGE_SORT, frameLimit);
    }
}


text:
using log4net;
using Microsoft.Practices.Prism.Logging;

namespace Smellyriver.TankInspector.Pro
{
    class Log4NetLogger : ILoggerFacade
    {

        private readonly ILog m_Logger = SafeLog.GetLogger("Prism");

        public void Log(string message, Category category, Priority priority)
        {
            switch (category)
            {
                case Category.Debug:
                    m_Logger.Debug(message);
                    break;
                case Category.Warn:
                    m_Logger.Warn(message);
                    break;
                case Category.Exception:
                    m_Logger.Error(message);
                    break;
                case Category.Info:
                    m_Logger.Info(message);
                    break;
            }
        }

    }
}


text:
Russia (``ru``)
===============

Forms
-----

.. automodule:: localflavor.ru.forms
    :members:

Data
----

.. autodata:: localflavor.ru.ru_regions.RU_COUNTY_CHOICES

.. autodata:: localflavor.ru.ru_regions.RU_REGIONS_CHOICES


text:
using content::BrowserThread;

namespace extensions {
namespace {

SkBitmap CreateBlankBitmapForScale(int size_dip, ui::ScaleFactor scale_factor) {
  SkBitmap bitmap;
  const float scale = ui::GetScaleForScaleFactor(scale_factor);
  bitmap.allocN32Pixels(static_cast<int>(size_dip * scale),
                        static_cast<int>(size_dip * scale));
  bitmap.eraseColor(SkColorSetARGB(0, 0, 0, 0));
  return bitmap;
}

SkBitmap EnsureBitmapSize(const SkBitmap& original, int size) {
  if (original.width() == size && original.height() == size)
    return original;

  SkBitmap resized = skia::ImageOperations::Resize(
      original, skia::ImageOperations::RESIZE_LANCZOS3, size, size);
  return resized;
}

// Used to test behavior including images defined by an image skia source.
// |GetImageForScale| simply returns image representation from the image given
// in the ctor.
class MockImageSkiaSource : public gfx::ImageSkiaSource {
 public:
  explicit MockImageSkiaSource(const gfx::ImageSkia& image)
      : image_(image) {
  }
  ~MockImageSkiaSource() override {}

  gfx::ImageSkiaRep GetImageForScale(float scale) override {
    return image_.GetRepresentation(scale);
  }

 private:
  gfx::ImageSkia image_;
};

class ExtensionIconImageTest : public ExtensionsTest,
                               public IconImage::Observer {
 public:
  ExtensionIconImageTest()
      : image_loaded_count_(0),
        quit_in_image_loaded_(false),
        ui_thread_(BrowserThread::UI, &ui_loop_),
        file_thread_(BrowserThread::FILE),
        io_thread_(BrowserThread::IO),
        notification_service_(content::NotificationService::Create()) {}

  ~ExtensionIconImageTest() override {}

  void WaitForImageLoad() {
    quit_in_image_loaded_ = true;
    base::MessageLoop::current()->Run();
    quit_in_image_loaded_ = false;
  }

  int ImageLoadedCount() {
    int result = image_loaded_count_;
    image_loaded_count_ = 0;
    return result;
  }

  scoped_refptr<Extension> CreateExtension(const char* name,
                                           Manifest::Location location) {
    // Create and load an extension.
    base::FilePath test_file;
    if (!PathService::Get(DIR_TEST_DATA, &test_file)) {
      EXPECT_FALSE(true);
      return NULL;
    }
    test_file = test_file.AppendASCII(name);
    int error_code = 0;
    std::string error;
    JSONFileValueDeserializer deserializer(
        test_file.AppendASCII("manifest.json"));
    scoped_ptr<base::DictionaryValue> valid_value = base::DictionaryValue::From(
        deserializer.Deserialize(&error_code, &error));
    EXPECT_EQ(0, error_code) << error;
    if (error_code != 0)
      return NULL;

    EXPECT_TRUE(valid_value.get());
    if (!valid_value)
      return NULL;

    return Extension::Create(test_file, location, *valid_value,
                             Extension::NO_FLAGS, &error);
  }

  // testing::Test overrides:
  void SetUp() override {
    file_thread_.Start();
    io_thread_.Start();
  }

  // IconImage::Delegate overrides:
  void OnExtensionIconImageChanged(IconImage* image) override {
    image_loaded_count_++;
    if (quit_in_image_loaded_)
      base::MessageLoop::current()->QuitWhenIdle();
  }

  gfx::ImageSkia GetDefaultIcon() {
    return gfx::ImageSkia(gfx::ImageSkiaRep(gfx::Size(16, 16), 1.0f));
  }

 private:
  int image_loaded_count_;
  bool quit_in_image_loaded_;
  base::MessageLoop ui_loop_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread file_thread_;
  content::TestBrowserThread io_thread_;
  scoped_ptr<content::NotificationService> notification_service_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionIconImageTest);
};

}  // namespace

TEST_F(ExtensionIconImageTest, Basic) {
  std::vector<ui::ScaleFactor> supported_factors;
  supported_factors.push_back(ui::SCALE_FACTOR_100P);
  supported_factors.push_back(ui::SCALE_FACTOR_200P);
  ui::test::ScopedSetSupportedScaleFactors scoped_supported(supported_factors);
  scoped_refptr<Extension> extension(CreateExtension(
      "extension_icon_image", Manifest::INVALID_LOCATION));
  ASSERT_TRUE(extension.get() != NULL);

  gfx::ImageSkia default_icon = GetDefaultIcon();

  // Load images we expect to find as representations in icon_image, so we
  // can later use them to validate icon_image.
  SkBitmap bitmap_16 =
      TestImageLoader::LoadAndGetExtensionBitmap(extension.get(), "16.png", 16);
  ASSERT_FALSE(bitmap_16.empty());

  // There is no image of size 32 defined in the extension manifest, so we
  // should expect manifest image of size 48 resized to size 32.
  SkBitmap bitmap_48_resized_to_32 =
      TestImageLoader::LoadAndGetExtensionBitmap(extension.get(), "48.png", 32);
  ASSERT_FALSE(bitmap_48_resized_to_32.empty());

  IconImage image(browser_context(),
                  extension.get(),
                  IconsInfo::GetIcons(extension.get()),
                  16,
                  default_icon,
                  this);

  // No representations in |image_| yet.
  gfx::ImageSkia::ImageSkiaReps image_reps = image.image_skia().image_reps();
  ASSERT_EQ(0u, image_reps.size());

  // Gets representation for a scale factor.
  gfx::ImageSkiaRep representation = image.image_skia().GetRepresentation(1.0f);

  // Before the image representation is loaded, image should contain blank
  // image representation.
  EXPECT_TRUE(gfx::BitmapsAreEqual(
      representation.sk_bitmap(),
      CreateBlankBitmapForScale(16, ui::SCALE_FACTOR_100P)));

  WaitForImageLoad();
  EXPECT_EQ(1, ImageLoadedCount());
  ASSERT_EQ(1u, image.image_skia().image_reps().size());

  representation = image.image_skia().GetRepresentation(1.0f);

  // We should get the right representation now.
  EXPECT_TRUE(gfx::BitmapsAreEqual(representation.sk_bitmap(), bitmap_16));
  EXPECT_EQ(16, representation.pixel_width());

  // Gets representation for an additional scale factor.
  representation = image.image_skia().GetRepresentation(2.0f);

  EXPECT_TRUE(gfx::BitmapsAreEqual(
      representation.sk_bitmap(),
      CreateBlankBitmapForScale(16, ui::SCALE_FACTOR_200P)));

  WaitForImageLoad();
  EXPECT_EQ(1, ImageLoadedCount());
  ASSERT_EQ(2u, image.image_skia().image_reps().size());

  representation = image.image_skia().GetRepresentation(2.0f);

  // Image should have been resized.
  EXPECT_EQ(32, representation.pixel_width());
  EXPECT_TRUE(gfx::BitmapsAreEqual(representation.sk_bitmap(),
                                   bitmap_48_resized_to_32));
}

// There is no resource with either exact or bigger size, but there is a smaller
// resource.
TEST_F(ExtensionIconImageTest, FallbackToSmallerWhenNoBigger) {
  std::vector<ui::ScaleFactor> supported_factors;
  supported_factors.push_back(ui::SCALE_FACTOR_100P);
  supported_factors.push_back(ui::SCALE_FACTOR_200P);
  ui::test::ScopedSetSupportedScaleFactors scoped_supported(supported_factors);
  scoped_refptr<Extension> extension(CreateExtension(
      "extension_icon_image", Manifest::INVALID_LOCATION));
  ASSERT_TRUE(extension.get() != NULL);

  gfx::ImageSkia default_icon = GetDefaultIcon();

  // Load images we expect to find as representations in icon_image, so we
  // can later use them to validate icon_image.
  SkBitmap bitmap_48 =
      TestImageLoader::LoadAndGetExtensionBitmap(extension.get(), "48.png", 48);
  ASSERT_FALSE(bitmap_48.empty());

  IconImage image(browser_context(),
                  extension.get(),
                  IconsInfo::GetIcons(extension.get()),
                  32,
                  default_icon,
                  this);

  gfx::ImageSkiaRep representation = image.image_skia().GetRepresentation(2.0f);

  WaitForImageLoad();
  EXPECT_EQ(1, ImageLoadedCount());
  ASSERT_EQ(1u, image.image_skia().image_reps().size());

  representation = image.image_skia().GetRepresentation(2.0f);

  // We should have loaded the biggest smaller resource resized to the actual
  // size.
  EXPECT_EQ(2.0f, representation.scale());
  EXPECT_EQ(64, representation.pixel_width());
  EXPECT_TRUE(gfx::BitmapsAreEqual(representation.sk_bitmap(),
                                   EnsureBitmapSize(bitmap_48, 64)));
}

// There is no resource with exact size, but there is a smaller and a bigger
// one. The bigger resource should be loaded.
TEST_F(ExtensionIconImageTest, FallbackToBigger) {
  scoped_refptr<Extension> extension(CreateExtension(
      "extension_icon_image", Manifest::INVALID_LOCATION));
  ASSERT_TRUE(extension.get() != NULL);

  gfx::ImageSkia default_icon = GetDefaultIcon();

  // Load images we expect to find as representations in icon_image, so we
  // can later use them to validate icon_image.
  SkBitmap bitmap_24 =
      TestImageLoader::LoadAndGetExtensionBitmap(extension.get(), "24.png", 24);
  ASSERT_FALSE(bitmap_24.empty());

  IconImage image(browser_context(),
                  extension.get(),
                  IconsInfo::GetIcons(extension.get()),
                  17,
                  default_icon,
                  this);

  gfx::ImageSkiaRep representation = image.image_skia().GetRepresentation(1.0f);

  WaitForImageLoad();
  EXPECT_EQ(1, ImageLoadedCount());
  ASSERT_EQ(1u, image.image_skia().image_reps().size());

  representation = image.image_skia().GetRepresentation(1.0f);

  // We should have loaded the smallest bigger (resized) resource.
  EXPECT_EQ(1.0f, representation.scale());
  EXPECT_EQ(17, representation.pixel_width());
  EXPECT_TRUE(gfx::BitmapsAreEqual(representation.sk_bitmap(),
                                   EnsureBitmapSize(bitmap_24, 17)));
}

// If resource set is empty, |GetRepresentation| should synchronously return
// default icon, without notifying observer of image change.
TEST_F(ExtensionIconImageTest, NoResources) {
  scoped_refptr<Extension> extension(CreateExtension(
      "extension_icon_image", Manifest::INVALID_LOCATION));
  ASSERT_TRUE(extension.get() != NULL);

  ExtensionIconSet empty_icon_set;
  gfx::ImageSkia default_icon = GetDefaultIcon();

  const int kRequestedSize = 24;
  IconImage image(browser_context(),
                  extension.get(),
                  empty_icon_set,
                  kRequestedSize,
                  default_icon,
                  this);

  gfx::ImageSkiaRep representation = image.image_skia().GetRepresentation(1.0f);
  EXPECT_TRUE(gfx::BitmapsAreEqual(
      representation.sk_bitmap(),
      EnsureBitmapSize(
          default_icon.GetRepresentation(1.0f).sk_bitmap(),
          kRequestedSize)));

  EXPECT_EQ(0, ImageLoadedCount());
  // We should have a default icon representation.
  ASSERT_EQ(1u, image.image_skia().image_reps().size());

  representation = image.image_skia().GetRepresentation(1.0f);
  EXPECT_TRUE(gfx::BitmapsAreEqual(
      representation.sk_bitmap(),
      EnsureBitmapSize(
          default_icon.GetRepresentation(1.0f).sk_bitmap(),
          kRequestedSize)));
}

// If resource set is invalid, image load should be done asynchronously and
// the observer should be notified when it's done. |GetRepresentation| should
// return the default icon representation once image load is done.
TEST_F(ExtensionIconImageTest, InvalidResource) {
  scoped_refptr<Extension> extension(CreateExtension(
      "extension_icon_image", Manifest::INVALID_LOCATION));
  ASSERT_TRUE(extension.get() != NULL);

  const int kInvalidIconSize = 24;
  ExtensionIconSet invalid_icon_set;
  invalid_icon_set.Add(kInvalidIconSize, "invalid.png");

  gfx::ImageSkia default_icon = GetDefaultIcon();

  IconImage image(browser_context(),
                  extension.get(),
                  invalid_icon_set,
                  kInvalidIconSize,
                  default_icon,
                  this);

  gfx::ImageSkiaRep representation = image.image_skia().GetRepresentation(1.0f);
  EXPECT_TRUE(gfx::BitmapsAreEqual(
      representation.sk_bitmap(),
      CreateBlankBitmapForScale(kInvalidIconSize, ui::SCALE_FACTOR_100P)));

  WaitForImageLoad();
  EXPECT_EQ(1, ImageLoadedCount());
  // We should have default icon representation now.
  ASSERT_EQ(1u, image.image_skia().image_reps().size());

  representation = image.image_skia().GetRepresentation(1.0f);
  EXPECT_TRUE(gfx::BitmapsAreEqual(
      representation.sk_bitmap(),
      EnsureBitmapSize(
          default_icon.GetRepresentation(1.0f).sk_bitmap(),
          kInvalidIconSize)));
}

// Test that IconImage works with lazily (but synchronously) created default
// icon when IconImage returns synchronously.
TEST_F(ExtensionIconImageTest, LazyDefaultIcon) {
  scoped_refptr<Extension> extension(CreateExtension(
      "extension_icon_image", Manifest::INVALID_LOCATION));
  ASSERT_TRUE(extension.get() != NULL);

  gfx::ImageSkia default_icon = GetDefaultIcon();
  gfx::ImageSkia lazy_default_icon(new MockImageSkiaSource(default_icon),
                                    default_icon.size());

  ExtensionIconSet empty_icon_set;

  const int kRequestedSize = 128;
  IconImage image(browser_context(),
                  extension.get(),
                  empty_icon_set,
                  kRequestedSize,
                  lazy_default_icon,
                  this);

  ASSERT_FALSE(lazy_default_icon.HasRepresentation(1.0f));

  gfx::ImageSkiaRep representation = image.image_skia().GetRepresentation(1.0f);

  // The resouce set is empty, so we should get the result right away.
  EXPECT_TRUE(lazy_default_icon.HasRepresentation(1.0f));
  EXPECT_TRUE(gfx::BitmapsAreEqual(
      representation.sk_bitmap(),
      EnsureBitmapSize(
          default_icon.GetRepresentation(1.0f).sk_bitmap(),
          kRequestedSize)));

  // We should have a default icon representation.
  ASSERT_EQ(1u, image.image_skia().image_reps().size());
}

// Test that IconImage works with lazily (but synchronously) created default
// icon when IconImage returns asynchronously.
TEST_F(ExtensionIconImageTest, LazyDefaultIcon_AsyncIconImage) {
  scoped_refptr<Extension> extension(CreateExtension(
      "extension_icon_image", Manifest::INVALID_LOCATION));
  ASSERT_TRUE(extension.get() != NULL);

  gfx::ImageSkia default_icon = GetDefaultIcon();
  gfx::ImageSkia lazy_default_icon(new MockImageSkiaSource(default_icon),
                                    default_icon.size());

  const int kInvalidIconSize = 24;
  ExtensionIconSet invalid_icon_set;
  invalid_icon_set.Add(kInvalidIconSize, "invalid.png");

  IconImage image(browser_context(),
                  extension.get(),
                  invalid_icon_set,
                  kInvalidIconSize,
                  lazy_default_icon,
                  this);

  ASSERT_FALSE(lazy_default_icon.HasRepresentation(1.0f));

  gfx::ImageSkiaRep representation = image.image_skia().GetRepresentation(1.0f);

  WaitForImageLoad();
  EXPECT_EQ(1, ImageLoadedCount());
  // We should have default icon representation now.
  ASSERT_EQ(1u, image.image_skia().image_reps().size());

  EXPECT_TRUE(lazy_default_icon.HasRepresentation(1.0f));

  representation = image.image_skia().GetRepresentation(1.0f);
  EXPECT_TRUE(gfx::BitmapsAreEqual(
      representation.sk_bitmap(),
      EnsureBitmapSize(
          default_icon.GetRepresentation(1.0f).sk_bitmap(),
          kInvalidIconSize)));
}

// Tests behavior of image created by IconImage after IconImage host goes
// away. The image should still return loaded representations. If requested
// representation was not loaded while IconImage host was around, transparent
// representations should be returned.
TEST_F(ExtensionIconImageTest, IconImageDestruction) {
  scoped_refptr<Extension> extension(CreateExtension(
      "extension_icon_image", Manifest::INVALID_LOCATION));
  ASSERT_TRUE(extension.get() != NULL);

  gfx::ImageSkia default_icon = GetDefaultIcon();

  // Load images we expect to find as representations in icon_image, so we
  // can later use them to validate icon_image.
  SkBitmap bitmap_16 =
      TestImageLoader::LoadAndGetExtensionBitmap(extension.get(), "16.png", 16);
  ASSERT_FALSE(bitmap_16.empty());

  scoped_ptr<IconImage> image(
      new IconImage(browser_context(),
                    extension.get(),
                    IconsInfo::GetIcons(extension.get()),
                    16,
                    default_icon,
                    this));

  // Load an image representation.
  gfx::ImageSkiaRep representation =
      image->image_skia().GetRepresentation(1.0f);

  WaitForImageLoad();
  EXPECT_EQ(1, ImageLoadedCount());
  ASSERT_EQ(1u, image->image_skia().image_reps().size());

  // Stash loaded image skia, and destroy |image|.
  gfx::ImageSkia image_skia = image->image_skia();
  image.reset();
  extension = NULL;

  // Image skia should still be able to get previously loaded representation.
  representation = image_skia.GetRepresentation(1.0f);

  EXPECT_EQ(1.0f, representation.scale());
  EXPECT_EQ(16, representation.pixel_width());
  EXPECT_TRUE(gfx::BitmapsAreEqual(representation.sk_bitmap(), bitmap_16));

  // When requesting another representation, we should not crash and return some
  // image of the size. It could be blank or a rescale from the existing 1.0f
  // icon.
  representation = image_skia.GetRepresentation(2.0f);

  EXPECT_EQ(16, representation.GetWidth());
  EXPECT_EQ(16, representation.GetHeight());
  EXPECT_EQ(2.0f, representation.scale());
}

// Test that new representations added to the image of an IconImage are cached
// for future use.
TEST_F(ExtensionIconImageTest, ImageCachesNewRepresentations) {
  // Load up an extension and create an icon image.
  scoped_refptr<Extension> extension(
      CreateExtension("extension_icon_image", Manifest::INVALID_LOCATION));
  ASSERT_TRUE(extension.get() != NULL);
  gfx::ImageSkia default_icon = GetDefaultIcon();
  scoped_ptr<IconImage> icon_image(
      new IconImage(browser_context(),
                    extension.get(),
                    IconsInfo::GetIcons(extension.get()),
                    16,
                    default_icon,
                    this));

  // Load an image representation.
  gfx::ImageSkiaRep representation =
      icon_image->image_skia().GetRepresentation(1.0f);
  WaitForImageLoad();

  // Cache for later use.
  gfx::Image prior_image = icon_image->image();

  // Now the fun part: access the image from the IconImage, and create a png
  // representation of it.
  gfx::Image image = icon_image->image();
  scoped_refptr<base::RefCountedMemory> image_as_png = image.As1xPNGBytes();

  // Access the image from the IconImage again, and get a png representation.
  // The two png representations should be exactly equal (the same object),
  // because image storage is shared, so when we created one from the first
  // image, all other images should also have that representation...
  gfx::Image image2 = icon_image->image();
  EXPECT_EQ(image_as_png.get(), image2.As1xPNGBytes().get());

  // ...even images that were copied before the representation was constructed.
  EXPECT_EQ(image_as_png.get(), prior_image.As1xPNGBytes().get());
}

}  // namespace extensions


text:
package org.chenmin.open.objector;

import java.util.Iterator;
import java.util.ServiceLoader;
/**
 * Spi 工厂构造器
 * @author Chenmin
 *
 */
public class ClassFactory {

	/**
	 * 创建接口的实现
	 * @param c
	 * @return
	 */
	public static <T> T create(Class<? extends T> c) {
		@SuppressWarnings("unchecked")
		ServiceLoader<T> serviceLoader = (ServiceLoader<T>) ServiceLoader.load(c);
		Iterator<T> it = serviceLoader.iterator();
		if (it.hasNext())
			return it.next();
		return null;
	}

}


text:
using System;
using Xunit;

namespace PactNet.Tests
{
    public class PactUriOptionsTests
    {
        [Fact]
        public void Ctor_WithEmptyUsername_ThrowsArgumentException()
        {
            const string username = "";
            const string password = "somepassword";

            Assert.Throws<ArgumentException>(() => new PactUriOptions(username, password));
        }

        [Fact]
        public void Ctor_WithInvalidUsername_ThrowsArgumentException()
        {
            const string username = "some:user";
            const string password = "somepassword";

            Assert.Throws<ArgumentException>(() => new PactUriOptions(username, password));
        }

        [Fact]
        public void Ctor_WithEmptyPassword_ThrowsArgumentException()
        {
            const string username = "someuser";
            const string password = "";

            Assert.Throws<ArgumentException>(() => new PactUriOptions(username, password));
        }

        [Fact]
        public void Ctor_WithValidUsernameAndPassword_ReturnsCorrectAuthorizationSchemeAndValue()
        {
            const string username = "Aladdin";
            const string password = "open sesame";
            var expectedAuthScheme = "Basic";
            var expectedAuthValue = "QWxhZGRpbjpvcGVuIHNlc2FtZQ==";

            var options = new PactUriOptions(username, password);

            Assert.Equal(expectedAuthScheme, options.AuthorizationScheme);
            Assert.Equal(expectedAuthValue, options.AuthorizationValue);
        }
    }
}


text:
package org.dasein.cloud.azurepack.compute.vm.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.dasein.cloud.azurepack.compute.image.model.WAPVhdModel;

import java.util.List;

/**
 * Created by vmunthiu on 3/4/2015.
 */
public class WAPVirtualMachinesModel {
    @JsonProperty("odata.metadata")
    private String odataMetadata;
    @JsonProperty("value")
    private List<WAPVirtualMachineModel> virtualMachines;

    public String getOdataMetadata() {
        return odataMetadata;
    }

    public void setOdataMetadata(String odataMetadata) {
        this.odataMetadata = odataMetadata;
    }

    public List<WAPVirtualMachineModel> getVirtualMachines() {
        return virtualMachines;
    }

    public void setVirtualMachines(List<WAPVirtualMachineModel> virtualMachines) {
        this.virtualMachines = virtualMachines;
    }
}


text:
import * as ts from 'typescript';
import {removeModuleIdOnlyForTesting} from './loader';
import {WebpackCompilerHost} from './compiler_host';
import {TypeScriptFileRefactor} from './refactor';

describe('@ngtools/webpack', () => {
  describe('loader', () => {
    describe('removeModuleId', () => {
      it('should work', () => {
        const host = new WebpackCompilerHost({}, '');
        host.writeFile('/file.ts', `
          export const obj = { moduleId: 123 };
          export const obj2 = { moduleId: 123, otherValue: 1 };
          export const obj3 = { otherValue: 1, moduleId: 123 };
        `, false);
        host.writeFile('/file2.ts', `
          @SomeDecorator({ moduleId: 123 }) class CLS {}
          @SomeDecorator({ moduleId: 123, otherValue1: 1 }) class CLS2 {}
          @SomeDecorator({ otherValue2: 2, moduleId: 123, otherValue3: 3 }) class CLS3 {}
          @SomeDecorator({ otherValue4: 4, moduleId: 123 }) class CLS4 {}
        `, false);

        const program = ts.createProgram(['/file.ts', '/file2.ts'], {}, host);

        const refactor = new TypeScriptFileRefactor('/file.ts', host, program);
        removeModuleIdOnlyForTesting(refactor);
        expect(refactor.sourceText).not.toMatch(/obj = \{\s+};/);
        expect(refactor.sourceText).not.toMatch(/\{\s*otherValue: 1\s*};/);

        const refactor2 = new TypeScriptFileRefactor('/file2.ts', host, program);
        removeModuleIdOnlyForTesting(refactor2);
        expect(refactor2.sourceText).toMatch(/\(\{\s+}\)/);
        expect(refactor2.sourceText).toMatch(/\(\{\s*otherValue1: 1\s*}\)/);
        expect(refactor2.sourceText).toMatch(/\(\{\s*otherValue2: 2\s*,\s*otherValue3: 3\s*}\)/);
        expect(refactor2.sourceText).toMatch(/\(\{\s*otherValue4: 4\s*}\)/);
      });

      it('should work without a root name', () => {
        const host = new WebpackCompilerHost({}, '');
        host.writeFile('/file.ts', `
          import './file2.ts';
        `, false);
        host.writeFile('/file2.ts', `
          @SomeDecorator({ moduleId: 123 }) class CLS {}
          @SomeDecorator({ moduleId: 123, otherValue1: 1 }) class CLS2 {}
          @SomeDecorator({ otherValue2: 2, moduleId: 123, otherValue3: 3 }) class CLS3 {}
          @SomeDecorator({ otherValue4: 4, moduleId: 123 }) class CLS4 {}
        `, false);

        const program = ts.createProgram(['/file.ts'], {}, host);
        const refactor = new TypeScriptFileRefactor('/file2.ts', host, program);
        removeModuleIdOnlyForTesting(refactor);
        expect(refactor.sourceText).toMatch(/\(\{\s+}\)/);
        expect(refactor.sourceText).toMatch(/\(\{\s*otherValue1: 1\s*}\)/);
        expect(refactor.sourceText).toMatch(/\(\{\s*otherValue2: 2\s*,\s*otherValue3: 3\s*}\)/);
        expect(refactor.sourceText).toMatch(/\(\{\s*otherValue4: 4\s*}\)/);
      });
    });
  });
});


text:
namespace
{

matrix::User* find_user(std::list<matrix::User>& users, std::string_view id)
{
  auto it = std::find_if(std::begin(users), std::end(users), [id](const auto& u){
    return u.id() == id;
  });
  if (it != std::end(users))
    return &*it;
  return nullptr;
}

matrix::Room* find_room(std::list<matrix::Room>& rooms, std::string_view id)
{
  auto it = std::find_if(std::begin(rooms), std::end(rooms), [id](const auto& r){
    return r.id() == id;
  });
  if (it != std::end(rooms))
    return &*it;
  return nullptr;
}

}  // Anonymous namespace

auto matrix::Client::room(std::size_t i) -> Room*
{
  auto it = std::begin(rooms_);
  std::advance(it, i);
  return &*it;
}

auto matrix::Client::user(std::string_view id) -> User*
{
  return find_user(users_, id);
}

auto matrix::Client::room(std::string_view id) -> Room*
{
  return find_room(rooms_, id);
}

auto matrix::Client::add_self(User&& self) -> User*
{
  users_.push_back(std::move(self));
  self_ = &users_.back();
  return self_;
}

auto matrix::Client::add_user(User&& user) -> User*
{
  users_.push_back(std::move(user));
  return &users_.back();
}

auto matrix::Client::add_room(Room&& room) -> Room*
{
  rooms_.push_back(std::move(room));
  return &rooms_.back();
}

void matrix::Client::add_message(Message&& message)
{
  if (auto* r = find_room(rooms_, message.room_id); r)
    r->add_message(std::move(message));
}


text:
require 'rails_helper'
require 'support/s2s_api_shared_context'

RSpec.describe 'S2sApi::V1::Zones', type: :request, s2s: true do
  let!(:application) { FactoryGirl.create(:application, account: admin.account) }
  let!(:test_application) { FactoryGirl.create(:application, account: admin.account, test: true) }
  let!(:zone1) { FactoryGirl.create(:zone, account: admin.account) }
  let!(:zone2) { FactoryGirl.create(:zone, account: admin.account, manager: manager) }
  let!(:beacon) { FactoryGirl.create(:beacon, manager: manager, zone: zone2) }

  describe '#index' do
    let(:json) { json_response[:zones] }
    let(:zone_ids) { json.map{|z| z[:id]} }

    it 'returns list of zones' do
      get '/s2s_api/v1/zones.json', access_token: admin_access_token.token

      expect(response.status).to eq(200)
      expect(json.size).to eq(2)

      expect(zone_ids).to match_array([zone1.id, zone2.id])
      expect(json.last).to eq(S2sApi::V1::ZoneSerializer.new(zone2).as_json(root: false))
      [:id, :name, :beacons, :beacon_ids].each do |key|
        expect(json.last).to have_key(key)
      end
    end

    it 'searches list of zones by name' do
      get '/s2s_api/v1/zones.json', name: zone1.name, access_token: admin_access_token.token

      expect(json.size).to eq(1)
      expect(zone_ids).to include(zone1.id)
    end

    it 'scopes list of zones for manager' do
      get '/s2s_api/v1/zones.json', access_token: manager_access_token.token

      expect(json.size).to eq(1)

      expect(zone_ids).to include(zone2.id)
      expect(zone_ids).not_to include(zone1.id)
    end

    it 'includes zone beacons' do
      get '/s2s_api/v1/zones.json', access_token: manager_access_token.token

      expect(json.first).to have_key(:beacon_ids)
      expect(json.first[:beacon_ids].size).to eq(1)

      expect(json.first[:beacon_ids]).to match_array(manager.beacons.pluck(:id))

      expect(json.first).to have_key(:beacons)
      expect(json.first[:beacons].size).to eq(1)

      expect(json.first[:beacons]).to eq(
        [S2sApi::V1::BeaconSerializer.new(beacon).attributes]
      )
    end
  end

  describe '#create' do
    let(:json) { json_response[:zone] }

    it 'saves valid zone' do
      expect {
        post '/s2s_api/v1/zones.json', access_token: admin_access_token.token, zone: {name: "Zone3", description: "Desc3", color: ZoneColors.sample}
      }.to change(application.zones, :count).by(1)

      expect(response.status).to eq(201)

      zone = Zone.last
      as_json = S2sApi::V1::ZoneSerializer.new(zone).as_json(root: false)

      expect(zone.name).to eq("Zone3")
      expect(zone.description).to eq("Desc3")
      expect(zone.manager).to be_nil
      expect(zone.applications_zones).not_to be_empty

      expect(json).to eq(as_json)
    end

    it 'does not save invalid zone' do
      expect {
        post '/s2s_api/v1/zones.json', access_token: admin_access_token.token, zone: {description: "Desc3"}
      }.not_to change(Zone, :count)
      expect(response.status).to eq(422)
    end

    it 'returns validation errors' do
      post '/s2s_api/v1/zones.json', access_token: admin_access_token.token, zone: {}

      expect(response.status).to eq(422)
      expect(json_response).to have_key(:errors)
      expect(json_response[:errors]).to have_key(:name)
    end

    it 'assigns zone manager' do
      post '/s2s_api/v1/zones.json', access_token: admin_access_token.token, zone: {name: "Name3", color: ZoneColors.sample }
      expect(Zone.last.manager).to eq(nil)

      post '/s2s_api/v1/zones.json', access_token: admin_access_token.token, zone: {name: "Name3", manager_id: manager.id, color: ZoneColors.sample }
      expect(Zone.last.manager).to eq(manager)
    end

    it 'assigns manager himself as zone manager' do
      expect {
        post '/s2s_api/v1/zones.json', access_token: manager_access_token.token, zone: {name: "Name3", color: ZoneColors.sample }
      }.to change(manager.zones, :count).by(1)

      expect(Zone.last.manager).to eq(manager)
    end

    context 'add beacon' do
      let(:subject) {
        post '/s2s_api/v1/zones.json', access_token: access_token, zone: {name: "Name3", beacon_ids: [beacon_to_add.id], color: ZoneColors.sample }
        beacon_to_add.reload
      }
      let(:beacon_to_add) { FactoryGirl.create(:beacon, account: admin.account, zone: zone1) }
      let(:access_token)  { manager_access_token.token }

      context 'with other manager' do
        it 'fails' do
          expect { subject }.not_to change(beacon_to_add, :zone)
        end
      end

      context 'with manager to zone by manager' do
        let(:beacon_to_add) { beacon }
        it 'succeeds' do
          expect { subject }.to change(beacon_to_add, :zone)
          expect(beacon_to_add.zone).to eq(Zone.last)
        end
      end

      context 'without manager to zone without manager' do
        let(:access_token)  { admin_access_token.token }
        it 'succeeds' do
          expect { subject }.to change(beacon_to_add, :zone)
        end
      end
    end
  end

  describe '#update' do
    it 'updates zone' do
      expect {
        put "/s2s_api/v1/zones/#{zone1.id}.json", access_token: admin_access_token.token, zone: {name: "Name3", description: "Desc3"}
        zone1.reload
      }.to change(zone1, :name).to("Name3") and
           change(zone1, :description).to("Desc3")
    end

    it 'allows manager to update only own zones' do
      expect {
        put "/s2s_api/v1/zones/#{zone2.id}.json", access_token: manager_access_token.token, zone: {name: "Name3"}
        zone2.reload
      }.to change(zone2, :name)
      expect(response.status).to eq(204)

      expect {
        put "/s2s_api/v1/zones/#{zone1.id}.json", access_token: manager_access_token.token, zone: {name: "Name4"}
        zone1.reload
      }.not_to change(zone1, :name)
      expect(response.status).to eq(403)
    end

    it 'allows superuser to manage all zones' do
      expect {
        put "/s2s_api/v1/zones/#{zone2.id}.json", access_token: admin_access_token.token, zone: {name: "Name3"}
        zone2.reload
      }.to change(zone2, :name)
      expect(response.status).to eq(204)
    end

    it 'removes other manager beacons from zone when changing manager' do
      other_manager = FactoryGirl.create(:admin, account: admin.account, role: :beacon_manager)

      expect {
        put "/s2s_api/v1/zones/#{zone2.id}.json", access_token: admin_access_token.token, zone: {manager_id: other_manager.id}
        zone2.reload
      }.to change(zone2.beacons, :count).by(-1)
      expect(beacon.reload.zone).to be_nil
    end

    it 'adds beacon to zone' do
      other_beacon = FactoryGirl.create(:beacon, manager: manager)

      expect {
        put "/s2s_api/v1/zones/#{zone2.id}.json", access_token: admin_access_token.token, zone: {beacon_ids: [other_beacon.id]}
        other_beacon.reload
      }.to change(other_beacon, :zone).to(zone2)
    end
  end

  describe '#destroy' do
    it 'succeeds' do
      expect {
        delete "/s2s_api/v1/zones/#{zone1.id}.json", access_token: admin_access_token.token
      }.to change(Zone, :count).by(-1)
      expect(response.status).to eq(204)
    end

    it 'fails manager removing not his zone' do
      expect {
        delete "/s2s_api/v1/zones/#{zone1.id}.json", access_token: manager_access_token.token
      }.not_to change(Zone, :count)
      expect(response.status).to eq(403)
    end
  end

  describe '#beacons' do
    let(:json) { json_response[:ranges] }
    let(:beacon_ids) { json.map{|b| b[:id]} }
    let!(:beacon1) { FactoryGirl.create(:beacon, account: admin.account, zone: zone1) }
    let!(:beacon2) { FactoryGirl.create(:beacon, account: admin.account) }

    it 'returns list of beacons in zone' do
      get "/s2s_api/v1/zones/#{zone1.id}/beacons.json", access_token: admin_access_token.token

      expect(response.status).to eq(200)
      expect(json.size).to eq(1)
      expect(beacon_ids).to include(beacon1.id)
      expect(beacon_ids).not_to include(beacon2.id)

      expect(json.first).to eq(S2sApi::V1::BeaconSerializer.new(beacon1).as_json(root: false))
      [:id, :name, :location, :proximity_id].each do |key|
        expect(json.last).to have_key(key)
      end
    end

    it "allows manager to fetch only his zone's beacons " do
      get "/s2s_api/v1/zones/#{zone2.id}/beacons.json", access_token: manager_access_token.token
      expect(response.status).to eq(200)

      get "/s2s_api/v1/zones/#{zone1.id}/beacons.json", access_token: manager_access_token.token
      expect(response.status).to eq(403)
    end
  end
end


text:
from django.conf.urls.defaults import *
from wui.api.views import *

urlpatterns = patterns('',
    url(r'^$', index, name='api-index'),
    url(r'^ns/(?P<ns>.+)/$', doc_namespace, name='api-namespace'),
    url(r'^(?P<ns>.*)-(?P<cls>.+)/$', doc_class, name='api-class'),
    url(r'^countries/$', countries_json, name='api-countries'),

    url(r'^dl/$', download, name='api-download'),
)


text:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();

myEmitter.on('myEvent_1', () => {});

// Внимание — считаются только разные имена, `myEvent_1` второй раз не будет добавлено
myEmitter.on('myEvent_1', () => {});

myEmitter.on('myEvent_2', () => {});

console.log('myEE.eventNames: ', myEmitter.eventNames());
// log:  myEE.eventNames:  [ 'myEvent_1', 'myEvent_2' ]


text:
<?php
foreach (apache_request_headers() as $header => $value)
{
  echo "$header: $value\n";
}
echo "\r\n";
print_r($_POST);


text:
import { CompilerContext } from '../core/CompilerContext';

declare function skipRedundantNodesTransform(
  context: CompilerContext,
): CompilerContext;

export { skipRedundantNodesTransform as transform };


text:
"""
    vcfexplorer.frontend

    VCF Explorer frontend package
"""

from flask import Blueprint

bp = Blueprint('frontend', __name__,
    template_folder='templates',
    static_folder='static',
    static_url_path='static'
)

from . import views


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>cocos.custom_clocks.ScreenReaderClock</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

      Trees

      Indices

          cocos . custom_clocks . ScreenReaderClock

        Toggle frames

Class cocos.custom_clocks.ScreenReaderClock

pyglet.clock._ClockBase --+
                          |
         pyglet.clock.Clock --+
                              |
                             ScreenReaderClock

Make frames happen every 1/framerate and takes screenshots

This class is compatible with pyglet 1.1.4release, it is not compatible
with pyglet 1.2dev

Methods

        __init__(self,
        framerate,
        template,
        duration)

Initialise a Clock, with optional framerate limit and custom
time function.

      float

        tick(self,
        poll=False)

Signify that one frame has passed.

Inherited from pyglet.clock.Clock:
      call_scheduled_functions,
      get_fps,
      get_fps_limit,
      get_sleep_time,
      schedule,
      schedule_interval,
      schedule_interval_soft,
      schedule_once,
      set_fps_limit,
      unschedule,
      update_time
Inherited from pyglet.clock._ClockBase:
      sleep

Constants

Inherited from pyglet.clock.Clock:
      MIN_SLEEP,
      SLEEP_UNDERSHOOT

Method Details

__init__

    (Constructor)
    __init__(self,
        framerate,
        template,
        duration)

  Initialise a Clock, with optional framerate limit and custom
time function.

Overrides:

      pyglet.clock.Clock.__init__

tick

    tick(self,
        poll=False)

  Signify that one frame has passed.

Returns:

float: The number of seconds since the last "tick", or 0 if this was
the first frame.

Overrides:

      pyglet.clock.Clock.tick

      Trees

      Indices

          cocos . custom_clocks . ScreenReaderClock

        Toggle frames

    Generated by Epydoc 3.0beta1 on Sun Aug 12 20:39:19 2012

      http://epydoc.sourceforge.net


text:
module.exports = {
    "@id": "/biosamples/ENCBS087RNA/",
    "@type": ["Biosample", "Item"],
    "accession": "ENCBS087RNA",
    "aliases": ["thomas-gingeras:K562-1"],
    "award": "/awards/U54HG007005/",
    "biosample_term_id": "EFO:0002067",
    "biosample_term_name": "K562",
    "biosample_type": "cell line",
    "culture_harvest_date": "2013-03-06",
    "culture_start_date": "2013-02-28",
    "description": "The continuous cell line K-562 was established by Lozzio and Lozzio from the pleural effusion of a 53-year-old female with chronic myelogenous leukemia in terminal blast crises. ENCODE3 RNA-seq evaluation replicate 1.",
    "donor": require('../donor/encdo000hum'),
    "lab": "/labs/brenton-graveley/",
    "lot_id": "59300853",
    "note": "K562 cell line replicate 1 used inENCODE3 RNA-seq evaluation",
    "organism": require('../organism/human'),
    "passage_number": 5,
    "product_id": "CCL-243",
    "source": require('../source'),
    "starting_amount": 100000.0,
    "starting_amount_units": "cells/ml",
    "submitted_by": require('../submitter'),
    "summary": "K562 cell line replicate 1 used inENCODE3 RNA-seq evaluation",
    "summary_object": {temp: "K562"},
    "treatments": [require('../treatment/CHEBI34730')],
    "url": "http://www.atcc.org/Products/All/CCL-243.aspx",
    "uuid": "2ee883ef-b0dd-4305-a69b-d881de132795"
};


text:
@interface NetMovieViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *playerView;
@property (weak, nonatomic) IBOutlet UIButton *playOrPause;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *items;
@property (nonatomic, strong) WYAVManager *manager;

@end

@implementation NetMovieViewController

#pragma mark - 懒加载
- (NSMutableArray *)items {
    if (!_items) {
        _items = [NSMutableArray array];
    }
    return _items;
}

- (WYAVManager *)manager {
    if (!_manager) {
        _manager = [WYAVManager shareManager];
    }
    return _manager;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];

    [self loadMoviewData];
}

- (void)loadMoviewData {
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/video?type=JSON"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 转模型
        NSDictionary *objDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *movies = objDic[@"videos"];
        for (NSDictionary *dict in movies) {
            MovieItem *item = [MovieItem itemWithDict:dict];
            [self.items addObject:item];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }] resume];
}

#pragma mark - 播放demo
- (IBAction)play:(UIButton *)btn {
    btn.selected = !btn.isSelected;
    if (btn.isSelected) {// 选中暂停
        [self.manager wy_pausePlay];
    }else { // 没选中播放
        [self.manager wy_resumPlay];
    }
}
- (IBAction)next:(UIButton *)btn {
}
- (IBAction)previous:(UIButton *)btn {
}
- (IBAction)start:(id)sender {
}

#pragma mark - tableView datasource/delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MovieCell *cell = [MovieCell cellWithTableView:tableView];
    cell.item = self.items[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    MovieItem *item = self.items[indexPath.row];
    [self.manager wy_createItemWithUrl:[NSURL URLWithString:item.url]];
    [self.manager wy_readyPlayWithUrl:nil];
    self.manager.wy_currentPlayerLayer.frame = self.playerView.layer.bounds;
    [self.playerView.layer addSublayer:self.manager.wy_currentPlayerLayer];
    [self.manager wy_startPlay];

}

@end


text:
Class.makeClass(Drawable, function Button(text, x, y, actionFunc) {
	this.init();

	this.x = x;
	this.y = y;
	this.text = text;
	this.action = actionFunc ? actionFunc : function() {};
});

Button.prototype.left = function() { return this.x; }
Button.prototype.right = function() { return this.x; }
Button.prototype.top = function() { return this.y; }
Button.prototype.bottom = function() { return this.y; }

Button.prototype.getColor = function() {
	return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + this.a + ')';
}

Button.prototype.render = function() {
	ctx.textAlign = 'center';
	ctx.textBaseline = 'middle';
	ctx.fillStyle = 'black';
	ctx.font = '18px Ariel';
	ctx.fillText(this.text, this.x, this.y);

	// note: Firefox only implements the 'width' property of TextMetrics, so that's all that we can safely use
	var textWidth = ctx.measureText(this.text).width;
	var padding = 6;

	var triInnerX = 3;
	var triOuterX = 8;
	var triVert = 4;

	if (this.selected) {
		ctx.beginPath();
		ctx.moveTo(this.x - (textWidth/2 + triInnerX), this.y);
		ctx.lineTo(this.x - (textWidth/2 + triInnerX + triOuterX), this.y - triVert);
		ctx.lineTo(this.x - (textWidth/2 + triInnerX + triOuterX), this.y + triVert);
		ctx.fill();

		ctx.beginPath();
		ctx.moveTo(this.x + (textWidth/2 + triInnerX), this.y);
		ctx.lineTo(this.x + (textWidth/2 + triInnerX + triOuterX), this.y - triVert);
		ctx.lineTo(this.x + (textWidth/2 + triInnerX + triOuterX), this.y + triVert);
		ctx.fill();
	}

	var boxLeft = this.x - (triInnerX + triOuterX + textWidth/2 + padding);
	var boxRight = this.x + (triInnerX + triOuterX + textWidth/2 + padding);

	var boxTop = this.y - (18/2 + padding);
	var boxBottom = this.y + (18/2 + padding);

	ctx.beginPath();
	ctx.moveTo(boxLeft, boxTop);
	ctx.lineTo(boxRight, boxTop);
	ctx.lineTo(boxRight, boxBottom);
	ctx.lineTo(boxLeft, boxBottom);
	ctx.lineTo(boxLeft, boxTop);
	ctx.stroke();
}


text:
angular
    .module('material.components.menuBar')
    .controller('MenuItemController', MenuItemController);
/**
 * @ngInject
 */
function MenuItemController($scope, $element, $attrs) {
    this.$element = $element;
    this.$attrs = $attrs;
    this.$scope = $scope;
}
MenuItemController.prototype.init = function (ngModel) {
    var $element = this.$element;
    var $attrs = this.$attrs;
    this.ngModel = ngModel;
    if ($attrs.type == 'checkbox' || $attrs.type == 'radio') {
        this.mode = $attrs.type;
        this.iconEl = $element[0].children[0];
        this.buttonEl = $element[0].children[1];
        if (ngModel) {
            // Clear ngAria set attributes
            this.initClickListeners();
        }
    }
};
// ngAria auto sets attributes on a menu-item with a ngModel.
// We don't want this because our content (buttons) get the focus
// and set their own aria attributes appropritately. Having both
// breaks NVDA / JAWS. This undeoes ngAria's attrs.
MenuItemController.prototype.clearNgAria = function () {
    var el = this.$element[0];
    var clearAttrs = ['role', 'tabindex', 'aria-invalid', 'aria-checked'];
    angular.forEach(clearAttrs, function (attr) {
        el.removeAttribute(attr);
    });
};
MenuItemController.prototype.initClickListeners = function () {
    var self = this;
    var ngModel = this.ngModel;
    var $scope = this.$scope;
    var $attrs = this.$attrs;
    var $element = this.$element;
    var mode = this.mode;
    this.handleClick = angular.bind(this, this.handleClick);
    var icon = this.iconEl;
    var button = angular.element(this.buttonEl);
    var handleClick = this.handleClick;
    $attrs.$observe('disabled', setDisabled);
    setDisabled($attrs.disabled);
    ngModel.$render = function render() {
        self.clearNgAria();
        if (isSelected()) {
            icon.style.display = '';
            button.attr('aria-checked', 'true');
        } else {
            icon.style.display = 'none';
            button.attr('aria-checked', 'false');
        }
    };
    $scope.$$postDigest(ngModel.$render);
    function isSelected() {
        if (mode == 'radio') {
            var val = $attrs.ngValue ? $scope.$eval($attrs.ngValue) : $attrs.value;
            return ngModel.$modelValue == val;
        } else {
            return ngModel.$modelValue;
        }
    }

    function setDisabled(disabled) {
        if (disabled) {
            button.off('click', handleClick);
        } else {
            button.on('click', handleClick);
        }
    }
};
MenuItemController.prototype.handleClick = function (e) {
    var mode = this.mode;
    var ngModel = this.ngModel;
    var $attrs = this.$attrs;
    var newVal;
    if (mode == 'checkbox') {
        newVal = !ngModel.$modelValue;
    } else if (mode == 'radio') {
        newVal = $attrs.ngValue ? this.$scope.$eval($attrs.ngValue) : $attrs.value;
    }
    ngModel.$setViewValue(newVal);
    ngModel.$render();
};


text:
## Introduction
The project objective is to use Packer with the Ansible provisioner to create a "ready to use" Wordpress image which will use an RDS database.

### Requirements
You need Packer, Docker, Ansible and the 'aws cli' configured.

### What I have done
- I created an RDS database with MariaDB engine using the aws cli:
```sh
  aws rds create-db-instance --db-name RDSDiego \
  --allocated-storage 5 \
  --db-instance-class db.t2.micro \
  --engine mariadb \
  --master-username YOU_DB_MASTER_USER \
  --master-user-password YOUR_DB_PASSWORD \
  --vpc-security-group-ids sg-04e8fb78 \
  --backup-retention-period 0 \
  --db-instance-identifier wordpress
```
> I created that security group I specified to only allow inbound traffic to port 3306, to be able to connect to the mariadb database.

You can get the database endpoint/host with:
```sh
aws rds describe-db-instances|grep Address
```
- I created a packer file to build the container and push it to an AWS ECR repository.
- I created an ansible playbook for the provisioning and configuration of extra repositories, nginx, php, wordpress and supervisor.
- Wordpress is configured to use the remote RDS database, which has a security group to only allow incoming connections on port 3306.

### How to run the project
- Edit your remote database details on ansible-playbook/group_vars/all.
- Configure the AWS key, secret, and ECR repository on packer_aws.json or pass the variables as I will explain below.

- To first test the packer build with a local docker image you can do:
```sh
  docker run -ti -p 8083:80 dispera/packer:latest /usr/bin/supervisord
```
> (I am forwarding local port 8083 to the container port 80, so I can then connect from a web browser to: localhost:8083)

- At this point, configure your ECR repository access with docker login:
Using AWS Cli, get your docker login credentials to be able to pull the image from the ECR Repository:
```sh
aws ecr get-login
```
You will get an ouput like the following, with the exact command to paste and make your login (so you are then authorized to pull images from this repository for 12hs)
```sh
docker login -u AWS -p {password} -e none {ecr_repository_ip}
```

- To have Packer build a container image and push it to an AWS ECR repository:
```sh
packer build packer_aws.json
```
> (you must complete the aws secret, key, and ECR repository in this file to run it like this) or, you can run it passing the variables from the cli:

```sh
packer build -var 'aws_access_key=KEY' -var 'aws_secret_key=SECRET' -var 'aws_ECR_repository=REPOSITORY' packer_aws.json
```

- Now, the image is ready. You can go to AWS ECS, and create a task which uses this image and runs on and instance on your ECS cluster. On the task creation, configure command as /usr/bin/supervisord, and forward a host port to port 80 on the container so you can connect to it from the web - like port 80 to port 80.

### How components interact between each other
- Using packer, you pull a centos image which you will provision using the specified ansible playbook.
- Then a resulting new container image will be tagged and pushed to the AWS ECR repository.

### What problems did I have
- I had never used Packer, Ansible, or ECS before this, so it was a nice opportunity to learn them, as well as refresh my docker skills.
- As I first tested this in virtualbox, I had then to adapt it for docker - meaning the nginx and php processes cannot run in the background, so I had to change the config files to the processes to run in the foreground. And I installed and configure supervisor (in the provisioning step through ansible) to start and manage them.
- At some point on my tests, the packer build was failing to pull the centos image from the docker hub. I checked the status and it turns out there was an incident and the hub was down for some time, so that can happen.
- I also noticed at some random times with the packer docker builder, a build can fail when copying a template into the container, and retrying it just finishes without errors.

### How would I have done things to have the best HA/automated architecture
- As this is running on an ECS Cluster, I would configure the cluster to run on multiple availability zones with an Elastic Load Balancer. And for the RDS database I would configure several snapshots. That would take care of the high availability. I would also configure Auto Scaling based on the application load, and I could setup read replicas for the database if required.

### Ideas to improve this kind of infrastructure.
- At this moment I am quite happy with how the project turned out other than the suggestions above.

### Scenario Question
Tomorrow we want to put this project in production. What would be your advices and choices to achieve that.
Regarding the infrastructure itself and also external services like the monitoring.
- I believe this application, being in an ECS container and with very restricted security groups, can easily be put into production as I find this very secure already. For the monitoring, I would look for the best monitoring solutions to help me monitor if the Wordpress site is down (I would try CloudKick as it seems to cover that).


text:
import {Request, Response} from 'express'

import {findUserByUsername} from '../../../db/repositories/userRepository'
import {Credentials} from '../../auth/types'
import {validatePassword, generateAccessToken} from '../helpers'

export default async (req: Request, res: Response) => {
  const {username, password}: Credentials = req.body

  try {
    const user = await findUserByUsername(username)

    await validatePassword(password, user.password)

    const json = {
      jwt: await generateAccessToken(user),
    }

    res.status(200).json(json)
  } catch (e) {
    res.sendStatus(401)
  }
}


text:
import Rebase from 're-base';

let base = Rebase.createClass({
    authDomain: "race-reportr.firebaseapp.com",
    databaseURL: "https://race-reportr.firebaseio.com",
});

export default base;


text:
const assert = require('assert');
const getLocation = require('../../getLocation');
const SourceMapConsumer = require('source-map').SourceMapConsumer;

module.exports = {
	description: 'basic sourcemap support',
	test(code, map) {
		assert.equal(map.version, 3);
		assert.ok(/^bundle\.(\w+)\.js/.test(map.file));

		const smc = new SourceMapConsumer(map);
		let generatedLoc; let originalLoc;

		// main.js
		generatedLoc = getLocation(code, code.indexOf("console.log( 'hello from main.js' )"));
		originalLoc = smc.originalPositionFor(generatedLoc);

		assert.equal(originalLoc.line, 4);
		assert.equal(originalLoc.column, 0);
		assert.equal(originalLoc.source, '../main.js');

		// foo.js
		generatedLoc = getLocation(code, code.indexOf("console.log( 'hello from foo.js' )"));
		originalLoc = smc.originalPositionFor(generatedLoc);

		assert.equal(originalLoc.line, 2);
		assert.equal(originalLoc.column, 1);
		assert.equal(originalLoc.source, '../foo.js');

		// bar.js
		generatedLoc = getLocation(code, code.indexOf("console.log( 'hello from bar.js' )"));
		originalLoc = smc.originalPositionFor(generatedLoc);

		assert.equal(originalLoc.line, 2);
		assert.equal(originalLoc.column, 1);
		assert.equal(originalLoc.source, '../bar.js');
	}
};


text:
FactoryGirl.define do
  factory :plan do
    sequence(:stripe_id) { |n| "plan_#{n}" }
    sequence(:name) { |n| "Plan #{n}" }
    statement_description ''
    active true
    public true
    paused_plan_id nil
    currency 'USD'
    interval_count 1
    interval 'month'
    amount 1999
    trial_period_days 30
    require_card_upfront true
    max_users 10
  end
end


text:
package io.moquette.spi.impl.security;

import org.apache.commons.codec.binary.Hex;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class DBAuthenticatorTest {

    private static final Logger LOG = LoggerFactory.getLogger(DBAuthenticatorTest.class);

    public static final String ORG_H2_DRIVER = "org.h2.Driver";
    public static final String JDBC_H2_MEM_TEST = "jdbc:h2:mem:test";
    public static final String SHA_256 = "SHA-256";
    private Connection connection;

    @Before
    public void setup() throws ClassNotFoundException, SQLException, NoSuchAlgorithmException {
        Class.forName(ORG_H2_DRIVER);
        this.connection = DriverManager.getConnection(JDBC_H2_MEM_TEST);
        Statement statement = this.connection.createStatement();
        try {
            statement.execute("DROP TABLE ACCOUNT");
        } catch (SQLException sqle) {
            LOG.info("Table not found, not dropping", sqle);
        }
        MessageDigest digest = MessageDigest.getInstance(SHA_256);
        String hash = new String(Hex.encodeHex(digest.digest("password".getBytes(StandardCharsets.UTF_8))));
        try {
            if (statement.execute("CREATE TABLE ACCOUNT ( LOGIN VARCHAR(64), PASSWORD VARCHAR(256))")) {
                throw new SQLException("can't create USER table");
            }
            if (statement.execute("INSERT INTO ACCOUNT ( LOGIN , PASSWORD ) VALUES ('dbuser', '" + hash + "')")) {
                throw new SQLException("can't insert in USER table");
            }
        } catch (SQLException sqle) {
            LOG.error("Table not created, not inserted", sqle);
            return;
        }
        LOG.info("Table User created");
        statement.close();
    }

    @Test
    public void Db_verifyValid() {
        final DBAuthenticator dbAuthenticator = new DBAuthenticator(
                ORG_H2_DRIVER,
                JDBC_H2_MEM_TEST,
                "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?",
                SHA_256);
        assertTrue(dbAuthenticator.checkValid(null, "dbuser", "password".getBytes()));
    }

    @Test
    public void Db_verifyInvalidLogin() {
        final DBAuthenticator dbAuthenticator = new DBAuthenticator(
                ORG_H2_DRIVER,
                JDBC_H2_MEM_TEST,
                "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?",
                SHA_256);
        assertFalse(dbAuthenticator.checkValid(null, "dbuser2", "password".getBytes()));
    }

    @Test
    public void Db_verifyInvalidPassword() {
        final DBAuthenticator dbAuthenticator = new DBAuthenticator(
                ORG_H2_DRIVER,
                JDBC_H2_MEM_TEST,
                "SELECT PASSWORD FROM ACCOUNT WHERE LOGIN=?",
                SHA_256);
        assertFalse(dbAuthenticator.checkValid(null, "dbuser", "wrongPassword".getBytes()));
    }

    @After
    public void teardown() {
        try {
            this.connection.close();
        } catch (SQLException e) {
            LOG.error("can't close connection", e);
        }
    }
}


text:
using System;

namespace Magnesium
{
    public class MgDisplaySurfaceCreateInfoKHR
	{
		public UInt32 Flags { get; set; }
		public IMgDisplayModeKHR DisplayMode { get; set; }
		public UInt32 PlaneIndex { get; set; }
		public UInt32 PlaneStackIndex { get; set; }
		public MgSurfaceTransformFlagBitsKHR Transform { get; set; }
		public float GlobalAlpha { get; set; }
		public MgDisplayPlaneAlphaFlagBitsKHR AlphaMode { get; set; }
		public MgExtent2D ImageExtent { get; set; }
	}
}


text:
/* modest-tny-stream-webkit.c */

#include "modest-tny-stream-webkit.h"
#include "modest-webkit-mime-part-view.h"
#include <tny-stream.h>

/* 'private'/'protected' functions */
static void  modest_tny_stream_webkit_class_init   (ModestTnyStreamWebkitClass *klass);
static void  modest_tny_stream_webkit_init         (ModestTnyStreamWebkit *obj);
static void  modest_tny_stream_webkit_finalize     (GObject *obj);

static void  modest_tny_stream_gtkhml_iface_init (gpointer g_iface, gpointer iface_data);

static void  stop_streams (ModestWebkitMimePartView *view, gpointer userdata);

/* list my signals */
enum {
	/* MY_SIGNAL_1, */
	/* MY_SIGNAL_2, */
	LAST_SIGNAL
};

typedef struct _ModestTnyStreamWebkitPrivate ModestTnyStreamWebkitPrivate;
struct _ModestTnyStreamWebkitPrivate {
	GString *buffer;
	GtkWidget *webview;

	gchar *mime_type;
	gchar *encoding;

	guint stop_streams_id;

	gssize max_size;
	gssize current_size;
};
#define MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
                                                       MODEST_TYPE_TNY_STREAM_WEBKIT, \
                                                       ModestTnyStreamWebkitPrivate))
/* globals */
static GObjectClass *parent_class = NULL;

/* uncomment the following if you have defined any signals */
/* static guint signals[LAST_SIGNAL] = {0}; */

GType
modest_tny_stream_webkit_get_type (void)
{
	static GType my_type = 0;
	if (!my_type) {
		static const GTypeInfo my_info = {
			sizeof(ModestTnyStreamWebkitClass),
			NULL,		/* base init */
			NULL,		/* base finalize */
			(GClassInitFunc) modest_tny_stream_webkit_class_init,
			NULL,		/* class finalize */
			NULL,		/* class data */
			sizeof(ModestTnyStreamWebkit),
			1,		/* n_preallocs */
			(GInstanceInitFunc) modest_tny_stream_webkit_init,
			NULL
		};

		static const GInterfaceInfo iface_info = {
			(GInterfaceInitFunc) modest_tny_stream_gtkhml_iface_init,
			NULL,         /* interface_finalize */
			NULL          /* interface_data */
                };

		my_type = g_type_register_static (G_TYPE_OBJECT,
		                                  "ModestTnyStreamWebkit",
		                                  &my_info, 0);

		g_type_add_interface_static (my_type, TNY_TYPE_STREAM,
					     &iface_info);

	}
	return my_type;
}

static void
modest_tny_stream_webkit_class_init (ModestTnyStreamWebkitClass *klass)
{
	GObjectClass *gobject_class;
	gobject_class = (GObjectClass*) klass;

	parent_class            = g_type_class_peek_parent (klass);
	gobject_class->finalize = modest_tny_stream_webkit_finalize;

	g_type_class_add_private (gobject_class, sizeof(ModestTnyStreamWebkitPrivate));
}

static void
modest_tny_stream_webkit_init (ModestTnyStreamWebkit *obj)
{
	ModestTnyStreamWebkitPrivate *priv;
	priv = MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE(obj);

	priv->buffer  = NULL;
	priv->webview = NULL;
	priv->stop_streams_id = 0;

	priv->max_size = 0;
	priv->current_size = 0;

	priv->mime_type = NULL;
	priv->encoding = NULL;
}

static void
modest_tny_stream_webkit_finalize (GObject *obj)
{
	ModestTnyStreamWebkitPrivate *priv;

	priv = MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE(obj);
	if (priv->buffer)
		g_string_free (priv->buffer, TRUE);

	g_free (priv->mime_type);
	g_free (priv->encoding);

	if (priv->stop_streams_id > 0) {
		g_signal_handler_disconnect (G_OBJECT (priv->webview), priv->stop_streams_id);
		priv->stop_streams_id = 0;
	}

	if (priv->webview) {
		g_object_unref (priv->webview);
		priv->webview = NULL;
	}
}

GObject*
modest_tny_stream_webkit_new (WebKitWebView *webview, const gchar *mime_type, const gchar *encoding)
{
	GObject *obj;
	ModestTnyStreamWebkitPrivate *priv;

	obj  = G_OBJECT(g_object_new(MODEST_TYPE_TNY_STREAM_WEBKIT, NULL));
	priv = MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE(obj);

	g_return_val_if_fail (webview, NULL);

	priv->buffer = g_string_new ("");

	priv->webview = g_object_ref (webview);
	priv->mime_type = g_strdup (mime_type);
	priv->encoding = g_strdup (encoding);

	priv->stop_streams_id = g_signal_connect (G_OBJECT (webview), "stop-streams",
						  G_CALLBACK (stop_streams), obj);
	priv->current_size = 0;

	return obj;
}

/* the rest are interface functions */

static ssize_t
webkit_read (TnyStream *self, char *buffer, size_t n)
{
	return -1; /* we cannot read */
}

static ssize_t
webkit_write (TnyStream *self, const char *buffer, size_t n)
{
	ModestTnyStreamWebkitPrivate *priv;

	priv = MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE(self);

	if (!priv->buffer) {
		g_print ("modest: cannot write to closed stream\n");
		return 0;
	}

	if (n == 0 || !buffer)
		return 0;

	if (!priv->webview || !GTK_WIDGET_VISIBLE (priv->webview))
		return -1;

	if (priv->max_size > 0) {

		/* We only use the maximum size for write method, and even we
		 * ignore and fake as we would do a successfull read */
		if (priv->current_size >= priv->max_size)
			return n;

		if (priv->current_size + n > priv->max_size)
			n = priv->max_size - priv->current_size;
	}

	if (!g_main_context_is_owner (NULL))
		gdk_threads_enter ();

	priv->buffer = g_string_append_len (priv->buffer, buffer, n);

	if (!g_main_context_is_owner (NULL))
		gdk_threads_leave ();
	priv->current_size += n;

	return n; /* hmmm */
}

static gint
webkit_flush (TnyStream *self)
{
	return 0;
}

static gint
webkit_close (TnyStream *self)
{
	ModestTnyStreamWebkitPrivate *priv;
	g_return_val_if_fail (self, 0);
	priv = MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE(self);

	if (priv->stop_streams_id > 0) {
		g_signal_handler_disconnect (G_OBJECT (priv->webview), priv->stop_streams_id);
		priv->stop_streams_id = 0;
	}
	if (priv->webview) {
		webkit_web_view_load_string (WEBKIT_WEB_VIEW (priv->webview), priv->buffer->str, priv->mime_type, priv->encoding, NULL);

		g_object_unref (priv->webview);
		priv->webview = NULL;
	}
	if (priv->buffer)
		g_string_free (priv->buffer, TRUE);
	priv->buffer = NULL;

	return 0;
}

static gboolean
webkit_is_eos (TnyStream *self)
{
	return TRUE;
}

static gint
webkit_reset (TnyStream *self)
{
	return 0;
}

static ssize_t
webkit_write_to_stream (TnyStream *self, TnyStream *output)
{
	return 0;
}

static void
stop_streams (ModestWebkitMimePartView *view, gpointer userdata)
{
	ModestTnyStreamWebkit *self = (ModestTnyStreamWebkit *) userdata;
	ModestTnyStreamWebkitPrivate *priv;

	g_return_if_fail (self);
	priv = MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE(self);

	if (priv->webview && priv->stop_streams_id > 0) {
		g_signal_handler_disconnect (G_OBJECT (priv->webview), priv->stop_streams_id);
		priv->stop_streams_id = 0;
	}

	if (priv->webview) {
		g_object_unref (priv->webview);
		priv->webview = NULL;
	}
}

void
modest_tny_stream_webkit_set_max_size (ModestTnyStreamWebkit *stream,
					gssize max_size)
{
	ModestTnyStreamWebkitPrivate *priv;

	g_return_if_fail (MODEST_IS_TNY_STREAM_WEBKIT (stream));
	priv = MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE (stream);

	priv->max_size = max_size;
}

gssize
modest_tny_stream_webkit_get_max_size (ModestTnyStreamWebkit *stream)
{
	ModestTnyStreamWebkitPrivate *priv;

	g_return_val_if_fail (MODEST_IS_TNY_STREAM_WEBKIT (stream), 0);
	priv = MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE (stream);

	return priv->max_size;
}

gboolean
modest_tny_stream_webkit_limit_reached (ModestTnyStreamWebkit *self)
{
	ModestTnyStreamWebkitPrivate *priv;

	g_return_val_if_fail (MODEST_IS_TNY_STREAM_WEBKIT (self), 0);
	priv = MODEST_TNY_STREAM_WEBKIT_GET_PRIVATE (self);

	return (priv->max_size > 0) && (priv->current_size >= priv->max_size);
}

static void
modest_tny_stream_gtkhml_iface_init (gpointer g_iface, gpointer iface_data)
{
        TnyStreamIface *klass;

	g_return_if_fail (g_iface);

	klass = (TnyStreamIface*) g_iface;

        klass->read            = webkit_read;
        klass->write           = webkit_write;
        klass->flush           = webkit_flush;
        klass->close           = webkit_close;
	klass->is_eos          = webkit_is_eos;
	klass->reset           = webkit_reset;
	klass->write_to_stream = webkit_write_to_stream;
}


text:
layout: post
title: easytranscript
subtitle: Kostenfreie Transkriptions-Software
bigimg: /img/easytranscript.jpg
---

Vor kurzem bin ich auf [_easytranscript_][1] gestoßen. Dabei handelt es sich um eine _kostenfreie Transkiptions-Software_, die an f4/f5 erinnert. Da es sich um ein Java-Programm handelt, kann die Software unter Linux, OS X und Windows genutzt werden. Erfreulich ist, dass der Support sehr gut ist und die Software zudem aktiv weiterentwickelt wird (letztes Update vom 22. November 2015). Die Oberfläche glänzt durch funktionale Schlichtheit. Bisher vermisse ich kein Feature (Zeitmarken, Projektverwaltung, Stenographie,…) – sogar Fußschalter werden unterstützt.

Ich plane [_easytranscript_][2] für meine anstehenden Transkriptionen zu nutzten. Von künftigen Erfahrungen, wie sich das Tool in meinen Workflow integriert, werde ich demnächst berichten.

[1]:	http://www.e-werkzeug.eu/index.php/de/produkte/easytranscript
[2]:	http://www.e-werkzeug.eu/index.php/de/produkte/easytranscript


text:
package com.intellij.openapi.project.ex;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.io.IOException;
import java.util.Collection;

public abstract class ProjectManagerEx extends ProjectManager {
  public static ProjectManagerEx getInstanceEx() {
    return (ProjectManagerEx)ApplicationManager.getApplication().getComponent(ProjectManager.class);
  }

  /**
   * @param filePath path to .ipr file or directory where .idea directory is located
   */
  @Nullable
  public abstract Project newProject(final String projectName, @NotNull String filePath, boolean useDefaultProjectSettings, boolean isDummy);

  @Nullable
  public abstract Project loadProject(@NotNull String filePath) throws IOException;

  public abstract boolean openProject(@NotNull Project project);

  public abstract boolean isProjectOpened(Project project);

  public abstract boolean canClose(@NotNull Project project);

  public abstract void saveChangedProjectFile(@NotNull VirtualFile file, @NotNull Project project);

  public abstract void blockReloadingProjectOnExternalChanges();
  public abstract void unblockReloadingProjectOnExternalChanges();

  @TestOnly
  public abstract void openTestProject(@NotNull Project project);

  @TestOnly
  @NotNull
  // returns remaining open test projects
  public abstract Collection<Project> closeTestProject(@NotNull Project project);

  // returns true on success
  public abstract boolean closeAndDispose(@NotNull Project project);

  @Nullable
  @Override
  public Project createProject(String name, String path) {
    return newProject(name, path, true, false);
  }

  @Nullable
  public abstract Project convertAndLoadProject(@NotNull String filePath) throws IOException;
}


text:
using content::FakeSpeechRecognitionManager;
using content::WebContents;

namespace speech {

class ChromeSpeechRecognitionTest : public InProcessBrowserTest {
 public:
  ChromeSpeechRecognitionTest() {}
  ~ChromeSpeechRecognitionTest() override {}

  void SetUp() override {
    // SpeechRecognition test specific SetUp.
    fake_speech_recognition_manager_.reset(
        new content::FakeSpeechRecognitionManager());
    fake_speech_recognition_manager_->set_should_send_fake_response(true);
    // Inject the fake manager factory so that the test result is returned to
    // the web page.
    content::SpeechRecognitionManager::SetManagerForTesting(
        fake_speech_recognition_manager_.get());

    InProcessBrowserTest::SetUp();
  }

  void TearDown() override {
    content::SpeechRecognitionManager::SetManagerForTesting(NULL);
    fake_speech_recognition_manager_->SetDelegate(NULL);
    InProcessBrowserTest::TearDown();
  }

 protected:
  scoped_ptr<content::FakeSpeechRecognitionManager>
      fake_speech_recognition_manager_;

 private:
  DISALLOW_COPY_AND_ASSIGN(ChromeSpeechRecognitionTest);
};

class SpeechWebContentsObserver : public content::WebContentsObserver {
 public:
  explicit SpeechWebContentsObserver(WebContents* web_contents)
      : WebContentsObserver(web_contents),
        render_view_host_changed_(false),
        web_contents_destroyed_(false) {}
  ~SpeechWebContentsObserver() override {}

  // content::WebContentsObserver overrides.
  void RenderViewHostChanged(content::RenderViewHost* old_host,
                             content::RenderViewHost* new_host) override {
    render_view_host_changed_ = true;
  }
  void WebContentsDestroyed() override { web_contents_destroyed_ = true; }

  bool web_contents_destroyed() { return web_contents_destroyed_; }
  bool render_view_host_changed() { return render_view_host_changed_; }

 private:
  bool render_view_host_changed_;
  bool web_contents_destroyed_;

  DISALLOW_COPY_AND_ASSIGN(SpeechWebContentsObserver);
};

// Tests that ChromeSpeechRecognitionManagerDelegate works properly
// when a WebContents goes away (WCO::WebContentsDestroyed) or the RVH
// changes within a WebContents (WCO::RenderViewHostChanged).
IN_PROC_BROWSER_TEST_F(ChromeSpeechRecognitionTest, BasicTearDown) {
  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
  net::SpawnedTestServer::SSLOptions ssl_options;
  net::SpawnedTestServer https_server(
      net::SpawnedTestServer::TYPE_HTTPS, ssl_options,
      base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
  ASSERT_TRUE(https_server.Start());

  GURL http_url =
      embedded_test_server()->GetURL("/speech/web_speech_test.html");
  GURL https_url(https_server.GetURL("files/speech/web_speech_test.html"));

  scoped_ptr<ChromeSpeechRecognitionManagerDelegate> delegate(
      new ChromeSpeechRecognitionManagerDelegate());
  static_cast<content::FakeSpeechRecognitionManager*>(
      fake_speech_recognition_manager_.get())->SetDelegate(delegate.get());

  ui_test_utils::NavigateToURL(browser(), http_url);
  WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  EXPECT_TRUE(web_contents);
  SpeechWebContentsObserver speech_contents_observer(web_contents);

  base::string16 success_title(base::ASCIIToUTF16("PASS"));
  base::string16 failure_title(base::ASCIIToUTF16("FAIL"));

  const char kRetriveTranscriptScript[] =
      "window.domAutomationController.send(window.getFirstTranscript())";
  const char kExpectedTranscript[] = "Pictures of the moon";

  {
    content::TitleWatcher title_watcher(web_contents, success_title);
    title_watcher.AlsoWaitForTitle(failure_title);
    EXPECT_TRUE(
        content::ExecuteScript(web_contents, "testSpeechRecognition()"));
    EXPECT_EQ(success_title, title_watcher.WaitAndGetTitle());

    std::string output;
    EXPECT_TRUE(content::ExecuteScriptAndExtractString(
        web_contents, kRetriveTranscriptScript, &output));
    EXPECT_EQ(kExpectedTranscript, output);
  }

  // Navigating to an https page will force RVH change within
  // |web_contents|, results in WCO::RenderViewHostChanged().
  ui_test_utils::NavigateToURL(browser(), https_url);

  EXPECT_TRUE(speech_contents_observer.render_view_host_changed());

  {
    content::TitleWatcher title_watcher(web_contents, success_title);
    title_watcher.AlsoWaitForTitle(failure_title);
    EXPECT_TRUE(
        content::ExecuteScript(web_contents, "testSpeechRecognition()"));
    EXPECT_EQ(success_title, title_watcher.WaitAndGetTitle());

    std::string output;
    EXPECT_TRUE(content::ExecuteScriptAndExtractString(
        web_contents, kRetriveTranscriptScript, &output));
    EXPECT_EQ(kExpectedTranscript, output);
  }

  // Close the tab to so that we see WCO::WebContentsDestroyed().
  chrome::CloseTab(browser());
  EXPECT_TRUE(speech_contents_observer.web_contents_destroyed());
}

}  // namespace speech


text:
package parser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import config.Model;
import fetcher.Page;

public class DoubanParser implements Parser{

	@Override
	public List<Map<String, String>> parse(Page page,Model model) {
		// TODO Auto-generated method stub
		List<Map<String, String>> datas = new ArrayList<Map<String,String>>();
		Document doc = Jsoup.parse(page.getContent());
		Map<String, String> data = new HashMap<String, String>();
		Elements elements = doc.select("div#link-report > div");
		for (Element element : elements) {
			data.put("content", element.text());
			data.put("origin_url", page.getUrl());
			datas.add(data);
		}
		return datas;
	}

}


text:
import _ from 'lodash'
import path from 'path'
import { TagExpressionParser } from 'cucumber-tag-expressions'

const FEATURE_LINENUM_REGEXP = /^(.*?)((?::[\d]+)+)?$/
const tagExpressionParser = new TagExpressionParser()

export default class PickleFilter {
  constructor({ featurePaths, names, tagExpression }) {
    this.featureUriToLinesMapping = this.getFeatureUriToLinesMapping(
      featurePaths || []
    )
    this.names = names || []
    if (tagExpression) {
      this.tagExpressionNode = tagExpressionParser.parse(tagExpression || '')
    }
  }

  getFeatureUriToLinesMapping(featurePaths) {
    const mapping = {}
    featurePaths.forEach(featurePath => {
      const match = FEATURE_LINENUM_REGEXP.exec(featurePath)
      if (match) {
        const uri = path.resolve(match[1])
        const linesExpression = match[2]
        if (linesExpression) {
          if (!mapping[uri]) {
            mapping[uri] = []
          }
          linesExpression
            .slice(1)
            .split(':')
            .forEach(line => {
              mapping[uri].push(parseInt(line))
            })
        }
      }
    })
    return mapping
  }

  matches({ pickle, uri }) {
    return (
      this.matchesAnyLine({ pickle, uri }) &&
      this.matchesAnyName(pickle) &&
      this.matchesAllTagExpressions(pickle)
    )
  }

  matchesAnyLine({ pickle, uri }) {
    const lines = this.featureUriToLinesMapping[path.resolve(uri)]
    if (lines) {
      return _.size(_.intersection(lines, _.map(pickle.locations, 'line'))) > 0
    }
    return true
  }

  matchesAnyName(pickle) {
    if (this.names.length === 0) {
      return true
    }
    return _.some(this.names, name => pickle.name.match(name))
  }

  matchesAllTagExpressions(pickle) {
    if (!this.tagExpressionNode) {
      return true
    }
    return this.tagExpressionNode.evaluate(_.map(pickle.tags, 'name'))
  }
}


text:
package org.ninjatasks.execution

import scala.concurrent.Promise
import akka.actor.ActorRef
import scala.concurrent.promise
import java.util.UUID

private[ninjatasks] object WorkerContext
{
	def apply(worker: ActorRef, workId: UUID) =
		new WorkerContext(promise[Int](), workId, worker)
}

/**
 * Promise used to signal cancellation of work being processed by workers.
 * Created by Gilad Ber on 4/26/2014.
 */
private[ninjatasks] class WorkerContext(val promise: Promise[Int], val workId: UUID, val worker: ActorRef)
{

	/**
	 * Finishes execution of the promise object, which will cause its wrapping future
	 * to also stop, hopefully causing the executing job to stop in the near future (depends
	 * on client code).
	 */
	def signalStop(): Unit =
	{
		println("Received signal to stop work " + workId)
		promise.success(1)
	}

}


text:
package ie.tcd.slscs.itut.NCIReader;

import org.htmlcleaner.*;

import java.util.HashMap;

public class NCITeiTagProvider extends HashMap<String, TagInfo> implements ITagInfoProvider {

    public NCITeiTagProvider() {
        TagInfo tagInfo;

        tagInfo = new TagInfo("address", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("address", tagInfo);

        tagInfo = new TagInfo("addrline", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("addrline", tagInfo);

        tagInfo = new TagInfo("author", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("author", tagInfo);

        tagInfo = new TagInfo("availability", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("availability", tagInfo);

        tagInfo = new TagInfo("biblStruct", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("biblStruct", tagInfo);

        tagInfo = new TagInfo("body", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("body", tagInfo);

        tagInfo = new TagInfo("byline", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("byline", tagInfo);

        tagInfo = new TagInfo("caption", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("caption", tagInfo);

        tagInfo = new TagInfo("catref", ContentType.none, BelongsTo.BODY, false, false, false, CloseTag.optional, Display.inline);
        tagInfo.setName("catRef");
        this.put("catref", tagInfo);
        this.put("catRef", tagInfo);

        tagInfo = new TagInfo("creation", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("creation", tagInfo);

        tagInfo = new TagInfo("Date", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("Date", tagInfo);

        tagInfo = new TagInfo("distributor", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("distributor", tagInfo);

        tagInfo = new TagInfo("div1", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("div1", tagInfo);

        tagInfo = new TagInfo("extent", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("extent", tagInfo);

        tagInfo = new TagInfo("fileDesc", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("fileDesc", tagInfo);

        tagInfo = new TagInfo("foreign", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("foreign", tagInfo);

        tagInfo = new TagInfo("group", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("group", tagInfo);

        tagInfo = new TagInfo("head", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("head", tagInfo);

        tagInfo = new TagInfo("hi", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("hi", tagInfo);

        tagInfo = new TagInfo("idno", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("idno", tagInfo);

        tagInfo = new TagInfo("imprint", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("imprint", tagInfo);

        tagInfo = new TagInfo("monogr", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("monogr", tagInfo);

        tagInfo = new TagInfo("p", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.optional, Display.block);
        this.put("p", tagInfo);

        tagInfo = new TagInfo("profileDesc", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("profileDesc", tagInfo);

        tagInfo = new TagInfo("publicationStmt", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("publicationStmt", tagInfo);

        tagInfo = new TagInfo("publisher", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("publisher", tagInfo);

        tagInfo = new TagInfo("pubPlace", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("pubPlace", tagInfo);

        tagInfo = new TagInfo("quote", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("quote", tagInfo);

        tagInfo = new TagInfo("s", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("s", tagInfo);

        tagInfo = new TagInfo("sourceDesc", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("sourceDesc", tagInfo);

        tagInfo = new TagInfo("tei.2", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("tei.2", tagInfo);

        tagInfo = new TagInfo("teiHeader", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("teiHeader", tagInfo);

        tagInfo = new TagInfo("text", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("text", tagInfo);

        tagInfo = new TagInfo("textClass", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("textClass", tagInfo);

        tagInfo = new TagInfo("title", ContentType.text, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("title", tagInfo);

        tagInfo = new TagInfo("titleStmt", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("titleStmt", tagInfo);

        tagInfo = new TagInfo("w", ContentType.all, BelongsTo.BODY, false, false, false, CloseTag.required, Display.block);
        this.put("w", tagInfo);
    }
    public TagInfo getTagInfo(String tagName) {
        return get(tagName);
    }

    /**
     * Removes tag info with specified name.
     * @param tagName Name of the tag to be removed from the tag provider.
     */
    public void removeTagInfo(String tagName) {
        if (tagName != null) {
            remove(tagName);
        }
    }

    /**
     * Sets new tag info.
     * @param tagInfo tag info to be added to the provider.
     */
    public void addTagInfo(TagInfo tagInfo) {
        if (tagInfo != null) {
            put(tagInfo.getName(), tagInfo);
        }
    }
}


text:
class MessagesController < ApplicationController
  before_action :authenticate_user!

  def index
    @messages = current_user.messages.includes(:actor)
                       .order(id: :desc)
                       .page params[:page]
    @message_groups = @messages.group_by { |message| message.created_at.to_date }
  end

  def show
    @message = Message.find params[:id]
    authorize @message
    unless @message.is_read
      @message.is_read = true
      @message.save
    end
    respond_to do |format|
      format.html { redirect_to @message.path }
      format.json { render json: { success: true } }
    end
  end

  def read_all
    Message.where(receiver_id: current_user.id).update_all(is_read: true)
    redirect_to messages_path
  end
end