text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>microservices</groupId>
        <artifactId>native-foundation</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <name>native-foundation:user-service</name>
    <artifactId>user-service</artifactId>
    <packaging>jar</packaging>
    <properties>
        <start-class>users.Application</start-class>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-hystrix-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>


text:
<?php

?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

 <link rel="stylesheet" type="text/css" href="<?php  echo base_url('/Bootstrap/css/bootstrap.css'); ?>" media="all"/>

<title> Patient Card </title>

            Patient Name   : <?php echo $pprofile->patientTitle.$pprofile->patientFullName;?>

Patient Hin : <?php echo $pprofile->patientHIN;?>

		 <img alt="12345" src="<?php echo base_url('/Barcode/barcode.php'); ?>?codetype=Code39&size=40&text=<?php echo $pprofile->patientHIN;?>" />

                <img style="width: 115px; height: 100px; padding-left: 2px;" src="<?php
                if ((strpos($pprofile->patientPhoto, 'null') !== FALSE) | $pprofile->patientPhoto == "" | $pprofile->patientPhoto == null) {
                    //echo base_url() . '/assets/ico/proimage.jpg';
                    {
                        if ($pprofile->patientGender == 'Male')
                            echo base_url() . "/assets/ico/proimage.jpg";
                        else if($pprofile->patientGender == 'Female')
                            echo base_url() . "/assets/ico/proimagefemale.png";
                        else {
                            echo base_url() . "/assets/ico/proimage.jpg";
                        }
                    }
                } else
                    echo base_url() . '/uploads/patient_photos/'.$pprofile->patientPhoto;
                ?>" />

        <div src="<?php
                if ((strpos($pprofile->patientPhoto, 'null') !== FALSE) | $pprofile->patientPhoto == "" | $pprofile->patientPhoto == null) {
                    //echo base_url() . '/assets/ico/proimage.jpg';
                    {
                        if ($pprofile->patientGender == 'Male')
                            echo base_url() . "/assets/ico/proimage.jpg";
                        else if($pprofile->patientGender == 'Female')
                            echo base_url() . "/assets/ico/proimagefemale.png";
                        else {
                            echo base_url() . "/assets/ico/proimage.jpg";
                        }
                    }
                } else
                    echo base_url() . '/uploads/patient_photos/'.$pprofile->patientPhoto;
                ?>"

Bring this card with you on every visit to the hospital.

රෝහලට පැමිණෙන සැම විටම මෙම කාඩ්පත රැගෙන එන්න.

                    <input type="button" class="btn  btn-primary"value="Print" name="btnPrint" id="btnPrint" onclick="printCard()">

redpajama_set_name: RedPajamaGithub


text:
A responive single-page application featuring a map of some restaurants in Vancouver, BC for my FEND at Udacity.

### App Functionality
- __Search Bar:__ Filters both the restaurants in the list view and the markers on the map.
- __List View:__ Show restaurants that have been searched for, additionally clicking on a restaurant activates its associated map marker.
- __Map:__ Shows each searched restaurant as a marker, each marker can be clicked and shows an unique image about the restaurant takedn by users and uploaded to Yelp in an infowindow.

