text:
package net.kalinovcic.ld32;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Map;
import java.awt.GraphicsEnvironment;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;

public class TrueTypeFont
{
    public final static int ALIGN_LEFT = 0;
    public final static int ALIGN_RIGHT = 1;
    public final static int ALIGN_CENTER = 2;

    private IntObject[] charArray = new IntObject[256];

    private Map<Character, IntObject> customChars = new HashMap<Character, IntObject>();

    private boolean antiAlias;
    private int fontSize = 0;
    private int fontHeight = 0;
    private int fontTextureID;

    private int textureWidth = 512;
    private int textureHeight = 512;

    private Font font;
    private FontMetrics fontMetrics;

    private int correctL = 9;
    private int correctR = 8;

    private class IntObject
    {
        public int width;
        public int height;

        public int storedX;
        public int storedY;
    }

    public TrueTypeFont(Font font, boolean antiAlias, char[] additionalChars)
    {
        this.font = font;
        this.fontSize = font.getSize() + 3;
        this.antiAlias = antiAlias;

        createSet(additionalChars);

        fontHeight -= 1;
        if(fontHeight <= 0)
            fontHeight = 1;
    }

    public TrueTypeFont(Font font, boolean antiAlias)
    {
        this(font, antiAlias, null);
    }

    public void setCorrection(boolean on)
    {
        if(on)
        {
            correctL = 2;
            correctR = 1;
        }
        else
        {
            correctL = 0;
            correctR = 0;
        }
    }

    private BufferedImage getFontImage(char ch)
    {
        BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) tempfontImage.getGraphics();
        if(antiAlias == true)
        {
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        }
        g.setFont(font);
        fontMetrics = g.getFontMetrics();
        int charwidth = fontMetrics.charWidth(ch) + 8;

        if(charwidth <= 0)
        {
            charwidth = 7;
        }
        int charheight = fontMetrics.getHeight() + 3;
        if(charheight <= 0)
        {
            charheight = fontSize;
        }

        BufferedImage fontImage;
        fontImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gt = (Graphics2D) fontImage.getGraphics();
        if(antiAlias == true)
        {
            gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        }
        gt.setFont(font);

        gt.setColor(Color.WHITE);
        int charx = 3;
        int chary = 1;
        gt.drawString(String.valueOf(ch), (charx), (chary) + fontMetrics.getAscent());

        return fontImage;

    }

    private void createSet(char[] customCharsArray)
    {
        if(customCharsArray != null && customCharsArray.length > 0)
        {
            textureWidth *= 2;
        }

        try
        {
            BufferedImage imgTemp = new BufferedImage(textureWidth, textureHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = (Graphics2D) imgTemp.getGraphics();

            g.setColor(new Color(0, 0, 0, 1));
            g.fillRect(0, 0, textureWidth, textureHeight);

            int rowHeight = 0;
            int positionX = 0;
            int positionY = 0;

            int customCharsLength = (customCharsArray != null) ? customCharsArray.length : 0;

            for(int i = 0; i < 256 + customCharsLength; i++)
            {
                char ch = (i < 256) ? (char) i : customCharsArray[i - 256];

                BufferedImage fontImage = getFontImage(ch);

                IntObject newIntObject = new IntObject();

                newIntObject.width = fontImage.getWidth();
                newIntObject.height = fontImage.getHeight();

                if(positionX + newIntObject.width >= textureWidth)
                {
                    positionX = 0;
                    positionY += rowHeight;
                    rowHeight = 0;
                }

                newIntObject.storedX = positionX;
                newIntObject.storedY = positionY;

                if(newIntObject.height > fontHeight)
                {
                    fontHeight = newIntObject.height;
                }

                if(newIntObject.height > rowHeight)
                {
                    rowHeight = newIntObject.height;
                }

                g.drawImage(fontImage, positionX, positionY, null);

                positionX += newIntObject.width;

                if(i < 256)
                {
                    charArray[i] = newIntObject;
                }
                else
                {
                    customChars.put(new Character(ch), newIntObject);
                }

                fontImage = null;
            }

            fontTextureID = loadImage(imgTemp);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private void drawQuad(float drawX, float drawY, float drawX2, float drawY2, float srcX, float srcY, float srcX2,
            float srcY2)
    {
        float DrawWidth = drawX2 - drawX;
        float DrawHeight = drawY2 - drawY;
        float TextureSrcX = srcX / textureWidth;
        float TextureSrcY = srcY / textureHeight;
        float SrcWidth = srcX2 - srcX;
        float SrcHeight = srcY2 - srcY;
        float RenderWidth = (SrcWidth / textureWidth);
        float RenderHeight = (SrcHeight / textureHeight);

        GL11.glTexCoord2f(TextureSrcX, TextureSrcY);
        GL11.glVertex2f(drawX, drawY);
        GL11.glTexCoord2f(TextureSrcX, TextureSrcY + RenderHeight);
        GL11.glVertex2f(drawX, drawY + DrawHeight);
        GL11.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY + RenderHeight);
        GL11.glVertex2f(drawX + DrawWidth, drawY + DrawHeight);
        GL11.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY);
        GL11.glVertex2f(drawX + DrawWidth, drawY);
    }

    public Font getFont()
    {
        return font;
    }

    public int getWidth(String whatchars)
    {
        int totalwidth = 0;
        IntObject intObject = null;
        int currentChar = 0;
        for(int i = 0; i < whatchars.length(); i++)
        {
            currentChar = whatchars.charAt(i);
            if(currentChar < 256)
                intObject = charArray[currentChar];
            else
                intObject = (IntObject) customChars.get(new Character((char) currentChar));

            if(intObject != null)
                totalwidth += intObject.width;
        }
        return totalwidth;
    }

    public int getTotalWidth(String whatchars)
    {
        return getTotalWidth(whatchars, 0, whatchars.length() - 1);
    }

    public int getTotalWidth(String whatchars, int startIndex, int endIndex)
    {
        IntObject intObject = null;
        int totalwidth = 0;
        for(int l = startIndex; l <= endIndex; l++)
        {
            int charCurrent = whatchars.charAt(l);
            if(charCurrent == '\n')
                break;

            if(charCurrent < 256)
                intObject = charArray[charCurrent];
            else
                intObject = (IntObject) customChars.get(new Character((char) charCurrent));

            totalwidth += intObject.width - correctL;
        }
        return totalwidth;
    }

    public int getHeight()
    {
        return fontHeight;
    }

    public int getHeight(String HeightString)
    {
        return fontHeight;
    }

    public int getLineHeight()
    {
        return fontHeight;
    }

    public void drawString(float x, float y, String whatchars, float scaleX, float scaleY)
    {
        drawString(x, y, whatchars, 0, whatchars.length() - 1, scaleX, scaleY, ALIGN_LEFT);
    }

    public void drawString(float x, float y, String whatchars, float scaleX, float scaleY, int format)
    {
        drawString(x, y, whatchars, 0, whatchars.length() - 1, scaleX, scaleY, format);
    }

    public void drawString(float x, float y, String whatchars, int startIndex, int endIndex, float scaleX,
            float scaleY, int format)
    {

        IntObject intObject = null;
        int charCurrent;

        int totalwidth = 0;
        int i = startIndex, d, c;
        float startY = 0;

        switch(format)
        {
        case ALIGN_RIGHT:
        {
            d = -1;
            c = correctR;

            while(i < endIndex)
            {
                if(whatchars.charAt(i) == '\n')
                    startY -= fontHeight;
                i++;
            }
            break;
        }
        case ALIGN_CENTER:
        {
            totalwidth = getTotalWidth(whatchars, startIndex, endIndex) / -2;
        }
        case ALIGN_LEFT:
        default:
        {
            d = 1;
            c = correctL;
            break;
        }
        }

        GL11.glBindTexture(GL11.GL_TEXTURE_2D, fontTextureID);
        GL11.glBegin(GL11.GL_QUADS);

        while(i >= startIndex && i <= endIndex)
        {

            charCurrent = whatchars.charAt(i);
            if(charCurrent < 256)
                intObject = charArray[charCurrent];
            else
                intObject = (IntObject) customChars.get(new Character((char) charCurrent));

            if(intObject != null)
            {
                if(d < 0)
                    totalwidth += (intObject.width - c) * d;
                if(charCurrent == '\n')
                {
                    startY -= fontHeight * d;
                    totalwidth = 0;
                    if(format == ALIGN_CENTER)
                    {
                        for(int l = i + 1; l <= endIndex; l++)
                        {
                            charCurrent = whatchars.charAt(l);
                            if(charCurrent == '\n')
                                break;

                            if(charCurrent < 256)
                                intObject = charArray[charCurrent];
                            else
                                intObject = (IntObject) customChars.get(new Character((char) charCurrent));

                            totalwidth += intObject.width - correctL;
                        }
                        totalwidth /= -2;
                    }
                }
                else
                {
                    drawQuad((totalwidth + intObject.width) * scaleX + x, startY * scaleY + y, totalwidth * scaleX + x,
                            (startY + intObject.height) * scaleY + y, intObject.storedX + intObject.width,
                            intObject.storedY + intObject.height, intObject.storedX, intObject.storedY);
                    if(d > 0)
                        totalwidth += (intObject.width - c) * d;
                }
                i += d;

            }
        }
        GL11.glEnd();
    }

    public static int loadImage(BufferedImage bufferedImage)
    {
        try
        {
            short width = (short) bufferedImage.getWidth();
            short height = (short) bufferedImage.getHeight();
            int bpp = (byte) bufferedImage.getColorModel().getPixelSize();
            ByteBuffer byteBuffer;
            DataBuffer db = bufferedImage.getData().getDataBuffer();
            if(db instanceof DataBufferInt)
            {
                int intI[] = ((DataBufferInt) (bufferedImage.getData().getDataBuffer())).getData();
                byte newI[] = new byte[intI.length * 4];
                for(int i = 0; i < intI.length; i++)
                {
                    byte b[] = intToByteArray(intI[i]);
                    int newIndex = i * 4;

                    newI[newIndex] = b[1];
                    newI[newIndex + 1] = b[2];
                    newI[newIndex + 2] = b[3];
                    newI[newIndex + 3] = b[0];
                }

                byteBuffer = ByteBuffer.allocateDirect(width * height * (bpp / 8)).order(ByteOrder.nativeOrder())
                        .put(newI);
            }
            else
                byteBuffer = ByteBuffer.allocateDirect(width * height * (bpp / 8)).order(ByteOrder.nativeOrder())
                        .put(((DataBufferByte) (bufferedImage.getData().getDataBuffer())).getData());
            byteBuffer.flip();

            int internalFormat = GL11.GL_RGBA8, format = GL11.GL_RGBA;
            IntBuffer textureId = BufferUtils.createIntBuffer(1);
            ;
            GL11.glGenTextures(textureId);
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId.get(0));

            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);

            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
            GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);

            GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE);

            // NOTE: GLU isn't in LWJGL 3!!! This is from lwjgl_util.jar that comes with LWJGL 2
            GLU.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D, internalFormat, width, height, format, GL11.GL_UNSIGNED_BYTE, byteBuffer);
            return textureId.get(0);

        }
        catch(Exception e)
        {
            e.printStackTrace();
            System.exit(-1);
        }

        return -1;
    }

    public static boolean isSupported(String fontname)
    {
        Font font[] = getFonts();
        for(int i = font.length - 1; i >= 0; i--)
            if(font[i].getName().equalsIgnoreCase(fontname))
                return true;
        return false;
    }

    public static Font[] getFonts()
    {
        return GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
    }

    public static byte[] intToByteArray(int value)
    {
        return new byte[]
        {
                (byte) (value >>> 24),
                (byte) (value >>> 16),
                (byte) (value >>> 8 ),
                (byte) (value >>> 0 ),
        };
    }

    public void destroy()
    {
        IntBuffer scratch = BufferUtils.createIntBuffer(1);
        scratch.put(0, fontTextureID);
        GL11.glDeleteTextures(scratch);
    }
}


