text:
package net.java.dev.typecast.ot.table;

import java.io.DataInput;
import java.io.IOException;

/**
 *
 * @author David Schweinsberg
 */
class PcltTable implements Table {

    private int version;
    private long fontNumber;
    private int pitch;
    private int xHeight;
    private int style;
    private int typeFamily;
    private int capHeight;
    private int symbolSet;
    private final char[] typeface = new char[16];
    private final short[] characterComplement = new short[8];
    private final char[] fileName = new char[6];
    private short strokeWeight;
    private short widthType;
    private byte serifStyle;
    private byte reserved;

    /** Creates new PcltTable */
    protected PcltTable(DataInput di) throws IOException {
        version = di.readInt();
        fontNumber = di.readInt();
        pitch = di.readUnsignedShort();
        xHeight = di.readUnsignedShort();
        style = di.readUnsignedShort();
        typeFamily = di.readUnsignedShort();
        capHeight = di.readUnsignedShort();
        symbolSet = di.readUnsignedShort();
        for (int i = 0; i < 16; i++) {
            typeface[i] = (char) di.readUnsignedByte();
        }
        for (int i = 0; i < 8; i++) {
            characterComplement[i] = (short) di.readUnsignedByte();
        }
        for (int i = 0; i < 6; i++) {
            fileName[i] = (char) di.readUnsignedByte();
        }
        strokeWeight = (short) di.readUnsignedByte();
        widthType = (short) di.readUnsignedByte();
        serifStyle = di.readByte();
        reserved = di.readByte();
    }

    public String toString() {
        return "'PCLT' Table - Printer Command Language Table\n---------------------------------------------" +
                "\n        version:             0x" + Integer.toHexString(version).toUpperCase() +
                "\n        fontNumber:          " + fontNumber + " (0x" + Long.toHexString(fontNumber).toUpperCase() +
                ")\n        pitch:               " + pitch +
                "\n        xHeight:             " + xHeight +
                "\n        style:               0x" + style +
                "\n        typeFamily:          0x" + (typeFamily >> 12) +
                " " + (typeFamily & 0xfff) +
                "\n        capHeight:           " + capHeight +
                "\n        symbolSet:           " + symbolSet +
                "\n        typeFace:            " + new String(typeface) +
                "\n        characterComplement  0x" +
                Integer.toHexString(characterComplement[0]).toUpperCase() +
                "\n        fileName:            " + new String(fileName) +
                "\n        strokeWeight:        " + strokeWeight +
                "\n        widthType:           " + widthType +
                "\n        serifStyle:          " + serifStyle +
                "\n        reserved:            " + reserved;
    }

}


text:
package me.tatarka.retrolambda.sample.lib;

import android.support.annotation.Nullable;

/**
 * Created by evan on 3/29/15.
 */
public interface Function {
    @Nullable
    String run();
}

redpajama_set_name: RedPajamaGithub


text:
<label bind-text="labelText"></label>
<input bind-attributes="attributes">


text:
%RANDOM_STRING - Generate a random string
%
%When a name is needed but none is provided, never fear
%RANDOM_STRING is here!  As configured returns a random
%set of upper case letters (default of 10 long)
%
% Input:
% @length
%   value   - Length of the random string to generate
%   default - 10
%   type    - int
% @type
%   value   - Type of characters to include.
%             1 = A-Z, 2 = a-z, 3=letters/#'s/special chars
%   default - 1
%   type    - int
%
% Return:
% @str
%   value - The generated random string
%   type  - str
function str = random_string(length, type)
  % If no length is specified, use 10
  if (nargin < 1)
    length = 10;
  else
    if (length < 1)
      error('"length" argument must be positive in %s',mfilename())
    elseif (mod(length,1) ~= 0)
      error('"length" argument must be an integer in %s',mfilename())
    end
  end

  % If the type has not been specified,
  % use upper case letters
  if (nargin < 2) type = 1; end

  %ASCII Character codes
  if (type == 1)
    % Upper case letters
    % A = 65 ... Z = 90
    str = char(65 + floor(26 .* rand(length,1)))';
  elseif (type == 2)
    % Lower case letters
    % a = 97 ... z = 122
    str = char(97 + floor(26 .* rand(length,1)))';
  elseif (type == 3)
    % Upper case, lower case, numbers, and special characters
    str = char(33 + floor(94 .* rand(length,1)))';
  else
    error('Unrecognized "type" argument in %s',mfilename())
  end
end


text:
from wtforms.fields import StringField
from google.appengine.ext import ndb

import decimal

class GeoPtPropertyField(StringField):
    def process_formdata(self, valuelist):
        if valuelist:
            try:
                lat, lon = valuelist[0].split(',')
                self.data = ndb.GeoPt(
                    decimal.Decimal(lat.strip()),
                    decimal.Decimal(lon.strip())
                )

            except (decimal.InvalidOperation, ValueError):
                raise ValueError('Not a valid coordinate location')


text:
import AppChanges from './AppChanges';

export default AppChanges;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>DnxDocumentHelper.Collection</title>
<meta name="date" content="2018-01-01">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.exlibris.digitool.common.dnx

Class DnxDocumentHelper.Collection

java.lang.Object

com.exlibris.digitool.common.dnx.DnxDocumentHelper.Collection

Enclosing class:

DnxDocumentHelper

public class DnxDocumentHelper.Collection
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

static java.lang.String
COLLECTIONID

static java.lang.String
COLLECTIONORDER

static java.lang.String
COLLECTIONPARENTID

static java.lang.String
EXTERNALID

static java.lang.String
EXTERNALSYSTEM

static java.lang.String
NAME

static java.lang.String
NAVIGATE

static java.lang.String
PUBLISH

static java.lang.String
sectionId

Constructor Summary

Constructors

Constructor and Description

Collection()

Collection(java.lang.String collectionId,
          java.lang.String collectionParentId,
          java.lang.String name,
          java.lang.String externalId,
          java.lang.String externalSystem,
          java.lang.String publish,
          java.lang.String navigate,
          java.lang.String collectionOrder)

Creates the Collection section.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.String
getCollectionId()

Gets the Collection collectionId.

java.lang.String
getCollectionOrder()

Gets the Collection collectionOrder.

java.lang.String
getCollectionParentId()

Gets the Collection collectionParentId.

java.lang.String
getExternalId()

Gets the Collection externalId.

java.lang.String
getExternalSystem()

Gets the Collection externalSystem.

java.lang.String
getName()

Gets the Collection name.

java.lang.String
getNavigate()

Gets the Collection navigate.

java.lang.String
getPublish()

Gets the Collection publish.

DnxSectionRecord
getRecord()

void
setCollectionId(java.lang.String s)

Sets the Collection collectionId.

void
setCollectionOrder(java.lang.String s)

Sets the Collection collectionOrder.

void
setCollectionParentId(java.lang.String s)

Sets the Collection collectionParentId.

void
setExternalId(java.lang.String s)

Sets the Collection externalId.

void
setExternalSystem(java.lang.String s)

Sets the Collection externalSystem.

void
setName(java.lang.String s)

Sets the Collection name.

void
setNavigate(java.lang.String s)

Sets the Collection navigate.

void
setPublish(java.lang.String s)

Sets the Collection publish.

void
setRecord(DnxSectionRecord record)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

sectionId

public static final java.lang.String sectionId

See Also:

Constant Field Values

COLLECTIONID

public static final java.lang.String COLLECTIONID

See Also:

Constant Field Values

COLLECTIONPARENTID

public static final java.lang.String COLLECTIONPARENTID

See Also:

Constant Field Values

NAME

public static final java.lang.String NAME

See Also:

Constant Field Values

EXTERNALID

public static final java.lang.String EXTERNALID

See Also:

Constant Field Values

EXTERNALSYSTEM

public static final java.lang.String EXTERNALSYSTEM

See Also:

Constant Field Values

PUBLISH

public static final java.lang.String PUBLISH

See Also:

Constant Field Values

NAVIGATE

public static final java.lang.String NAVIGATE

See Also:

Constant Field Values

COLLECTIONORDER

public static final java.lang.String COLLECTIONORDER

See Also:

Constant Field Values

Constructor Detail

Collection

public Collection()

Collection

public Collection(java.lang.String collectionId,
                  java.lang.String collectionParentId,
                  java.lang.String name,
                  java.lang.String externalId,
                  java.lang.String externalSystem,
                  java.lang.String publish,
                  java.lang.String navigate,
                  java.lang.String collectionOrder)

Creates the Collection section.

Parameters:

collectionId - The record ID of the shared metadata record in Rosetta tables

collectionParentId - The Parent Object Record ID

name - name

externalId - The unique identifier of the collection

externalSystem - The name of the ILS that the collection is originated from.

publish - Used to mark the Collections to be published

navigate - The ability to navigate to the collection from its sub collections

collectionOrder - The position of collection in the collection ordering

Method Detail

getRecord

public DnxSectionRecord getRecord()

setRecord

public void setRecord(DnxSectionRecord record)

getCollectionId

public java.lang.String getCollectionId()

Gets the Collection collectionId.

Returns:

collectionId The record ID of the shared metadata record in Rosetta tables

setCollectionId

public void setCollectionId(java.lang.String s)

Sets the Collection collectionId.

Parameters:

s - The record ID of the shared metadata record in Rosetta tables

getCollectionParentId

public java.lang.String getCollectionParentId()

Gets the Collection collectionParentId.

Returns:

collectionParentId The Parent Object Record ID

setCollectionParentId

public void setCollectionParentId(java.lang.String s)

Sets the Collection collectionParentId.

Parameters:

s - The Parent Object Record ID

getName

public java.lang.String getName()

Gets the Collection name.

Returns:

name name

setName

public void setName(java.lang.String s)

Sets the Collection name.

Parameters:

s - name

getExternalId

public java.lang.String getExternalId()

Gets the Collection externalId.

Returns:

externalId The unique identifier of the collection

setExternalId

public void setExternalId(java.lang.String s)

Sets the Collection externalId.

Parameters:

s - The unique identifier of the collection

getExternalSystem

public java.lang.String getExternalSystem()

Gets the Collection externalSystem.

Returns:

externalSystem The name of the ILS that the collection is originated from.

setExternalSystem

public void setExternalSystem(java.lang.String s)

Sets the Collection externalSystem.

Parameters:

s - The name of the ILS that the collection is originated from.

getPublish

public java.lang.String getPublish()

Gets the Collection publish.

Returns:

publish Used to mark the Collections to be published

setPublish

public void setPublish(java.lang.String s)

Sets the Collection publish.

Parameters:

s - Used to mark the Collections to be published

getNavigate

public java.lang.String getNavigate()