### Project Details
##### Courses from Udacity
- [Intro to Ajax](https://www.udacity.com/course/intro-to-ajax--ud110)
- [Javascript Design Patterns](https://www.udacity.com/course/javascript-design-patterns--ud989)

##### Helpful Resources
- [Project 5 Overview WebCast](https://github.com/udacity/fend-office-hours/tree/master/Javascript%20Design%20Patterns/P5%20Project%20Overview)
- [Google Maps](https://developers.google.com/maps/documentation/)
- [Knockout JS Tutorials](http://learn.knockoutjs.com/)
- [Yelp Developers](https://www.yelp.ca/developers)
- [Google Search](https://www.google.ca/)

##### Special Thanks To
- [Udacity ND discussion forum](https://discussions.udacity.com/categories)
- [Udacity Vancouver Meetup](http://www.meetup.com/Udacity-Vancouver-Meetup/)
-  Hot Developer Bitsofbits

#### Udacity Code Review And Feedback
- [Always start a new line for each selector and declaration](https://udacity.github.io/frontend-nanodegree-styleguide/css.html#selector-declaration-separation)
- [The benefits of using a CDN](https://gtmetrix.com/why-use-a-cdn.html)
- [CDN library](https://cdnjs.com/libraries)
- [Instructions of handling Google maps asynchronously ](https://discussions.udacity.com/t/handling-google-maps-in-async-and-fallback/34282)
- [Make map responsive stackoverflow](https://stackoverflow.com/questions/1556921/google-map-api-v3-set-bounds-and-center)
- [Set bounce for google map](https://developers.google.com/maps/documentation/javascript/reference?hl=en#LatLng)


text:
package embedconflict

import (
	"os"
	"os/exec"
	"strings"
	"testing"
)

func TestEmbedConflict(t *testing.T) {
	cmd := exec.Command("protoc", "--gogo_out=.", "-I=../../../../../:../../protobuf/:.", "ec.proto")
	data, err := cmd.CombinedOutput()
	if err == nil && !strings.Contains(string(data), "Plugin failed with status code 1") {
		t.Errorf("Expected error, got: %s", data)
		if err := os.Remove("ec.pb.go"); err != nil {
			t.Error(err)
		}
	}
	t.Logf("received expected error = %v and output = %v", err, string(data))
}

func TestEmbedMarshaler(t *testing.T) {
	cmd := exec.Command("protoc", "--gogo_out=.", "-I=../../../../../:../../protobuf/:.", "em.proto")
	data, err := cmd.CombinedOutput()
	dataStr := string(data)
	t.Logf("received error = %v and output = %v", err, dataStr)
	if !strings.Contains(dataStr, "WARNING: found non-") || !strings.Contains(dataStr, "unsafe_marshaler") {
		t.Errorf("Expected WARNING: found non-[marshaler unsafe_marshaler] C with embedded marshaler D")
	}
	if err := os.Remove("em.pb.go"); err != nil {
		t.Error(err)
	}
}

func TestEmbedExtend(t *testing.T) {
	cmd := exec.Command("protoc", "--gogo_out=.", "-I=../../../../../:../../protobuf/:.", "ee.proto")
	data, err := cmd.CombinedOutput()
	if err == nil && !strings.Contains(string(data), "Plugin failed with status code 1") {
		t.Errorf("Expected error, got: %s", data)
		if err := os.Remove("ee.pb.go"); err != nil {
			t.Error(err)
		}
	}
	t.Logf("received expected error = %v and output = %v", err, string(data))
}

func TestCustomName(t *testing.T) {
	cmd := exec.Command("protoc", "--gogo_out=.", "-I=../../../../../:../../protobuf/:.", "en.proto")
	data, err := cmd.CombinedOutput()
	if err == nil && !strings.Contains(string(data), "Plugin failed with status code 1") {
		t.Errorf("Expected error, got: %s", data)
		if err := os.Remove("en.pb.go"); err != nil {
			t.Error(err)
		}
	}
	t.Logf("received expected error = %v and output = %v", err, string(data))
}

func TestRepeatedEmbed(t *testing.T) {
	cmd := exec.Command("protoc", "--gogo_out=.", "-I=../../../../../:../../protobuf/:.", "er.proto")
	data, err := cmd.CombinedOutput()
	if err == nil && !strings.Contains(string(data), "Plugin failed with status code 1") {
		t.Errorf("Expected error, got: %s", data)
		if err := os.Remove("er.pb.go"); err != nil {
			t.Error(err)
		}
	}
	dataStr := string(data)
	t.Logf("received error = %v and output = %v", err, dataStr)
	warning := "ERROR: found repeated embedded field B in message A"
	if !strings.Contains(dataStr, warning) {
		t.Errorf("Expected " + warning)
	}
}

func TestTakesTooLongToDebug(t *testing.T) {
	cmd := exec.Command("protoc", "--gogo_out=.", "-I=../../../../../:../../protobuf/:.", "eb.proto")
	data, err := cmd.CombinedOutput()
	if err == nil && !strings.Contains(string(data), "Plugin failed with status code 1") {
		t.Errorf("Expected error, got: %s", data)
		if err := os.Remove("eb.pb.go"); err != nil {
			t.Error(err)
		}
	}
	dataStr := string(data)
	t.Logf("received error = %v and output = %v", err, dataStr)
	warning := "ERROR: found embedded bytes field"
	if !strings.Contains(dataStr, warning) {
		t.Errorf("Expected " + warning)
	}
}


text:
module Initialize
  ( withGameInit
  ) where

import Graphics.UI.SDL as SDL
import Graphics.UI.SDL.Mixer
import Graphics.Rendering.OpenGL

import GlobalSettings

withGameInit :: (Surface -> IO ()) -> IO ()
withGameInit f = do
  withInit [InitEverything] $ do
    window <- setVideoMode windowWidth windowHeight windowDepth [OpenGL]
    showCursor False
    openAudio 44100 AudioS16Sys 2 4096
    initOpenGL
    f window
    closeAudio

initOpenGL :: IO ()
initOpenGL = do
  mapM_ ($= Enabled) [ texture Texture2D
                     , blend
                     ]
  matrixMode $= Projection
  ortho 0 w 0 h (-1) 1
  matrixMode $= Modelview 0
    where
      w = realToFrac windowWidth
      h = realToFrac windowHeight


text:
package cmd

import (
	"flag"

	"fmt"
	"net/http"

	"github.com/uber/kraken/build-index/tagclient"
	"github.com/uber/kraken/lib/dockerregistry/transfer"
	"github.com/uber/kraken/lib/healthcheck"
	"github.com/uber/kraken/lib/store"
	"github.com/uber/kraken/lib/upstream"
	"github.com/uber/kraken/metrics"
	"github.com/uber/kraken/nginx"
	"github.com/uber/kraken/origin/blobclient"
	"github.com/uber/kraken/proxy/proxyserver"
	"github.com/uber/kraken/proxy/registryoverride"
	"github.com/uber/kraken/utils/configutil"
	"github.com/uber/kraken/utils/flagutil"
	"github.com/uber/kraken/utils/log"

	"github.com/uber-go/tally"
	"go.uber.org/zap"
)

// Flags defines proxy CLI flags.
type Flags struct {
	Ports         flagutil.Ints
	ServerPort    int
	ConfigFile    string
	KrakenCluster string
	SecretsFile   string
}

// ParseFlags parses proxy CLI flags.
func ParseFlags() *Flags {
	var flags Flags
	flag.Var(
		&flags.Ports, "port", "port to listen on (may specify multiple)")
	flag.IntVar(
		&flags.ServerPort, "server-port", 0, "http server port to listen on")
	flag.StringVar(
		&flags.ConfigFile, "config", "", "configuration file path")
	flag.StringVar(
		&flags.KrakenCluster, "cluster", "", "cluster name (e.g. prod01-zone1)")
	flag.StringVar(
		&flags.SecretsFile, "secrets", "", "path to a secrets YAML file to load into configuration")
	flag.Parse()
	return &flags
}

type options struct {
	config  *Config
	metrics tally.Scope
	logger  *zap.Logger
}

// Option defines an optional Run parameter.
type Option func(*options)

// WithConfig ignores config/secrets flags and directly uses the provided config
// struct.
func WithConfig(c Config) Option {
	return func(o *options) { o.config = &c }
}

// WithMetrics ignores metrics config and directly uses the provided tally scope.
func WithMetrics(s tally.Scope) Option {
	return func(o *options) { o.metrics = s }
}

// WithLogger ignores logging config and directly uses the provided logger.
func WithLogger(l *zap.Logger) Option {
	return func(o *options) { o.logger = l }
}

// Run runs the proxy.
func Run(flags *Flags, opts ...Option) {
	if len(flags.Ports) == 0 {
		panic("must specify a port")
	}

	var overrides options
	for _, o := range opts {
		o(&overrides)
	}

	var config Config
	if overrides.config != nil {
		config = *overrides.config
	} else {
		if err := configutil.Load(flags.ConfigFile, &config); err != nil {
			panic(err)
		}
		if flags.SecretsFile != "" {
			if err := configutil.Load(flags.SecretsFile, &config); err != nil {
				panic(err)
			}
		}
	}

	if overrides.logger != nil {
		log.SetGlobalLogger(overrides.logger.Sugar())
	} else {
		zlog := log.ConfigureLogger(config.ZapLogging)
		defer zlog.Sync()
	}

	stats := overrides.metrics
	if stats == nil {
		s, closer, err := metrics.New(config.Metrics, flags.KrakenCluster)
		if err != nil {
			log.Fatalf("Failed to init metrics: %s", err)
		}
		stats = s
		defer closer.Close()
	}

	go metrics.EmitVersion(stats)

	cas, err := store.NewCAStore(config.CAStore, stats)
	if err != nil {
		log.Fatalf("Failed to create store: %s", err)
	}

	tls, err := config.TLS.BuildClient()
	if err != nil {
		log.Fatalf("Error building client tls config: %s", err)
	}

	origins, err := config.Origin.Build(upstream.WithHealthCheck(healthcheck.Default(tls)))
	if err != nil {
		log.Fatalf("Error building origin host list: %s", err)
	}

	r := blobclient.NewClientResolver(blobclient.NewProvider(blobclient.WithTLS(tls)), origins)
	originCluster := blobclient.NewClusterClient(r)

	buildIndexes, err := config.BuildIndex.Build(upstream.WithHealthCheck(healthcheck.Default(tls)))
	if err != nil {
		log.Fatalf("Error building build-index host list: %s", err)
	}

	tagClient := tagclient.NewClusterClient(buildIndexes, tls)

	transferer := transfer.NewReadWriteTransferer(stats, tagClient, originCluster, cas)

	// Open preheat function only if server-port was defined.
	if flags.ServerPort != 0 {
		server := proxyserver.New(stats, originCluster)
		addr := fmt.Sprintf(":%d", flags.ServerPort)
		log.Infof("Starting http server on %s", addr)
		go func() {
			log.Fatal(http.ListenAndServe(addr, server.Handler()))
		}()
	}

	registry, err := config.Registry.Build(config.Registry.ReadWriteParameters(transferer, cas, stats))
	if err != nil {
		log.Fatalf("Error creating registry: %s", err)
	}
	go func() {
		log.Info("Starting registry...")
		log.Fatal(registry.ListenAndServe())
	}()

	ros := registryoverride.NewServer(config.RegistryOverride, tagClient)
	go func() {
		log.Fatal(ros.ListenAndServe())
	}()

	log.Info("Starting nginx...")
	log.Fatal(nginx.Run(config.Nginx, map[string]interface{}{
		"ports": flags.Ports,
		"registry_server": nginx.GetServer(
			config.Registry.Docker.HTTP.Net, config.Registry.Docker.HTTP.Addr),
		"registry_override_server": nginx.GetServer(
			config.RegistryOverride.Listener.Net, config.RegistryOverride.Listener.Addr)},
		nginx.WithTLS(config.TLS)))
}


text:
Reports synchronization which use this as their lock
expression. Constructs reported include synchronized
blocks which lock this, and calls to wait(),
notify() or notifyAll() which target wait().
Such constructs, like synchronized methods, make it hard to track just who is locking on a given
object, and make possible "denial of service" attacks on objects. As an alternative, consider
locking on a private instance variable, access to which can be completely controlled.


text:
var cp = require('child_process'),
	fs = require('fs'),
	path = require('path'),
	package = require('./package.json');

module.exports.requireNative = requireNative;
module.exports.install = install;

function requireNative(basePath, moduleName) {
	moduleName = moduleName || package.name;

// Look for binary for this platform
	var v8 = 'v8-'+ /[0-9]+\.[0-9]+/.exec(process.versions.v8)[0];
	var modPath = path.join(basePath, 'bin', process.platform+ '-'+ process.arch+ '-'+ v8, moduleName);
	try {
		fs.statSync(modPath + '.node');
	} catch (ex) {
		// No binary!
		throw new Error('`' + modPath + '.node` is missing. Try reinstalling `' + package.name + '`?');
	}

// Pull in implementation
	return require(modPath);
}

// Parse args
var force = false, debug = false;
var
	arch = process.arch,
	platform = process.platform,
	v8 = /[0-9]+\.[0-9]+/.exec(process.versions.v8)[0];
var args = process.argv.slice(2).filter(function(arg) {
	if (arg === '-f') {
		force = true;
		return false;
	} else if (arg.substring(0, 13) === '--target_arch') {
		arch = arg.substring(14);
	} else if (arg === '--debug') {
		debug = true;
	}
	return true;
});

var modPath = platform+ '-'+ arch+ '-v8-'+ v8;
var moduleFileName;
var basePath;

function install(argBasePath, moduleName) {
	if (!{ia32: true, x64: true, arm: true}.hasOwnProperty(arch)) {
		console.error('Unsupported (?) architecture: `'+ arch+ '`');
		process.exit(1);
	}

	basePath = argBasePath;
	moduleFileName = (moduleName || package.name) + ".node";

	// Test for pre-built library
	if (!force) {
		try {
			fs.statSync(path.join(basePath, 'bin', modPath, moduleFileName));
			console.log('`'+ modPath+ '` exists; testing');
			cp.execFile(process.execPath, [path.join(basePath, 'binary-test')], function(err, stdout, stderr) {
				if (err || stdout !== 'pass' || stderr) {
					console.log('Problem with the binary; manual build incoming');
					build();
				} else {
					console.log('Binary is fine; exiting');
				}
			});
		} catch (ex) {
			// Stat failed
			build();
		}
	} else {
		build();
	}
}

// Build it
function build() {
	cp.spawn(
		process.platform === 'win32' ? 'node-gyp.cmd' : 'node-gyp',
		['rebuild'].concat(args),
		{customFds: [0, 1, 2]})
	.on('exit', function(err) {
		if (err) {
			if (err === 127) {
				console.error(
					'node-gyp not found! Please upgrade your install of npm! You need at least 1.1.5 (I think) '+
					'and preferably 1.1.30.'
				);
			} else {
				console.error('Build failed');
			}
			return process.exit(err);
		}
		afterBuild();
	});
}

// Move it to expected location
function afterBuild() {
	var targetPath = path.join(basePath, 'build', debug ? 'Debug' : 'Release', moduleFileName);
	var installPath = path.join(basePath, 'bin', modPath, moduleFileName);

	try {
		fs.mkdirSync(path.join(basePath, 'bin', modPath));
	} catch (ex) {}

	try {
		fs.statSync(targetPath);
	} catch (ex) {
		console.error('Build succeeded but target not found');
		process.exit(1);
	}
	fs.renameSync(targetPath, installPath);
	console.log('Installed in `'+ installPath+ '`');
}


text:
title: Кастомизация подписей в Web-контролах
sidebar: flexberry-aspnet_sidebar
keywords: Flexberry ASP-NET, Web UI (Контролы)
toc: true
permalink: ru/fa_web-controls-custom-captions.html
lang: ru
---

Подписи к контролам храняться в строковых ресурсах в *.resx-файлах соответствующих тому или иному контролу.
Например подписи к элементам WebObjectListView храняться в проекте `ICSSoft.STORMNET.Web.AjaxControls` в файле `Resources/WebObjectListView.resx`,
а подписи к контролу DatePicker в том же проекте ICSSoft.STORMNET.Web.AjaxControls в файле Resources/DatePicker.resx, и т.д.

Если на прикладном уровне требуется переопределить подпись к тому или иному элементу контрола, достаточно в прикладном проекте создать файл со строковыми ресурсами, с именем соответствующим контролу, и переопределить в нем желаемый строковый ресурс.
Например, чтобы в контроле WebObjectListView изменить подпись к кнопке обновления с "Обновить" на "Обновить список", достаточно в прикладном проеекте создать файл `Resources/WebObjectListView.resx`
и определить в нем строковый ресурс "ToolbarButtonRefreshCaption" со значением "Обновить список".
Актуальный перечень доступных `*.resx-файлов` и их содержимое лучше смотреть в проекте `ICSSoft.STORMNET.Web.AjaxControls` в каталоге `Resources`.

## Разработка контролов с кастомизируемыми подписями

Для того, чтобы подписи разрабатываемых контролов были кастомизируемы (при помощи ранее описанного подхода), в designer-e генерируемых `*.resx-файлов` необходимо заменять использование стандартного `ResourceManager-a ` на `ICSSoft.STORMNET.Web.Tools.Resources.ResourceManger`.

Например в `WebObjectListView.Designer.cs`, соответствующем файлу `WebObjectListView.resx`, следующий сгенерированный код:

```csharp
private static global::System.Resources.ResourceManager resourceMan;

private static global::System.Globalization.CultureInfo resourceCulture;

[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal WebObjectListView() {
}

/// <summary>
///   Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
	get {
		if (object.ReferenceEquals(resourceMan, null)) {
		    // Обратите внимание, в автоматически сгенерированном коде первым параметром отдается полный путь к *.resx-файлу, включая пространство имен.
			// В этом случае для компонента не будет недоступна кастомизация подписей.
			global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ICSSoft.STORMNET.Web.AjaxControls.Resources.WebObjectListView", typeof(WebObjectListView).Assembly);
			resourceMan = temp;
		}
		return resourceMan;
	}
}

```

был заменен на:

```csharp
private static ICSSoft.STORMNET.Web.Tools.Resources.ResourceManager resourceManager;

private static global::System.Globalization.CultureInfo resourceCulture;

[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal WebObjectListView() {
}

/// <summary>
///   Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static ICSSoft.STORMNET.Web.Tools.Resources.ResourceManager ResourceManager {
	get {
		if (object.ReferenceEquals(resourceManager, null)) {
		    // Обратите внимание, что здесь первым параметром отдается не полный путь к *.resx-файлу, а путь относительно каталога Resources.
			// Ожидается, что строковые ресурсы как в сборке ICSSoft.STORMNET.Web.AjaxControls, так и в прикладном приложении нажодятся в каталоге Resources в файле WebObjectListView.resx.
			ICSSoft.STORMNET.Web.Tools.Resources.ResourceManager temp = new ICSSoft.STORMNET.Web.Tools.Resources.ResourceManager("WebObjectListView", typeof(WebObjectListView).Assembly);
			resourceManager = temp;
		}
		return resourceManager;
	}
}
```

**Важно: в designer-e прикладного *.resx-файла ничего изменять не нужно.**


text:
require 'rails_helper'

RSpec.describe Michibiki::SkipService do
  let(:skip_service) { Michibiki::SkipService.new(skip_strategy: skip_strategy) }

  describe '#valid?' do
    subject { skip_service.valid? }
    context 'when strategy exists' do
      let(:skip_strategy) { 'profile_setting_redirector' } # in dummy app
      it do
        expect {
          subject
        }.not_to change { skip_service.errors[:invalid_strategy] }
      end
    end

    context "when strategy doesn't exist" do
      let(:skip_strategy) { 'invalid_strategy' }
      let(:messages) { [invalid_strategy: I18n.t('michibiki.skip_failure.invalid_strategy')] }
      it do
        expect {
          subject
        }.to change { skip_service.errors[:invalid_strategy] }.to(messages)
      end
    end
  end
end


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.odistagon.pds" version="0.3.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>PadDmgSim</name>
    <description>
        Calculates Pad game damage.
    </description>
    <author email="odistagon@gmail.com" href="">
        odistagon
    </author>
    <content src="paddmgsim.html" />
    <access origin="*" />

	<preference name="SplashScreen" value="splash" />
	<preference name="SplashScreenDelay" value="6000" />
</widget>


text:
package com.neoblogger.store.neo4j.util;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;

/**
 * Helper for quick transaction wrapped activities
 */
public class WithTransaction
{

    /**
     * Set a property on a node
     *
     * @param service
     * @param node
     * @param key
     * @param value
     */
    public static void setProperty( GraphDatabaseService service, Node node, String key, String value )
    {
        Transaction tx = service.beginTx();
        try
        {
            node.setProperty( key, value );
            tx.success();
        } finally
        {
            tx.finish();
        }

    }
}


text:
package com.doubtech.universalremote.providers;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import com.doubtech.universalremote.providers.URPContract.Buttons;
import com.doubtech.universalremote.providers.URPContract.Parents;
import com.doubtech.universalremote.providers.providerdo.Button;
import com.doubtech.universalremote.providers.providerdo.Parent;
import com.doubtech.universalremote.utils.StringUtils;

/**
 * @hide
 * @author a1.jackson
 *
 */
public abstract class AbstractUniversalRemoteProvider extends ContentProvider {
    private static final String TAG = "AbstractUniversalRemoteProvider";
    private static final boolean DEBUG = false;
    private static final boolean DEBUG_CURSOR = false;
    private UriMatcher mUriMatcher;

    public AbstractUniversalRemoteProvider() {
        mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

        mUriMatcher.addURI(getAuthority(), URPContract.TABLE_BRANDS_PATH, URPContract.TABLE_BRANDS);
        mUriMatcher.addURI(getAuthority(), URPContract.TABLE_MODELS_PATH, URPContract.TABLE_MODELS);
        mUriMatcher.addURI(getAuthority(), URPContract.TABLE_BUTTONS_PATH, URPContract.TABLE_BUTTONS);
        mUriMatcher.addURI(getAuthority(), URPContract.TABLE_BUTTONS_PATH + "/*", URPContract.TABLE_BUTTONS);
        mUriMatcher.addURI(getAuthority(), URPContract.TABLE_BUTTON_LAYOUT_PATH, URPContract.TABLE_BUTTON_LAYOUT);
        mUriMatcher.addURI(getAuthority(), URPContract.TABLE_PROVIDER_DETAILS_PATH, URPContract.TABLE_PROVIDER_DETAILS);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Implement this to handle requests to delete one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO: Implement this to handle requests to insert a new row.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public boolean onCreate() {
        // TODO: Implement this to initialize your content provider on startup.
        return false;
    }

    @SuppressWarnings("unused")
    @Override
    public synchronized AssetFileDescriptor openAssetFile(Uri uri, String mode)
            throws FileNotFoundException {
        List<String> segments = uri.getPathSegments();
        String table = segments.get(0);
        if (URPContract.TABLE_BUTTONS_PATH.equals(table)) {
            Parent nodes = getCachedDetails(Parent.fromUri(uri));

            if (!nodes.needsToFetch() && DEBUG) {
                synchronized(this) {
                    Log.d(TAG, "[ASSET] ============================");
                    Log.d(TAG, "[ASSET] " + StringUtils.implode("/", uri.getPathSegments()));
                    Log.d(TAG, "[ASSET] /" + StringUtils.implode("/", nodes.getPath()));
                    Log.d(TAG, "[ASSET] " + nodes.getName());
                    Log.d(TAG, "[ASSET] " + getIconId(nodes));
                    Log.d(TAG, "[ASSET] ============================\n\n");
                }
                return openButtonIconAsset(nodes);
            }
        } else if (URPContract.TABLE_PROVIDER_DETAILS_PATH.equals(table)) {
            int iconId = getProviderIcon();
            try {
                if (0 != iconId) {
                    return getContext()
                            .getResources()
                            .openRawResourceFd(iconId);
                }
            } catch (Exception e) {
                Log.d("UniversalRemote", "Could not open icon file.", e);
            }
        }
        return null;
    }

    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode)
            throws FileNotFoundException {
        List<String> segments = uri.getPathSegments();
        String table = segments.get(0);
        if (URPContract.TABLE_BUTTONS_PATH.equals(table)) {
            Parent[] nodes = getChildren(Parent.fromUri(uri));

            if (nodes.length > 0) {
                return openButtonIcon(nodes[0]);
            }
        }
        return null;
    }

    ParcelFileDescriptor openButtonIcon(Parent button) throws FileNotFoundException {
        File file = getIconFile(button);
        if (null != file) {
            return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        }
        return null;
    }

    /**
     * Gets a resource id for the icon for a button.
     * @param button The button that needs a label
     * @return Returns 0 if there is no resource icon for this button or the R.drawable id
     */
    public int getIconId(Parent button) {
        return 0;
    }

    /**
     * Gets a file path for an image to be used as a button label.
     *
     * NOTE:
     * This will be passed through the provider system so the icon can be in the
     * application's data directory.
     * @param button
     * @return Returns null if no file is found for this button or the path to the file
     */
    public File getIconFile(Parent button) {
        return null;
    }

    AssetFileDescriptor openButtonIconAsset(Parent button) {
        int iconId = getIconId(button);
        try {
            if (0 != iconId) {
                return getContext()
                        .getResources()
                        .openRawResourceFd(iconId);
            }
        } catch (Exception e) {
            Log.d("UniversalRemote", "Could not open icon file.", e);
        }
        return null;
    }

    private String[] getSegments(Uri uri) {
        List<String> fullSegments = uri.getPathSegments();
        String[] segments = new String[fullSegments.size() - 1];
        for (int i = 0; i < segments.length; i++) {
            segments[i] = fullSegments.get(i + 1);
        }
        return segments;
    }

    @Override
    public Cursor query(final Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        try {
            List<String> segments = uri.getPathSegments();
            String table = segments.get(0);
            if (URPContract.TABLE_PROVIDER_DETAILS_PATH.equals(table)) {
                MatrixCursor cursor = new MatrixCursor(URPContract.ProviderDetails.ALL);
                cursor.addRow(new Object[] {
                    getAuthority(),
                    getProviderName(),
                    getProviderDescription(),
                    isProviderEnabled() ? 1 : 0
                });
                cursor.moveToFirst();
                return cursor;
            } else if (URPContract.TABLE_BUTTON_DETAILS_PATH.equals(table)) {
                return getCursor(new Parent[] { getCachedDetails(Parent.fromUri(uri)) });
            } else if (URPContract.TABLE_BUTTONS_PATH.equals(table)) {
                Parent[] nodes = getChildren(Parent.fromUri(uri));
                return getCursor(nodes);
            } else if (URPContract.BUTTON_COMMAND_SEND.equals(table)) {
                // TODO Might want to replace with a single thread executor.
                new Thread() {
                    public void run() {
                        try {
                            Button button = (Button) getCachedDetails(Parent.fromUri(uri));
                            sendButtons(new Button[] { button });
                        } catch (Exception e) {
                            // Gotta catch em all so buggy plugins don't bring down
                            // the main application.
                            if (!onError(e)) {
                                Log.e(TAG, "Error sending button " + uri + "\n" + e.getMessage(), e);
                            }
                        }
                    }
                }.start();
                return new MatrixCursor(new String[] {"Sent"});
            }
        } catch (Exception e) {
            // Gotta catch em all so buggy plugins don't bring down
            // the main application.
            if (!onError(e)) {
                Log.d(TAG, e.getMessage(), e);
                throw new IllegalArgumentException(e.getMessage(), e);
            } else {
                return null;
            }
        }
        throw new IllegalArgumentException("Unknown query: " + uri);
    }

    /**
     * An error was caught during a query or button send operation.
     * @param e
     * @returns Return true if you have handled this exception and do not want to show the extra error logs.
     */
    public boolean onError(Exception e) {
        // Override this if you are concerned with handling error messages.
        return false;
    }

    private Cursor getCursor(Parent[] nodes) {
        MatrixCursor cursor;
        if (nodes.length > 0) {
            cursor = new MatrixCursor(nodes[0].getColumns());
            String table = "";
            for (String col : nodes[0].getColumns()) {
                table += col + "\t";
            }
            if (DEBUG_CURSOR) Log.d(TAG, table);
            for (Parent node : nodes) {
                if (DEBUG_CURSOR) {
                    String row = "";
                    for (Object col : node.toRow()) {
                        row += col + "\t";
                    }
                    Log.d(TAG, row);
                }
                cursor.addRow(node.toRow());
            }
        } else {
            cursor = new MatrixCursor(Parents.ALL);
        }
        cursor.moveToFirst();
        return cursor;
    }
    /**
     * If this node's details haven't been loaded yet it's details will be populated
     * here.
     * @param parent
     * @return
     */
    public Parent getCachedDetails(Parent parent) {
        parent = Parent.getCached(parent);
        if (!parent.needsToFetch()) {
            return parent;
        }

        parent = getDetails(parent);
        return Parent.getCached(parent);
    }
    public abstract Parent[] getChildren(Parent parent);

    /**
     * If this node's details haven't been loaded yet it's details will be populated
     * here.
     * @param parent
     * @return
     */
    public abstract Parent getDetails(Parent parent);

    public abstract String getProviderName();
    public abstract String getProviderDescription();
    public abstract boolean isProviderEnabled();

    public abstract Button[] sendButtons(Button[] buttons);

    public String getButtonsColNameButtonIdentifier() {
        return Buttons.COLUMN_BUTTON_IDENTIFIER;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        // TODO: Implement this to handle requests to update one or more rows.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public abstract String getAuthority();

    public boolean hasButtonSets(Parent node) {
        return false;
    }

    public String getDescription(Parent node) {
        return null;
    }

    /**
     * Returns true if the parent is the root of the provider's nodes.
     * @return
     */
    public boolean isRoot(Parent parent) {
        return null == parent || parent.getPath().length == 0;
    }

    /**
     * Returns an icon representing this provider
     * @return
     */
    public int getProviderIcon() {
        return 0;
    }
}


text:
<?php

namespace Pushok\Tests;

use PHPUnit\Framework\TestCase;
use Pushok\AuthProvider\Token;
use Pushok\Client;
use Pushok\Notification;
use ReflectionClass;

class ClientTest extends TestCase
{
    public function testAmountOfAddedMessages()
    {
        $notification = $this->createMock(Notification::class);
        $notification2 = $this->createMock(Notification::class);
        $notification3 = $this->createMock(Notification::class);
        $notification4 = $this->createMock(Notification::class);

        $client = $this->getClient();

        $client->addNotification($notification);
        $client->addNotifications([$notification, $notification2, $notification3]);
        $client->addNotification($notification4);

        $this->assertEquals(4, count($client->getNotifications()));
    }

    private function getClient(): Client
    {
        $authProvider = $this->createMock(Token::class);

        $client = new Client($authProvider, $production = false);

        return $client;
    }

    public function testPrepareHandle()
    {
        $client = $this->getClient();

        $method = (new ReflectionClass($client))->getMethod('prepareHandle');
        $method->setAccessible(true);

        $notification = $this->createMock(Notification::class);

        $ch = $method->invoke($client, $notification);

        $this->assertIsResource($ch);
        $this->assertTrue(curl_errno($ch) === 0);
    }
}


text:
const url = require('url');
const path = require('path');
const unschema = require('unschema');
const result = require('lodash.result');

type PrimitiveType =
  | 'null'
  | 'string'
  | 'number'
  | 'integer'
  | 'object'
  | 'array'
  | 'boolean'

type StringFormat =
  | 'uri'
  | 'email'
  | 'date-time'
  | 'uuid'

type ObjectProperties = {
  [id: string]: Schema; // eslint-disable-line no-use-before-define
};

type ArrayItems =
  | Schema // eslint-disable-line no-use-before-define
  | Array<Schema> // eslint-disable-line no-use-before-define

type LinkDescriptionObject = {
  href: string;
  rel: string;
};

type Schema = {
  type: ?PrimitiveType;
  properties: ?ObjectProperties;
  items: ?ArrayItems;
  minimum: ?number;
  maximum: ?number;
  multipleOf: ?number;
  exclusiveMinimum: ?boolean;
  exclusiveMaximum: ?boolean;
  minLength: ?number;
  maxLength: ?number;
  $ref: ?string;
  example: ?any;
  format: ?StringFormat;
  links: LinkDescriptionObject[];
};

function resolvePointer(schema: Schema, rootSchema: Schema): Schema {
  if (typeof schema.$ref === 'string') {
    const matched = schema.$ref.match(/^#\/(.+)/);
    if (matched) {
      const pathStr = matched[1].replace(/\//g, '.');
      return result(rootSchema, pathStr);
    }
  }
  return schema;
}

function generate(root: Schema): any {
  const dbJSON = {};
  const properties = root.properties || {};
  Object.keys(properties).forEach(resourceName => {
    if (!properties[resourceName]) {
      return;
    }

    const resource = resolvePointer(properties[resourceName], root);

    if (!Array.isArray(resource.links)) {
      return;
    }

    resource.links.forEach(link => {
      if (link.rel !== 'instances') {
        return;
      }
      const { pathname } = url.parse(link.href);
      if (pathname) {
        const basename = path.basename(pathname);
        dbJSON[basename] = [unschema(resource, root)];
      }
    });
  });
  return dbJSON;
}

module.exports = generate;


text:
package fr.sii.ogham.sample.standard.sms;

import java.io.IOException;

import fr.sii.ogham.core.builder.MessagingBuilder;
import fr.sii.ogham.core.exception.MessagingException;
import fr.sii.ogham.core.service.MessagingService;
import fr.sii.ogham.sms.message.Sms;

public class BasicSampleExternalProperties {

	public static void main(String[] args) throws MessagingException, IOException {
		// Instantiate the messaging service using default behavior and
		// provided properties
		// Load properties from file that is in classpath (src/main/resources/sms.properties)
		MessagingService service = MessagingBuilder.standard()
				.environment()
					.properties("/sms.properties")                 // <1>
					.and()
				.build();
		// send the sms using fluent API
		service.send(new Sms()
						.message().string("sms content")
						.to("+33752962193"));
	}

}


text:
@interface TSHAlphaVideoView : OpenGLView

- (void)displayPixelBuffer:(CVImageBufferRef)pixelBuffer;
- (void)prepareForBackground;

@end


text:
class NppEditor : public EditorBase
{
    public:
        NppEditor(const QString& name, const QString& binPath);

        virtual QStringList getCommandArguments(const QString &filename, unsigned int line);
        virtual void setFocus();
        virtual bool openContent(const QString&);
};

#endif // NPPEDITOR_H


text:
package org.apache.commons.collections4.map;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import org.apache.commons.collections4.Unmodifiable;
import org.apache.commons.collections4.collection.UnmodifiableCollection;
import org.apache.commons.collections4.set.UnmodifiableSet;

/**
 * Decorates another {@code SortedMap} to ensure it can't be altered.
 *

 * This class is Serializable from Commons Collections 3.1.
 *

 *

 * Attempts to modify it will result in an UnsupportedOperationException.
 *

 *
 * @param <K> the type of the keys in this map
 * @param <V> the type of the values in this map
 * @since 3.0
 */
public final class UnmodifiableSortedMap<K, V>
        extends AbstractSortedMapDecorator<K, V>
        implements Unmodifiable, Serializable {

    /** Serialization version */
    private static final long serialVersionUID = 5805344239827376360L;

    /**
     * Factory method to create an unmodifiable sorted map.
     *
     * @param <K>  the key type
     * @param <V>  the value type
     * @param map  the map to decorate, must not be null
     * @return a new unmodifiable sorted map
     * @throws NullPointerException if map is null
     * @since 4.0
     */
    public static <K, V> SortedMap<K, V> unmodifiableSortedMap(final SortedMap<K, ? extends V> map) {
        if (map instanceof Unmodifiable) {
            @SuppressWarnings("unchecked") // safe to upcast
            final SortedMap<K, V> tmpMap = (SortedMap<K, V>) map;
            return tmpMap;
        }
        return new UnmodifiableSortedMap<>(map);
    }

    /**
     * Constructor that wraps (not copies).
     *
     * @param map  the map to decorate, must not be null
     * @throws NullPointerException if map is null
     */
    @SuppressWarnings("unchecked") // safe to upcast
    private UnmodifiableSortedMap(final SortedMap<K, ? extends V> map) {
        super((SortedMap<K, V>) map);
    }

    /**
     * Write the map out using a custom routine.
     *
     * @param out  the output stream
     * @throws IOException if an error occurs while writing to the stream
     * @since 3.1
     */
    private void writeObject(final ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();
        out.writeObject(map);
    }

    /**
     * Read the map in using a custom routine.
     *
     * @param in  the input stream
     * @throws IOException if an error occurs while reading from the stream
     * @throws ClassNotFoundException if an object read from the stream can not be loaded
     * @since 3.1
     */
    @SuppressWarnings("unchecked")
    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        map = (Map<K, V>) in.readObject();
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException();
    }

    @Override
    public V put(final K key, final V value) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(final Map<? extends K, ? extends V> mapToCopy) {
        throw new UnsupportedOperationException();
    }

    @Override
    public V remove(final Object key) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Set<Map.Entry<K, V>> entrySet() {
        return UnmodifiableEntrySet.unmodifiableEntrySet(super.entrySet());
    }

    @Override
    public Set<K> keySet() {
        return UnmodifiableSet.unmodifiableSet(super.keySet());
    }

    @Override
    public Collection<V> values() {
        return UnmodifiableCollection.unmodifiableCollection(super.values());
    }

    @Override
    public K firstKey() {
        return decorated().firstKey();
    }

    @Override
    public K lastKey() {
        return decorated().lastKey();
    }

    @Override
    public Comparator<? super K> comparator() {
        return decorated().comparator();
    }

    @Override
    public SortedMap<K, V> subMap(final K fromKey, final K toKey) {
        return new UnmodifiableSortedMap<>(decorated().subMap(fromKey, toKey));
    }

    @Override
    public SortedMap<K, V> headMap(final K toKey) {
        return new UnmodifiableSortedMap<>(decorated().headMap(toKey));
    }

    @Override
    public SortedMap<K, V> tailMap(final K fromKey) {
        return new UnmodifiableSortedMap<>(decorated().tailMap(fromKey));
    }

}


text:
#ifndef TALK_APP_WEBRTC_WEBRTCJSON_H_
#define TALK_APP_WEBRTC_WEBRTCJSON_H_

#include <string>
#include <vector>

#ifdef WEBRTC_RELATIVE_PATH
#include "json/json.h"
#else
#include "third_party/jsoncpp/json.h"
#endif

#include "talk/p2p/base/candidate.h"
#include "talk/p2p/base/sessiondescription.h"

namespace cricket {
class SessionDescription;
}

namespace webrtc {

void JsonSerializeSessionDescription(
    const cricket::SessionDescription* sdp,
    const std::vector<cricket::Candidate>& candidates,
    Json::Value* media);

bool JsonDeserializeSessionDescription(
    const Json::Value& message,
    cricket::SessionDescription* sdp,
    std::vector<cricket::Candidate>* candidates);

}  // namespace webrtc

#endif  // TALK_APP_WEBRTC_WEBRTCJSON_H_


text:
package BASE;

import java.util.Scanner;

public class ·ÖÖ§_01 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int F = scanner.nextInt();
		if(F>60){

			System.out.println("Speed: "+F+" - Speeding");
		}else{
			System.out.println("Speed: " + F + " - OK");

		}

	}
}


text:
import {
  AsyncTestCompleter,
  beforeEach,
  ddescribe,
  xdescribe,
  describe,
  expect,
  iit,
  inject,
  it,
  xit
} from '../../testing/testing_internal';

import {
  fakeAsync,
  flushMicrotasks
} from '../../testing';

import {el} from '@angular/platform-browser/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';

import {isPresent} from '../../src/facade/lang';
import {MockAnimationPlayer} from '../../testing/animation/mock_animation_player';
import {ActiveAnimationPlayersMap} from '../../src/animation/active_animation_players_map';

export function main() {
  describe('ActiveAnimationsPlayersMap', function() {
    var playersMap;
    var elementNode;
    var animationName = 'animationName';

    beforeEach(() => {
      playersMap = new ActiveAnimationPlayersMap();
      elementNode = el('

');
    });

    afterEach(() => {
      getDOM().remove(elementNode);
      elementNode = null;
    });

    it('should register a player an allow it to be accessed', () => {
      var player = new MockAnimationPlayer();
      playersMap.set(elementNode, animationName, player);

      expect(playersMap.find(elementNode, animationName)).toBe(player);
      expect(playersMap.findAllPlayersByElement(elementNode)).toEqual([player]);
      expect(playersMap.getAllPlayers()).toEqual([player]);
      expect(playersMap.length).toEqual(1);
    });

    it('should remove a registered player when remove() is called', () => {
      var player = new MockAnimationPlayer();
      playersMap.set(elementNode, animationName, player);
      expect(playersMap.find(elementNode, animationName)).toBe(player);
      expect(playersMap.length).toEqual(1);
      playersMap.remove(elementNode, animationName);
      expect(playersMap.find(elementNode, animationName)).not.toBe(player);
      expect(playersMap.length).toEqual(0);
    });

    it('should allow multiple players to be registered on the same element', () => {
      var player1 = new MockAnimationPlayer();
      var player2 = new MockAnimationPlayer();
      playersMap.set(elementNode, 'myAnimation1', player1);
      playersMap.set(elementNode, 'myAnimation2', player2);
      expect(playersMap.length).toEqual(2);
      expect(playersMap.findAllPlayersByElement(elementNode)).toEqual([
        player1,
        player2
      ]);
    });

    it('should only allow one player to be set for a given element/animationName pair', () => {
      var player1 = new MockAnimationPlayer();
      var player2 = new MockAnimationPlayer();
      playersMap.set(elementNode, animationName, player1);
      expect(playersMap.find(elementNode, animationName)).toBe(player1);
      expect(playersMap.length).toEqual(1);
      playersMap.set(elementNode, animationName, player2);
      expect(playersMap.find(elementNode, animationName)).toBe(player2);
      expect(playersMap.length).toEqual(1);
    });
  });
}


text:
package engine

import (
	"vitess.io/vitess/go/sqltypes"
	querypb "vitess.io/vitess/go/vt/proto/query"
)

var _ Primitive = (*Subquery)(nil)

// Subquery specifies the parameters for a subquery primitive.
type Subquery struct {
	// Cols defines the column numbers from the underlying primitive
	// to be returned.
	Cols     []int
	Subquery Primitive
}

// RouteType returns a description of the query routing type used by the primitive
func (sq *Subquery) RouteType() string {
	return sq.Subquery.RouteType()
}

// Execute performs a non-streaming exec.
func (sq *Subquery) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
	inner, err := sq.Subquery.Execute(vcursor, bindVars, wantfields)
	if err != nil {
		return nil, err
	}
	return sq.buildResult(inner), nil
}

// StreamExecute performs a streaming exec.
func (sq *Subquery) StreamExecute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool, callback func(*sqltypes.Result) error) error {
	return sq.Subquery.StreamExecute(vcursor, bindVars, wantfields, func(inner *sqltypes.Result) error {
		return callback(sq.buildResult(inner))
	})
}

// GetFields fetches the field info.
func (sq *Subquery) GetFields(vcursor VCursor, bindVars map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
	inner, err := sq.Subquery.GetFields(vcursor, bindVars)
	if err != nil {
		return nil, err
	}
	return &sqltypes.Result{Fields: sq.buildFields(inner)}, nil
}

// buildResult builds a new result by pulling the necessary columns from
// the subquery in the requested order.
func (sq *Subquery) buildResult(inner *sqltypes.Result) *sqltypes.Result {
	result := &sqltypes.Result{Fields: sq.buildFields(inner)}
	result.Rows = make([][]sqltypes.Value, 0, len(inner.Rows))
	for _, innerRow := range inner.Rows {
		row := make([]sqltypes.Value, 0, len(sq.Cols))
		for _, col := range sq.Cols {
			row = append(row, innerRow[col])
		}
		result.Rows = append(result.Rows, row)
	}
	result.RowsAffected = inner.RowsAffected
	return result
}

func (sq *Subquery) buildFields(inner *sqltypes.Result) []*querypb.Field {
	if len(inner.Fields) == 0 {
		return nil
	}
	fields := make([]*querypb.Field, 0, len(sq.Cols))
	for _, col := range sq.Cols {
		fields = append(fields, inner.Fields[col])
	}
	return fields
}


text:
/**
 * Liquid Fire Transitions
 */
var transition = function () {
    this.transition(
        this.fromRoute('welcome'),
        this.toRoute('explorer'),
        this.use('toLeft'),
        this.reverse('toRight')
    );
};

export default transition;


text:
<?php
declare(strict_types=1);

namespace Kafka\Protocol;

use Kafka\Exception\NotSupported;
use Kafka\Exception\Protocol as ProtocolException;
use function substr;

class LeaveGroup extends Protocol
{
    /**
     * @param mixed[] $payloads
     *
     * @throws NotSupported
     * @throws ProtocolException
     */
    public function encode(array $payloads = []): string
    {
        if (! isset($payloads['group_id'])) {
            throw new ProtocolException('given leave group data invalid. `group_id` is undefined.');
        }

        if (! isset($payloads['member_id'])) {
            throw new ProtocolException('given leave group data invalid. `member_id` is undefined.');
        }

        $header = $this->requestHeader('kafka-php', self::LEAVE_GROUP_REQUEST, self::LEAVE_GROUP_REQUEST);
        $data   = self::encodeString($payloads['group_id'], self::PACK_INT16);
        $data  .= self::encodeString($payloads['member_id'], self::PACK_INT16);

        return self::encodeString($header . $data, self::PACK_INT32);
    }

    /**
     * @return mixed[]
     */
    public function decode(string $data): array
    {
        $errorCode = self::unpack(self::BIT_B16_SIGNED, substr($data, 0, 2));

        return ['errorCode' => $errorCode];
    }
}


text:
CREATE OR REPLACE FUNCTION devilry__on_candidate_after_insert_or_update() RETURNS TRIGGER AS $$
BEGIN
    PERFORM devilry__rebuild_assignmentgroupcacheddata(NEW.assignment_group_id);
    IF TG_OP = 'UPDATE' AND NEW.assignment_group_id != OLD.assignment_group_id THEN
        PERFORM devilry__rebuild_assignmentgroupcacheddata(OLD.assignment_group_id);
    END IF;
    RETURN NEW;
END
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS devilry__on_candidate_after_insert_or_update
    ON core_candidate;
CREATE TRIGGER devilry__on_candidate_after_insert_or_update
    AFTER INSERT OR UPDATE ON core_candidate
    FOR EACH ROW
        EXECUTE PROCEDURE devilry__on_candidate_after_insert_or_update();

CREATE OR REPLACE FUNCTION devilry__on_candidate_after_delete() RETURNS TRIGGER AS $$
BEGIN
    PERFORM devilry__rebuild_assignmentgroupcacheddata(OLD.assignment_group_id);
    RETURN OLD;
END
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS devilry__on_candidate_after_delete
    ON core_candidate;
CREATE TRIGGER devilry__on_candidate_after_delete
    AFTER DELETE ON core_candidate
    FOR EACH ROW
        EXECUTE PROCEDURE devilry__on_candidate_after_delete();

--
-- Create a new core_candidateassignmentgrouphistory when a core_candidate entry is
-- inserted.
--
CREATE OR REPLACE FUNCTION devilry__on_candidate_insert_add_history() RETURNS TRIGGER AS $$
DECLARE
    var_user_id integer;
BEGIN
    IF TG_OP = 'INSERT' THEN
        SELECT user_id
        FROM core_relatedstudent
        WHERE id = NEW.relatedstudent_id
        INTO var_user_id;
        INSERT INTO core_candidateassignmentgrouphistory (
            assignment_group_id,
            user_id,
            created_datetime,
            is_add)
        VALUES (
            NEW.assignment_group_id,
            var_user_id,
            now(),
            TRUE);
    END IF;
    RETURN NEW;
END
$$ LANGUAGE  plpgsql;

DROP TRIGGER IF EXISTS devilry__on_candidate_insert_add_history_trigger
    ON core_candidate;
CREATE TRIGGER devilry__on_candidate_insert_add_history_trigger
    AFTER INSERT ON core_candidate
    FOR EACH ROW
        EXECUTE PROCEDURE devilry__on_candidate_insert_add_history();

--
-- Create a new core_candidateassignmentgrouphistory when core_candidate.assignment_group_id
-- is updated/changed.
--
CREATE OR REPLACE FUNCTION devilry__on_candidate_update_add_history() RETURNS TRIGGER AS $$
DECLARE
    var_user_id integer;
BEGIN
    IF TG_OP = 'UPDATE' AND NEW.assignment_group_id <> OLD.assignment_group_id THEN
        SELECT user_id
        FROM core_relatedstudent
        WHERE id = NEW.relatedstudent_id
        INTO var_user_id;

        -- We create a history entry for the group the user was added to.
        INSERT INTO core_candidateassignmentgrouphistory (
            assignment_group_id,
            user_id,
            created_datetime,
            is_add)
        VALUES (
            NEW.assignment_group_id,
            var_user_id,
            now(),
            TRUE);

        -- And we create a history entry for the group the user was removed from.
        INSERT INTO core_candidateassignmentgrouphistory (
            assignment_group_id,
            user_id,
            created_datetime,
            is_add)
        VALUES (
            OLD.assignment_group_id,
            var_user_id,
            now(),
            FALSE);
    END IF;
    RETURN NEW;
END
$$ LANGUAGE  plpgsql;

DROP TRIGGER IF EXISTS devilry__on_candidate_update_add_history_trigger
    ON core_candidate;
CREATE TRIGGER devilry__on_candidate_update_add_history_trigger
    AFTER UPDATE ON core_candidate
    FOR EACH ROW
        EXECUTE PROCEDURE devilry__on_candidate_update_add_history();

--
-- Create a new core_candidateassignmentgrouphistory when a core_candidate entry is
-- deleted.
--
CREATE OR REPLACE FUNCTION devilry__on_candidate_delete_add_history() RETURNS TRIGGER AS $$
DECLARE
    var_user_id integer;
BEGIN
    IF TG_OP = 'DELETE' THEN
        IF EXISTS (
              SELECT 1
              FROM core_assignmentgroup
              WHERE id = OLD.assignment_group_id AND internal_is_being_deleted = TRUE
            ) THEN
            RETURN NULL;
        END IF;

        SELECT user_id
        FROM core_relatedstudent
        WHERE id = OLD.relatedstudent_id
        INTO var_user_id;
        INSERT INTO core_candidateassignmentgrouphistory (
            assignment_group_id,
            user_id,
            created_datetime,
            is_add)
        VALUES (
            OLD.assignment_group_id,
            var_user_id,
            now(),
            FALSE);
        RETURN OLD;
    END IF;
END
$$ LANGUAGE  plpgsql;

DROP TRIGGER IF EXISTS devilry__on_candidate_delete_add_history_trigger
    ON core_candidate;
CREATE TRIGGER devilry__on_candidate_delete_add_history_trigger
    AFTER DELETE ON core_candidate
    FOR EACH ROW
        EXECUTE PROCEDURE devilry__on_candidate_delete_add_history();


text:
// Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.worker;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import com.google.common.hash.HashCode;
import com.google.devtools.build.lib.actions.ActionExecutionMetadata;
import com.google.devtools.build.lib.actions.ActionInput;
import com.google.devtools.build.lib.actions.ActionInputHelper;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.MetadataProvider;
import com.google.devtools.build.lib.actions.ResourceManager;
import com.google.devtools.build.lib.actions.ResourceManager.ResourceHandle;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnExecutedEvent;
import com.google.devtools.build.lib.actions.SpawnResult;
import com.google.devtools.build.lib.actions.Spawns;
import com.google.devtools.build.lib.actions.UserExecException;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.exec.BinTools;
import com.google.devtools.build.lib.exec.RunfilesTreeUpdater;
import com.google.devtools.build.lib.exec.SpawnRunner;
import com.google.devtools.build.lib.exec.local.LocalEnvProvider;
import com.google.devtools.build.lib.sandbox.SandboxHelpers;
import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxInputs;
import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxOutputs;
import com.google.devtools.build.lib.util.io.FileOutErr;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.worker.WorkerProtocol.WorkRequest;
import com.google.devtools.build.lib.worker.WorkerProtocol.WorkResponse;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.regex.Pattern;

/**
 * A spawn runner that launches Spawns the first time they are used in a persistent mode and then
 * shards work over all the processes.
 */
final class WorkerSpawnRunner implements SpawnRunner {
  public static final String ERROR_MESSAGE_PREFIX =
      "Worker strategy cannot execute this %s action, ";
  public static final String REASON_NO_FLAGFILE =
      "because the command-line arguments do not contain at least one @flagfile or --flagfile=";
  public static final String REASON_NO_TOOLS = "because the action has no tools";
  public static final String REASON_NO_EXECUTION_INFO =
      "because the action's execution info does not contain 'supports-workers=1'";

  /** Pattern for @flagfile.txt and --flagfile=flagfile.txt */
  private static final Pattern FLAG_FILE_PATTERN = Pattern.compile("(?:@|--?flagfile=)(.+)");

  private final SandboxHelpers helpers;
  private final Path execRoot;
  private final WorkerPool workers;
  private final Multimap<String, String> extraFlags;
  private final ExtendedEventHandler reporter;
  private final SpawnRunner fallbackRunner;
  private final LocalEnvProvider localEnvProvider;
  private final boolean sandboxUsesExpandedTreeArtifactsInRunfiles;
  private final BinTools binTools;
  private final ResourceManager resourceManager;
  private final RunfilesTreeUpdater runfilesTreeUpdater;

  public WorkerSpawnRunner(
      SandboxHelpers helpers,
      Path execRoot,
      WorkerPool workers,
      Multimap<String, String> extraFlags,
      ExtendedEventHandler reporter,
      SpawnRunner fallbackRunner,
      LocalEnvProvider localEnvProvider,
      boolean sandboxUsesExpandedTreeArtifactsInRunfiles,
      BinTools binTools,
      ResourceManager resourceManager,
      RunfilesTreeUpdater runfilesTreeUpdater) {
    this.helpers = helpers;
    this.execRoot = execRoot;
    this.workers = Preconditions.checkNotNull(workers);
    this.extraFlags = extraFlags;
    this.reporter = reporter;
    this.fallbackRunner = fallbackRunner;
    this.localEnvProvider = localEnvProvider;
    this.sandboxUsesExpandedTreeArtifactsInRunfiles = sandboxUsesExpandedTreeArtifactsInRunfiles;
    this.binTools = binTools;
    this.resourceManager = resourceManager;
    this.runfilesTreeUpdater = runfilesTreeUpdater;
  }

  @Override
  public String getName() {
    return "worker";
  }

  @Override
  public SpawnResult exec(Spawn spawn, SpawnExecutionContext context)
      throws ExecException, IOException, InterruptedException {
    if (!Spawns.supportsWorkers(spawn) && !Spawns.supportsMultiplexWorkers(spawn)) {
      // TODO(ulfjack): Don't circumvent SpawnExecutionPolicy. Either drop the warning here, or
      // provide a mechanism in SpawnExecutionPolicy to report warnings.
      reporter.handle(
          Event.warn(
              String.format(ERROR_MESSAGE_PREFIX + REASON_NO_EXECUTION_INFO, spawn.getMnemonic())));
      return fallbackRunner.exec(spawn, context);
    }

    context.report(
        ProgressStatus.SCHEDULING,
        WorkerKey.makeWorkerTypeName(Spawns.supportsMultiplexWorkers(spawn)));
    return actuallyExec(spawn, context);
  }

  @Override
  public boolean canExec(Spawn spawn) {
    return Spawns.supportsWorkers(spawn) || Spawns.supportsMultiplexWorkers(spawn);
  }

  @Override
  public boolean handlesCaching() {
    return false;
  }

  private SpawnResult actuallyExec(Spawn spawn, SpawnExecutionContext context)
      throws ExecException, IOException, InterruptedException {
    if (spawn.getToolFiles().isEmpty()) {
      throw new UserExecException(
          String.format(ERROR_MESSAGE_PREFIX + REASON_NO_TOOLS, spawn.getMnemonic()));
    }

    runfilesTreeUpdater.updateRunfilesDirectory(
        execRoot,
        spawn.getRunfilesSupplier(),
        context.getPathResolver(),
        binTools,
        spawn.getEnvironment(),
        context.getFileOutErr());

    // We assume that the spawn to be executed always gets at least one @flagfile.txt or
    // --flagfile=flagfile.txt argument, which contains the flags related to the work itself (as
    // opposed to start-up options for the executed tool). Thus, we can extract those elements from
    // its args and put them into the WorkRequest instead.
    List<String> flagFiles = new ArrayList<>();
    ImmutableList<String> workerArgs = splitSpawnArgsIntoWorkerArgsAndFlagFiles(spawn, flagFiles);
    ImmutableMap<String, String> env =
        localEnvProvider.rewriteLocalEnv(spawn.getEnvironment(), binTools, "/tmp");

    MetadataProvider inputFileCache = context.getMetadataProvider();

    SortedMap<PathFragment, HashCode> workerFiles =
        WorkerFilesHash.getWorkerFilesWithHashes(
            spawn,
            context.getArtifactExpander(),
            context.getPathResolver(),
            context.getMetadataProvider());

    HashCode workerFilesCombinedHash = WorkerFilesHash.getCombinedHash(workerFiles);

    SandboxInputs inputFiles =
        helpers.processInputFiles(
            context.getInputMapping(sandboxUsesExpandedTreeArtifactsInRunfiles),
            spawn,
            context.getArtifactExpander(),
            execRoot);
    SandboxOutputs outputs = helpers.getOutputs(spawn);

    WorkerKey key =
        new WorkerKey(
            workerArgs,
            env,
            execRoot,
            spawn.getMnemonic(),
            workerFilesCombinedHash,
            workerFiles,
            context.speculating(),
            Spawns.supportsMultiplexWorkers(spawn));

    Instant startTime = Instant.now();
    WorkResponse response =
        execInWorker(spawn, key, context, inputFiles, outputs, flagFiles, inputFileCache);
    Duration wallTime = Duration.between(startTime, Instant.now());

    FileOutErr outErr = context.getFileOutErr();
    response.getOutputBytes().writeTo(outErr.getErrorStream());

    int exitCode = response.getExitCode();
    SpawnResult result =
        new SpawnResult.Builder()
            .setRunnerName(getName())
            .setExitCode(exitCode)
            .setStatus(
                exitCode == 0 ? SpawnResult.Status.SUCCESS : SpawnResult.Status.NON_ZERO_EXIT)
            .setWallTime(wallTime)
            .build();
    reporter.post(new SpawnExecutedEvent(spawn, result, startTime));
    return result;
  }

  /**
   * Splits the command-line arguments of the {@code Spawn} into the part that is used to start the
   * persistent worker ({@code workerArgs}) and the part that goes into the {@code WorkRequest}
   * protobuf ({@code flagFiles}).
   */
  private ImmutableList<String> splitSpawnArgsIntoWorkerArgsAndFlagFiles(
      Spawn spawn, List<String> flagFiles) throws UserExecException {
    ImmutableList.Builder<String> workerArgs = ImmutableList.builder();
    for (String arg : spawn.getArguments()) {
      if (FLAG_FILE_PATTERN.matcher(arg).matches()) {
        flagFiles.add(arg);
      } else {
        workerArgs.add(arg);
      }
    }

    if (flagFiles.isEmpty()) {
      throw new UserExecException(
          String.format(ERROR_MESSAGE_PREFIX + REASON_NO_FLAGFILE, spawn.getMnemonic()));
    }

    return workerArgs
        .add("--persistent_worker")
        .addAll(
            MoreObjects.firstNonNull(
                extraFlags.get(spawn.getMnemonic()), ImmutableList.<String>of()))
        .build();
  }

  private WorkRequest createWorkRequest(
      Spawn spawn,
      SpawnExecutionContext context,
      List<String> flagfiles,
      MetadataProvider inputFileCache,
      int workerId)
      throws IOException {
    WorkRequest.Builder requestBuilder = WorkRequest.newBuilder();
    for (String flagfile : flagfiles) {
      expandArgument(execRoot, flagfile, requestBuilder);
    }

    List<ActionInput> inputs =
        ActionInputHelper.expandArtifacts(spawn.getInputFiles(), context.getArtifactExpander());

    for (ActionInput input : inputs) {
      byte[] digestBytes = inputFileCache.getMetadata(input).getDigest();
      ByteString digest;
      if (digestBytes == null) {
        digest = ByteString.EMPTY;
      } else {
        digest = ByteString.copyFromUtf8(HashCode.fromBytes(digestBytes).toString());
      }

      requestBuilder
          .addInputsBuilder()
          .setPath(input.getExecPathString())
          .setDigest(digest)
          .build();
    }
    return requestBuilder.setRequestId(workerId).build();
  }

  /**
   * Recursively expands arguments by replacing @filename args with the contents of the referenced
   * files. The @ itself can be escaped with @@. This deliberately does not expand --flagfile= style
   * arguments, because we want to get rid of the expansion entirely at some point in time.
   *
   * <p>Also check that the argument is not an external repository label, because they start with
   * `@` and are not flagfile locations.
   *
   * @param execRoot the current execroot of the build (relative paths will be assumed to be
   *     relative to this directory).
   * @param arg the argument to expand.
   * @param requestBuilder the WorkRequest to whose arguments the expanded arguments will be added.
   * @throws java.io.IOException if one of the files containing options cannot be read.
   */
  static void expandArgument(Path execRoot, String arg, WorkRequest.Builder requestBuilder)
      throws IOException {
    if (arg.startsWith("@") && !arg.startsWith("@@") && !isExternalRepositoryLabel(arg)) {
      for (String line :
          Files.readAllLines(
              Paths.get(execRoot.getRelative(arg.substring(1)).getPathString()), UTF_8)) {
        expandArgument(execRoot, line, requestBuilder);
      }
    } else {
      requestBuilder.addArguments(arg);
    }
  }

  private static boolean isExternalRepositoryLabel(String arg) {
    return arg.matches("^@.*//.*");
  }

  private WorkResponse execInWorker(
      Spawn spawn,
      WorkerKey key,
      SpawnExecutionContext context,
      SandboxInputs inputFiles,
      SandboxOutputs outputs,
      List<String> flagFiles,
      MetadataProvider inputFileCache)
      throws InterruptedException, ExecException {
    Worker worker = null;
    WorkResponse response;
    WorkRequest request;

    ActionExecutionMetadata owner = spawn.getResourceOwner();
    try {
      try {
        inputFiles.materializeVirtualInputs(execRoot);
      } catch (IOException e) {
        throw new UserExecException(
            ErrorMessage.builder()
                .message("IOException while materializing virtual inputs:")
                .exception(e)
                .build()
                .toString());
      }

      try {
        worker = workers.borrowObject(key);
        request =
            createWorkRequest(spawn, context, flagFiles, inputFileCache, worker.getWorkerId());
      } catch (IOException e) {
        throw new UserExecException(
            ErrorMessage.builder()
                .message("IOException while borrowing a worker from the pool:")
                .exception(e)
                .build()
                .toString());
      }

      try {
        context.prefetchInputs();
      } catch (IOException e) {
        throw new UserExecException(
            ErrorMessage.builder()
                .message("IOException while prefetching for worker:")
                .exception(e)
                .build()
                .toString());
      }

      try (ResourceHandle handle =
          resourceManager.acquireResources(owner, spawn.getLocalResources())) {
        context.report(ProgressStatus.EXECUTING, WorkerKey.makeWorkerTypeName(key.getProxied()));
        try {
          worker.prepareExecution(inputFiles, outputs, key.getWorkerFilesWithHashes().keySet());
        } catch (IOException e) {
          throw new UserExecException(
              ErrorMessage.builder()
                  .message("IOException while preparing the execution environment of a worker:")
                  .logFile(worker.getLogFile())
                  .exception(e)
                  .build()
                  .toString());
        }

        try {
          worker.putRequest(request);
        } catch (IOException e) {
          throw new UserExecException(
              ErrorMessage.builder()
                  .message(
                      "Worker process quit or closed its stdin stream when we tried to send a"
                          + " WorkRequest:")
                  .logFile(worker.getLogFile())
                  .exception(e)
                  .build()
                  .toString());
        }

        try {
          response = worker.getResponse();
        } catch (IOException e) {
          // If protobuf couldn't parse the response, try to print whatever the failing worker wrote
          // to stdout - it's probably a stack trace or some kind of error message that will help
          // the user figure out why the compiler is failing.
          String recordingStreamMessage = worker.getRecordingStreamMessage();
          throw new UserExecException(
              ErrorMessage.builder()
                  .message(
                      "Worker process returned an unparseable WorkResponse!\n\n"
                          + "Did you try to print something to stdout? Workers aren't allowed to "
                          + "do this, as it breaks the protocol between Bazel and the worker "
                          + "process.")
                  .logText(recordingStreamMessage)
                  .exception(e)
                  .build()
                  .toString());
        }
      }

      if (response == null) {
        throw new UserExecException(
            ErrorMessage.builder()
                .message("Worker process did not return a WorkResponse:")
                .logFile(worker.getLogFile())
                .logSizeLimit(4096)
                .build()
                .toString());
      }

      try {
        context.lockOutputFiles();
        worker.finishExecution(execRoot);
      } catch (IOException e) {
        throw new UserExecException(
            ErrorMessage.builder()
                .message("IOException while finishing worker execution:")
                .exception(e)
                .build()
                .toString());
      }
    } catch (ExecException e) {
      if (worker != null) {
        try {
          workers.invalidateObject(key, worker);
        } catch (IOException e1) {
          // The original exception is more important / helpful, so we'll just ignore this one.
        }
        worker = null;
      }

      throw e;
    } finally {
      if (worker != null) {
        workers.returnObject(key, worker);
      }
    }

    return response;
  }
}


text:
package com.eaw1805.data.model.army.comparators;

import com.eaw1805.data.model.army.ArmyType;

import java.io.Serializable;
import java.util.Comparator;

/**
 * Used to sort army types based on type (In,Ca,Ar,CC,...) and ID.
 */
public class ArmyTypeOrder
        implements Comparator<ArmyType>, Serializable {

    /**
     * For serialization purposes.
     */
    static final long serialVersionUID = -338756993124229948L;

    /**
     * Compares its two arguments for order.  Returns a negative integer,
     * zero, or a positive integer as the first argument is less than, equal
     * to, or greater than the second.

     * In the foregoing description, the notation
     * <tt>sgn(</tt>expression<tt>)</tt> designates the mathematical
     * signum function, which is defined to return one of <tt>-1</tt>,
     * <tt>0</tt>, or <tt>1</tt> according to whether the value of
     * expression is negative, zero or positive.

     * The implementor must ensure that <tt>sgn(compare(x, y)) ==
     * -sgn(compare(y, x))</tt> for all <tt>x</tt> and <tt>y</tt>.  (This
     * implies that <tt>compare(x, y)</tt> must throw an exception if and only
     * if <tt>compare(y, x)</tt> throws an exception.)

     * The implementor must also ensure that the relation is transitive:
     * <tt>((compare(x, y)>0) && (compare(y, z)>0))</tt> implies
     * <tt>compare(x, z)>0</tt>.

     * Finally, the implementor must ensure that <tt>compare(x, y)==0</tt>
     * implies that <tt>sgn(compare(x, z))==sgn(compare(y, z))</tt> for all
     * <tt>z</tt>.

     * It is generally the case, but not strictly required that
     * <tt>(compare(x, y)==0) == (x.equals(y))</tt>.  Generally speaking,
     * any comparator that violates this condition should clearly indicate
     * this fact.  The recommended language is "Note: this comparator
     * imposes orderings that are inconsistent with equals."
     *
     * @param armyType1 the first object to be compared.
     * @param armyType2 the second object to be compared.
     * @return a negative integer, zero, or a positive integer as the
     *         first argument is less than, equal to, or greater than the
     *         second.
     * @throws ClassCastException if the arguments' types prevent them from
     *                            being compared by this comparator.
     */
    @Override
    public int compare(final ArmyType armyType1, final ArmyType armyType2) {
        int comparison = 0;
        // First check type.
        final int aTypeId1 = getTypeOrder(armyType1.getType());
        final int aTypeId2 = getTypeOrder(armyType2.getType());

        if (aTypeId1 < aTypeId2) {
            comparison = -1;

        } else if (aTypeId1 > aTypeId2) {
            comparison = 1;

        } else {
            // Then check id.
            if (armyType1.getIntId() < armyType2.getIntId()) {
                comparison = -1;

            } else if (armyType1.getIntId() > armyType2.getIntId()) {
                comparison = 1;
            }
        }

        return comparison;
    }

    public int getTypeOrder(final String type) {
        if (type.equals("In")) {
            return 1;

        } else if (type.equals("Ca")) {
            return 2;

        } else if (type.equals("Ar")) {
            return 3;

        } else if (type.equals("Kt")) {
            return 4;

        }
        return 5;
    }
}


text:
using System;
using System.Text.RegularExpressions;
using Foundatio.Metrics;

namespace Foundatio.Tests.Queue {
    public class SimpleWorkItem : IHaveMetricName {
        public string Data { get; set; }
        public int Id { get; set; }

        public string GetMetricName()
        {
            return Regex.Replace(Data, "\\W+", string.Empty);
        }
    }
}


text:
import { IResultMessage, ResultStatus } from './../../interfaces/index';
export class ResultMessage implements IResultMessage {
    resultStatus: ResultStatus;
    message: string;
    dataResult?: any;
    totalCount?: number;
}