text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { MessageService } from '../../messages/message.service';

import { Product, ProductResolved } from '../product';
import { ProductService } from '../product.service';

@Component({
  templateUrl: './product-edit.component.html',
  styleUrls: ['./product-edit.component.css']
})
export class ProductEditComponent implements OnInit {
  pageTitle = 'Product Edit';
  errorMessage: string;

  private dataIsValid: { [key: string]: boolean } = {};

  get isDirty(): boolean {
    return JSON.stringify(this.originalProduct) !== JSON.stringify(this.currentProduct);
  }

  private currentProduct: Product;
  private originalProduct: Product;

  get product(): Product {
    return this.currentProduct;
  }
  set product(value: Product) {
    this.currentProduct = value;
    // Clone the object to retain a copy
    this.originalProduct = value ? { ...value } : null;
  }

  constructor(private productService: ProductService,
              private messageService: MessageService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit(): void {
    this.route.data.subscribe(data => {
      const resolvedData: ProductResolved = data['resolvedData'];
      this.errorMessage = resolvedData.error;
      this.onProductRetrieved(resolvedData.product);
    });
  }

  onProductRetrieved(product: Product): void {
    this.product = product;

    if (!this.product) {
      this.pageTitle = 'No product found';
    } else {
      if (this.product.id === 0) {
        this.pageTitle = 'Add Product';
      } else {
        this.pageTitle = `Edit Product: ${this.product.productName}`;
      }
    }
  }

  deleteProduct(): void {
    if (this.product.id === 0) {
      // Don't delete, it was never saved.
      this.onSaveComplete(`${this.product.productName} was deleted`);
    } else {
      if (confirm(`Really delete the product: ${this.product.productName}?`)) {
        this.productService.deleteProduct(this.product.id).subscribe({
          next: () => this.onSaveComplete(`${this.product.productName} was deleted`),
          error: err => this.errorMessage = err
        });
      }
    }
  }

  isValid(path?: string): boolean {
    this.validate();
    if (path) {
      return this.dataIsValid[path];
    }
    return (this.dataIsValid &&
      Object.keys(this.dataIsValid).every(d => this.dataIsValid[d] === true));
  }

  reset(): void {
    this.dataIsValid = null;
    this.currentProduct = null;
    this.originalProduct = null;
  }

  saveProduct(): void {
    if (this.isValid()) {
      if (this.product.id === 0) {
        this.productService.createProduct(this.product).subscribe({
          next: () => this.onSaveComplete(`The new ${this.product.productName} was saved`),
          error: err => this.errorMessage = err
        });
      } else {
        this.productService.updateProduct(this.product).subscribe({
          next: () => this.onSaveComplete(`The updated ${this.product.productName} was saved`),
          error: err => this.errorMessage = err
        });
      }
    } else {
      this.errorMessage = 'Please correct the validation errors.';
    }
  }

  onSaveComplete(message?: string): void {
    if (message) {
      this.messageService.addMessage(message);
    }
    this.reset();

    // Navigate back to the product list
    this.router.navigate(['/products']);
  }

  validate(): void {
    // Clear the validation object
    this.dataIsValid = {};

    // 'info' tab
    if (this.product.productName &&
      this.product.productName.length >= 3 &&
      this.product.productCode) {
      this.dataIsValid['info'] = true;
    } else {
      this.dataIsValid['info'] = false;
    }

    // 'tags' tab
    if (this.product.category &&
      this.product.category.length >= 3) {
      this.dataIsValid['tags'] = true;
    } else {
      this.dataIsValid['tags'] = false;
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
from django.db import models

# Create your models here.
class People(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()
    def __unicode__(self):
	return self.name


text:
namespace BigEgg.Tools.ConsoleExtension.Tests.Parameters.Errors
{
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using BigEgg.Tools.ConsoleExtension.Parameters.Errors;

    [TestClass]
    public class DevelopPropertyTypeMismatchErrorTest
    {
        [TestMethod]
        public void ConstructorTest()
        {
            var error = new DevelopPropertyTypeMismatchError("GitClone", "Repository", "Boolean", new List<string>() { "string" });
            Assert.AreEqual(ErrorType.Develop_PropertyTypeMismatch, error.ErrorType);
            Assert.AreEqual("GitClone", error.TypeName);
            Assert.AreEqual("Repository", error.PropertyName);
            Assert.AreEqual("Boolean", error.CurrentType);
            Assert.AreEqual("string", error.SupportedTypes.Single());
            Assert.IsTrue(error.StopProcessing);
        }
    }
}


text:
package org.elasticsearch.action.admin.indices.settings.get;

import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.MasterNodeReadOperationRequestBuilder;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.common.util.ArrayUtils;

public class GetSettingsRequestBuilder extends MasterNodeReadOperationRequestBuilder<
    GetSettingsRequest,
    GetSettingsResponse,
    GetSettingsRequestBuilder> {

    public GetSettingsRequestBuilder(ElasticsearchClient client, GetSettingsAction action, String... indices) {
        super(client, action, new GetSettingsRequest().indices(indices));
    }

    public GetSettingsRequestBuilder setIndices(String... indices) {
        request.indices(indices);
        return this;
    }

    public GetSettingsRequestBuilder addIndices(String... indices) {
        request.indices(ArrayUtils.concat(request.indices(), indices));
        return this;
    }

    /**
     * Specifies what type of requested indices to ignore and wildcard indices expressions.
     * <p>
     * For example indices that don't exist.
     */
    public GetSettingsRequestBuilder setIndicesOptions(IndicesOptions options) {
        request.indicesOptions(options);
        return this;
    }

    public GetSettingsRequestBuilder setNames(String... names) {
        request.names(names);
        return this;
    }
}


text:
namespace _03.Unicode_Characters
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    class Unicode_Characters
    {
        static void Main()
        {
            var unicodeString = Console.ReadLine();
            var result = unicodeString.Select(t => string.Format("u{0:x4} ", Convert.ToUInt16(t))).ToList();
            var output = new StringBuilder();
            foreach (var item in result)
            {
                output.Append("\\" + item.Trim()).ToString();
            }
            Console.WriteLine(output);
        }
    }
}


text:
package app

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"net"
	"reflect"
	"strconv"
	"strings"

	"k8s.io/klog"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/conversion"
	"k8s.io/apimachinery/pkg/runtime"

	appsv1 "github.com/openshift/api/apps/v1"
	buildv1 "github.com/openshift/api/build/v1"
	"github.com/openshift/library-go/pkg/git"
	"github.com/openshift/origin/pkg/oc/lib/newapp"
	"github.com/openshift/origin/pkg/util"

	s2igit "github.com/openshift/source-to-image/pkg/scm/git"
)

const (
	volumeNameInfix = "volume"

	GenerationWarningAnnotation = "app.generate.openshift.io/warnings"
)

// NameSuggester is an object that can suggest a name for itself
type NameSuggester interface {
	SuggestName() (string, bool)
}

// NameSuggestions suggests names from a collection of NameSuggesters
type NameSuggestions []NameSuggester

// SuggestName suggests a name given a collection of NameSuggesters
func (s NameSuggestions) SuggestName() (string, bool) {
	for i := range s {
		if s[i] == nil {
			continue
		}
		if name, ok := s[i].SuggestName(); ok {
			return name, true
		}
	}
	return "", false
}

// IsParameterizableValue returns true if the value contains standard replacement
// syntax, to preserve the value for use inside of the generated output. Passing
// parameters into output is only valid if the output is used inside of a template.
func IsParameterizableValue(s string) bool {
	return strings.Contains(s, "${") || strings.Contains(s, "$(")
}

// Generated is a list of runtime objects
type Generated struct {
	Items []runtime.Object
}

// WithType extracts a list of runtime objects with the specified type
func (g *Generated) WithType(slicePtr interface{}) bool {
	found := false
	v, err := conversion.EnforcePtr(slicePtr)
	if err != nil || v.Kind() != reflect.Slice {
		// This should not happen at runtime.
		panic("need ptr to slice")
	}
	t := v.Type().Elem()
	for i := range g.Items {
		obj := reflect.ValueOf(g.Items[i]).Elem()
		if !obj.Type().ConvertibleTo(t) {
			continue
		}
		found = true
		v.Set(reflect.Append(v, obj.Convert(t)))
	}
	return found
}

func nameFromGitURL(url *s2igit.URL) (string, bool) {
	if url == nil {
		return "", false
	}
	// from path
	if name, ok := git.NameFromRepositoryURL(&url.URL); ok {
		return name, true
	}
	// TODO: path is questionable
	if len(url.URL.Host) > 0 {
		// from host with port
		if host, _, err := net.SplitHostPort(url.URL.Host); err == nil {
			return host, true
		}
		// from host without port
		return url.URL.Host, true
	}
	return "", false
}

// SourceRef is a reference to a build source
type SourceRef struct {
	URL        *s2igit.URL
	Dir        string
	Name       string
	ContextDir string
	Secrets    []buildv1.SecretBuildSource
	ConfigMaps []buildv1.ConfigMapBuildSource

	SourceImage     *ImageRef
	ImageSourcePath string
	ImageDestPath   string

	DockerfileContents string

	Binary bool

	RequiresAuth bool
}

// SuggestName returns a name derived from the source URL
func (r *SourceRef) SuggestName() (string, bool) {
	if r == nil {
		return "", false
	}
	if len(r.Name) > 0 {
		return r.Name, true
	}
	return nameFromGitURL(r.URL)
}

// BuildSource returns an OpenShift BuildSource from the SourceRef
func (r *SourceRef) BuildSource() (*buildv1.BuildSource, []buildv1.BuildTriggerPolicy) {
	triggers := []buildv1.BuildTriggerPolicy{
		{
			Type: buildv1.GitHubWebHookBuildTriggerType,
			GitHubWebHook: &buildv1.WebHookTrigger{
				Secret: GenerateSecret(20),
			},
		},
		{
			Type: buildv1.GenericWebHookBuildTriggerType,
			GenericWebHook: &buildv1.WebHookTrigger{
				Secret: GenerateSecret(20),
			},
		},
	}
	source := &buildv1.BuildSource{}
	source.Secrets = r.Secrets
	source.ConfigMaps = r.ConfigMaps

	if len(r.DockerfileContents) != 0 {
		source.Dockerfile = &r.DockerfileContents
		source.Type = buildv1.BuildSourceDockerfile
	}
	if r.URL != nil {
		source.Git = &buildv1.GitBuildSource{
			URI: r.URL.StringNoFragment(),
			Ref: r.URL.URL.Fragment,
		}
		source.ContextDir = r.ContextDir
		source.Type = buildv1.BuildSourceGit
	}
	if r.Binary {
		source.Binary = &buildv1.BinaryBuildSource{}
		source.Type = buildv1.BuildSourceBinary
	}
	if r.SourceImage != nil {
		objRef := r.SourceImage.ObjectReference()
		imgSrc := buildv1.ImageSource{}
		imgSrc.From = objRef
		imgSrc.Paths = []buildv1.ImageSourcePath{
			{
				SourcePath:     r.ImageSourcePath,
				DestinationDir: r.ImageDestPath,
			},
		}
		triggers = append(triggers, buildv1.BuildTriggerPolicy{
			Type: buildv1.ImageChangeBuildTriggerType,
			ImageChange: &buildv1.ImageChangeTrigger{
				From: &objRef,
			},
		})
		source.Images = []buildv1.ImageSource{imgSrc}
		source.Type = buildv1.BuildSourceImage
	}
	return source, triggers
}

// BuildStrategyRef is a reference to a build strategy
type BuildStrategyRef struct {
	Strategy newapp.Strategy
	Base     *ImageRef
}

// BuildStrategy builds an OpenShift BuildStrategy from a BuildStrategyRef
func (s *BuildStrategyRef) BuildStrategy(env Environment, dockerStrategyOptions *buildv1.DockerStrategyOptions) (*buildv1.BuildStrategy, []buildv1.BuildTriggerPolicy) {
	switch s.Strategy {
	case newapp.StrategyPipeline:
		return &buildv1.BuildStrategy{
			JenkinsPipelineStrategy: &buildv1.JenkinsPipelineBuildStrategy{
				Env: env.List(),
			},
			Type: buildv1.JenkinsPipelineBuildStrategyType,
		}, s.Base.BuildTriggers()

	case newapp.StrategyDocker:
		var triggers []buildv1.BuildTriggerPolicy
		strategy := &buildv1.DockerBuildStrategy{
			Env: env.List(),
		}
		if dockerStrategyOptions != nil {
			strategy.BuildArgs = dockerStrategyOptions.BuildArgs
		}
		if s.Base != nil {
			ref := s.Base.ObjectReference()
			strategy.From = &ref
			triggers = s.Base.BuildTriggers()
		}
		return &buildv1.BuildStrategy{
			DockerStrategy: strategy,
			Type:           buildv1.DockerBuildStrategyType,
		}, triggers

	case newapp.StrategySource:
		return &buildv1.BuildStrategy{
			SourceStrategy: &buildv1.SourceBuildStrategy{
				From: s.Base.ObjectReference(),
				Env:  env.List(),
			},
			Type: buildv1.SourceBuildStrategyType,
		}, s.Base.BuildTriggers()
	}

	klog.Error("BuildStrategy called with unknown strategy")
	return nil, nil
}

// BuildRef is a reference to a build configuration
type BuildRef struct {
	Source                *SourceRef
	Input                 *ImageRef
	Strategy              *BuildStrategyRef
	DockerStrategyOptions *buildv1.DockerStrategyOptions
	Output                *ImageRef
	Env                   Environment
	Binary                bool
}

// BuildConfig creates a buildConfig resource from the build configuration reference
func (r *BuildRef) BuildConfig() (*buildv1.BuildConfig, error) {
	name, ok := NameSuggestions{r.Source, r.Output}.SuggestName()
	if !ok {
		return nil, fmt.Errorf("unable to suggest a name for this BuildConfig from %q", r.Source.URL)
	}
	var source *buildv1.BuildSource
	triggers := []buildv1.BuildTriggerPolicy{}
	if r.Source != nil {
		source, triggers = r.Source.BuildSource()
	}
	if source == nil {
		source = &buildv1.BuildSource{}
	}
	strategy := &buildv1.BuildStrategy{}
	strategyTriggers := []buildv1.BuildTriggerPolicy{}
	if r.Strategy != nil {
		strategy, strategyTriggers = r.Strategy.BuildStrategy(r.Env, r.DockerStrategyOptions)
	}
	output, err := r.Output.BuildOutput()
	if err != nil {
		return nil, err
	}

	if !r.Binary {
		configChangeTrigger := buildv1.BuildTriggerPolicy{
			Type: buildv1.ConfigChangeBuildTriggerType,
		}
		triggers = append(triggers, configChangeTrigger)
		triggers = append(triggers, strategyTriggers...)
	} else {
		// remove imagechangetriggers from binary buildconfigs because
		// triggered builds will fail (no binary input available)
		filteredTriggers := []buildv1.BuildTriggerPolicy{}
		for _, trigger := range triggers {
			if trigger.Type != buildv1.ImageChangeBuildTriggerType {
				filteredTriggers = append(filteredTriggers, trigger)
			}
		}
		triggers = filteredTriggers
	}
	return &buildv1.BuildConfig{
		// this is ok because we know exactly how we want to be serialized
		TypeMeta: metav1.TypeMeta{APIVersion: buildv1.SchemeGroupVersion.String(), Kind: "BuildConfig"},
		ObjectMeta: metav1.ObjectMeta{
			Name: name,
		},
		Spec: buildv1.BuildConfigSpec{
			Triggers: triggers,
			CommonSpec: buildv1.CommonSpec{
				Source:   *source,
				Strategy: *strategy,
				Output:   *output,
			},
		},
	}, nil
}

type DeploymentHook struct {
	Shell string
}

// DeploymentConfigRef is a reference to a deployment configuration
type DeploymentConfigRef struct {
	Name     string
	Images   []*ImageRef
	Env      Environment
	Labels   map[string]string
	AsTest   bool
	PostHook *DeploymentHook
}

// DeploymentConfig creates a deploymentConfig resource from the deployment configuration reference
//
// TODO: take a pod template spec as argument
func (r *DeploymentConfigRef) DeploymentConfig() (*appsv1.DeploymentConfig, error) {
	if len(r.Name) == 0 {
		suggestions := NameSuggestions{}
		for i := range r.Images {
			suggestions = append(suggestions, r.Images[i])
		}
		name, ok := suggestions.SuggestName()
		if !ok {
			return nil, fmt.Errorf("unable to suggest a name for this DeploymentConfig")
		}
		r.Name = name
	}

	selector := map[string]string{
		"deploymentconfig": r.Name,
	}
	if len(r.Labels) > 0 {
		if err := util.MergeInto(selector, r.Labels, 0); err != nil {
			return nil, err
		}
	}

	triggers := []appsv1.DeploymentTriggerPolicy{
		// By default, always deploy on change
		{
			Type: appsv1.DeploymentTriggerOnConfigChange,
		},
	}

	template := corev1.PodSpec{}
	for i := range r.Images {
		c, containerTriggers, err := r.Images[i].DeployableContainer()
		if err != nil {
			return nil, err
		}
		triggers = append(triggers, containerTriggers...)
		template.Containers = append(template.Containers, *c)
	}

	// Create EmptyDir volumes for all container volume mounts
	for _, c := range template.Containers {
		for _, v := range c.VolumeMounts {
			template.Volumes = append(template.Volumes, corev1.Volume{
				Name: v.Name,
				VolumeSource: corev1.VolumeSource{
					EmptyDir: &corev1.EmptyDirVolumeSource{Medium: corev1.StorageMediumDefault},
				},
			})
		}
	}

	for i := range template.Containers {
		template.Containers[i].Env = append(template.Containers[i].Env, r.Env.List()...)
	}

	dc := &appsv1.DeploymentConfig{
		// this is ok because we know exactly how we want to be serialized
		TypeMeta: metav1.TypeMeta{APIVersion: appsv1.SchemeGroupVersion.String(), Kind: "DeploymentConfig"},
		ObjectMeta: metav1.ObjectMeta{
			Name: r.Name,
		},
		Spec: appsv1.DeploymentConfigSpec{
			Replicas: 1,
			Test:     r.AsTest,
			Selector: selector,
			Template: &corev1.PodTemplateSpec{
				ObjectMeta: metav1.ObjectMeta{
					Labels: selector,
				},
				Spec: template,
			},
			Triggers: triggers,
		},
	}
	if r.PostHook != nil {
		//dc.Spec.Strategy.Type = "Rolling"
		if len(r.PostHook.Shell) > 0 {
			dc.Spec.Strategy.RecreateParams = &appsv1.RecreateDeploymentStrategyParams{
				Post: &appsv1.LifecycleHook{
					ExecNewPod: &appsv1.ExecNewPodHook{
						Command: []string{"/bin/sh", "-c", r.PostHook.Shell},
					},
				},
			}
		}
	}

	return dc, nil
}

// GenerateSecret generates a random secret string
func GenerateSecret(n int) string {
	b := make([]byte, base64.URLEncoding.DecodedLen(n))
	if _, err := rand.Read(b); err != nil {
		panic(err) // rand should never fail
	}
	return base64.URLEncoding.EncodeToString(b)
}

// ContainerPortsFromString extracts sets of port specifications from a comma-delimited string. Each segment
// must be a single port number (container port) or a colon delimited pair of ports (container port and host port).
func ContainerPortsFromString(portString string) ([]corev1.ContainerPort, error) {
	ports := []corev1.ContainerPort{}
	for _, s := range strings.Split(portString, ",") {
		port, ok := checkPortSpecSegment(s)
		if !ok {
			return nil, fmt.Errorf("%q is not valid: you must specify one (container) or two (container:host) port numbers", s)
		}
		ports = append(ports, port)
	}
	return ports, nil
}

func checkPortSpecSegment(s string) (port corev1.ContainerPort, ok bool) {
	if strings.Contains(s, ":") {
		pair := strings.Split(s, ":")
		if len(pair) != 2 {
			return
		}
		container, err := strconv.Atoi(pair[0])
		if err != nil {
			return
		}
		host, err := strconv.Atoi(pair[1])
		if err != nil {
			return
		}
		return corev1.ContainerPort{ContainerPort: int32(container), HostPort: int32(host)}, true
	}

	container, err := strconv.Atoi(s)
	if err != nil {
		return
	}
	return corev1.ContainerPort{ContainerPort: int32(container)}, true
}

// LabelsFromSpec turns a set of specs NAME=VALUE or NAME- into a map of labels,
// a remove label list, or an error.
func LabelsFromSpec(spec []string) (map[string]string, []string, error) {
	labels := map[string]string{}
	var remove []string
	for _, labelSpec := range spec {
		if strings.Index(labelSpec, "=") != -1 {
			parts := strings.Split(labelSpec, "=")
			if len(parts) != 2 {
				return nil, nil, fmt.Errorf("invalid label spec: %v", labelSpec)
			}
			labels[parts[0]] = parts[1]
		} else if strings.HasSuffix(labelSpec, "-") {
			remove = append(remove, labelSpec[:len(labelSpec)-1])
		} else {
			return nil, nil, fmt.Errorf("unknown label spec: %s", labelSpec)
		}
	}
	for _, removeLabel := range remove {
		if _, found := labels[removeLabel]; found {
			return nil, nil, fmt.Errorf("can not both modify and remove a label in the same command")
		}
	}
	return labels, remove, nil
}


text:
class Type {
	private Double myField;
	public void meth(Double p) {
		myField = p;
	}
}


text:
import Queue, time, numpy

from colorificworker import ColorificWorker

def main():
    notification_q = Queue.Queue()

    cw = ColorificWorker(notification_q)

    cw.start()
    cw.alert_red()
    time.sleep(5)
    cw.color_shift(cw.BLUE)
    time.sleep(5)
    cw.alert_red()
    time.sleep(20)
    cw.join()
    #while True:
        #try:
            #test = 1
        #except KeyboardInterrupt:
            #smw.join()
            #return
        #except EOFError:
            #smw.join()
            #return

if __name__ == '__main__':
    main()


text:
package org.beaucatcher.mongo.cdriver

import akka.dispatch._
import akka.util.duration._
import org.beaucatcher.mongo._
import org.beaucatcher.bson._
import org.beaucatcher.channel._
import org.beaucatcher.driver._
import org.beaucatcher.wire._

private[cdriver] final class ChannelDriverAsyncCollection(override val name: String, override val context: ChannelDriverContext) extends AsyncDriverCollection {

    import RawEncoded._

    private[cdriver] def connection: Connection = context.connection

    private def newRaw() = RawEncoded(context.driver.backend)
    // must be lazy since it uses stuff that isn't available at construct
    private implicit lazy val fieldsEncoder = newFieldsQueryEncoder(context.driver.backend)

    override def count[Q](query: Q, options: CountOptions)(implicit queryEncoder: QueryEncoder[Q]): Future[Long] = {
        val raw = newRaw()
        raw.writeField("count", name)
        raw.writeField("query", query)
        raw.writeFieldLongOption("limit", options.limit)
        raw.writeFieldLongOption("skip", options.skip)
        raw.writeField("fields", options.fields)

        connection.sendCommand(queryFlags(options.overrideQueryFlags), database.name, raw) map { reply =>
            val result = decodeCommandResult[BugIfDecoded](reply, "n")
            result.result.throwIfNotOk()
            result.fields.get("n") match {
                case Some(n: Number) =>
                    n.longValue()
                case _ =>
                    throw new MongoException("Missing/incorrect 'n' field in count command result: " + result)
            }
        }
    }

    override def distinct[Q, V](key: String, options: DistinctOptions[Q])(implicit queryEncoder: QueryEncoder[Q], valueDecoder: ValueDecoder[V]): Future[Iterator[V]] = {
        import CodecUtils._

        val raw = newRaw()
        raw.writeField("distinct", name)
        raw.writeField("key", key)
        raw.writeField("query", options.query)

        connection.sendCommand(queryFlags(options.overrideQueryFlags), database.name, raw) map { reply =>
            val result = decodeCommandResultFields[BugIfDecoded](reply, RawField("values", Some(RawBufferDecoded.rawBufferValueDecoder)))
            result.result.throwIfNotOk()
            result.fields.get("values") match {
                case Some(RawBufferDecoded(buf)) =>
                    // 'buf' should be an encoded array value
                    readArrayValues[V](buf).iterator
                case _ =>
                    throw new MongoException("Missing/incorrect 'values' field in distinct command result: " + result)
            }
        }
    }

    private def computeBatchSize(rawBatchSize: Int, rawLimit: Long): (Int, Long) = {
        val DEFAULT_BATCH = 100
        val limit = if (rawLimit <= 0) Long.MaxValue else rawLimit
        val batchSize = math.min(if (rawBatchSize <= 0) DEFAULT_BATCH else rawBatchSize,
            math.min(limit, Int.MaxValue).intValue())
        (batchSize, limit)
    }

    override def find[Q, E](query: Q, options: FindOptions)(implicit queryEncoder: QueryEncoder[Q], resultDecoder: QueryResultDecoder[E]): Future[AsyncCursor[E]] = {
        val skip = options.skip.getOrElse(0L)
        val (batchSize, limit) = computeBatchSize(options.batchSize.getOrElse(0), options.limit.getOrElse(0L))

        connection.sendQuery[Q, Fields](queryFlags(options.overrideQueryFlags), fullName,
            skip.intValue, batchSize, limit, query, options.fields)
            .map({ replyCursor =>
                replyCursor.flatMap({ reply =>
                    reply.iterator[E]()
                })
            })
    }

    private def findOne[Q, E](flags: Int, query: Q, fields: Option[Fields])(implicit querySupport: QueryEncoder[Q], resultDecoder: QueryResultDecoder[E]): Future[Option[E]] = {
        connection.sendQueryOne[Q, Fields](flags, fullName, query, fields)
            .map({ replyOption =>
                replyOption.map({ reply =>
                    reply.iterator[E]().next()
                })
            })
    }

    override def findOne[Q, E](query: Q, options: FindOneOptions)(implicit queryEncoder: QueryEncoder[Q], resultDecoder: QueryResultDecoder[E]): Future[Option[E]] = {
        findOne(queryFlags(options.overrideQueryFlags), query, options.fields)
    }

    override def findOneById[I, E](id: I, options: FindOneByIdOptions)(implicit idEncoder: IdEncoder[I], resultDecoder: QueryResultDecoder[E]): Future[Option[E]] = {
        val raw = newRaw()
        raw.writeFieldAny("_id", id)
        findOne(queryFlags(options.overrideQueryFlags), raw, options.fields)
    }

    override def findIndexes(): Future[AsyncCursor[CollectionIndex]] =
        throw new UnsupportedOperationException("FIXME") // TODO

    override def findAndModify[Q, M, S, E](query: Q, modifier: Option[M], options: FindAndModifyOptions[S])(implicit queryEncoder: QueryEncoder[Q], modifierEncoder: ModifierEncoder[M], resultDecoder: QueryResultDecoder[E], sortEncoder: QueryEncoder[S]): Future[Option[E]] = {
        if (options.flags.contains(FindAndModifyRemove)) {
            if (modifier.isDefined) {
                throw new BugInSomethingMongoException("Does not make sense to provide a replacement or modifier object to findAndModify with remove flag")
            }
        } else if (modifier.isEmpty) {
            throw new BugInSomethingMongoException("Must provide a replacement or modifier object to findAndModify")
        }

        val raw = newRaw()
        raw.writeField("findandmodify", name)
        raw.writeField("query", query)
        raw.writeField("fields", options.fields)
        raw.writeField("sort", options.sort)
        raw.writeFieldAsModifier("update", modifier)
        for (flag <- options.flags) {
            flag match {
                case FindAndModifyNew =>
                    raw.writeField("new", true)
                case FindAndModifyRemove =>
                    raw.writeField("remove", true)
                case findAndModifyUpsert =>
                    raw.writeField("upsert", true)
            }
        }

        connection.sendCommand(0 /* flags */ , database.name, raw) map { reply =>
            val result = decodeCommandResult[E](reply, "value")
            if (result.result.ok) {
                result.fields.get("value") match {
                    case Some(null) =>
                        None
                    case Some(x) =>
                        // note: this asInstanceOf doesn't do anything other than
                        // make it compile, due to erasure
                        Some(x.asInstanceOf[E])
                    case _ =>
                        None
                }
            } else if (result.result.errmsg == "No matching object found") {
                // This case is in the Java driver, don't know which versions
                // of mongo require it or what
                None
            } else {
                result.result.throwIfNotOk()
                None // not reached
            }
        }
    }

    // this has to be lazy or else "database" won't be ready
    private lazy val safe = GetLastError.safe(database.name)

    private def throwOnFail(f: Future[WriteResult]): Future[WriteResult] = {
        f.map(_.throwIfNotOk())
    }

    override def insert[E](o: E)(implicit upsertEncoder: UpsertEncoder[E]): Future[WriteResult] = {
        // TODO have a way to set "continue on error" flag, which is in the
        // WriteConcern in the Java driver.
        throwOnFail(connection.sendInsert(0 /* flags */ , fullName, Seq(o), safe))
    }

    private def updateFlags(options: UpdateOptions): Int = {
        var flags = 0
        for (flag <- options.flags) {
            flag match {
                case UpdateUpsert =>
                    flags |= Mongo.UPDATE_FLAG_UPSERT
                case UpdateMulti =>
                    flags |= Mongo.UPDATE_FLAG_MULTI_UPDATE
            }
        }
        flags
    }

    override def save[Q](query: Q, options: UpdateOptions)(implicit queryEncoder: UpdateQueryEncoder[Q], upsertEncoder: UpsertEncoder[Q]): Future[WriteResult] = {
        throwOnFail(connection.sendSave(fullName, updateFlags(options), query, safe))
    }

    override def update[Q, M](query: Q, modifier: M, options: UpdateOptions)(implicit queryEncoder: QueryEncoder[Q], modifierEncoder: ModifierEncoder[M]): Future[WriteResult] = {
        throwOnFail(connection.sendUpdate(fullName, updateFlags(options), query, modifier, safe))
    }

    override def updateUpsert[Q, U](query: Q, modifier: U, options: UpdateOptions)(implicit queryEncoder: QueryEncoder[Q], upsertEncoder: UpsertEncoder[U]): Future[WriteResult] = {
        throwOnFail(connection.sendUpdateUpsert(fullName, updateFlags(options), query, modifier, safe))
    }

    private def remove[Q](flags: Int, query: Q)(implicit querySupport: QueryEncoder[Q]): Future[WriteResult] = {
        throwOnFail(connection.sendDelete(fullName, flags, query, safe))
    }

    override def remove[Q](query: Q)(implicit queryEncoder: QueryEncoder[Q]): Future[WriteResult] = {
        // TODO support DELETE_FLAG_SINGLE_REMOVE (Java driver just sets
        // this iff the query has an _id in it)
        remove[Q](0 /* flags */ , query)
    }

    override def removeById[I](id: I)(implicit idEncoder: IdEncoder[I]): Future[WriteResult] = {
        val raw = newRaw()
        raw.writeFieldAny("_id", id)
        remove[RawEncoded](Mongo.DELETE_FLAG_SINGLE_REMOVE, raw)
    }

    override def ensureIndex[Q](keys: Q, options: IndexOptions)(implicit queryEncoder: QueryEncoder[Q]): Future[WriteResult] = {
        val indexName = options.name.getOrElse(defaultIndexName(keys))
        val raw = newRaw()
        raw.writeField("name", indexName)
        raw.writeField("ns", fullName)
        raw.writeFieldIntOption("v", options.v)
        for (flag <- options.flags) {
            flag match {
                case IndexUnique => raw.writeField("unique", true)
                case IndexBackground => raw.writeField("background", true)
                case IndexDropDups => raw.writeField("dropDups", true)
                case IndexSparse => raw.writeField("sparse", true)
            }
        }
        raw.writeField[Q]("key", keys)

        connection.sendInsert(0 /* flags */ , database.name + ".system.indexes", Seq(raw), safe)
    }

    override def dropIndex(indexName: String): Future[CommandResult] = {
        val raw = newRaw()
        raw.writeField("deleteIndexes", name)
        raw.writeField("index", indexName)
        connection.sendCommand(0 /* query flags */ , database.name, raw) map { reply =>
            val result = decodeCommandResult[BugIfDecoded](reply).result
            // Java driver ignores if errmsg is "ns not found" and this
            // appears to be needed with mongod 2.0.2 for example.
            if (!result.ok && result.errmsg == Some("ns not found"))
                CommandResult.ok
            else
                result.throwIfNotOk()
        }
    }
}


text:
Hightower::Engine.routes.draw do
  resources :events, only: [:index]
  resources :segments, only: [:index]
  resources :users, only: [:index, :show]
  root to: 'segments#index'
end


text:
module.exports.beginPull = function taskQueuePull(cb) {
  cb();
};

module.exports.finish = function taskQueueShift() {};


text:
layout: post
title: 'ReactJS : setup ava for testing react components'
excerpt: 'Adding ava.js to react project to test react components'
date: 2017-05-31 23:59:00 IST
updated: 2017-05-31 23:59:00 IST
categories: javascript, react
tags: javascript, react, testing, ava
---

[Ava.js][ava] is a futuristic test runner, which runs your tests concurrently. This will force you to write tests without
depending on a global state or state of other test cases.

## Installation

Let's start with installing ava globally.

```sh
npm i -g ava
```

Once the installation finishes, add ava to our project.

```sh
ava --init
```

## Babel config

Since our project already have `babel` config, we want ava to use the same babel setup to transpile the test code.
For this we need to use specia keyword `inherit` in ava's babel config.

```json
// package.json

{
  "ava": {
    "babel": "inherit"
  }
}
```

## Adding mocked browser envionment

Unlike other libraries React need browser enviornment for `ReactDOM.render` and simulate events.
We will use `browser-env` to add mocked browser envionment. `browser-env` will add variables like `window`, `document` etc to the global namespace.

Install the `browser-env` using

```
npm i --save-dev browser-env
```

and add a helper file to load the needed browser global variables.

```js
// tests/helpers/browser-env.js
import browserEnv from 'browser-env';
browserEnv(['window', 'document']);
```

By default, `browserEnv()` add all global browser variables to global scope, which not a good idea. `browserEnv(['window', 'document'])` will expose the needed ones.
Since our `tests/helpers/browser-env.js` doesn't get transpiled by ava, we need to use `babel-register` to transpile this on the fly.

```
npm i --save-dev babel-register
```

Now we need to specify `babel-register` & browser-env helper we wrote in ava's register config to load before the tests.

```json
// package.json

{
  "ava": {
    "babel": "inherit",
    "register": [
      "babel-register",
      "./test/helpers/browser-env.js"
    ]
  }
}
```

## Ignoring the CSS and Images

Now if we try to run tests for the components which import any css or images, the nodejs will throw an error since they are not valid JavaScript.
We can fix this issue by using [ignore-styles][ignore_styles].

```
npm i --save-dev ignore-styles
```

Now we can load this in ava's register hook.

```json
// package.json

{
  "ava": {
    "babel": "inherit",
    "register": [
      "babel-register",
      "./test/helpers/browser-env.js",
      "ignore-styles"
    ]
  }
}
```

Now we are ready to our first test case.

## First unit test

Now lets write our first test case

```js
import test from 'ava';

import React from 'react';
import { shallow } from 'enzyme';

import HelloWorld from '../src/HelloWorld';

test('it renders', (t) => {
  const wrapper = shallow(<HelloWorld title="Title" desc="desc"/>);
  t.true(wrapper.hasClass('hello-world'));
})
```

Now when we run the command `ava`,

<video loop autoplay src="https://s3.ap-south-1.amazonaws.com/revathskumar-blog-images/2017/ava-test-runner/ava-runner.mov" ></video>

## Snapshot testing

Snapshot testing is introduced with jest, to compare and make sure UI didn't changed unexpectedly. Ava supports snapshot testing using `snapshot` assetion method.

```js
import test from 'ava';
import render from 'react-test-renderer';

import HelloWorld from '../src/HelloWorld';

test('HelloWorld snapshot', t => {
  const tree = render.create(
    <HelloWorld title="Title" desc="desc"/>
  ).toJSON();
  t.snapshot(tree);
});
```

This will create snapshot in `__snapshots__` folder similar to jest. All the snapshots should be added to source control along with the code.
Use `-u` option to update the snapshots for the latest changes.

[ava]: https://github.com/avajs/ava
[ignore_styles]: http://npm.im/ignore-styles


text:
#ifndef __YAMAMOTO_H__
#define __YAMAMOTO_H__
/**
 * \brief Perform TSQR and construct Yamamoto's basis kernel representation [Q1-S; Q2][Q1-S]^-1[Q1-S; Q2]
 *          on a (sub)-column of processors
 *
 * \param[in,out] A m-by-b dense tall-skinny matrix [tree_Y\R] on output
 * \param[in] lda_A lda of A
 * \param[in,out] Qm m-by-b dense tall-skinny matrix [Q1-I; Q2] on output
 * \param[in] lda_Qm lda of Qm
 * \param[in] m number of rows in A
 * \param[in] b number of columns in A
 * \param[in,out] W b-by-b matrix (must be preallocated containing [L \ U] = LU(Q1-S)
 * \param[in] myRank rank in communicator column
 * \param[in] numPes number of processes in column
 * \param[in] root the root of the tree (who will own R at the end)
 * \param[in] req_id request id to use for send/recv
 * \param[in] cdt MPI communicator for column
 * \param[in,out] signs S
 **/
void Yamamoto(double *   A,
              int64_t    lda_A,
              double *   Qm,
              int64_t    lda_Qm,
              int64_t    m,
              int64_t    b,
              double *   W,
              int64_t    myRank,
              int64_t    numPes,
              int64_t    root,
              int64_t    req_id,
              CommData_t cdt);

#endif


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.jenkins-ci.plugins</groupId>
    <artifactId>plugin</artifactId>
    <version>2.13</version>
  </parent>

  <groupId>org.csanchez.jenkins.plugins</groupId>
  <artifactId>kubernetes</artifactId>
  <version>0.9-SNAPSHOT</version>
  <name>Kubernetes plugin</name>
  <description>Jenkins plugin to run dynamic slaves in a Kubernetes/Docker environment</description>
  <packaging>hpi</packaging>
  <url>https://wiki.jenkins-ci.org/display/JENKINS/Kubernetes+Plugin</url>

  <scm>
    <connection>scm:git:ssh://github.com/jenkinsci/kubernetes-plugin.git</connection>
    <developerConnection>scm:git:ssh://git@github.com/jenkinsci/kubernetes-plugin.git</developerConnection>
    <url>https://github.com/jenkinsci/kubernetes-plugin</url>
    <tag>HEAD</tag>
  </scm>

  <developers>
    <developer>
      <id>carlos</id>
      <name>Carlos Sanchez</name>
      <email>carlos@apache.org</email>
    </developer>
  </developers>

  <properties>
    <java.level>8</java.level>
    <jackson.version>2.5.0</jackson.version>
    <spring.version>3.2.14.RELEASE</spring.version>
    <jenkins.version>2.9</jenkins.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.jenkins-ci.plugins</groupId>
      <artifactId>one-shot-executor</artifactId>
      <version>1.1-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>org.jenkins-ci.plugins</groupId>
      <artifactId>credentials</artifactId>
      <version>1.22</version>
    </dependency>

    <dependency>
      <groupId>io.fabric8</groupId>
      <artifactId>kubernetes-client</artifactId>
      <version>1.3.98</version>
    </dependency>

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.1</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.7</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.jenkins-ci.tools</groupId>
        <artifactId>maven-hpi-plugin</artifactId>
        <configuration>
          <pluginFirstClassLoader>true</pluginFirstClassLoader>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <!-- get every artifact through repo.jenkins-ci.org, which proxies all the artifacts that we need -->
  <repositories>
    <repository>
      <id>repo.jenkins-ci.org</id>
      <url>http://repo.jenkins-ci.org/public/</url>
    </repository>
  </repositories>

  <pluginRepositories>
    <pluginRepository>
      <id>repo.jenkins-ci.org</id>
      <url>http://repo.jenkins-ci.org/public/</url>
    </pluginRepository>
  </pluginRepositories>

</project>


text:
¿Cómo lo llevamos?

        {% for progress in site.data.progresses %}
            {% assign loopindex = forloop.index | modulo: 2 %}

{{ progress.name }}

        {% endfor %}

    {% for comment in site.data.comments.progresses %}
    {% if forloop.first %}

    {% endif %}

{{ comment }}

    {% if forloop.last %}

    {% endif %}
    {% endfor %}


text:
require 'spec_helper'

RSpec.describe OneviewSDK::API2800::C7000::ServerHardware do
  include_context 'shared context'

  it 'inherits from OneviewSDK::API2600::C7000::ServerHardware' do
    expect(described_class).to be < OneviewSDK::API2600::C7000::ServerHardware
  end
end


text:
layout: post
microblog: true
date: 2011-10-31 23:04 +0300
guid: http://desparoz.micro.blog/2011/10/31/t131099343989121024.html
---
Started Walk with @walkmeter at 7:04 AM, Walkmeter will speak your replies to me.


text:
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk.internal.protocolparser.dynamicimpl;

import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.dynamicimpl.JavaCodeGenerator.FileScope;
import org.chromium.sdk.internal.protocolparser.dynamicimpl.JavaCodeGenerator.MethodScope;
import org.chromium.sdk.internal.protocolparser.dynamicimpl.JavaCodeGenerator.Util;
import org.json.simple.JSONObject;

/**
 * A parser that generates dynamic proxy implementation of JsonType interface
 * for a {@link JSONObject}.
 * It creates dynamic proxy instance in 2 steps. First {@link #parseValue(Object, ObjectData)}
 * outputs {@link ObjectData}, which gets stored in field storage array. Later, when we are
 * about to return the value to a user, it is converted to a dynamic proxy instance by
 * {@link #VALUE_FINISHER} converter. We have to store an intermediate value for easier data
 * manipulation (dynamic proxy does not have any interfaces that we could make use of).
 */
class JsonTypeParser<T> extends SlowParser<ObjectData> {
  private final RefToType<T> refToType;
  private final boolean isNullable;
  private final boolean isSubtyping;

  JsonTypeParser(RefToType<T> refToType, boolean isNullable, boolean isSubtyping) {
    this.refToType = refToType;
    this.isNullable = isNullable;
    this.isSubtyping = isSubtyping;
  }

  RefToType<T> getType() {
    return refToType;
  }

  @Override
  public ObjectData parseValue(Object value, ObjectData thisData)
      throws JsonProtocolParseException {
    if (isNullable && value == null) {
      return null;
    }
    if (value == null) {
      throw new JsonProtocolParseException("null input");
    }
    TypeHandler<T> typeHandler = refToType.get();
    if (isSubtyping) {
      return typeHandler.parse(value, thisData);
    } else {
      return typeHandler.parseRootImpl(value);
    }
  }

  @Override
  public FieldLoadedFinisher getValueFinisher() {
    return VALUE_FINISHER;
  }

  @Override
  public JsonTypeParser<?> asJsonTypeParser() {
    return this;
  }

  public boolean isSubtyping() {
    return isSubtyping;
  }

  private static final FieldLoadedFinisher VALUE_FINISHER = new FieldLoadedFinisher() {
    @Override
    Object getValueForUser(Object cachedValue) {
      if (cachedValue == null) {
        return null;
      }
      ObjectData data = (ObjectData) cachedValue;
      return data.getProxy();
    }
  };

  @Override
  public void appendFinishedValueTypeNameJava(FileScope scope) {
    scope.append(refToType.getTypeClass().getCanonicalName());
  }

  @Override
  public void appendInternalValueTypeNameJava(FileScope classScope) {
    classScope.append(classScope.getTypeImplReference(refToType.get()));
  }

  @Override
  void writeParseCode(MethodScope scope, String valueRef,
      String superValueRef, String resultRef) {
    String typeName = scope.getTypeImplReference(refToType.get());
    scope.startLine(typeName + " " + resultRef + ";\n");

    scope.startLine("if (" + valueRef+ " == null) {\n");
    if (isNullable) {
      scope.startLine("  " + resultRef+ " = null;\n");
    } else {
      scope.startLine("  throw new " + Util.BASE_PACKAGE +
          ".JsonProtocolParseException(\"null input\");\n");
    }
    scope.startLine("} else {\n");
    if (isSubtyping) {
      scope.startLine("  " + resultRef + " = new " + typeName + "(" + valueRef + ", " +
          superValueRef + ");\n");
    } else {
      scope.startLine("  " + resultRef + " = " + typeName + ".parse(" + valueRef + ");\n");
    }
    scope.startLine("}\n");
  }

  @Override
  boolean javaCodeThrowsException() {
    return true;
  }
}


text:
bool
Matrix4D::TestClass()
{
	SPEW((GROUP_STUFF_TEST, "Starting Matrix4D test...\n"));
	SPEW((GROUP_STUFF_TEST, "  Matrix4D::TestClass() is stubbed out!"));
	return false;
}


text:
<?php

namespace Madrasse\AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PersonType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('forname')
            ->add('phone')
            ->add('email')
            ->add('birthday', 'datepicker')
            ->add('birthplace')
            ->add('gender', 'choice', array(
                'choices' => array('masculin' => 'Masculin', 'feminin' => 'Féminin'),
                'label' => 'Sexe'
            ))
            ->add('address')
            ->add('zip')
            ->add('city')
            ->add('status')
            ->add('pathRedirect', 'hidden', [
                'mapped'    => false,
                'data'      => $options['pathRedirect']
            ]);
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class'         => 'Madrasse\AdminBundle\Entity\Person',
            'pathRedirect'       => null,
            'translation_domain' => 'person',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'madrasse_adminbundle_person';
    }
}


text:
"""Let's Encrypt user-supplied configuration."""
import copy
import os

from six.moves.urllib import parse  # pylint: disable=import-error
import zope.interface

from letsencrypt import constants
from letsencrypt import errors
from letsencrypt import interfaces
from letsencrypt import le_util

@zope.interface.implementer(interfaces.IConfig)
class NamespaceConfig(object):
    """Configuration wrapper around :class:`argparse.Namespace`.

    For more documentation, including available attributes, please see
    :class:`letsencrypt.interfaces.IConfig`. However, note that
    the following attributes are dynamically resolved using
    :attr:`~letsencrypt.interfaces.IConfig.work_dir` and relative
    paths defined in :py:mod:`letsencrypt.constants`:

      - `accounts_dir`
      - `csr_dir`
      - `in_progress_dir`
      - `key_dir`
      - `renewer_config_file`
      - `temp_checkpoint_dir`

    :ivar namespace: Namespace typically produced by
        :meth:`argparse.ArgumentParser.parse_args`.
    :type namespace: :class:`argparse.Namespace`

    """