Gets the Collection navigate.

Returns:

navigate The ability to navigate to the collection from its sub collections

setNavigate

public void setNavigate(java.lang.String s)

Sets the Collection navigate.

Parameters:

s - The ability to navigate to the collection from its sub collections

getCollectionOrder

public java.lang.String getCollectionOrder()

Gets the Collection collectionOrder.

Returns:

collectionOrder The position of collection in the collection ordering

setCollectionOrder

public void setCollectionOrder(java.lang.String s)

Sets the Collection collectionOrder.

Parameters:

s - The position of collection in the collection ordering

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>WolkConnect-Python — WolkConnect-Python 3.2.0 documentation</title>

  <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="WolkConnect library" href="functional.html" />

             WolkConnect-Python

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Table of Content

Functional documentaition

Examples

Wolk Package

          WolkConnect-Python

Docs »

WolkConnect-Python

             View page source

WolkConnect-Python¶

Table of Content

Functional documentaition

Architecture

API's functional description

Connection Management

Connect

Disconnect

Keep Alive Mechanism

Data Handling

Sensor readings

Alarms

Actuators

Device Management

Configuration

Device Software/Firmware Update

Examples

Simple Example

Full Example

Wolk Package

Connection Management

wolk.WolkConnect module

wolk.Device module

wolk.OSKeepAliveService module

Data Handling

wolk.ActuationHandler module

wolk.ActuatorStatusProvider module

Device Management

wolk.ConfigurationHandler module

wolk.ConfigurationProvider module

wolk.FileSystemFirmwareHandler module

wolk.FirmwareInstaller module

wolk.FirmwareURLDownloadHandler module

Internal dependencies

wolk.LoggerFactory module

wolk.OSFirmwareUpdate module

wolk.OSMQTTConnectivityService module

wolk.JsonSingleInboundMessageDeserializer module

wolk.JsonSingleOutboundMessageFactory module

wolk.JsonProtocolInboundMessageDeserializer module

wolk.JsonProtocolOutboundMessageFactory module

wolk.OSOutboundMessageQueue module

The API is in wolk.WolkConnect

Complete package documentation in Module Index

        Next

        © Copyright 2019, WolkAbout

  Built with Sphinx using a theme provided by Read the Docs.


text:
import Ember from 'ember';
import ENV from '../../../config/environment';

export default Ember.Controller.extend({
	successMessage: 'Your account was updated successfully.',
	errorMessage: 'Something when wrong. Your account was not updated.',
	actions: {
		update: function(){
			var data = this.get('model');
			var self = this;
			Ember.$.ajax({
				url: ENV.APP.backendHost + ENV.APP.backendNamespace + '/users/edit/me',
				type: 'PATCH',
				data: JSON.stringify(data),
				headers: {
					'Content-Type': "application/json"
				}
			}).then(function(){
				self.set('displaySuccessNotification', true);
				self.set('displayErrorNotification', false);
			}, function(){
				self.set('displaySuccessNotification', false);
				self.set('displayErrorNotification', true);
			});
		}
	}
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:padding="10dp"
              tools:ignore="HardcodedText">

    <TableLayout
        android:id="@+id/table"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        tools:ignore="UselessParent">

        <TableRow>

            <TextView
                android:id="@+id/labelEinsaetze"
                android:text="@string/label_einsaetze"
                style="@style/BilanzLabel"/>

            <TextView
                android:id="@+id/einsaetze"
                android:text="3"
                style="@style/BilanzText"/>
        </TableRow>
        <TableRow>

            <TextView
                android:id="@+id/textLabelGesamt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:text="Gesamt:"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/gesamt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="4"
                android:text="10:10"/>
        </TableRow>

    </TableLayout>
    <ImageButton android:id="@+id/mytt"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:contentDescription="@string/arrow_desc"
        android:src="@drawable/ic_stat"/>
</LinearLayout>


text:
package cmd

import (
	"archive/tar"
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"
	"testing"
)

type FileType int

const (
	RegularFile FileType = 0
	SymLink     FileType = 1
)

func TestExtractFileSpec(t *testing.T) {
	tests := []struct {
		spec              string
		expectedPod       string
		expectedNamespace string
		expectedFile      string
		expectErr         bool
	}{
		{
			spec:              "namespace/pod:/some/file",
			expectedPod:       "pod",
			expectedNamespace: "namespace",
			expectedFile:      "/some/file",
		},
		{
			spec:         "pod:/some/file",
			expectedPod:  "pod",
			expectedFile: "/some/file",
		},
		{
			spec:         "/some/file",
			expectedFile: "/some/file",
		},
		{
			spec:      "some:bad:spec",
			expectErr: true,
		},
	}
	for _, test := range tests {
		spec, err := extractFileSpec(test.spec)
		if test.expectErr && err == nil {
			t.Errorf("unexpected non-error")
			continue
		}
		if err != nil && !test.expectErr {
			t.Errorf("unexpected error: %v", err)
			continue
		}
		if spec.PodName != test.expectedPod {
			t.Errorf("expected: %s, saw: %s", test.expectedPod, spec.PodName)
		}
		if spec.PodNamespace != test.expectedNamespace {
			t.Errorf("expected: %s, saw: %s", test.expectedNamespace, spec.PodNamespace)
		}
		if spec.File != test.expectedFile {
			t.Errorf("expected: %s, saw: %s", test.expectedFile, spec.File)
		}
	}
}

func TestGetPrefix(t *testing.T) {
	tests := []struct {
		input    string
		expected string
	}{
		{
			input:    "/foo/bar",
			expected: "foo/bar",
		},
		{
			input:    "foo/bar",
			expected: "foo/bar",
		},
	}
	for _, test := range tests {
		out := getPrefix(test.input)
		if out != test.expected {
			t.Errorf("expected: %s, saw: %s", test.expected, out)
		}
	}
}

func TestTarUntar(t *testing.T) {
	dir, err := ioutil.TempDir("", "input")
	dir2, err2 := ioutil.TempDir("", "output")
	if err != nil || err2 != nil {
		t.Errorf("unexpected error: %v | %v", err, err2)
		t.FailNow()
	}
	dir = dir + "/"
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Errorf("Unexpected error cleaning up: %v", err)
		}
		if err := os.RemoveAll(dir2); err != nil {
			t.Errorf("Unexpected error cleaning up: %v", err)
		}
	}()

	files := []struct {
		name     string
		data     string
		fileType FileType
	}{
		{
			name:     "foo",
			data:     "foobarbaz",
			fileType: RegularFile,
		},
		{
			name:     "dir/blah",
			data:     "bazblahfoo",
			fileType: RegularFile,
		},
		{
			name:     "some/other/directory/",
			data:     "with more data here",
			fileType: RegularFile,
		},
		{
			name:     "blah",
			data:     "same file name different data",
			fileType: RegularFile,
		},
		{
			name:     "gakki",
			data:     "/tmp/gakki",
			fileType: SymLink,
		},
	}

	for _, file := range files {
		filepath := path.Join(dir, file.name)
		if err := os.MkdirAll(path.Dir(filepath), 0755); err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if file.fileType == RegularFile {
			f, err := os.Create(filepath)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			defer f.Close()
			if _, err := io.Copy(f, bytes.NewBuffer([]byte(file.data))); err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if err := f.Close(); err != nil {
				t.Fatal(err)
			}
		} else if file.fileType == SymLink {
			err := os.Symlink(file.data, filepath)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
		} else {
			t.Fatalf("unexpected file type: %v", file)
		}

	}

	writer := &bytes.Buffer{}
	if err := makeTar(dir, dir, writer); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	reader := bytes.NewBuffer(writer.Bytes())
	if err := untarAll(reader, dir2, ""); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	for _, file := range files {
		absPath := filepath.Join(dir2, strings.TrimPrefix(dir, os.TempDir()))
		filePath := filepath.Join(absPath, file.name)

		if file.fileType == RegularFile {
			f, err := os.Open(filePath)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			defer f.Close()
			buff := &bytes.Buffer{}
			if _, err := io.Copy(buff, f); err != nil {
				t.Fatal(err)
			}
			if err := f.Close(); err != nil {
				t.Fatal(err)
			}
			if file.data != string(buff.Bytes()) {
				t.Fatalf("expected: %s, saw: %s", file.data, string(buff.Bytes()))
			}
		} else if file.fileType == SymLink {
			dest, err := os.Readlink(filePath)

			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			if file.data != dest {
				t.Fatalf("expected: %s, saw: %s", file.data, dest)
			}
		} else {
			t.Fatalf("unexpected file type: %v", file)
		}
	}
}

// TestCopyToLocalFileOrDir tests untarAll in two cases :
// 1: copy pod file to local file
// 2: copy pod file into local directory
func TestCopyToLocalFileOrDir(t *testing.T) {
	dir, err := ioutil.TempDir(os.TempDir(), "input")
	dir2, err2 := ioutil.TempDir(os.TempDir(), "output")
	if err != nil || err2 != nil {
		t.Errorf("unexpected error: %v | %v", err, err2)
		t.FailNow()
	}
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Errorf("Unexpected error cleaning up: %v", err)
		}
		if err := os.RemoveAll(dir2); err != nil {
			t.Errorf("Unexpected error cleaning up: %v", err)
		}
	}()

	files := []struct {
		name          string
		data          string
		dest          string
		destDirExists bool
	}{
		{
			name:          "foo",
			data:          "foobarbaz",
			dest:          "path/to/dest",
			destDirExists: false,
		},
		{
			name:          "dir/blah",
			data:          "bazblahfoo",
			dest:          "dest/file/path",
			destDirExists: true,
		},
	}

	for _, file := range files {
		func() {
			// setup
			srcFilePath := filepath.Join(dir, file.name)
			destPath := filepath.Join(dir2, file.dest)
			if err := os.MkdirAll(filepath.Dir(srcFilePath), 0755); err != nil {
				t.Errorf("unexpected error: %v", err)
				t.FailNow()
			}
			srcFile, err := os.Create(srcFilePath)
			if err != nil {
				t.Errorf("unexpected error: %v", err)
				t.FailNow()
			}
			defer srcFile.Close()

			if _, err := io.Copy(srcFile, bytes.NewBuffer([]byte(file.data))); err != nil {
				t.Errorf("unexpected error: %v", err)
				t.FailNow()
			}
			if file.destDirExists {
				if err := os.MkdirAll(destPath, 0755); err != nil {
					t.Errorf("unexpected error: %v", err)
					t.FailNow()
				}
			}

			// start tests
			srcTarFilePath := filepath.Join(dir, file.name+".tar")
			// here use tar command to create tar file instead of calling makeTar func
			// because makeTar func can not generate correct header name
			err = exec.Command("tar", "cf", srcTarFilePath, srcFilePath).Run()
			if err != nil {
				t.Errorf("unexpected error: %v", err)
				t.FailNow()
			}
			srcTarFile, err := os.Open(srcTarFilePath)
			if err != nil {
				t.Errorf("unexpected error: %v", err)
				t.FailNow()
			}
			defer srcTarFile.Close()

			if err := untarAll(srcTarFile, destPath, getPrefix(srcFilePath)); err != nil {
				t.Errorf("unexpected error: %v", err)
				t.FailNow()
			}

			actualDestFilePath := destPath
			if file.destDirExists {
				actualDestFilePath = filepath.Join(destPath, filepath.Base(srcFilePath))
			}
			_, err = os.Stat(actualDestFilePath)
			if err != nil && os.IsNotExist(err) {
				t.Errorf("expecting %s exists, but actually it's missing", actualDestFilePath)
			}
			destFile, err := os.Open(actualDestFilePath)
			if err != nil {
				t.Errorf("unexpected error: %v", err)
				t.FailNow()
			}
			defer destFile.Close()
			buff := &bytes.Buffer{}
			io.Copy(buff, destFile)
			if file.data != string(buff.Bytes()) {
				t.Errorf("expected: %s, actual: %s", file.data, string(buff.Bytes()))
			}
		}()
	}

}