    def __init__(self, namespace):
        self.namespace = namespace

        self.namespace.config_dir = os.path.abspath(self.namespace.config_dir)
        self.namespace.work_dir = os.path.abspath(self.namespace.work_dir)
        self.namespace.logs_dir = os.path.abspath(self.namespace.logs_dir)

        # Check command line parameters sanity, and error out in case of problem.
        check_config_sanity(self)

    def __getattr__(self, name):
        return getattr(self.namespace, name)

    @property
    def server_path(self):
        """File path based on ``server``."""
        parsed = parse.urlparse(self.namespace.server)
        return (parsed.netloc + parsed.path).replace('/', os.path.sep)

    @property
    def accounts_dir(self):  # pylint: disable=missing-docstring
        return os.path.join(
            self.namespace.config_dir, constants.ACCOUNTS_DIR, self.server_path)

    @property
    def backup_dir(self):  # pylint: disable=missing-docstring
        return os.path.join(self.namespace.work_dir, constants.BACKUP_DIR)

    @property
    def csr_dir(self):  # pylint: disable=missing-docstring
        return os.path.join(self.namespace.config_dir, constants.CSR_DIR)

    @property
    def in_progress_dir(self):  # pylint: disable=missing-docstring
        return os.path.join(self.namespace.work_dir, constants.IN_PROGRESS_DIR)