func TestTarDestinationName(t *testing.T) {
	dir, err := ioutil.TempDir(os.TempDir(), "input")
	dir2, err2 := ioutil.TempDir(os.TempDir(), "output")
	if err != nil || err2 != nil {
		t.Errorf("unexpected error: %v | %v", err, err2)
		t.FailNow()
	}
	defer func() {
		if err := os.RemoveAll(dir); err != nil {
			t.Errorf("Unexpected error cleaning up: %v", err)
		}
		if err := os.RemoveAll(dir2); err != nil {
			t.Errorf("Unexpected error cleaning up: %v", err)
		}
	}()

	files := []struct {
		name string
		data string
	}{
		{
			name: "foo",
			data: "foobarbaz",
		},
		{
			name: "dir/blah",
			data: "bazblahfoo",
		},
		{
			name: "some/other/directory",
			data: "with more data here",
		},
		{
			name: "blah",
			data: "same file name different data",
		},
	}

	// ensure files exist on disk
	for _, file := range files {
		filepath := path.Join(dir, file.name)
		if err := os.MkdirAll(path.Dir(filepath), 0755); err != nil {
			t.Errorf("unexpected error: %v", err)
			t.FailNow()
		}
		f, err := os.Create(filepath)
		if err != nil {
			t.Errorf("unexpected error: %v", err)
			t.FailNow()
		}
		defer f.Close()
		if _, err := io.Copy(f, bytes.NewBuffer([]byte(file.data))); err != nil {
			t.Errorf("unexpected error: %v", err)
			t.FailNow()
		}
	}

	reader, writer := io.Pipe()
	go func() {
		if err := makeTar(dir, dir2, writer); err != nil {
			t.Errorf("unexpected error: %v", err)
		}
	}()

	tarReader := tar.NewReader(reader)
	for {
		hdr, err := tarReader.Next()
		if err == io.EOF {
			break
		} else if err != nil {
			t.Errorf("unexpected error: %v", err)
			t.FailNow()
		}

		if !strings.HasPrefix(hdr.Name, path.Base(dir2)) {
			t.Errorf("expected %q as destination filename prefix, saw: %q", path.Base(dir2), hdr.Name)
		}
	}
}


text:
package gov.nih.nci.cabig.caaers.web.selenium;

import junit.framework.TestCase;

import com.thoughtworks.selenium.Selenium;

/**
 * @author Karthik Iyer
 *
 */
public class AjaxWidgets extends TestCase {
	Selenium selenium;

	public AjaxWidgets(Selenium selenium) {
		super();
		this.selenium = selenium;
	}

	public void clickNext(String nextButton) {
		selenium.click(nextButton);
		selenium.waitForPageToLoad(CaaersSeleniumTestCase.waitTime);
	}

	public void confirmOK(String expectedMessage) throws InterruptedException {
		/*
		 * confirmMessage should have the following format: original: Are you
		 * sure you want to delete this? transformed: ^Are you sure you want to
		 * delete this[\\s\\S]$
		 */
		for (int second = 0;; second++) {
			if (second >= 60)
				fail("timeout");
			try {
				if (selenium.isConfirmationPresent())
					break;
			} catch (Exception e) {
			}
			Thread.sleep(1000);
		}
		String actual = selenium.getConfirmation();
		// selenium.chooseOkOnNextConfirmation();
		// System.out.println(s+" confirmMessage: "+confirmMessage);
		assertTrue("Did not see matching confirm message. " + "\n Expected: "
				+ expectedMessage + "\n Actual: " + actual, actual
				.matches(expectedMessage));
	}

	public void login() throws Exception {
		selenium.open("/caaers/public/login");
		selenium.waitForPageToLoad(CaaersSeleniumTestCase.waitTime);
		selenium.type("j_username", "SYSTEM_ADMIN");
		selenium.type("j_password", "system_admin");
		selenium.click("power_btn");
		selenium.waitForPageToLoad(CaaersSeleniumTestCase.waitTime);

	}

	public void typeAutosuggest(String element, String text, String elemPresent)
			throws InterruptedException {
		selenium.click(element);
		String elemValue = selenium.getValue(element);

		for (int i = 0; i < elemValue.length(); i++)
			selenium.typeKeys(element, "\b");
		selenium.typeKeys(element, text);
		waitForElementPresent("//div[@id='" + elemPresent + "']/ul/li");

		selenium.click("//div[@id='" + elemPresent + "']/ul/li[1]");
		selenium.click(element);
	}

	public void waitForElementPresent(String xPathElement)
			throws InterruptedException {
		for (int second = 0;; second++) {
			if (second >= 60)
				fail("Timed out waiting for element to be created: "
						+ xPathElement);
			try {
				if (selenium.isElementPresent(xPathElement))
					break;
			} catch (Exception e) {
			}
			Thread.sleep(1000);

		}
	}

	public void waitForElementNotPresent(String xPathElement)
			throws InterruptedException {
		for (int second = 0;; second++) {
			if (second >= 60)
				fail("Timed out waiting for element to be removed: "
						+ xPathElement);
			try {
				if (!selenium.isElementPresent(xPathElement))
					break;
			} catch (Exception e) {
			}
			Thread.sleep(1000);
		}
	}

	public void addPanel(String clickableElement, String waitForElementPresent)
			throws InterruptedException {
		selenium.click(clickableElement);
		waitForElementPresent(waitForElementPresent);
	}

	public void removePanel(String clickableElement, String confirmMessage)
			throws InterruptedException {
		// clickableElement should be set to the delete 'X' used to delete
		// panels
		// Set confirmMessage to null if no confirmation dialog will appear
		selenium.click(clickableElement);
		if (confirmMessage != null)
			confirmOK(confirmMessage);
		waitForElementNotPresent(clickableElement);
	}

	public void removeLastPanel(String clickableElement, String confirmMessage)
			throws Exception {
		/*
		 * Removes the last panel which has the clickable element. It should be
		 * of the following form: Original: //input[@id=
		 * 'participant.organizationIdentifiers[1].primaryIndicator']/parent::td/parent::tr/descendant::img[@alt='delete']
		 * Use: //input[@id=
		 * 'participant.organizationIdentifiers[?].primaryIndicator']/parent::td/parent::tr/descendant::img[@alt='delete']
		 *
		 * ClickableElement should be set to the delete 'X' used to delete
		 * panels. Set confirmMessage to null if no confirmation dialog will
		 * appear.
		 */
		String latestClickableElement = computeLatestElement(clickableElement,
				true);
		selenium.click(latestClickableElement);
		if (confirmMessage != null)
			confirmOK(confirmMessage);
		waitForElementNotPresent(latestClickableElement);
	}

	public void addLastPanel(String clickableElement,
			String waitForElementPresent) throws Exception {
		/*
		 * waitForElementPresent should have an array index in the Name. For ex:
		 * if element is://span[@id=
		 * 'assignment.preExistingConditions[0].preExistingCondition.text'] then
		 * fashion the string as//span[@id=
		 * 'assignment.preExistingConditions[?].preExistingCondition.text']
		 */
		String latestElement = computeLatestElement(waitForElementPresent,
				false);
		selenium.click(clickableElement);
		waitForElementPresent(latestElement);
	}

	public int computeLatestElementIndex(String waitForElementPresent,
			boolean exists) throws Exception {
		String[] parts = split(waitForElementPresent);

		boolean loop = true;
		int i = 0;
		for (; loop; i++) {
			if (!(selenium.isElementPresent(parts[0] + i + parts[1])))
				loop = false;
			/*System.out.println("\n checking through: " + parts[0] + i
					+ parts[1]);*/
		}
		i--;
		if (exists) {
			// return parts[0] + (--i) + parts[1];
			return (--i);
		} else
			return i;

	}

	public String[] split(String waitForElementPresent) throws Exception {
		if (waitForElementPresent.indexOf('?') == -1)
			throw new Exception("Element is malformed. \n Value passed:\n"
					+ waitForElementPresent
					+ "\n does not have '?' character as required.");
		String parts[] = waitForElementPresent.split("\\?");
		if (parts.length < 2) {
			String temp[] = { parts[0], "" };
			parts = temp;
		}
		return parts;
	}

	public String computeLatestElement(String waitForElementPresent,
			boolean exists) throws Exception {
		String parts[] = split(waitForElementPresent);
		return parts[0]
				+ computeLatestElementIndex(waitForElementPresent, exists)
				+ parts[1];
	}