    @property
    def key_dir(self):  # pylint: disable=missing-docstring
        return os.path.join(self.namespace.config_dir, constants.KEY_DIR)

    @property
    def temp_checkpoint_dir(self):  # pylint: disable=missing-docstring
        return os.path.join(
            self.namespace.work_dir, constants.TEMP_CHECKPOINT_DIR)

    def __deepcopy__(self, _memo):
        # Work around https://bugs.python.org/issue1515 for py26 tests :( :(
        # https://travis-ci.org/letsencrypt/letsencrypt/jobs/106900743#L3276
        new_ns = copy.deepcopy(self.namespace)
        return type(self)(new_ns)

class RenewerConfiguration(object):
    """Configuration wrapper for renewer."""

    def __init__(self, namespace):
        self.namespace = namespace

    def __getattr__(self, name):
        return getattr(self.namespace, name)

    @property
    def archive_dir(self):  # pylint: disable=missing-docstring
        return os.path.join(self.namespace.config_dir, constants.ARCHIVE_DIR)

    @property
    def live_dir(self):  # pylint: disable=missing-docstring
        return os.path.join(self.namespace.config_dir, constants.LIVE_DIR)

    @property
    def renewal_configs_dir(self):  # pylint: disable=missing-docstring
        return os.path.join(
            self.namespace.config_dir, constants.RENEWAL_CONFIGS_DIR)

    @property
    def renewer_config_file(self):  # pylint: disable=missing-docstring
        return os.path.join(
            self.namespace.config_dir, constants.RENEWER_CONFIG_FILENAME)

def check_config_sanity(config):
    """Validate command line options and display error message if
    requirements are not met.

    :param config: IConfig instance holding user configuration
    :type args: :class:`letsencrypt.interfaces.IConfig`

    """
    # Port check
    if config.http01_port == config.tls_sni_01_port:
        raise errors.ConfigurationError(
            "Trying to run http-01 and tls-sni-01 "
            "on the same port ({0})".format(config.tls_sni_01_port))

    # Domain checks
    if config.namespace.domains is not None:
        for domain in config.namespace.domains:
            # This may be redundant, but let's be paranoid
            le_util.enforce_domain_sanity(domain)


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Other Lock Types - EXTENSION</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Thread 4.7.0">
<link rel="up" href="../synchronization.html" title="Synchronization">
<link rel="prev" href="locks.html" title="Lock Types">
<link rel="next" href="lock_functions.html" title="Lock functions">

Home
Libraries
People
FAQ
More

Other Lock Types
      - EXTENSION

Strict
        Locks

Class
          template strict_lock

Class
          template nested_strict_lock

Non
          Member Function make_strict_lock

Non
          Member Function make_nested_strict_lock

Locking
        pointers

Class
          template const_strict_lock_ptr

Class
          template strict_lock_ptr

Externally
        Locked

Template
          Class externally_locked

Template
          Class externally_locked<T&>

swap(externally_locked&,
          externally_locked&)

Class
        template shared_lock_guard

shared_lock_guard(SharedLockable &
          m)

shared_lock_guard(SharedLockable &
          m,boost::adopt_lock_t)

~shared_lock_guard()

Class
        template reverse_lock

reverse_lock(Lock &
          m)

~reverse_lock()

Strict
        Locks

Class
          template strict_lock

Class
          template nested_strict_lock

Non
          Member Function make_strict_lock

Non
          Member Function make_nested_strict_lock

// #include <boost/thread/locks.hpp>
// #include <boost/thread/strict_lock.hpp>

namespace boost
{