	public void clickCalendar(String linkId) throws InterruptedException {
		/*
		 * selenium.clickAt("//a[@id='" + linkId + "']", "");
		 * waitForElementPresent("//div[text()='Today']");
		 * selenium.clickAt("//div[text()='Today']", "");
		 * selenium.clickAt("//div[text()='Today']", "");
		 */
		selenium.click("//a[@id='participant.dateOfBirth-calbutton']");
		waitForElementPresent("//div[text()='Today']");
		selenium.click("//div[text()='Today']");
		selenium.clickAt("//div[text()='Today']", "(0,0)");
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.Authentication
{
    using System;
    using System.Data;

    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Entities;
    using DotNetNuke.Entities.Modules;

    /// <summary>
    /// DNN-4016
    /// The UserAuthenticationInfo class provides the Entity Layer for the
    /// user information in the Authentication Systems.
    /// </summary>
    [Serializable]
    public class UserAuthenticationInfo : BaseEntityInfo, IHydratable
    {
        public UserAuthenticationInfo()
        {
            this.AuthenticationToken = Null.NullString;
            this.AuthenticationType = Null.NullString;
            this.UserAuthenticationID = Null.NullInteger;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and Sets the ID of the User Record in the Authentication System.
        /// </summary>
        /// -----------------------------------------------------------------------------
        public int UserAuthenticationID { get; set; }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and Sets the PackageID for the Authentication System.
        /// </summary>
        /// -----------------------------------------------------------------------------
        public int UserID { get; set; }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and Sets the type (name) of the Authentication System (eg DNN, OpenID, LiveID).
        /// </summary>
        /// -----------------------------------------------------------------------------
        public string AuthenticationType { get; set; }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and Sets the url for the Logoff Control.
        /// </summary>
        /// -----------------------------------------------------------------------------
        public string AuthenticationToken { get; set; }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets or sets and sets the Key ID.
        /// </summary>
        /// <returns>An Integer.</returns>
        /// -----------------------------------------------------------------------------
        public virtual int KeyID
        {
            get
            {
                return this.UserAuthenticationID;
            }

            set
            {
                this.UserAuthenticationID = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Fills a UserAuthenticationInfo from a Data Reader.
        /// </summary>
        /// <param name="dr">The Data Reader to use.</param>
        /// -----------------------------------------------------------------------------
        public virtual void Fill(IDataReader dr)
        {
            this.UserAuthenticationID = Null.SetNullInteger(dr["UserAuthenticationID"]);
            this.UserID = Null.SetNullInteger(dr["UserID"]);
            this.AuthenticationType = Null.SetNullString(dr["AuthenticationType"]);
            this.AuthenticationToken = Null.SetNullString(dr["AuthenticationToken"]);

            // Fill base class fields
            this.FillInternal(dr);
        }
    }
}


text:
FactoryGirl.define do
  factory :entry do
  end
end


text:
import { FormControl } from "@angular/forms";

export function ValidateField(input: FormControl) {
    return input.valid || input.untouched
}


text:
package org.shaolin.bmdp.runtime.entity;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import com.sun.xml.txw2.output.IndentingXMLStreamWriter;

public final class EntityUtil {

	@SuppressWarnings("unchecked")
	public static <T> T unmarshaller(Class<T> entityType, InputStream in)
			throws JAXBException {
		Unmarshaller unmarshaller = createUnmarshaller(entityType);
		return (T) unmarshaller.unmarshal(in);
	}

	@SuppressWarnings("unchecked")
	public static <T> T unmarshaller(Class<T> entityType, Reader reader)
			throws JAXBException {
		Unmarshaller unmarshaller = createUnmarshaller(entityType);
		return (T) unmarshaller.unmarshal(reader);
	}

	public static void marshaller(Object entity, Writer writer)
			throws JAXBException {
//		marshaller.marshal(entity, writer);

	    Marshaller marshaller = createMarshaller(entity.getClass());
		XMLOutputFactory xof = XMLOutputFactory.newInstance();
		CDataXMLStreamWriter cdataStreamWriter = null;
		try {
			XMLStreamWriter streamWriter = new IndentingXMLStreamWriter(xof.createXMLStreamWriter(writer));
			cdataStreamWriter = new CDataXMLStreamWriter(streamWriter);
			marshaller.marshal(entity, cdataStreamWriter);
		} catch (XMLStreamException e) {
			throw new JAXBException(e.getMessage(), e);
		} finally {
			if (cdataStreamWriter != null) {
				try {
					cdataStreamWriter.flush();
					cdataStreamWriter.close();
				} catch (XMLStreamException e) {
				}
			}
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static Unmarshaller createUnmarshaller(Class<?> clazz)
			throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
		return jaxbContext.createUnmarshaller();
	}

	public static Marshaller createMarshaller(Class<?> clazz)
			throws JAXBException {
		JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
		Marshaller marshaller = jaxbContext.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "");
		return marshaller;
	}

}


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace System.Net.NetworkInformation{
    public class GatewayIPAddressInformationCollection :ICollection<GatewayIPAddressInformation>
    {
        Collection<GatewayIPAddressInformation> addresses = new Collection<GatewayIPAddressInformation>();

        protected internal GatewayIPAddressInformationCollection(){
        }

        /// <include file='doc\HttpListenerPrefixCollection.uex' path='docs/doc[@for="HttpListenerPrefixCollection.CopyTo"]/*' />
        public virtual void CopyTo(GatewayIPAddressInformation[] array, int offset) {
            addresses.CopyTo(array,offset);
        }

        /// <include file='doc\HttpListenerPrefixCollection.uex' path='docs/doc[@for="HttpListenerPrefixCollection.Count"]/*' />
        public virtual int Count {
            get {
                return addresses.Count;
            }
        }

        public virtual bool IsReadOnly {
            get {
                return true;
            }
        }

        public virtual GatewayIPAddressInformation this[int index]
        {
            get{
                return (GatewayIPAddressInformation)addresses[index];
            }
        }

        /// <include file='doc\HttpListenerPrefixCollection.uex' path='docs/doc[@for="HttpListenerPrefixCollection.Add"]/*' />
        public virtual void Add(GatewayIPAddressInformation address) {
                throw new NotSupportedException(SR.GetString(SR.net_collection_readonly));
        }

        internal void InternalAdd(GatewayIPAddressInformation address) {
            addresses.Add(address);
        }

        /// <include file='doc\HttpListenerPrefixCollection.uex' path='docs/doc[@for="HttpListenerPrefixCollection.Contains"]/*' />
        public virtual bool Contains(GatewayIPAddressInformation address) {
            return addresses.Contains(address);
        }

        public virtual IEnumerator<GatewayIPAddressInformation> GetEnumerator() {
            return (IEnumerator<GatewayIPAddressInformation>) addresses.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return this.GetEnumerator();
        }

        /// <include file='doc\HttpListenerPrefixCollection.uex' path='docs/doc[@for="HttpListenerPrefixCollection.Remove"]/*' />
        public virtual bool Remove(GatewayIPAddressInformation address) {
            throw new NotSupportedException(SR.GetString(SR.net_collection_readonly));
        }

        /// <include file='doc\HttpListenerPrefixCollection.uex' path='docs/doc[@for="HttpListenerPrefixCollection.Clear"]/*' />
        public virtual void Clear() {
            throw new NotSupportedException(SR.GetString(SR.net_collection_readonly));
        }
    }
}


text:
import angular from 'angular';

import configModule from '../app-config';

import openFdaService from './open-fda-service';
import foodRecallService from './food-recall-service';
import cacheService from './cache-service';
import localStorageService from './local-storage-service';

export default angular.module('fdaFoodRecalls.services', [ configModule.name ])
  .service('openFdaService', openFdaService)
  .service('foodRecallService', foodRecallService)
  .service('cacheService', cacheService)
  .service('localStorageService', localStorageService)
;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fusion.Engine.Graphics {

	/// <summary>
	/// Defines target texture formats
	/// </summary>
	public enum TargetFormat {
		LowDynamicRange,
		LowDynamicRangeMSAA,
		HighDynamicRange,
	}
}


text:
require 'rubygems'
require 'test/unit'
require 'headliner/helper'

class HeadlinerTest < Test::Unit::TestCase

  include ActionView::Helpers::TagHelper
  include Headliner::Helper

  # Make the blank? method available without loading Rails
  Object.class_eval do
    def blank?
      if respond_to?(:empty?) && respond_to?(:strip)
        empty? or strip.empty?
      elsif respond_to?(:empty?)
        empty?
      else
        !self
      end
    end
  end

  def test_title_is_saved
    title "Headliner", ""
    assert_equal "Headliner", @title
  end

  def test_title_is_saved_with_headline
    headline = save_title "Headliner", "Headliner: a plugin for setting page titles"
    assert_equal "Headliner", @title
    assert_equal "Headliner: a plugin for setting page titles", headline
  end

  def test_title_is_site_when_empty
    title :site => "the.railsi.st"
    assert_equal nil, @title
  end

  def test_title_removes_all_tags
    title 'Headliner is cool'
    assert_equal "Headliner is cool", @title
  end

  def test_title_removes_all_tags_but_displays_tags_in_views
    original_title = save_title 'Headliner is cool', ''
    assert_equal "Headliner is cool", @title
    assert_equal 'Headliner is cool', original_title
  end

  def test_title_is_lowercase
    @title = "Headliner"
    full_title = display_title :site => "the.railsi.st", :lowercase => true
    assert_equal "<title>the.railsi.st | headliner</title>", full_title
  end

  def test_title_is_reversed
    @title = "Headliner"
    full_title = display_title :site => "the.railsi.st", :reverse => true
    assert_equal "<title>Headliner | the.railsi.st</title>", full_title
  end

  def test_title_has_custom_separator
    @title = "Headliner"
    full_title = display_title :site => "the.railsi.st", :separator => "—"
    assert_equal "<title>the.railsi.st — Headliner</title>", full_title
  end

  def test_title_has_custom_prefix_and_suffix
    @title = "Headliner"
    full_title = display_title :site => "the.railsi.st", :prefix => "  ", :suffix => "  "
    assert_equal "<title>the.railsi.st  |  Headliner</title>", full_title
  end

  def test_title_has_no_prefix_and_has_custom_separator
    @title = "Headliner"
    full_title = display_title :site => "the.railsi.st", :prefix => false, :separator => ":"
    assert_equal "<title>the.railsi.st: Headliner</title>", full_title
  end

  def test_title_has_no_suffix_and_has_custom_separator
    @title = "Headliner"
    full_title = display_title :site => "the.railsi.st", :suffix => false, :separator => "~"
    assert_equal "<title>the.railsi.st ~Headliner</title>", full_title
  end

  def test_title_has_no_prefix_and_suffix_and_has_custom_separator
    @title = "Headliner"
    full_title = display_title :site => "the.railsi.st",
                               :prefix => false,
                               :suffix => false,
                               :separator => "—"
    assert_equal "<title>the.railsi.st—Headliner</title>", full_title
  end

  def test_title_has_all_custom_options
    @title = "Headliner"
    full_title = display_title :site => "the.railsi.st",
                               :prefix => " ",
                               :suffix => " ",
                               :separator => ".:.",
                               :lowercase => true,
                               :reverse => true
    assert_equal "<title>headliner .:. the.railsi.st</title>", full_title
  end

end


text:
using NewEngine.Engine.components;
using NewEngine.Engine.Core;
using OpenTK;
using OpenTK.Audio.OpenAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewEngine.Engine.Audio {
    public class AudioSource : GameComponent {
        private int _sourceId;
        private bool _is3D;

        public AudioSource() {
            AL.GenSources(1, out _sourceId);
            AL.Source(_sourceId, ALSourcef.Gain, 1);
            AL.Source(_sourceId, ALSourcef.Pitch, 1);
            AL.Source(_sourceId, ALSource3f.Position, 0, 0, 0);
        }

        public void Play(string filename) {
            Stop();

            int buffer;
            AL.GenBuffers(1, out buffer);
            WaveData waveFile = new WaveData(filename);
            AL.BufferData(buffer, waveFile.SoundFormat, waveFile.SoundData, waveFile.SoundData.Length, waveFile.SampleRate);
            waveFile.dispose();

            AL.Source(_sourceId, ALSourcei.Buffer, buffer);
            Continue();
        }

        public void Delete() {
            AL.DeleteSources(1, ref _sourceId);
        }

        public void SetVolume(float volume) {
            AL.Source(_sourceId, ALSourcef.Gain, volume);
        }

        public void SetPitch(float pitch) {
            AL.Source(_sourceId, ALSourcef.Pitch, pitch);
        }

        public void SetLooping(bool loop) {
            AL.Source(_sourceId, ALSourceb.Looping, loop);
        }

        public void Pause() {
            AL.SourcePause(_sourceId);
        }

        public void Continue() {
            AL.SourcePlay(_sourceId);
        }

        public void Stop() {
            AL.SourceStop(_sourceId);
        }

        public bool IsPlaying() {
            int isPlaying;
            AL.GetSource(_sourceId, ALGetSourcei.SourceState, out isPlaying);

            if (isPlaying == (int)ALSourceState.Playing)
                return true;
            else
                return false;
        }

        public void Is3D(bool value) {
            _is3D = value;
        }

        public override void Update(float deltaTime) {
            if (_is3D)
                AL.Source(_sourceId, ALSource3f.Position, Transform.GetTransformedPosition().X, Transform.GetTransformedPosition().Y, Transform.GetTransformedPosition().Z);
            else {
                var position = AudioMaster.GetAudioListnerPosition();
                AL.Source(_sourceId, ALSource3f.Position, position.X, position.Y, position.Z);
            }
        }
    }
}


text:
class Admin::ControlsController < ApplicationController
  layout "admin"

  include ManyHelper
  include AutofilterHelper

  # List Controls
  def index
    @controls = filtered_controls

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @controls }
    end
  end

  # Show a Control
  def show
    @control = Control.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @control }
    end
  end

  # New control form
  def new
    @control = Control.new
    @control.effective_at = Date.today

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @control }
    end
  end

  # Edit control form
  def edit
    @control = Control.find(params[:id])
  end

  # Create a control
  def create
    @control = Control.new(params[:control])

    respond_to do |format|
      if @control.save
        format.html { redirect_to(edit_control_path(@control), :notice => 'Control was successfully created.') }
        format.xml  { render :xml => @control, :status => :created, :location => @control }
      else
        flash.now[:error] = "Could not create."
        format.html { render :action => "new" }
        format.xml  { render :xml => @control.errors, :status => :unprocessable_entity }
      end
    end
  end

  # Update a control
  def update
    @control = Control.find(params[:id])

    # Connect to related Control Objectives
    co_ids = params["control"].delete("co_ids") || []

    if !equal_ids(co_ids, @control.sections)
      @control.sections = []
      co_ids.each do |co_id|
        co = Section.find(co_id)
        @control.sections << co
      end
    end

    respond_to do |format|
      res = @control.save
      if res && @control.authored_update(current_user, params["control"])
        format.html { redirect_to(edit_control_path(@control), :notice => 'Control was successfully updated.') }
        format.xml  { head :ok }
      else
        flash.now[:error] = "Could not update."
        format.html { render :action => "edit" }
        format.xml  { render :xml => @control.errors, :status => :unprocessable_entity }
      end
    end
  end

  # Delete a control
  def destroy
    control = Control.find(params[:id])
    success = control && control.biz_process_controls.destroy &&
        control.system_controls.destroy &&
        control.control_document_descriptors.destroy &&
        control.destroy

    respond_to do |format|
      format.html { redirect_to(controls_url) }
      format.xml  { head :ok }
    end
  end

  # Slug for AJAX
  def slug
    respond_to do |format|
      format.js { Control.find(params[:id]).slug }
    end
  end

  # Many2many relationship to Systems
  def systems
    lefts = filtered_controls
    if lefts.empty?
      flash[:error] = 'No company controls'
      redirect_to controls_path
      return
    end
    if request.put?
      raise "cannot save without cycle" unless @cycle
      control = Control.find(params[:id])
      if params[:control]
        ids = params[:control]["system_ids"] || []
      else
        ids = []
      end
      #ids = params[:control]["system_ids"]
      control.system_controls.each do |sc|
        if sc.cycle == @cycle && !ids.include?(sc.system_id)
          ids.delete(sc.system_id)
          sc.authored_destroy(current_user)
        end
      end
      ids.each do |id|
        res = control.system_controls.create(:system => System.find(id), :cycle => @cycle)#, :modified_by => current_user)
        # FIXME why is this necessary?
        res.save!
      end
      # FIXME
      control.reload
    else
      if params[:id]
        control = Control.find(params[:id])
      else
        control = lefts.first
      end
    end
    if @cycle
      @left_nested = control.system_controls_for_cycle(@cycle)
    end
    get_many2many(:left_class => Control,
                  :right_class => System,
                  :lefts => lefts,
                  :show_slugfilter => true,
                 )
  end

  # Many2many relationship to Control Objectives
  def sections
    if request.put?
      post_many2many(:left_class => Control,
                     :right_class => Section,
                     :lefts => filtered_controls)
    else
      get_many2many(:left_class => Control,
                    :right_class => Section,
                    :lefts => filtered_controls,
                    :show_slugfilter => true)
    end
  end

  # Many2many relationship to Biz Processes
  def biz_processes
    if request.put?
      post_many2many(:left_class => Control,
                     :right_class => BizProcess,
                     :lefts => filtered_controls)
    else
      get_many2many(:left_class => Control,
                    :right_class => BizProcess,
                    :lefts => filtered_controls,
                    :show_slugfilter => true)
    end
  end

  # Many2many relationship to self (which controls implement other controls)
  def controls
    if request.put?
      post_many2many(:left_class => Control,
                     :right_class => Control,
                     :right_relation => :implemented_controls,
                     :right_ids => :implemented_control_ids,
                     :lefts => filtered_controls)
    else
      get_many2many(:left_class => Control,
                    :lefts => filtered_controls.
                        joins(:program).
                        where(:programs => { :company => true }),
                    :right_class => Control,
                    :right_ids => :implemented_control_ids,
                    :show_slugfilter => true)
    end
  end

  # Many2many relationship to Document Descriptors (describing what evidence can be attached)
  def evidence_descriptors
    if request.put?
      post_many2many(:left_class => Control,
                     :right_class => DocumentDescriptor,
                     :right_relation => :evidence_descriptors,
                     :right_ids => :evidence_descriptor_ids,
                     :lefts => filtered_controls)
    else
      get_many2many(:left_class => Control,
                    :lefts => filtered_controls,
                    :right_class => DocumentDescriptor,
                    :right_ids => :evidence_descriptor_ids,
                    :show_slugfilter => true)
    end
  end

  # Another way to attach a biz process
  def add_biz_process
    @control = Control.find(params[:id])
  end

  # Another way to attach a biz process
  def create_biz_process
    @control = Control.find(params[:id])
    @biz_process_control = BizProcessControl.new(params[:biz_process_control])
    @biz_process_control.control = @control
    if @biz_process_control.save
      flash[:notice] = 'Biz Process was successfully attached.'
      redirect_to edit_control_path(@biz_process_control.control)
    else
      redirect_to add_biz_process_control_path(@biz_process_control.control)
    end
  end

  # Another way to detach a biz process
  def destroy_biz_process
    bpc = BizProcessControl.first(:control_id => params[:id], :biz_process_id => params[:biz_process_id])
    if bpc.destroy
      flash[:notice] = 'Biz Process was successfully detached.'
    else
      flash[:error] = 'Failed'
    end
    redirect_to edit_control_path(bpc.control)
  end

  # Another way to detach an implemented control
  def destroy_section
    cs = ControlSection.first(:control_id => params[:id], :section_id => params[:section_id])
    if cs && cs.destroy
      flash[:notice] = 'Section was successfully detached.'
    else
      flash[:error] = 'Failed'
    end
    redirect_to edit_control_path(Control.find(params[:id]))
  end

  # Detach a control mapping from the implemented_controls perspective
  def destroy_control
    cc = ControlControl.
        where(:implemented_control_id => params[:id],
              :control_id => params[:control_id]).
        first
    if cc && cc.destroy
      flash[:notice] = 'Control was successfully detached.'
    else
      flash[:error] = 'Failed'
    end
    redirect_to edit_control_path(Control.find(params[:id]))
  end

  # Detach a implemented_control mapping from the implementing controls perspective
  def destroy_implemented_control
    cc = ControlControl.
        where(:control_id => params[:id],
              :implemented_control_id => params[:implemented_control_id]).
        first
    if cc && cc.destroy
      flash[:notice] = 'Control was successfully detached.'
    else
      flash[:error] = 'Failed'
    end
    redirect_to edit_control_path(Control.find(params[:id]))
  end

  def implement
    unless @company
      flash[:error] = 'Must set a company first.'
      redirect_to controls_path
      return
    end
    @origin = Control.find(params[:id])

    @control = Control.new
    @control.program = @company
    @control.slug = "#{@company.slug}-#{@origin.slug}"
    @control.implemented_controls << @origin
    @control.title = @origin.title
    @control.is_key = @origin.is_key
    @control.frequency = @origin.frequency
    @control.frequency_type = @origin.frequency_type
    @control.fraud_related = @origin.fraud_related
    @control.technical = @origin.technical
    @control.assertion = @origin.assertion
    @control.effective_at = @origin.effective_at
    @control.business_area = @origin.business_area

    respond_to do |format|
      if @control.save
        format.html { redirect_to(edit_control_path(@control), :notice => 'Control was successfully created.') }
        format.xml  { render :xml => @control, :status => :created, :location => @control }
      else
        flash.now[:error] = "Could not create."
        format.html { redirect_to controls_path }
        format.xml  { render :xml => @control.errors, :status => :unprocessable_entity }
      end
    end
  end
end


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web.Mvc;

using MVC4ManyToMany.Models.ViewModels;
using MVC4ManyToManyDatabase;
using MVC4ManyToManyDomain;

namespace MVC4ManyToMany.Controllers
{
    public class UserProfileController : Controller
    {
        private readonly MVC4ManyToManyContext db = new MVC4ManyToManyContext();

        public ActionResult Index()
        {
            var userProfiles = db.UserProfiles.ToList();
            var userProfileViewModels = userProfiles.Select(userProfile => userProfile.ToViewModel()).ToList();

            return View(userProfileViewModels);
        }

        public ActionResult Create()
        {
            var userProfileViewModel = new UserProfileViewModel { Courses = PopulateCourseData() };

            return View(userProfileViewModel);
        }

        [HttpPost]
        public ActionResult Create(UserProfileViewModel userProfileViewModel)
        {
            if (ModelState.IsValid)
            {
                var userProfile = userProfileViewModel.ToDomainModel();
                AddOrUpdateCourses(userProfile, userProfileViewModel.Courses);
                db.UserProfiles.Add(userProfile);
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(userProfileViewModel);
        }

        public ActionResult Edit(int id = 0)
        {
            // Get all courses
            var allDbCourses = db.Courses.ToList();

            // Get the user we are editing and include the courses already subscribed to
            var userProfile = db.UserProfiles.Include("Courses").FirstOrDefault(x => x.UserProfileID == id);
            var userProfileViewModel = userProfile.ToViewModel(allDbCourses);

            return View(userProfileViewModel);
        }

        [HttpPost]
        public ActionResult Edit(UserProfileViewModel userProfileViewModel)
        {
            if (ModelState.IsValid)
            {
                var originalUserProfile = db.UserProfiles.Find(userProfileViewModel.UserProfileID);

                // Add or update new courses
                // AddOrUpdateCourses(originalUserProfile, userProfileViewModel.Courses);

                // Add or update courses keeping original
                AddOrUpdateKeepExistingCourses(originalUserProfile, userProfileViewModel.Courses);

                db.Entry(originalUserProfile).CurrentValues.SetValues(userProfileViewModel);
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(userProfileViewModel);
        }

        public ActionResult Details(int id = 0)
        {
            // Get all courses
            var allDbCourses = db.Courses.ToList();

            // Get the user we are editing and include the courses already subscribed to
            var userProfile = db.UserProfiles.Include("Courses").FirstOrDefault(x => x.UserProfileID == id);
            var userProfileViewModel = userProfile.ToViewModel(allDbCourses);

            return View(userProfileViewModel);
        }

        public ActionResult Delete(int id = 0)
        {
            var userProfileIQueryable = from u in db.UserProfiles.Include("Courses")
                                  where u.UserProfileID == id
                                  select u;

            if (!userProfileIQueryable.Any())
            {
                return HttpNotFound("User not found.");
            }

            var userProfile = userProfileIQueryable.First();
            var userProfileViewModel = userProfile.ToViewModel();

            return View(userProfileViewModel);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            var userProfile = db.UserProfiles.Include("Courses").Single(u => u.UserProfileID == id);
            DeleteUserProfile(userProfile);

            return RedirectToAction("Index");
        }

        private void DeleteUserProfile(UserProfile userProfile)
        {
            if (userProfile.Courses != null)
            {
                foreach (var course in userProfile.Courses.ToList())
                {
                    userProfile.Courses.Remove(course);
                }
            }

            db.UserProfiles.Remove(userProfile);
            db.SaveChanges();
        }

        private ICollection<AssignedCourseData> PopulateCourseData()
        {
            var courses = db.Courses;
            var assignedCourses = new List<AssignedCourseData>();

            foreach (var item in courses)
            {
                assignedCourses.Add(new AssignedCourseData
                {
                    CourseID = item.CourseID,
                    CourseDescription = item.CourseDescripcion,
                    Assigned = false
                });
            }

            return assignedCourses;
        }

        private void AddOrUpdateCourses(UserProfile userProfile, IEnumerable<AssignedCourseData> assignedCourses)
        {
            if (assignedCourses == null) return;

            if (userProfile.UserProfileID != 0)
            {
                // Existing user - drop their existing courses and add the new ones if any
                foreach (var course in userProfile.Courses.ToList())
                {
                    userProfile.Courses.Remove(course);
                }

                foreach (var course in assignedCourses.Where(c => c.Assigned))
                {
                    userProfile.Courses.Add(db.Courses.Find(course.CourseID));
                }
            }
            else
            {
                // New user
                foreach (var assignedCourse in assignedCourses.Where(c => c.Assigned))
                {
                    var course = new Course { CourseID = assignedCourse.CourseID };
                    db.Courses.Attach(course);
                    userProfile.Courses.Add(course);
                }
            }
        }

        private void AddOrUpdateKeepExistingCourses(UserProfile userProfile, IEnumerable<AssignedCourseData> assignedCourses)
        {
            var webCourseAssignedIDs = assignedCourses.Where(c => c.Assigned).Select(webCourse => webCourse.CourseID);
            var dbCourseIDs = userProfile.Courses.Select(dbCourse => dbCourse.CourseID);
            var courseIDs = dbCourseIDs as int[] ?? dbCourseIDs.ToArray();
            var coursesToDeleteIDs = courseIDs.Where(id => !webCourseAssignedIDs.Contains(id)).ToList();

            // Delete removed courses
            foreach (var id in coursesToDeleteIDs)
            {
                userProfile.Courses.Remove(db.Courses.Find(id));
            }

            // Add courses that user doesn't already have
            foreach (var id in webCourseAssignedIDs)
            {
                if (!courseIDs.Contains(id))
                {
                    userProfile.Courses.Add(db.Courses.Find(id));
                }
            }
        }
    }
}


text:
package org.hswebframework.web.counter.redis;

import org.hswebframework.web.concurrent.counter.Counter;
import org.redisson.api.RAtomicLong;

/**
 * TODO 完成注释
 *
 * @author zhouhao
 */
public class RedissonCounter implements Counter {

    private final RAtomicLong atomicLong;

    public RedissonCounter(RAtomicLong rAtomicLong) {
        this.atomicLong = rAtomicLong;
    }

    @Override
    public long get() {
        return atomicLong.get();
    }

    @Override
    public void set(long num) {
        atomicLong.set(num);
    }

    @Override
    public long getAndAdd(long num) {
        return atomicLong.getAndAdd(num);
    }

    @Override
    public void add(long num) {
        atomicLong.addAndGet(num);
    }

    @Override
    public void increment() {
        atomicLong.incrementAndGet();
    }

    @Override
    public void decrement() {
        atomicLong.decrementAndGet();
    }

    @Override
    public long incrementAndGet() {
        return atomicLong.incrementAndGet();
    }

    @Override
    public long decrementAndGet() {
        return atomicLong.decrementAndGet();
    }
}


text:
using eShopLegacyMVC.Services;
using log4net;
using System.IO;
using System.Net;
using System.Web.Mvc;

namespace eShopLegacyMVC.Controllers
{
    public class PicController : Controller
    {
        private static readonly ILog _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public const string GetPicRouteName = "GetPicRouteTemplate";

        private ICatalogService service;

        public PicController(ICatalogService service)
        {
            this.service = service;
        }

        // GET: Pic/5.png
        [HttpGet]
        [Route("items/{catalogItemId:int}/pic", Name = GetPicRouteName)]
        public ActionResult Index(int catalogItemId)
        {
            _log.Info($"Now loading... /items/Index?{catalogItemId}/pic");

            if (catalogItemId <= 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var item = service.FindCatalogItem(catalogItemId);

            if (item != null)
            {
                var webRoot = Server.MapPath("~/Pics");
                var path = Path.Combine(webRoot, item.PictureFileName);

                string imageFileExtension = Path.GetExtension(item.PictureFileName);
                string mimetype = GetImageMimeTypeFromImageFileExtension(imageFileExtension);

                var buffer = System.IO.File.ReadAllBytes(path);

                return File(buffer, mimetype);
            }

            return HttpNotFound();
        }

        private string GetImageMimeTypeFromImageFileExtension(string extension)
        {
            string mimetype;

            switch (extension)
            {
                case ".png":
                    mimetype = "image/png";
                    break;
                case ".gif":
                    mimetype = "image/gif";
                    break;
                case ".jpg":
                case ".jpeg":
                    mimetype = "image/jpeg";
                    break;
                case ".bmp":
                    mimetype = "image/bmp";
                    break;
                case ".tiff":
                    mimetype = "image/tiff";
                    break;
                case ".wmf":
                    mimetype = "image/wmf";
                    break;
                case ".jp2":
                    mimetype = "image/jp2";
                    break;
                case ".svg":
                    mimetype = "image/svg+xml";
                    break;
                default:
                    mimetype = "application/octet-stream";
                    break;
            }

            return mimetype;
        }
    }
}


text:
<component name="ProjectDictionaryState">
  <dictionary name="bhale">
    <words>
      <w>deserializing</w>
      <w>tbody</w>
      <w>thead</w>
      <w>unregister</w>
    </words>
  </dictionary>
</component>


text:
import { Component } from '@angular/core';
import { NavbarComponent } from './components/navbar/navbar.component';
import {ROUTER_DIRECTIVES} from '@angular/router';
import { SearchComponent } from './components/search/search.component';
import { AboutComponent } from './components/about/about.component';

import { AlbumComponent } from './components/album/album.component';

import { ArtistComponent } from './components/artist/artist.component';

import {HTTP_PROVIDERS} from '@angular/http';
import {SpotifyService} from './services/spotify.service';

@Component({
moduleId:module.id,
selector: 'my-app',
    templateUrl: 'app.component.html',
directives:[ROUTER_DIRECTIVES, NavbarComponent],
precompile:[SearchComponent, AboutComponent],
providers:[HTTP_PROVIDERS, SpotifyService]
})
export class AppComponent { }


text: Solutions for the [Advent of Code](http://adventofcode.com/).


text:
<?php //-->

namespace Eden\Eventbrite;

/**
 * Eventbrite venue
 *
 * @vendor Eden
 * @package Eventbrite
 * @author Airon Paul Dumael airon.dumael@gmail.com
 */
class Venue extends Base
{
    const URL_NEW = 'https://www.eventbrite.com/json/venue_new';
    const URL_UPDATE = 'https://www.eventbrite.com/json/venue_update';

    protected $query = array();

    /**
     * Sets token or user and api
     *
     * @param string $user
     * @param string|bool|null $api
     * @return void
     */
    public function __construct($user, $api = false)
    {
        //argument test
        Argument::i()
            //Argument 1 must be a string
            ->test(1, 'string')
            //Argument 2 must be a string, bool or null
            ->test(2, 'string', 'bool', 'null');

        $this->api = $api;
        $this->user = $user;
    }

    /**
     * set id in query
     *
     * @param int
     * @return Eden\Eventbrite\Venue
     */
    public function setId($id)
    {
        //Argument 1 must be an int
        Argument::i()->test(1, 'int');

        $this->query['id'] = $id;

        return $this;
    }

    /**
     * set organizer id in query
     *
     * @param int
     * @return Eden\Eventbrite\Venue
     */
    public function setOrganizerId($organizerId)
    {
        //Argument 1 must be an int
        Argument::i()->test(1, 'int');

        $this->query['organizer_id'] = $organizerId;

        return $this;
    }

    /**
     * set name in query
     *
     * @param string
     * @return Eden\Eventbrite\Venue
     */
    public function setName($name)
    {
        //Argument 1 must be an string
        Argument::i()->test(1, 'string');

        $this->query['name'] = $name;

        return $this;
    }

    /**
     * set address in query
     *
     * @param string
     * @return Eden\Eventbrite\Venue
     */
    public function setAddress($address)
    {
        //Argument 1 must be an string
        Argument::i()->test(1, 'string');

        $this->query['address'] = $address;

        return $this;
    }

    /**
     * set address_2 in query
     *
     * @param string
     * @return Eden\Eventbrite\Venue
     */
    public function setAddress2($address2)
    {
        //Argument 1 must be an string
        Argument::i()->test(1, 'string');

        $this->query['address_2'] = $address2;

        return $this;
    }

    /**
     * set city in query
     *
     * @param string
     * @return Eden\Eventbrite\Venue
     */
    public function setCity($city)
    {
        //Argument 1 must be an string
        Argument::i()->test(1, 'string');

        $this->query['city'] = $city;

        return $this;
    }

    /**
     * set region in query
     *
     * @param string
     * @return Eden\Eventbrite\Venue
     */
    public function setRegion($region)
    {
        //Argument 1 must be an string
        Argument::i()->test(1, 'string');

        $this->query['region'] = $region;

        return $this;
    }

    /**
     * set postal code in query
     *
     * @param string
     * @return Eden\Eventbrite\Venue
     */
    public function setPostalCode($postalCode)
    {
        //Argument 1 must be an string
        Argument::i()->test(1, 'string');

        $this->query['postal_code'] = $postalCode;

        return $this;
    }

    /**
     * set country_code in query
     *
     * @param string
     * @return Eden\Eventbrite\Venue
     */
    public function setCountryCode($countryCode)
    {
        //Argument 1 must be an string
        Argument::i()->test(1, 'string');

        $this->query['country_code'] = $countryCode;

        return $this;
    }

    /**
     * Creates the venue
     *
     * @return array
     */
    public function create()
    {
        if (!isset($this->query['organizer_id'])) {
            Exception::i()
                ->setMessage(Exception::ORGANIZER_ORGANIZER_ID_NOT_SET)
                ->trigger();
        }

        if (!isset($this->query['name'])) {
            Exception::i()
                ->setMessage(Exception::ORGANIZER_NAME_NOT_SET)
                ->trigger();
        }

        if (!isset($this->query['country_code'])) {
            Exception::i()
                ->setMessage(Exception::ORGANIZER_COUNTRY_CODE_NOT_SET)
                ->trigger();
        }

        return $this->getJsonResponse(self::URL_NEW, $this->query);
    }

    /**
     * Updates the venue
     *
     * @return array
     */
    public function update()
    {
        if (!isset($this->query['id'])) {
            Exception::i()
                ->setMessage(Exception::ORGANIZER_ID_NOT_SET)
                ->trigger();
        }

        return $this->getJsonResponse(self::URL_UPDATE, $this->query);
    }
}


text:
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace ReVersion.Models
{
    public class BaseModel : INotifyPropertyChanged, IModel
    {
        #region Property Helpers

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = "")
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        #endregion
    }
}


text:
import binascii
from neo.Network.core.mixin import serializable
from typing import TYPE_CHECKING, Union

if TYPE_CHECKING:
    from neo.Network.core import BinaryReader
    from neo.Network.core.io.binary_writer import BinaryWriter

class UIntBase(serializable.SerializableMixin):
    _data = bytearray()
    _hash: int = 0

    def __init__(self, num_bytes: int, data: Union[bytes, bytearray] = None) -> None:
        super(UIntBase, self).__init__()

        if data is None:
            self._data = bytearray(num_bytes)

        else:
            if isinstance(data, bytes):
                # make sure it's mutable for string representation
                self._data = bytearray(data)
            elif isinstance(data, bytearray):
                self._data = data
            else:
                raise TypeError("Invalid data type {}. Expecting bytes or bytearray".format(type(data)))

            # now make sure we're working with raw bytes
            try:
                self._data = bytearray(binascii.unhexlify(self._data.decode()))
            except UnicodeDecodeError:
                # decode() fails most of the time if data is already in raw bytes. In that case there is nothing to be done.
                pass
            except binascii.Error:
                # however in some cases like bytes.fromhex('1122') decoding passes,
                # but binascii fails because it was actually already in rawbytes. Still nothing to be done.
                pass

            if len(self._data) != num_bytes:
                raise ValueError("Invalid UInt: data length {} != specified num_bytes {}".format(len(self._data), num_bytes))

        self._hash = self.get_hash_code()

    @property
    def size(self) -> int:
        """ Count of data bytes. """
        return len(self._data)

    def get_hash_code(self) -> int:
        """ Get a uint32 identifier. """
        slice_length = 4 if len(self._data) >= 4 else len(self._data)
        return int.from_bytes(self._data[:slice_length], 'little')

    def serialize(self, writer: 'BinaryWriter') -> None:
        """ Serialize object. """
        writer.write_bytes(self._data)

    def deserialize(self, reader: 'BinaryReader') -> None:
        """ Deserialize object. """
        self._data = reader.read_bytes(self.size)

    def to_array(self) -> bytearray:
        """ get the raw data. """
        return self._data

    def to_string(self) -> str:
        """ Convert the data to a human readable format (data is in reverse order). """
        db = bytearray(self._data)
        db.reverse()
        return db.hex()

    def __eq__(self, other) -> bool:
        if other is None:
            return False

        if not isinstance(other, UIntBase):
            return False

        if other is self:
            return True

        if self._data == other._data:
            return True

        return False

    def __hash__(self):
        return self._hash

    def __str__(self):
        return self.to_string()

    def _compare_to(self, other) -> int:
        if not isinstance(other, UIntBase):
            raise TypeError('Cannot compare %s to type %s' % (type(self).__name__, type(other).__name__))

        x = self.to_array()
        y = other.to_array()

        if len(x) != len(y):
            raise ValueError('Cannot compare %s with length %s to %s with length %s' % (type(self).__name__, len(x), type(other).__name__, len(y)))

        length = len(x)

        for i in range(length - 1, 0, -1):
            if x[i] > y[i]:
                return 1
            if x[i] < y[i]:
                return -1

        return 0

    def __lt__(self, other):
        return self._compare_to(other) < 0

    def __gt__(self, other):
        return self._compare_to(other) > 0

    def __le__(self, other):
        return self._compare_to(other) <= 0

    def __ge__(self, other):
        return self._compare_to(other) >= 0


text:
/* Manage javascript for expression administration
 * @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt  GNU/GPL License v2 or later
 */
$(document).ready(function(){
    // Tooltip inside em-var
    $(".em-expression").tooltip();
});
$(document).on('click','.em-expression a',function(e){
    e.preventDefault();
    window.open($(this).attr('href'));
});


text:
using System.Text.Json;
using System.Xml.Linq;
using Azure.Core;

namespace Azure.Data.Tables.Models
{
    public partial class TableServiceError
    {
        internal static TableServiceError DeserializeTableServiceError(JsonElement element)
        {
            string message = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("Message"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    message = property.Value.GetString();
                    continue;
                }
            }
            return new TableServiceError(message);
        }

        internal static TableServiceError DeserializeTableServiceError(XElement element)
        {
            string message = default;
            if (element.Element("Message") is XElement messageElement)
            {
                message = (string)messageElement;
            }
            return new TableServiceError(message);
        }
    }
}


text:
namespace _12.Google
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class StartUp
    {
        public static void Main(string[] args)
        {
            var persons = new List<Person>();
            var line = string.Empty;

            while ((line = Console.ReadLine()) != "End")
            {
                var lineTokens = line
                    .Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
                    .ToArray();

                var personName = lineTokens[0];

                if (persons.All(p => p.Name != personName))
                {
                    persons.Add(new Person(personName));
                }

                var currentPerson = persons
                    .FirstOrDefault(p => p.Name == personName);

                switch (lineTokens[1])
                {
                    case "company":
                        var companyName = lineTokens[2];
                        var department = lineTokens[3];
                        var salary = decimal.Parse(lineTokens[4]);
                        currentPerson.AddCompany(new Company(companyName, department, salary));
                        break;

                    case "pokemon":
                        var pokemonName = lineTokens[2];
                        var type = lineTokens[3];
                        currentPerson.AddPokemon(new Pokemon(pokemonName, type));
                        break;

                    case "parents":
                        var parentName = lineTokens[2];
                        var parentBirthday = lineTokens[3];
                        currentPerson.AddParent(new Parent(parentName, parentBirthday));
                        break;

                    case "children":
                        var childName = lineTokens[2];
                        var childBirthday = lineTokens[3];
                        currentPerson.AddChild(new Child(childName, childBirthday));
                        break;

                    case "car":
                        var model = lineTokens[2];
                        var speed = int.Parse(lineTokens[3]);
                        currentPerson.AddCar(new Car(model, speed));
                        break;
                }
            }

            var name = Console.ReadLine();
            var person = persons.FirstOrDefault(p => p.Name == name);
            Console.WriteLine(person.ToString());
        }
    }
}


text:
SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT")
EXECUTABLE=$(find $SCRIPTPATH/target/webserver.jar 2> /dev/null)

if [[ $? != 0 ]]; then
	echo "Executable not found :("
else
	echo "Executing $EXECUTABLE"
	java -jar $EXECUTABLE
fi


text:
"""This module provides maps and sets that report unused elements."""

_monitored_values = []

def FinishMonitoring(includeDart2jsOnly, logger):
    for value in _monitored_values:
        if value._dart2jsOnly and not includeDart2jsOnly:
            continue
        value.CheckUsage(logger)

class MonitoredCollection(object):

    def __init__(self, name, dart2jsOnly):
        self.name = name
        self._used_keys = set()
        self._dart2jsOnly = dart2jsOnly
        _monitored_values.append(self)

class Dict(MonitoredCollection):
    """Wrapper for a dict that reports unused keys."""

    def __init__(self, name, map, dart2jsOnly=False):
        super(Dict, self).__init__(name, dart2jsOnly)
        self._map = map

    def __getitem__(self, key):
        self._used_keys.add(key)
        return self._map[key]

    def __setitem__(self, key, value):
        self._map[key] = value

    def __contains__(self, key):
        self._used_keys.add(key)
        return key in self._map

    def __iter__(self):
        return self._map.__iter__()

    def get(self, key, default=None):
        self._used_keys.add(key)
        return self._map.get(key, default)

    def keys(self):
        return self._map.keys()

    def CheckUsage(self, logger):
        for v in sorted(self._map.keys()):
            if v not in self._used_keys:
                logger.warn(
                    'dict \'%s\' has unused key \'%s\'' % (self.name, v))

class Set(MonitoredCollection):
    """Wrapper for a set that reports unused keys."""

    def __init__(self, name, a_set, dart2jsOnly=False):
        super(Set, self).__init__(name, dart2jsOnly)
        self._set = a_set

    def __contains__(self, key):
        self._used_keys.add(key)
        return key in self._set

    def __iter__(self):
        return self._set.__iter__()

    def add(self, key):
        self._set += [key]

    def CheckUsage(self, logger):
        for v in sorted(self._set):
            if v not in self._used_keys:
                logger.warn('set \'%s\' has unused key \'%s\'' % (self.name, v))


text:
//  ColumbusWithDateISO.cs  (c) 2003 Kari Laitinen

//  http://www.naturalprogramming.com

//  2004-11-12  File created.
//  2004-11-12  Last modification.

//  Compilation: csc ColumbusWithDateISO.cs DateISO.cs

using System ;

class ColumbusWithDateISO
{
   static void Main()
   {
      DateISO date_of_discovery_of_america = new DateISO( "1492-10-12" ) ;

      DateISO date_of_first_moon_landing  =  new DateISO( "1969-7-20" ) ;

      Console.Write(
          "\n   Christopher Columbus discovered America on "
        +  date_of_discovery_of_america  +  "\n   That was a "
        +  date_of_discovery_of_america.get_day_of_week() ) ;

      Console.Write(
          "\n\n   Apollo 11 landed on the moon on "
        +  date_of_first_moon_landing  +  "\n   That was a "
        +  date_of_first_moon_landing.get_day_of_week() ) ;

      int  years_between, months_between, days_between ;

      date_of_discovery_of_america.get_distance_to(
                                    date_of_first_moon_landing,
                                    out years_between,
                                    out months_between,
                                    out days_between  ) ;

      Console.Write( "\n\n   America was discovered "
                  +  years_between   +  " years, "
                  +  months_between  +  " months, and "
                  +  days_between    +  " days"
                  +  "\n   before the first moon landing.\n" ) ;
   }
}


text:
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
                      _In_ wchar_t *command_line, _In_ int show_command) {
  // Attach to console when present (e.g., 'flutter run') or create a
  // new console when running with a debugger.
  if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
    CreateAndAttachConsole();
  }

  // Initialize COM, so that it is available for use in the library and/or
  // plugins.
  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

  flutter::DartProject project(L"data");

  std::vector<std::string> command_line_arguments =
      GetCommandLineArguments();

  project.set_dart_entrypoint_arguments(std::move(command_line_arguments));

  FlutterWindow window(project);
  Win32Window::Point origin(10, 10);
  Win32Window::Size size(1280, 720);
  if (!window.CreateAndShow(L"memory_leaks_images", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

  ::MSG msg;
  while (::GetMessage(&msg, nullptr, 0, 0)) {
    ::TranslateMessage(&msg);
    ::DispatchMessage(&msg);
  }

  ::CoUninitialize();
  return EXIT_SUCCESS;
}


text:
package com.java.mastery.lambda_expression.functional_interface;

import java.util.function.Function;

/**
 * Created by ANAN011 on 24/4/2017.
 *
 * @author Prajesh Ananthan, arvato Systems Malaysia Sdn Bhd
 */
public class FunctionTest1 {
  public static void main(String[] args) {
    System.out.println(getStringLengthWithFunction("claris"));
  }

  private static int getStringLengthWithFunction(String name) {
    Function<String, Integer> function = x -> x.length();
    return function.apply(name);
  }
}


text:
using System;

namespace Obvs.MessageDispatcher.Configuration
{
    public interface IMessageDispatcherConfigurationWithFactory<TMessage> : IMessageDispatcherConfiguration<TMessage>
        where TMessage : class
    {
        IObservable<MessageDispatchResult<TMessage>> DispatchMessages();
    }

    public interface IMessageDispatcherConfiguration<TMessage>
        where TMessage : class
    {
        IMessageDispatcherConfigurationWithFactory<TMessage> WithMessageHandlerSelectorFactory(Func<IMessageHandlerSelector> messageHandlerSelectorFactory);
    }

    internal class MessageDispatcherConfiguration<TMessage> : IMessageDispatcherConfigurationWithFactory<TMessage>
        where TMessage : class
    {
        private readonly IObservable<TMessage> _messages;
        private Func<IMessageHandlerSelector> _messageHandlerSelectorFactory;

        public MessageDispatcherConfiguration(IObservable<TMessage> messages)
        {
            if(messages == null) throw new ArgumentNullException(nameof(messages));

            _messages = messages;
        }

        public IObservable<TMessage> Messages => _messages;
        public Func<IMessageHandlerSelector> MessageHandlerSelectorFactory => _messageHandlerSelectorFactory;

        public IMessageDispatcherConfigurationWithFactory<TMessage> WithMessageHandlerSelectorFactory(Func<IMessageHandlerSelector> messageHandlerSelectorFactory)
        {
            if(messageHandlerSelectorFactory == null) throw new ArgumentNullException(nameof(messageHandlerSelectorFactory));

            _messageHandlerSelectorFactory = messageHandlerSelectorFactory;

            return this;
        }

        public IObservable<MessageDispatchResult<TMessage>> DispatchMessages() => new MessageDispatcher<TMessage>(_messages, _messageHandlerSelectorFactory);
    }

    public static class MessageDispatcherConfigurationWithFactoryExtensions
    {
        public static IDisposable DispatchMessages<TMessage>(this IMessageDispatcherConfigurationWithFactory<TMessage> messageDispatcherConfigurationWithFactory, Action<MessageDispatchResult<TMessage>> onNextMessageDispatchResult, Action<Exception> onError, Action onCompleted)
            where TMessage : class
        {
            return messageDispatcherConfigurationWithFactory.DispatchMessages().Subscribe(onNextMessageDispatchResult, onError, onCompleted);
        }

        public static IDisposable DispatchMessages<TMessage>(this IMessageDispatcherConfigurationWithFactory<TMessage> messageDispatcherConfigurationWithFactory, IObserver<MessageDispatchResult<TMessage>> observer)
            where TMessage : class
        {
            return messageDispatcherConfigurationWithFactory.DispatchMessages().Subscribe(observer);
        }
    }
}


text:
#ifndef ST_SCENE_H_
#define ST_SCENE_H_

typedef struct stscene stscene;

typedef void (*stscenef)(stscene*);

struct stscene {
	char *name;
	int statemax;
	int state;
	stscenef function;
	sslist link;
};

static inline stscene*
st_scene(char *name, stscenef function, int statemax)
{
	assert(statemax < 16); /* single id char */
	stscene *scene = malloc(sizeof(*scene));
	if (ssunlikely(scene == NULL))
		return NULL;
	scene->name = name;
	scene->state = 0;
	scene->statemax = statemax;
	scene->function = function;
	ss_listinit(&scene->link);
	return scene;
}

static inline void
st_scenefree(stscene *scene)
{
	free(scene);
}

#endif


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/t1SeqA2.dir/t1SeqA2.cpp.o"
  "../../../../bin/t1SeqA2.pdb"
  "../../../../bin/t1SeqA2"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/t1SeqA2.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
namespace REFileSystem
{
    partial class REFileExists
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.lpInput = new RE.RELinkPoint();
            this.lpExists = new RE.RELinkPoint();
            this.lpNotFound = new RE.RELinkPoint();
            this.panItemClient.SuspendLayout();
            this.SuspendLayout();
            //
            // panItemClient
            //
            this.panItemClient.Controls.Add(this.lpNotFound);
            this.panItemClient.Controls.Add(this.lpExists);
            this.panItemClient.Controls.Add(this.lpInput);
            this.panItemClient.Size = new System.Drawing.Size(227, 35);
            //
            // lpInput
            //
            this.lpInput.AllowDrop = true;
            this.lpInput.Caption = "input";
            this.lpInput.ConnectedTo = null;
            this.lpInput.ConnectionColor = System.Drawing.Color.Transparent;
            this.lpInput.Direction = RE.RELinkPointDirection.Input;
            this.lpInput.Key = "input";
            this.lpInput.Location = new System.Drawing.Point(10, 10);
            this.lpInput.Name = "lpInput";
            this.lpInput.Size = new System.Drawing.Size(65, 16);
            this.lpInput.TabIndex = 0;
            this.lpInput.Signal += new RE.RELinkPointSignal(this.lpInput_Signal);
            //
            // lpExists
            //
            this.lpExists.AllowDrop = true;
            this.lpExists.Caption = "exists";
            this.lpExists.ConnectedTo = null;
            this.lpExists.ConnectionColor = System.Drawing.Color.Transparent;
            this.lpExists.Direction = RE.RELinkPointDirection.Output;
            this.lpExists.Key = "exists";
            this.lpExists.Location = new System.Drawing.Point(81, 10);
            this.lpExists.Name = "lpExists";
            this.lpExists.Size = new System.Drawing.Size(65, 16);
            this.lpExists.TabIndex = 1;
            //
            // lpNotFound
            //
            this.lpNotFound.AllowDrop = true;
            this.lpNotFound.Caption = "not found";
            this.lpNotFound.ConnectedTo = null;
            this.lpNotFound.ConnectionColor = System.Drawing.Color.Transparent;
            this.lpNotFound.Direction = RE.RELinkPointDirection.Output;
            this.lpNotFound.Key = "notfound";
            this.lpNotFound.Location = new System.Drawing.Point(152, 10);
            this.lpNotFound.Name = "lpNotFound";
            this.lpNotFound.Size = new System.Drawing.Size(65, 16);
            this.lpNotFound.TabIndex = 2;
            //
            // REFileExists
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Caption = "File Exists";
            this.Name = "REFileExists";
            this.Resizable = false;
            this.Size = new System.Drawing.Size(234, 60);
            this.panItemClient.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private RE.RELinkPoint lpInput;
        private RE.RELinkPoint lpExists;
        private RE.RELinkPoint lpNotFound;
    }
}