  template<typename Lockable>
  class strict_lock;
  template <typename Lock>
  class nested_strict_lock;
  template <typename Lockable>
  struct is_strict_lock_sur_parole<strict_lock<Lockable> >;
  template <typename Lock>
  struct is_strict_lock_sur_parole<nested_strict_lock<Lock> >;

#if ! defined BOOST_THREAD_NO_MAKE_STRICT_LOCK
  template <typename Lockable>
  strict_lock<Lockable> make_strict_lock(Lockable& mtx);
#endif
#if ! defined BOOST_THREAD_NO_MAKE_NESTED_STRICT_LOCK
  template <typename Lock>
  nested_strict_lock<Lock> make_nested_strict_lock(Lock& lk);
#endif

}

Class
          template strict_lock

strict_lock(Lockable &
            m)

~strict_lock()

// #include <boost/thread/locks.hpp>
// #include <boost/thread/strict_lock.hpp>

template<typename BasicLockable>
class strict_lock
{
public:
    typedef BasicLockable mutex_type;
    strict_lock(strict_lock const& m_) = delete;
    strict_lock& operator=(strict_lock const& m_) = delete;
    explicit strict_lock(mutex_type& m_);
    ~strict_lock();

    bool owns_lock(mutex_type const* l) const noexcept;
};

            strict_lock is a model of StrictLock.

            strict_lock is the simplest
            StrictLock: on construction
            it acquires ownership of the implementation of the BasicLockable concept supplied
            as the constructor parameter. On destruction, the ownership is released.
            This provides simple RAII-style locking of a BasicLockable object, to facilitate
            exception-safe locking and unlocking.

            See
            also boost::lock_guard

strict_lock(Lockable &
            m)

Effects:

                    Stores a reference to m.
                    Invokes m.lock().

Throws:

                    Any exception thrown by the call to m.lock().

~strict_lock()

Effects:

                    Invokes m.unlock()
                    on the Lockable object passed
                    to the constructor.

Throws:

                    Nothing.

Class
          template nested_strict_lock

nested_strict_lock(Lock &
            lk)

~nested_strict_lock() noexcept

bool owns_lock(mutex_type
            const*
            l)
            const noexcept

// #include <boost/thread/locks.hpp>
// #include <boost/thread/strict_lock.hpp>

template<typename Lock>
class nested_strict_lock
{
public:
    typedef BasicLockable mutex_type;
    nested_strict_lock(nested_strict_lock const& m_) = delete;
    nested_strict_lock& operator=(nested_strict_lock const& m_) = delete;
    explicit nested_strict_lock(Lock& lk),
    ~nested_strict_lock() noexcept;

    bool owns_lock(mutex_type const* l) const noexcept;
};

            nested_strict_lock is a model
            of StrictLock.

            A nested strict lock is a scoped lock guard ensuring a mutex is locked
            on its scope, by taking ownership of a nesting lock, locking the mutex
            on construction if not already locked and restoring the ownership to
            the nesting lock on destruction.

            See
            also strict_lock, boost::unique_lock

nested_strict_lock(Lock &
            lk)

Requires:

                    lk.mutex()
                    != null_ptr.

Effects:

                    Stores the reference to the lock parameter lk
                    and takes ownership on it. If the lock doesn't owns the mutex
                    lock it.

Postcondition:

                    owns_lock(lk.mutex()).

Throws:

                    - lock_error when BOOST_THREAD_THROW_IF_PRECONDITION_NOT_SATISFIED
                    is defined and lk.mutex() == null_ptr

                    - Any exception that @c lk.lock() can throw.

~nested_strict_lock() noexcept

Effects:

                    Restores ownership to the nesting lock.

bool owns_lock(mutex_type
            const*
            l)
            const noexcept

Return:

                    Whether if this lock is locking that mutex.

Non
          Member Function make_strict_lock

template <typename Lockable>
strict_lock<Lockable> make_strict_lock(Lockable& m); // EXTENSION

Returns:

                  a strict_lock as if initialized with {m}.

Throws:

                  Any exception thrown by the call to m.lock().

Non
          Member Function make_nested_strict_lock

template <typename Lock>
nested_strict_lock<Lock> make_nested_strict_lock(Lock& lk); // EXTENSION

Returns:

                  a nested_strict_lock as if initialized with {lk}.

Throws:

                  Any exception thrown by the call to lk.lock().

Locking
        pointers

Class
          template const_strict_lock_ptr

Class
          template strict_lock_ptr

// #include <boost/thread/synchroniezd_value.hpp>
// #include <boost/thread/strict_lock_ptr.hpp>

namespace boost
{

  template<typename T, typename Lockable = mutex>
  class strict_lock_ptr;
  template<typename T, typename Lockable = mutex>
  class const_strict_lock_ptr;
}

Class
          template const_strict_lock_ptr

const_strict_lock_ptr(T const&,Lockable&)

const_strict_lock_ptr(T const&,Lockable&,adopt_lock_t)

~const_strict_lock_ptr()

operator->()
            const

operator*()
            const

// #include <boost/thread/synchroniezd_value.hpp>
// #include <boost/thread/strict_lock_ptr.hpp>

template <typename T, typename Lockable = mutex>
class const_strict_lock_ptr
{
public:
  typedef T value_type;
  typedef Lockable mutex_type;

  const_strict_lock_ptr(const_strict_lock_ptr const& m_) = delete;
  const_strict_lock_ptr& operator=(const_strict_lock_ptr const& m_) = delete;

  const_strict_lock_ptr(T const& val, Lockable & mtx);
  const_strict_lock_ptr(T const& val, Lockable & mtx, adopt_lock_t tag);

  ~const_strict_lock_ptr();

  const T* operator->() const;
  const T& operator*() const;

};

const_strict_lock_ptr(T const&,Lockable&)

const_strict_lock_ptr(T const& val, Lockable & m);

Effects:

                    Invokes m.lock(),
                    stores a reference to it and to the value type val.

Throws:

                    Any exception thrown by the call to m.lock().

const_strict_lock_ptr(T const&,Lockable&,adopt_lock_t)

const_strict_lock_ptr(T const& val, Lockable & m, adopt_lock_t tag);

Effects:

                    Stores a reference to it and to the value type val.

Throws:

                    Nothing.

~const_strict_lock_ptr()

~const_strict_lock_ptr();

Effects:

                    Invokes m.unlock()
                    on the Lockable object passed
                    to the constructor.

Throws:

                    Nothing.

operator->()
            const

const T* operator->() const;

Return:

                    return a constant pointer to the protected value.

Throws:

                    Nothing.

operator*()
            const

const T& operator*() const;

Return:

                    return a constant reference to the protected value.

Throws:

                    Nothing.

Class
          template strict_lock_ptr

strict_lock_ptr(T const&,Lockable&)

strict_lock_ptr(T const&,Lockable&,adopt_lock_t)

~strict_lock_ptr()

operator->()

operator*()

// #include <boost/thread/synchroniezd_value.hpp>
// #include <boost/thread/strict_lock_ptr.hpp>

template <typename T, typename Lockable = mutex>
class strict_lock_ptr : public const_strict_lock_ptr<T,Lockable>
{
public:
  strict_lock_ptr(strict_lock_ptr const& m_) = delete;
  strict_lock_ptr& operator=(strict_lock_ptr const& m_) = delete;

  strict_lock_ptr(T & val, Lockable & mtx);
  strict_lock_ptr(T & val, Lockable & mtx, adopt_lock_t tag);
  ~strict_lock_ptr();

  T* operator->();
  T& operator*();

};

strict_lock_ptr(T const&,Lockable&)

strict_lock_ptr(T const& val, Lockable & m);

Effects:

                    Invokes m.lock(),
                    stores a reference to it and to the value type val.

Throws:

                    Any exception thrown by the call to m.lock().

strict_lock_ptr(T const&,Lockable&,adopt_lock_t)

strict_lock_ptr(T const& val, Lockable & m, adopt_lock_t tag);

Effects:

                    Stores a reference to it and to the value type val.

Throws:

                    Nothing.

~strict_lock_ptr()

~ strict_lock_ptr();

Effects:

                    Invokes m.unlock()
                    on the Lockable object passed
                    to the constructor.

Throws:

                    Nothing.

operator->()

T* operator->();

Return:

                    return a pointer to the protected value.

Throws:

                    Nothing.

operator*()

T& operator*();

Return:

                    return a reference to the protected value.

Throws:

                    Nothing.

Externally
        Locked

Template
          Class externally_locked

Template
          Class externally_locked<T&>

swap(externally_locked&,
          externally_locked&)

// #include <boost/thread/externally_locked.hpp>
template <class T, typename MutexType = boost::mutex>
class externally_locked;
template <class T, typename MutexType>
class externally_locked<T&, MutexType>;

template <typename T, typename MutexType>
void swap(externally_locked<T, MutexType> & lhs, externally_locked<T, MutexType> & rhs);

Template
          Class externally_locked

externally_locked(mutex_type&,
            const T&)

externally_locked(mutex_type&,
            T&&)

externally_locked(mutex_type&)

externally_locked(externally_locked&&)

externally_locked(externally_locked&)

externally_locked(externally_locked&&)

externally_locked(externally_locked&)

get(strict_lock<mutex_type>&)

get(nested_strict_lock<Lock>&)

get(Lock&)

// #include <boost/thread/externally_locked.hpp>

template <class T, typename MutexType>
class externally_locked
{
  //BOOST_CONCEPT_ASSERT(( CopyConstructible<T> ));
  BOOST_CONCEPT_ASSERT(( BasicLockable<MutexType> ));

public:
  typedef MutexType mutex_type;

  externally_locked(mutex_type& mtx, const T& obj);
  externally_locked(mutex_type& mtx,T&& obj);
  explicit externally_locked(mutex_type& mtx);
  externally_locked(externally_locked const& rhs);
  externally_locked(externally_locked&& rhs);
  externally_locked& operator=(externally_locked const& rhs);
  externally_locked& operator=(externally_locked&& rhs);

  // observers
  T& get(strict_lock<mutex_type>& lk);
  const T& get(strict_lock<mutex_type>& lk) const;

  template <class Lock>
  T& get(nested_strict_lock<Lock>& lk);
  template <class Lock>
  const T& get(nested_strict_lock<Lock>& lk) const;

  template <class Lock>
  T& get(Lock& lk);
  template <class Lock>
  T const& get(Lock& lk) const;

 mutex_type* mutex() const noexcept;

  // modifiers
  void lock();
  void unlock();
  bool try_lock();
  void swap(externally_locked&);
};

            externally_locked is
            a model of Lockable, it cloaks an object
            of type T, and actually
            provides full access to that object through the get and set member functions,
            provided you pass a reference to a strict lock object.

            Only the specificities respect to Lockable are described here.

externally_locked(mutex_type&,
            const T&)

externally_locked(mutex_type& mtx, const T& obj);

Requires:

                    T is a model of CopyConstructible.

Effects:

                    Constructs an externally locked object copying the cloaked type.

Throws:

                    Any exception thrown by the call to T(obj).

externally_locked(mutex_type&,
            T&&)

externally_locked(mutex_type& mtx,T&& obj);

Requires:

                    T is a model of Movable.

Effects:

                    Constructs an externally locked object by moving the cloaked
                    type.

Throws:

                    Any exception thrown by the call to T(obj).

externally_locked(mutex_type&)

externally_locked(mutex_type& mtx);

Requires:

                    T is a model of DefaultConstructible.

Effects:

                    Constructs an externally locked object by default constructing
                    the cloaked type.

Throws:

                    Any exception thrown by the call to T().

externally_locked(externally_locked&&)

externally_locked(externally_locked&& rhs);

Requires:

                    T is a model of Movable.

Effects:

                    Move constructs an externally locked object by moving the cloaked
                    type and copying the mutex reference

Throws:

                    Any exception thrown by the call to T(T&&).

externally_locked(externally_locked&)

externally_locked(externally_locked& rhs);

Requires:

                    T is a model of Copyable.

Effects:

                    Copy constructs an externally locked object by copying the cloaked
                    type and copying the mutex reference

Throws:

                    Any exception thrown by the call to T(T&).

externally_locked(externally_locked&&)

externally_locked& operator=(externally_locked&& rhs);

Requires:

                    T is a model of Movable.

Effects:

                    Move assigns an externally locked object by moving the cloaked
                    type and copying the mutex reference

Throws:

                    Any exception thrown by the call to T::operator=(T&&).

externally_locked(externally_locked&)

externally_locked& operator=(externally_locked const& rhs);

Requires:

                    T is a model of Copyable.

Effects:

                    Copy assigns an externally locked object by copying the cloaked
                    type and copying the mutex reference

Throws:

                    Any exception thrown by the call to T::operator=(T&).

get(strict_lock<mutex_type>&)

T& get(strict_lock<mutex_type>& lk);
const T& get(strict_lock<mutex_type>& lk) const;

Requires:

                    The lk parameter
                    must be locking the associated mutex.

Returns:

                    A reference to the cloaked object

Throws:

                    lock_error if
                    BOOST_THREAD_THROW_IF_PRECONDITION_NOT_SATISFIED
                    is defined and the run-time preconditions are not satisfied .

get(nested_strict_lock<Lock>&)

template <class Lock>
T& get(nested_strict_lock<Lock>& lk);
template <class Lock>
const T& get(nested_strict_lock<Lock>& lk) const;

Requires:

                    is_same<mutex_type,
                    typename Lock::mutex_type> and the lk
                    parameter must be locking the associated mutex.

Returns:

                    A reference to the cloaked object

Throws:

                    lock_error if
                    BOOST_THREAD_THROW_IF_PRECONDITION_NOT_SATISFIED
                    is defined and the run-time preconditions are not satisfied .

get(Lock&)

template <class Lock>
T& get(Lock& lk);
template <class Lock>
T const& get(Lock& lk) const;

Requires:

                    Lock is a model
                    of StrictLock, is_same<mutex_type,
                    typename Lock::mutex_type> and the lk
                    parameter must be locking the associated mutex.

Returns:

                    A reference to the cloaked object

Throws:

                    lock_error if
                    BOOST_THREAD_THROW_IF_PRECONDITION_NOT_SATISFIED
                    is defined and the run-time preconditions are not satisfied .

Template
          Class externally_locked<T&>

externally_locked<T&>(mutex_type&,
            T&)

externally_locked<T&>(externally_locked&&)

externally_locked(externally_locked&&)

externally_locked(externally_locked&)

get(strict_lock<mutex_type>&)

get(nested_strict_lock<Lock>&)

get(Lock&)

// #include <boost/thread/externally_locked.hpp>

template <class T, typename MutexType>
class externally_locked<T&, MutexType>
{
  //BOOST_CONCEPT_ASSERT(( CopyConstructible<T> ));
  BOOST_CONCEPT_ASSERT(( BasicLockable<MutexType> ));

public:
  typedef MutexType mutex_type;

  externally_locked(mutex_type& mtx, T& obj);
  explicit externally_locked(mutex_type& mtx);
  externally_locked(externally_locked const& rhs) noexcept;
  externally_locked(externally_locked&& rhs) noexcept;
  externally_locked& operator=(externally_locked const& rhs) noexcept;
  externally_locked& operator=(externally_locked&& rhs) noexcept;

  // observers
  T& get(strict_lock<mutex_type>& lk);
  const T& get(strict_lock<mutex_type>& lk) const;

  template <class Lock>
  T& get(nested_strict_lock<Lock>& lk);
  template <class Lock>
  const T& get(nested_strict_lock<Lock>& lk) const;

  template <class Lock>
  T& get(Lock& lk);
  template <class Lock>
  T const& get(Lock& lk) const;

 mutex_type* mutex() const noexcept;

  // modifiers
  void lock();
  void unlock();
  bool try_lock();
  void swap(externally_locked&) noexcept;
};

            externally_locked is
            a model of Lockable, it cloaks an object
            of type T, and actually
            provides full access to that object through the get and set member functions,
            provided you pass a reference to a strict lock object.

            Only the specificities respect to Lockable are described here.

externally_locked<T&>(mutex_type&,
            T&)

externally_locked<T&>(mutex_type& mtx, T& obj) noexcept;

Effects:

                    Constructs an externally locked object copying the cloaked reference.

externally_locked<T&>(externally_locked&&)

externally_locked(externally_locked&& rhs) noexcept;

Effects:

                    Moves an externally locked object by moving the cloaked type
                    and copying the mutex reference

externally_locked(externally_locked&&)

externally_locked& operator=(externally_locked&& rhs);

Effects:

                    Move assigns an externally locked object by copying the cloaked
                    reference and copying the mutex reference

externally_locked(externally_locked&)

externally_locked& operator=(externally_locked const& rhs);

Requires:

                    T is a model of Copyable.

Effects:

                    Copy assigns an externally locked object by copying the cloaked
                    reference and copying the mutex reference

Throws:

                    Any exception thrown by the call to T::operator=(T&).

get(strict_lock<mutex_type>&)

T& get(strict_lock<mutex_type>& lk);
const T& get(strict_lock<mutex_type>& lk) const;

Requires:

                    The lk parameter
                    must be locking the associated mutex.

Returns:

                    A reference to the cloaked object

Throws:

                    lock_error if
                    BOOST_THREAD_THROW_IF_PRECONDITION_NOT_SATISFIED
                    is defined and the run-time preconditions are not satisfied .

get(nested_strict_lock<Lock>&)

template <class Lock>
T& get(nested_strict_lock<Lock>& lk);
template <class Lock>
const T& get(nested_strict_lock<Lock>& lk) const;

Requires:

                    is_same<mutex_type,
                    typename Lock::mutex_type> and the lk
                    parameter must be locking the associated mutex.

Returns:

                    A reference to the cloaked object

Throws:

                    lock_error if
                    BOOST_THREAD_THROW_IF_PRECONDITION_NOT_SATISFIED
                    is defined and the run-time preconditions are not satisfied .

get(Lock&)

template <class Lock>
T& get(Lock& lk);
template <class Lock>
T const& get(Lock& lk) const;

Requires:

                    Lock is a model
                    of StrictLock, is_same<mutex_type,
                    typename Lock::mutex_type> and the lk
                    parameter must be locking the associated mutex.

Returns:

                    A reference to the cloaked object

Throws:

                    lock_error if
                    BOOST_THREAD_THROW_IF_PRECONDITION_NOT_SATISFIED
                    is defined and the run-time preconditions are not satisfied .

swap(externally_locked&,
          externally_locked&)

template <typename T, typename MutexType>
void swap(externally_locked<T, MutexType> & lhs, externally_locked<T, MutexType> & rhs)

Class
        template shared_lock_guard

shared_lock_guard(SharedLockable &
          m)

shared_lock_guard(SharedLockable &
          m,boost::adopt_lock_t)

~shared_lock_guard()

// #include <boost/thread/shared_lock_guard.hpp>
namespace boost
{
  template<typename SharedLockable>
  class shared_lock_guard
  {
  public:
      shared_lock_guard(shared_lock_guard const&) = delete;
      shared_lock_guard& operator=(shared_lock_guard const&) = delete;

      explicit shared_lock_guard(SharedLockable& m_);
      shared_lock_guard(SharedLockable& m_,boost::adopt_lock_t);

      ~shared_lock_guard();
  };
}

          shared_lock_guard is very simple:
          on construction it acquires shared ownership of the implementation of the
          SharedLockable concept supplied
          as the constructor parameter. On destruction, the ownership is released.
          This provides simple RAII-style locking of a SharedLockable object, to facilitate
          exception-safe shared locking and unlocking. In addition, the shared_lock_guard(SharedLockable &m, boost::adopt_lock_t) constructor allows the shared_lock_guard object to take
          shared ownership of a lock already held by the current thread.

shared_lock_guard(SharedLockable &
          m)

Effects:

                  Stores a reference to m.
                  Invokes m.lock_shared()().

Throws:

                  Any exception thrown by the call to m.lock_shared()().

shared_lock_guard(SharedLockable &
          m,boost::adopt_lock_t)

Precondition:

                  The current thread owns a lock on m
                  equivalent to one obtained by a call to m.lock_shared()().

Effects:

                  Stores a reference to m.
                  Takes ownership of the lock state of m.

Throws:

                  Nothing.

~shared_lock_guard()

Effects:

                  Invokes m.unlock_shared()() on the SharedLockable object
                  passed to the constructor.

Throws:

                  Nothing.

Class
        template reverse_lock

reverse_lock(Lock &
          m)

~reverse_lock()

// #include <boost/thread/reverse_lock.hpp>
namespace boost
{

  template<typename Lock>
  class reverse_lock
  {
  public:
      reverse_lock(reverse_lock const&) = delete;
      reverse_lock& operator=(reverse_lock const&) = delete;

      explicit reverse_lock(Lock& m_);
      ~reverse_lock();
  };
}

          reverse_lock reverse the operations
          of a lock: it provide for RAII-style, that unlocks the lock at construction
          time and lock it at destruction time. In addition, it transfer ownership
          temporarily, so that the mutex can not be locked using the Lock.

          An instance of reverse_lock doesn't own
          the lock never.

reverse_lock(Lock &
          m)

Effects:

                  Stores a reference to m.
                  Invokes m.unlock()
                  if m owns his lock
                  and then stores the mutex by calling m.release().

Postcondition:

                  !m. owns_lock()() &&
                  m.mutex()==0.

Throws:

                  Any exception thrown by the call to m.unlock().

~reverse_lock()

Effects:

                  Let be mtx the stored mutex*. If not 0 Invokes mtx->lock()
                  and gives again the mtx
                  to the Lock using
                  the adopt_lock_t
                  overload.

Throws:

                  Any exception thrown by mtx->lock().

Remarks:

                  Note that if mtx->lock()
                  throws an exception while unwinding the program will terminate,
                  so don't use reverse_lock if an exception can be thrown.

Copyright © 2007 -11 Anthony Williams
Copyright © 2011 -15 Vicente J. Botet Escriba

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package com.navercorp.pinpoint.plugin.redisson;

/**
 * @author jaehong.kim
 */
public class CommandContext {
    private long beginTime;
    private long endTime;
    private boolean fail;

    public long getBeginTime() {
        return beginTime;
    }

    public void setBeginTime(long beginTime) {
        this.beginTime = beginTime;
    }

    public long getEndTime() {
        return endTime;
    }

    public void setEndTime(long endTime) {
        this.endTime = endTime;
    }

    public boolean isFail() {
        return fail;
    }

    public void setFail(boolean fail) {
        this.fail = fail;
    }

    public long getElapsedTime() {
        long result = endTime - beginTime;
        return result > 0 ? result : 0;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("{beginTime=");
        builder.append(beginTime);
        builder.append(", endTime=");
        builder.append(endTime);
        builder.append(", fail=");
        builder.append(fail);
        builder.append(", elapsed=");
        builder.append(getElapsedTime());
        builder.append("}");
        return builder.toString();
    }
}


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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>org.eveo</groupId>
    <artifactId>mt-election-model</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>nexus</id>
            <name>project</name>
            <url>http://188.226.147.218:8081/repository/maven-releases</url>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
            </snapshots>
        </repository>
        <repository>
            <id>nexus-snapshots</id>
            <name>project</name>
            <url>http://188.226.147.218:8081/repository/maven-snapshots</url>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
            </snapshots>
        </repository>
    </repositories>
</project>


text:
#include "tensorflow/core/profiler/utils/tf_op_utils.h"

#include "tensorflow/core/platform/test.h"

namespace tensorflow {
namespace profiler {
namespace {

TEST(TfOpUtilsTest, TfOpTest) {
  const absl::string_view kName = "OpName:OpType";
  TfOp tf_op = ParseTfOpFullname(kName);
  EXPECT_EQ(tf_op.name, "OpName");
  EXPECT_EQ(tf_op.type, "OpType");
  EXPECT_EQ(TfOpEventName(kName), "OpType");  // type only
}

TEST(TfOpUtilsTest, InternalTfOpTest) {
  const absl::string_view kName = "OpName:_InternalOpType";
  TfOp tf_op = ParseTfOpFullname(kName);
  EXPECT_EQ(tf_op.name, "OpName");
  EXPECT_EQ(tf_op.type, "_InternalOpType");
  EXPECT_EQ(TfOpEventName(kName), "_InternalOpType");  // type only
}

TEST(TfOpUtilsTest, TfOpWithPathTest) {
  const absl::string_view kName = "path/to/name:OpType";
  TfOp tf_op = ParseTfOpFullname(kName);
  EXPECT_EQ(tf_op.name, "path/to/name");
  EXPECT_EQ(tf_op.type, "OpType");
  EXPECT_EQ(TfOpEventName(kName), "OpType");  // type only
}

TEST(TfOpUtilsTest, ShortDatasetOpTest) {
  const absl::string_view kName = "Iterator::Batch";
  TfOp tf_op = ParseTfOpFullname(kName);
  EXPECT_EQ(tf_op.name, kName);
  EXPECT_TRUE(IsDatasetOp(tf_op.type));
  EXPECT_EQ(TfOpEventName(kName), kName);
}

TEST(TfOpUtilsTest, LongDatasetOpTest) {
  const absl::string_view kName = "Iterator::Batch::Map::TfRecord";
  TfOp tf_op = ParseTfOpFullname(kName);
  EXPECT_EQ(tf_op.name, kName);
  EXPECT_TRUE(IsDatasetOp(tf_op.type));
  EXPECT_EQ(TfOpEventName(kName), "Iterator::TfRecord");  // shorter name
}

TEST(TfOpUtilsTest, TraceMeTest) {
  const absl::string_view kName = "MyTraceMe";
  TfOp tf_op = ParseTfOpFullname(kName);
  EXPECT_EQ(tf_op.name, kName);
  EXPECT_TRUE(IsUnknownOp(tf_op.type));
  EXPECT_EQ(TfOpEventName(kName), kName);
}

TEST(TfOpUtilsTest, TraceMeWithColonTest) {
  // "12345" is not a valid op type.
  const absl::string_view kName = "RunStep/Server:54635";
  TfOp tf_op = ParseTfOpFullname(kName);
  EXPECT_EQ(tf_op.name, kName);
  EXPECT_TRUE(IsUnknownOp(tf_op.type));
  EXPECT_EQ(TfOpEventName(kName), kName);
}

TEST(TfOpUtilsTest, TraceMeWithDoubleColonTest) {
  const absl::string_view kName = "XLA::StartProgram";
  TfOp tf_op = ParseTfOpFullname(kName);
  EXPECT_EQ(tf_op.name, kName);
  EXPECT_TRUE(IsUnknownOp(tf_op.type));
  EXPECT_EQ(TfOpEventName(kName), kName);
}

TEST(TfOpUtilsTest, TraceMeWithTrailingWhitespaceTest) {
  const absl::string_view kName = "SessionRun ";
  const absl::string_view kNameTrimmed = "SessionRun";
  TfOp tf_op = ParseTfOpFullname(kName);
  EXPECT_EQ(tf_op.name, kName);
  EXPECT_TRUE(IsUnknownOp(tf_op.type));
  EXPECT_EQ(TfOpEventName(kName), kNameTrimmed);
}

}  // namespace
}  // namespace profiler
}  // namespace tensorflow