text:
package it.polimi.dima.giftlist.presentation.view.fragment;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hannesdorfmann.fragmentargs.FragmentArgs;
import com.hannesdorfmann.mosby.mvp.MvpFragment;
import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.hannesdorfmann.mosby.mvp.MvpView;
import com.squareup.leakcanary.RefWatcher;

import org.greenrobot.eventbus.EventBus;

import javax.inject.Inject;

import butterknife.ButterKnife;
import icepick.Icepick;
import it.polimi.dima.giftlist.ApplicationComponent;
import it.polimi.dima.giftlist.GiftlistApplication;
import it.polimi.dima.giftlist.di.HasComponent;
import it.polimi.dima.giftlist.presentation.navigation.IntentStarter;

/**
 * Created by Elena on 11/08/2016.
 */
public abstract class BaseMvpFragment<V extends MvpView, P extends MvpPresenter<V>>
        extends MvpFragment <V, P> {

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FragmentArgs.inject(this);
    }

    @LayoutRes protected abstract int getLayoutRes();

    @Nullable @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        Icepick.restoreInstanceState(this, savedInstanceState);
        return inflater.inflate(getLayoutRes(), container, false);
    }

    @Override public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Icepick.saveInstanceState(this, outState);
    }

    @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        injectDependencies();
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);
    }

    @Override public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = GiftlistApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }

    abstract protected void injectDependencies();

    protected ApplicationComponent getApplicationComponent() {
        return ((GiftlistApplication) getActivity().getApplication()).getApplicationComponent();
    }

    /**
     * Gets a component for dependency injection by its type.
     * This pattern allows to avoid ugly casting in each fragment
     */
    @SuppressWarnings("unchecked")
    protected <C> C getComponent(Class<C> componentType) {
        return componentType.cast(((HasComponent<C>) getActivity()).getComponent());
    }

    protected void replaceFragment(int containerViewId, Fragment fragment) {
        FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(containerViewId, fragment);
        transaction.addToBackStack(null);
        // Commit the transaction
        transaction.commit();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.brackit.server.tx.log.impl;

import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import org.brackit.server.tx.log.Loggable;

/**
 * @author Ou Yi
 *
 */
public class SimpleLogBuffer implements LogBuffer {
	private Queue<Loggable> logEntries = new LinkedList<Loggable>();

	private int maxCapacity = 1024 * 2000;

	private int size = 0;

	private long lastFlushedLSN = -1;

	@Override
	public synchronized boolean add(Loggable loggable) {
		if (size + loggable.getSize() <= maxCapacity) {
			logEntries.add(loggable);
			size += loggable.getSize();
			return true;
		} else {
			return false;
		}
	}

	@Override
	public synchronized byte[] pollToFlush(long lsn) {
		if (lastFlushedLSN >= lsn) {
			return null;
		}

		List<Loggable> entriesToFlush = new LinkedList<Loggable>();
		int byteCount = 0;
		Loggable loggable = this.logEntries.poll();

		while (loggable != null) // && Loggable.getLSN() <= lsn)
		{
			entriesToFlush.add(loggable);
			byteCount += loggable.getSize() + Constants.FIELD_LENGTH_LEN;
			lastFlushedLSN = loggable.getLSN();

			loggable = logEntries.poll();
		}

		ByteBuffer bb = ByteBuffer.allocate(byteCount);

		for (Loggable entry : entriesToFlush) {
			byte[] bytes = entry.toBytes();

			if (entry.getSize() != bytes.length) {
				throw new RuntimeException(entry.toString());
			}

			bb.putInt(bytes.length);
			bb.put(bytes);
		}

		size = 0;
		return bb.array();
	}

	@Override
	public synchronized Loggable get(long lsn) {
		if (lsn >= lastFlushedLSN) {
			for (Loggable loggable : logEntries) {
				if (loggable.getLSN() == lsn) {
					return loggable;
				}
			}
		}

		return null;
	}
}


text:
Менеджер шаблонов
=================

## Настройка

Настройте репозиторий в DI контейнере

```php
// bootstrap.php

\Yii::$container->set(
    \ymaker\email\templates\repositories\EmailTemplatesRepositoryInterface::class,
    \ymaker\email\templates\repositories\EmailTemplatesRepository::class
);

// или config/main.php
`container` => [
    'singletons' => [
        // ...
        \ymaker\email\templates\repositories\EmailTemplatesRepositoryInterface::class =>
            \ymaker\email\templates\repositories\EmailTemplatesRepository::class,
    ],
],
```

## Использование

Вы можете брать данные для замены ключей в шаблоне из методов классов,
компонентов приложения, баз данных, виджетов и т.п.

### Пример письма

```
        {project-name}
Dear {username}, thank you for buying products on our shop!

Products you buying
{products-table}

For information about delivery you can {support-callcenter-link} or {support-email-link}.

{goodbye-message}
```

### Замена ключей данными

```php
// получение шаблона по ключу

/* @var string $productsTable HTML table of bought products */
$productsTable = \app\modules\shop\widgets\BoughtProductsTable::widget([
    'buyerId' => Yii::$app->getUser()->id,
]);

/* @var \app\components\Configuration $config Component with configuration from dashboard */
$config = Yii::$app->get('config');

$supportCallcenterLink = \yii\helpers\Html::a(
    \Yii::t('shop', 'call to us'),
    $config->supportCallcenterNumber
);
$supportEmailLink = \yii\helpers\Html::a(
    \Yii::t('shop', 'write to e-mail'),
    $config->supportEmailAddress
);

$template->parseBody([
    'project-name'              => \Yii::$app->name,
    'username'                  => \Yii::$app->getIdentity()->firstname,
    'products-table'            => $productsTable,
    'support-callcenter-link'   => $supportCallcenterLink,
    'support-email-link'        => $supportEmailLink,
    'goodbye-message'           => \app\bots\EmailBot::generateGoodbyeMessage(),
]);
```

## Методы менеджера шаблонов

| Метод                                     | Описание                                                                      | Возвращает                        |
|-------------------------------------------|-------------------------------------------------------------------------------|-----------------------------------|
|`getTemplate($key, $language = null)`      |возвращает шаблон по ключу и языку                                             |`null` или `EmailTemplateModel`    |
|`getAllTemplates($key)`                    |возвращает шаблоны на все языках                                               |`null` или `EmailTemplateModel[]`  |
|`getFirstOrDefault($key, $default = null)` |возбращает либо шаблон на первом попавшимся языке либо стандартное значение    |`mixed`                            |
|`hasTemplate($key)`                        |проверяет существует ли шаблон с заданым ключём                                |`bool`                             |


text:
import logging

from allura import model as M

log = logging.getLogger(__name__)

def main():
    M.Mailbox.query.update({'queue': []},
                           {'$set': {'queue_empty': True}},
                           multi=True)

    M.Mailbox.query.update({'queue': {'$ne': []}},
                           {'$set': {'queue_empty': False}},
                           multi=True)

if __name__ == '__main__':
    main()


text:
"""Bag distance measure"""

from __future__ import division
import collections

from py_stringmatching import utils
from py_stringmatching.similarity_measure.sequence_similarity_measure import \
                                                    SequenceSimilarityMeasure

class BagDistance(SequenceSimilarityMeasure):
    """Bag distance measure class.
    """
    def __init__(self):
        super(BagDistance, self).__init__()

    def get_raw_score(self, string1, string2):
        """
        Computes the bag distance between two strings.

        For two strings X and Y, the Bag distance is:
        :math:`max( |bag(string1)-bag(string2)|, |bag(string2)-bag(string1)| )`

        Args:
            string1,string2 (str): Input strings

        Returns:
            Bag distance (int)

        Raises:
            TypeError : If the inputs are not strings

        Examples:
            >>> bd = BagDistance()
            >>> bd.get_raw_score('cat', 'hat')
            1
            >>> bd.get_raw_score('Niall', 'Neil')
            2
            >>> bd.get_raw_score('aluminum', 'Catalan')
            5
            >>> bd.get_raw_score('ATCG', 'TAGC')
            0
            >>> bd.get_raw_score('abcde', 'xyz')
            5

        References:
            * http://www.icmlc.org/icmlc2011/018_icmlc2011.pdf
        """
        # input validations
        utils.sim_check_for_none(string1, string2)
        utils.sim_check_for_string_inputs(string1, string2)
        if utils.sim_check_for_exact_match(string1, string2):
            return 0

        len_str1 = len(string1)
        len_str2 = len(string2)

        if len_str1 == 0:
            return len_str2

        if len_str2 == 0:
            return len_str1

        bag1 = collections.Counter(string1)
        bag2 = collections.Counter(string2)

        size1 = sum((bag1 - bag2).values())
        size2 = sum((bag2 - bag1).values())

        # returning the max of difference of sets
        return max(size1, size2)

    def get_sim_score(self, string1, string2):
        """
        Computes the normalized bag similarity between two strings.

        Args:
            string1,string2 (str): Input strings

        Returns:
            Normalized bag similarity (float)

        Raises:
            TypeError : If the inputs are not strings

        Examples:
            >>> bd = BagDistance()
            >>> bd.get_sim_score('cat', 'hat')
            0.6666666666666667
            >>> bd.get_sim_score('Niall', 'Neil')
            0.6
            >>> bd.get_sim_score('aluminum', 'Catalan')
            0.375
            >>> bd.get_sim_score('ATCG', 'TAGC')
            1.0
            >>> bd.get_sim_score('abcde', 'xyz')
            0.0

        References:
            * http://www.icmlc.org/icmlc2011/018_icmlc2011.pdf
        """
        raw_score = self.get_raw_score(string1, string2)
        string1_len = len(string1)
        string2_len = len(string2)
        if string1_len == 0 and string2_len == 0:
            return 1.0
        return 1 - (raw_score / max(string1_len, string2_len))


text:
package services_test

import (
	"context"
	"errors"
	"fmt"
	"testing"

	dpb "google.golang.org/protobuf/types/known/durationpb"
	spb "google.golang.org/protobuf/types/known/structpb"
	tpb "google.golang.org/protobuf/types/known/timestamppb"
	wpb "google.golang.org/protobuf/types/known/wrapperspb"
	"github.com/google/go-cmp/cmp"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/testing/protocmp"
	"github.com/google/tink/go/aead"
	"github.com/google/tink/go/jwt"
	"github.com/google/tink/go/signature"
	"github.com/google/tink/testing/go/services"
	pb "github.com/google/tink/testing/go/proto/testing_api_go_grpc"
)

func verifiedJWTFromResponse(response *pb.JwtVerifyResponse) (*pb.JwtToken, error) {
	switch r := response.Result.(type) {
	case *pb.JwtVerifyResponse_VerifiedJwt:
		return r.VerifiedJwt, nil
	case *pb.JwtVerifyResponse_Err:
		return nil, errors.New(r.Err)
	default:
		return nil, fmt.Errorf("response.Result has unexpected type %T", r)
	}
}

func signedCompactJWTFromResponse(response *pb.JwtSignResponse) (string, error) {
	switch r := response.Result.(type) {
	case *pb.JwtSignResponse_SignedCompactJwt:
		return r.SignedCompactJwt, nil
	case *pb.JwtSignResponse_Err:
		return "", errors.New(r.Err)
	default:
		return "", fmt.Errorf("response.Result has unexpected type %T", r)
	}
}

func jwkSetFromResponse(response *pb.JwtToJwkSetResponse) (string, error) {
	switch r := response.Result.(type) {
	case *pb.JwtToJwkSetResponse_JwkSet:
		return r.JwkSet, nil
	case *pb.JwtToJwkSetResponse_Err:
		return "", errors.New(r.Err)
	default:
		return "", fmt.Errorf("response.Result has unexpected type %T", r)
	}
}

func keysetFromResponse(response *pb.JwtFromJwkSetResponse) ([]byte, error) {
	switch r := response.Result.(type) {
	case *pb.JwtFromJwkSetResponse_Keyset:
		return r.Keyset, nil
	case *pb.JwtFromJwkSetResponse_Err:
		return nil, errors.New(r.Err)
	default:
		return nil, fmt.Errorf("response.Result has unexpected type %T", r)
	}
}

type jwtTestCase struct {
	tag       string
	rawJWT    *pb.JwtToken
	validator *pb.JwtValidator
}

func TestJWTComputeInvalidJWT(t *testing.T) {
	for _, tc := range []jwtTestCase{
		{
			tag:    "nil rawJWT",
			rawJWT: nil,
		},
		{
			tag: "invalid json array string",
			rawJWT: &pb.JwtToken{
				CustomClaims: map[string]*pb.JwtClaimValue{
					"cc-array": &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_JsonArrayValue{JsonArrayValue: "{35}"}},
				},
			},
		},
		{
			tag: "invalid json object string",
			rawJWT: &pb.JwtToken{
				CustomClaims: map[string]*pb.JwtClaimValue{
					"cc-object": &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_JsonObjectValue{JsonObjectValue: `["o":"a"]`}},
				},
			},
		},
	} {
		t.Run(tc.tag, func(t *testing.T) {
			keysetService := &services.KeysetService{}
			jwtService := &services.JWTService{}
			ctx := context.Background()
			template, err := proto.Marshal(jwt.HS256Template())
			if err != nil {
				t.Fatalf("proto.Marshal(jwt.HS256Template()) failed: %v", err)
			}
			keyset, err := genKeyset(ctx, keysetService, template)
			if err != nil {
				t.Fatalf("genKeyset failed: %v", err)
			}
			signResponse, err := jwtService.ComputeMacAndEncode(ctx, &pb.JwtSignRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: keyset}, RawJwt: tc.rawJWT})
			if err != nil {
				t.Fatalf("jwtService.ComputeMacAndEncode() err = %v, want nil", err)
			}
			if _, err := signedCompactJWTFromResponse(signResponse); err == nil {
				t.Fatalf("JwtSignResponse: error = nil, want error")
			}
		})
	}
}

func TestSuccessfulJwtMacCreation(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}
	ctx := context.Background()

	template, err := proto.Marshal(jwt.HS256Template())
	if err != nil {
		t.Fatalf("proto.Marshal(jwt.HS256Template()) failed: %v, want nil", err)
	}

	keyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}

	result, err := jwtService.CreateJwtMac(ctx, &pb.CreationRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: keyset}})
	if err != nil {
		t.Fatalf("CreateJwtMac with good keyset failed with gRPC error: %v, want nil", err)
	}
	if result.GetErr() != "" {
		t.Fatalf("CreateJwtMac with good keyset failed with result.GetErr() = %q, want empty string", result.GetErr())
	}
}

func TestFailingJwtMacCreation(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}
	ctx := context.Background()

	// We use signature keys -- then we cannot create a JwtMac
	template, err := proto.Marshal(aead.AES128GCMKeyTemplate())
	if err != nil {
		t.Fatalf("proto.Marshal(signature.ECDSAP256KeyTemplate()) failed: %v", err)
	}

	badKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}

	result, err := jwtService.CreateJwtMac(ctx, &pb.CreationRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: badKeyset}})
	if err != nil {
		t.Fatalf("CreateJwtMac with bad keyset failed with gRPC error: %v", err)
	}
	if result.GetErr() == "" {
		t.Fatalf("result.GetErr() of bad keyset after CreateJwtMac is empty, want not empty")
	}
}

func TestJWTComputeMACWithInvalidKeysetFails(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}
	ctx := context.Background()
	template, err := proto.Marshal(aead.AES256GCMKeyTemplate())
	if err != nil {
		t.Fatalf("proto.Marshal(jwt.AES256GCMKeyTemplate()) failed: %v", err)
	}
	keyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}
	rawJWT := &pb.JwtToken{
		TypeHeader: &wpb.StringValue{Value: "JWT"},
		Issuer:     &wpb.StringValue{Value: "issuer"},
	}
	signResponse, err := jwtService.ComputeMacAndEncode(ctx, &pb.JwtSignRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: keyset}, RawJwt: rawJWT})
	if err != nil {
		t.Fatalf("jwtService.ComputeMacAndEncode() err = %v, want nil", err)
	}
	if _, err := signedCompactJWTFromResponse(signResponse); err == nil {
		t.Fatalf("JwtSignResponse: error = nil, want error")
	}
}

func TestJWTComputeAndVerifyMac(t *testing.T) {
	for _, tc := range []jwtTestCase{
		{
			tag: "all claims and custom claims",
			rawJWT: &pb.JwtToken{
				TypeHeader: &wpb.StringValue{Value: "JWT"},
				Issuer:     &wpb.StringValue{Value: "issuer"},
				Subject:    &wpb.StringValue{Value: "subject"},
				JwtId:      &wpb.StringValue{Value: "tink"},
				Audiences:  []string{"audience"},
				Expiration: &tpb.Timestamp{Seconds: 123456},
				NotBefore:  &tpb.Timestamp{Seconds: 12345},
				IssuedAt:   &tpb.Timestamp{Seconds: 1234},
				CustomClaims: map[string]*pb.JwtClaimValue{
					"cc-null":   &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_NullValue{}},
					"cc-num":    &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_NumberValue{NumberValue: 5.67}},
					"cc-bool":   &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_BoolValue{BoolValue: true}},
					"cc-string": &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_StringValue{StringValue: "foo bar"}},
					"cc-array":  &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_JsonArrayValue{JsonArrayValue: "[35]"}},
					"cc-object": &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_JsonObjectValue{JsonObjectValue: `{"key":"val"}`}},
				},
			},
			validator: &pb.JwtValidator{
				ExpectedTypeHeader: &wpb.StringValue{Value: "JWT"},
				ExpectedIssuer:     &wpb.StringValue{Value: "issuer"},
				ExpectedAudience:   &wpb.StringValue{Value: "audience"},
				Now:                &tpb.Timestamp{Seconds: 12345},
				ClockSkew:          &dpb.Duration{Seconds: 0},
			},
		},
		{
			tag: "without custom claims",
			rawJWT: &pb.JwtToken{
				TypeHeader: &wpb.StringValue{Value: "JWT"},
				Issuer:     &wpb.StringValue{Value: "issuer"},
				Subject:    &wpb.StringValue{Value: "subject"},
				Audiences:  []string{"audience"},
			},
			validator: &pb.JwtValidator{
				ExpectedTypeHeader:     &wpb.StringValue{Value: "JWT"},
				ExpectedIssuer:         &wpb.StringValue{Value: "issuer"},
				ExpectedAudience:       &wpb.StringValue{Value: "audience"},
				AllowMissingExpiration: true,
			},
		},
		{
			tag: "without expiration",
			rawJWT: &pb.JwtToken{
				Subject: &wpb.StringValue{Value: "subject"},
			},
			validator: &pb.JwtValidator{
				AllowMissingExpiration: true,
			},
		},
		{
			tag: "clock skew",
			rawJWT: &pb.JwtToken{
				Expiration: &tpb.Timestamp{Seconds: 1234},
			},
			validator: &pb.JwtValidator{
				Now:       &tpb.Timestamp{Seconds: 1235},
				ClockSkew: &dpb.Duration{Seconds: 2},
			},
		},
	} {
		t.Run(tc.tag, func(t *testing.T) {
			keysetService := &services.KeysetService{}
			jwtService := &services.JWTService{}
			ctx := context.Background()
			template, err := proto.Marshal(jwt.HS256Template())
			if err != nil {
				t.Fatalf("proto.Marshal(jwt.HS256Template()) failed: %v", err)
			}
			keyset, err := genKeyset(ctx, keysetService, template)
			if err != nil {
				t.Fatalf("genKeyset failed: %v", err)
			}

			signResponse, err := jwtService.ComputeMacAndEncode(ctx, &pb.JwtSignRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: keyset}, RawJwt: tc.rawJWT})
			if err != nil {
				t.Fatalf("jwtService.ComputeMacAndEncode() err = %v, want nil", err)
			}
			compact, err := signedCompactJWTFromResponse(signResponse)
			if err != nil {
				t.Fatalf("JwtSignResponse_Err: %v", err)
			}
			verifyResponse, err := jwtService.VerifyMacAndDecode(ctx, &pb.JwtVerifyRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: keyset}, SignedCompactJwt: compact, Validator: tc.validator})
			if err != nil {
				t.Fatalf("jwtService.VerifyMacAndDecode() err = %v, want nil", err)
			}
			verifiedJWT, err := verifiedJWTFromResponse(verifyResponse)
			if err != nil {
				t.Fatalf("JwtVerifyResponse_Err: %v", err)
			}
			if !cmp.Equal(verifiedJWT, tc.rawJWT, protocmp.Transform()) {
				t.Errorf("verifiedJWT doesn't match expected value: (+ got, - want) %v", cmp.Diff(verifiedJWT, tc.rawJWT, protocmp.Transform()))
			}
		})
	}
}

func TestJWTVerifyMACFailures(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}
	ctx := context.Background()
	template, err := proto.Marshal(jwt.HS256Template())
	if err != nil {
		t.Fatalf("proto.Marshal(jwt.HS256Template()) failed: %v", err)
	}
	keyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}
	rawJWT := &pb.JwtToken{
		TypeHeader: &wpb.StringValue{Value: "JWT"},
		Expiration: &tpb.Timestamp{Seconds: 123456},
		NotBefore:  &tpb.Timestamp{Seconds: 12345},
		IssuedAt:   &tpb.Timestamp{Seconds: 1234},
	}
	signResponse, err := jwtService.ComputeMacAndEncode(ctx, &pb.JwtSignRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: keyset}, RawJwt: rawJWT})
	if err != nil {
		t.Fatalf("jwtService.ComputeMacAndEncode() err = %v, want nil", err)
	}
	compact, err := signedCompactJWTFromResponse(signResponse)
	if err != nil {
		t.Fatalf("JwtSignResponse_Err: %v", err)
	}
	validator := &pb.JwtValidator{
		ExpectedTypeHeader: &wpb.StringValue{Value: "JWT"},
		Now:                &tpb.Timestamp{Seconds: 12345},
	}
	verifyResponse, err := jwtService.VerifyMacAndDecode(ctx, &pb.JwtVerifyRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: keyset}, SignedCompactJwt: compact, Validator: validator})
	if err != nil {
		t.Fatalf("jwtService.VerifyMacAndDecode() err = %v, want nil", err)
	}
	if _, err := verifiedJWTFromResponse(verifyResponse); err != nil {
		t.Fatalf("JwtVerifyResponse_Err: %v", err)
	}
	for _, tc := range []jwtTestCase{
		{
			tag: "unexpected type header",
			validator: &pb.JwtValidator{
				ExpectedTypeHeader: &wpb.StringValue{Value: "unexpected"},
				Now:                &tpb.Timestamp{Seconds: 12345},
			},
		},
		{
			tag: "expired token",
			validator: &pb.JwtValidator{
				ExpectedTypeHeader: &wpb.StringValue{Value: "JWT"},
				Now:                &tpb.Timestamp{Seconds: 999999999999},
			},
		},
		{
			tag: "expect issued in the past",
			validator: &pb.JwtValidator{
				ExpectedTypeHeader:    &wpb.StringValue{Value: "JWT"},
				Now:                   &tpb.Timestamp{Seconds: 1233},
				ExpectIssuedInThePast: true,
			},
		},
	} {
		t.Run(tc.tag, func(t *testing.T) {
			verifyResponse, err := jwtService.VerifyMacAndDecode(ctx, &pb.JwtVerifyRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: keyset}, SignedCompactJwt: compact, Validator: tc.validator})
			if err != nil {
				t.Fatalf("jwtService.VerifyMacAndDecode() err = %v, want nil", err)
			}
			if _, err := verifiedJWTFromResponse(verifyResponse); err == nil {
				t.Fatalf("JwtVerifyResponse_Err: nil, want error")
			}
		})
	}
}

func TestSuccessfulJwtSignVerifyCreation(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}
	ctx := context.Background()

	template, err := proto.Marshal(jwt.ES256Template())
	if err != nil {
		t.Fatalf("proto.Marshal(hybrid.ES256Template()) failed: %v", err)
	}

	privateKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}

	result, err := jwtService.CreateJwtPublicKeySign(ctx, &pb.CreationRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: privateKeyset}})
	if err != nil {
		t.Fatalf("CreateJwtPublicKeySign with good keyset failed with gRPC error: %v, want nil", err)
	}
	if result.GetErr() != "" {
		t.Fatalf("CreateJwtPublicKeySign with good keyset failed with result.GetErr() = %q, want empty string", result.GetErr())
	}
}

func TestSuccessfulJwtVerifyCreation(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}
	ctx := context.Background()

	template, err := proto.Marshal(jwt.ES256Template())
	if err != nil {
		t.Fatalf("proto.Marshal(hybrid.ES256Template()) failed: %v", err)
	}

	privateKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}
	publicKeyset, err := pubKeyset(ctx, keysetService, privateKeyset)
	if err != nil {
		t.Fatalf("pubKeyset failed: %v", err)
	}

	result, err := jwtService.CreateJwtPublicKeyVerify(ctx, &pb.CreationRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: publicKeyset}})
	if err != nil {
		t.Fatalf("CreateJwtPublicKeyVerify with good keyset failed with gRPC error: %v", err)
	}
	if result.GetErr() != "" {
		t.Fatalf("CreateJwtPublicKeyVerify with good keyset failed with result.GetErr() = %q, want empty string", result.GetErr())
	}
}

func TestFailingJwtSignCreation(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}
	ctx := context.Background()

	// We use signature keys -- then we cannot create a hybrid encrypt
	template, err := proto.Marshal(signature.ECDSAP256KeyTemplate())
	if err != nil {
		t.Fatalf("proto.Marshal(signature.ECDSAP256KeyTemplate()) failed: %v", err)
	}

	privateKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}

	result, err := jwtService.CreateJwtPublicKeySign(ctx, &pb.CreationRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: privateKeyset}})
	if err != nil {
		t.Fatalf("CreateJwtPublicKeySign with bad keyset failed with gRPC error: %v", err)
	}
	if result.GetErr() == "" {
		t.Fatalf("CreateJwtPublicKeySign with bad keyset succeeded")
	}
}

func TestFailingJwtVerifyCreation(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}
	ctx := context.Background()

	// We use signature keys -- then we cannot create a hybrid encrypt
	template, err := proto.Marshal(signature.ECDSAP256KeyTemplate())
	if err != nil {
		t.Fatalf("proto.Marshal(signature.ECDSAP256KeyTemplate()) failed: %v", err)
	}

	privateKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}
	publicKeyset, err := pubKeyset(ctx, keysetService, privateKeyset)
	if err != nil {
		t.Fatalf("pubKeyset failed: %v", err)
	}

	result, err := jwtService.CreateJwtPublicKeyVerify(ctx, &pb.CreationRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: publicKeyset}})
	if err != nil {
		t.Fatalf("CreateJwtPublicKeyVerify with good keyset failed with gRPC error: %v", err)
	}
	if result.GetErr() == "" {
		t.Fatalf("CreateJwtPublicKeyVerify with bad keyset succeeded")
	}
}

func TestJWTPublicKeySignWithInvalidKeysetFails(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}

	ctx := context.Background()
	template, err := proto.Marshal(aead.AES256GCMKeyTemplate())
	if err != nil {
		t.Fatalf("proto.Marshal(aead.AES256GCMKeyTemplate()) failed: %v", err)
	}
	privateKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}
	rawJWT := &pb.JwtToken{
		Subject: &wpb.StringValue{Value: "tink-subject"},
	}
	signResponse, err := jwtService.PublicKeySignAndEncode(ctx, &pb.JwtSignRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: privateKeyset}, RawJwt: rawJWT})
	if err != nil {
		t.Fatalf("jwtService.PublicKeySignAndEncode() err = %v", err)
	}
	if _, err := signedCompactJWTFromResponse(signResponse); err == nil {
		t.Fatalf("JwtSignResponse_Err: nil want error")
	}
}

func TestJWTPublicKeySignInvalidTokenFails(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}

	ctx := context.Background()
	template, err := proto.Marshal(jwt.ES256Template())
	if err != nil {
		t.Fatalf("proto.Marshal(jwt.ES256Template()) failed: %v", err)
	}
	privateKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}
	for _, tc := range []jwtTestCase{
		{
			tag:    "nil rawJWT",
			rawJWT: nil,
		},
		{
			tag: "invalid json array string",
			rawJWT: &pb.JwtToken{
				CustomClaims: map[string]*pb.JwtClaimValue{
					"cc-array": &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_JsonArrayValue{JsonArrayValue: "{35}"}},
				},
			},
		},
		{
			tag: "invalid json object string",
			rawJWT: &pb.JwtToken{
				CustomClaims: map[string]*pb.JwtClaimValue{
					"cc-object": &pb.JwtClaimValue{Kind: &pb.JwtClaimValue_JsonObjectValue{JsonObjectValue: `["o":"a"]`}},
				},
			},
		},
	} {
		t.Run(tc.tag, func(t *testing.T) {
			signResponse, err := jwtService.PublicKeySignAndEncode(ctx, &pb.JwtSignRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: privateKeyset}, RawJwt: tc.rawJWT})
			if err != nil {
				t.Fatalf("jwtService.PublicKeySignAndEncode() err = %v", err)
			}
			if _, err := signedCompactJWTFromResponse(signResponse); err == nil {
				t.Fatalf("JwtSignResponse_Err: nil want error")
			}
		})
	}
}

func TestJWTPublicKeyVerifyFails(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}

	ctx := context.Background()
	template, err := proto.Marshal(jwt.ES256Template())
	if err != nil {
		t.Fatalf("proto.Marshal(jwt.ES256Template()) failed: %v", err)
	}
	privateKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}
	publicKeyset, err := pubKeyset(ctx, keysetService, privateKeyset)
	if err != nil {
		t.Fatalf("pubKeyset failed: %v", err)
	}
	rawJWT := &pb.JwtToken{
		Subject: &wpb.StringValue{Value: "tink-subject"},
	}
	signResponse, err := jwtService.PublicKeySignAndEncode(ctx, &pb.JwtSignRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: privateKeyset}, RawJwt: rawJWT})
	if err != nil {
		t.Fatalf("jwtService.PublicKeySignAndEncode() err = %v", err)
	}
	compact, err := signedCompactJWTFromResponse(signResponse)
	if err != nil {
		t.Fatalf("JwtSignResponse_Err failed: %v", err)
	}
	validator := &pb.JwtValidator{
		ExpectedTypeHeader: &wpb.StringValue{Value: "JWT"},
	}
	verifyResponse, err := jwtService.PublicKeyVerifyAndDecode(ctx, &pb.JwtVerifyRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: publicKeyset}, SignedCompactJwt: compact, Validator: validator})
	if err != nil {
		t.Fatalf("jwtVerifySignature failed: %v", err)
	}
	if _, err := verifiedJWTFromResponse(verifyResponse); err == nil {
		t.Fatalf("JwtVerifyResponse_Err: nil want error")
	}
}

func TestJWTPublicKeySignAndEncodeVerifyAndDecode(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}

	ctx := context.Background()
	template, err := proto.Marshal(jwt.ES256Template())
	if err != nil {
		t.Fatalf("proto.Marshal(jwt.ES256Template()) failed: %v", err)
	}
	privateKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}
	publicKeyset, err := pubKeyset(ctx, keysetService, privateKeyset)
	if err != nil {
		t.Fatalf("pubKeyset failed: %v", err)
	}
	rawJWT := &pb.JwtToken{
		Subject: &wpb.StringValue{Value: "tink-subject"},
	}
	signResponse, err := jwtService.PublicKeySignAndEncode(ctx, &pb.JwtSignRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: privateKeyset}, RawJwt: rawJWT})
	if err != nil {
		t.Fatalf("jwtService.PublicKeySignAndEncode() err = %v", err)
	}
	compact, err := signedCompactJWTFromResponse(signResponse)
	if err != nil {
		t.Fatalf("JwtSignResponse_Err failed: %v", err)
	}
	validator := &pb.JwtValidator{
		AllowMissingExpiration: true,
	}
	verifyResponse, err := jwtService.PublicKeyVerifyAndDecode(ctx, &pb.JwtVerifyRequest{AnnotatedKeyset: &pb.AnnotatedKeyset{SerializedKeyset: publicKeyset}, SignedCompactJwt: compact, Validator: validator})
	if err != nil {
		t.Fatalf("jwtVerifySignature failed: %v", err)
	}
	verifiedJWT, err := verifiedJWTFromResponse(verifyResponse)
	if err != nil {
		t.Fatalf("JwtVerifyResponse_Err: %v", err)
	}
	if !cmp.Equal(verifiedJWT, rawJWT, protocmp.Transform()) {
		t.Errorf("verifiedJWT doesn't match expected value: (+ got, - want) %v", cmp.Diff(verifiedJWT, rawJWT, protocmp.Transform()))
	}
}

func TestToJwkSetWithPrivateKeyFails(t *testing.T) {
	keysetService := &services.KeysetService{}
	jwtService := &services.JWTService{}

	ctx := context.Background()
	template, err := proto.Marshal(jwt.ES256Template())
	if err != nil {
		t.Fatalf("proto.Marshal(jwt.ES256Template()) failed: %v", err)
	}
	privateKeyset, err := genKeyset(ctx, keysetService, template)
	if err != nil {
		t.Fatalf("genKeyset failed: %v", err)
	}
	toJWKResponse, err := jwtService.ToJwkSet(ctx, &pb.JwtToJwkSetRequest{Keyset: privateKeyset})
	if err != nil {
		t.Fatalf("jwtService.ToJwkSet() err = %v, want nil", err)
	}
	if _, err := jwkSetFromResponse(toJWKResponse); err == nil {
		t.Fatalf("JwtToJwkSetResponse_Err: = nil, want error")
	}
}

func TestFromJwkSetPrivateKeyFails(t *testing.T) {
	jwtService := &services.JWTService{}
	ctx := context.Background()
	jwkES256PublicKey := `{
	  "keys":[{
	  "kty":"EC",
	  "crv":"P-256",
	  "x":"wO6uIxh8SkKOO8VjZXNRTteRcwCPE4_4JElKyaa0fcQ",
	  "y":"7oRiYhnmkP6nqrdXWgtsWUWq5uFRLJkhyVFiWPRB278",
		"d":"8oRinhnmkYjkqrdXWgtsWUWq5uFRLJkhyVFiWPRB278",
	  "use":"sig","alg":"ES256","key_ops":["verify"],
	  "kid":"EhuduQ"}]
	}`
	fromJWKResponse, err := jwtService.FromJwkSet(ctx, &pb.JwtFromJwkSetRequest{JwkSet: jwkES256PublicKey})
	if err != nil {
		t.Fatalf("jwtService.FromJwkSet() err = %v, want nil", err)
	}
	if _, err := keysetFromResponse(fromJWKResponse); err == nil {
		t.Fatalf("JwtFromJwkSetResponse_Err = nil, want error")
	}
}

func TestFromJwkToJwkSet(t *testing.T) {
	jwtService := &services.JWTService{}
	ctx := context.Background()
	jwkES256PublicKey := `{
	  "keys":[{
	  "kty":"EC",
	  "crv":"P-256",
	  "x":"wO6uIxh8SkKOO8VjZXNRTteRcwCPE4_4JElKyaa0fcQ",
	  "y":"7oRiYhnmkP6nqrdXWgtsWUWq5uFRLJkhyVFiWPRB278",
	  "use":"sig","alg":"ES256","key_ops":["verify"],
	  "kid":"EhuduQ"}]
	}`
	fromJWKResponse, err := jwtService.FromJwkSet(ctx, &pb.JwtFromJwkSetRequest{JwkSet: jwkES256PublicKey})
	if err != nil {
		t.Fatalf("jwtService.FromJwkSet() err = %v, want nil", err)
	}
	ks, err := keysetFromResponse(fromJWKResponse)
	if err != nil {
		t.Fatalf("JwtFromJwkSetResponse_Err: = %v, want nil", err)
	}
	toJWKResponse, err := jwtService.ToJwkSet(ctx, &pb.JwtToJwkSetRequest{Keyset: ks})
	if err != nil {
		t.Fatalf("jwtService.ToJwkSet() err = %v, want nil", err)
	}
	jwkSet, err := jwkSetFromResponse(toJWKResponse)
	if err != nil {
		t.Fatalf("JwtToJwkSetResponse_Err: = %v, want nil", err)
	}
	got := &spb.Struct{}
	if err := got.UnmarshalJSON([]byte(jwkSet)); err != nil {
		t.Fatalf("got.UnmarshalJSON() err = %v, want nil", err)
	}
	want := &spb.Struct{}
	if err := want.UnmarshalJSON([]byte(jwkES256PublicKey)); err != nil {
		t.Fatalf("want.UnmarshalJSON() err = %v, want nil", err)
	}
	if !cmp.Equal(want, got, protocmp.Transform()) {
		t.Errorf("mismatch in jwk sets: diff (-want,+got): %v", cmp.Diff(want, got, protocmp.Transform()))
	}
}


text:
import click
from arrow.cli import pass_context
from arrow.decorators import custom_exception, dict_output

@click.command('addComment')
@click.argument("comment")
@click.option(
    "--metadata",
    help=""
)
@pass_context
@custom_exception
@dict_output
def cli(ctx, comment, metadata=""):
    """TODO: Undocumented

Output:

    ???
    """
    return ctx.gi.cannedcomments.addComment(comment, metadata=metadata)


text:
package main.browser.database;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import main.browser.Browser;
import main.sonogram.Sonogram;
import main.sonogram.Sonogram.EnumSonogramQuality;

public class SonogramReviewPanel extends JPanel {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private final DatabaseCard databaseCard;
	private final JList<Sonogram> sonogramReviewList;
	private final SonogramReviewListener sonogramReviewListener;
	private final ButtonBar buttonBar;
	private final JButton doneButton;
	private Sonogram previousSonogram;

	public SonogramReviewPanel(DatabaseCard dbc) {
		super();
		databaseCard = dbc;
		sonogramReviewListener = new SonogramReviewListener();
		sonogramReviewList = new JList<Sonogram>();
		sonogramReviewList.addListSelectionListener(sonogramReviewListener);
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		add(Browser.reviewSonogramsLabel);
        JScrollPane listScrollPane = new JScrollPane(sonogramReviewList);
        add(listScrollPane);
        add(buttonBar = new ButtonBar());
		doneButton = new JButton("Done");
		doneButton.setActionCommand("done");
		doneButton.addActionListener(sonogramReviewListener);;
		add(doneButton);
	}

	public void setupReviewList() {
		Sonogram[] tempArray = new Sonogram[0];
		sonogramReviewList.setListData(databaseCard.sonogramPreferenceAndReviewPanel.sonogramSet.toArray(tempArray));
        sonogramReviewList.addListSelectionListener(sonogramReviewListener);
        sonogramReviewList.setVisibleRowCount(15);
        sonogramReviewList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        sonogramReviewList.setSelectedIndex(0);
	}

	private class ButtonBar extends JPanel {
		/**
		 *
		 */
		private static final long serialVersionUID = 1L;
		final JPanel playClearButtonPanel;
		final JButton playButton;
		final JButton clearButton;
		final JRadioButton cleanButton;
		final JRadioButton noisyButton;
		final JRadioButton otherBirdButton;
		final JRadioButton noisyOtherBirdButton;
		final ButtonGroup sonogramQualityButtonGroup;
		final JPanel sonogramQualityButtonBar;

		ButtonBar() {
			setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
			playClearButtonPanel = new JPanel();
			playClearButtonPanel.setLayout(new BoxLayout(playClearButtonPanel, BoxLayout.Y_AXIS));
			playButton = new JButton("Play");
			playButton.setActionCommand("play");
			playButton.addActionListener(sonogramReviewListener);
			playClearButtonPanel.add(playButton);
			clearButton = new JButton("Clear");
			clearButton.setActionCommand("clear");
			clearButton.addActionListener(sonogramReviewListener);
			playClearButtonPanel.add(clearButton);
			add(playClearButtonPanel);
			cleanButton = new JRadioButton("Clean");
			cleanButton.setActionCommand("clean");
			cleanButton.addActionListener(sonogramReviewListener);
			noisyButton = new JRadioButton("Noisy");
			noisyButton.setActionCommand("noisy");
			noisyButton.addActionListener(sonogramReviewListener);
			otherBirdButton = new JRadioButton("Other Bird");
			otherBirdButton.setActionCommand("other bird");
			otherBirdButton.addActionListener(sonogramReviewListener);
			noisyOtherBirdButton = new JRadioButton("Noisy & Other Bird");
			noisyOtherBirdButton.setActionCommand("noisy & other bird");
			noisyOtherBirdButton.addActionListener(sonogramReviewListener);
			sonogramQualityButtonGroup = new ButtonGroup();
			sonogramQualityButtonGroup.add(cleanButton);
			sonogramQualityButtonGroup.add(noisyButton);
			sonogramQualityButtonGroup.add(otherBirdButton);
			sonogramQualityButtonGroup.add(noisyOtherBirdButton);
			sonogramQualityButtonBar = new JPanel();
			sonogramQualityButtonBar.setLayout(new BoxLayout(sonogramQualityButtonBar, BoxLayout.Y_AXIS));
			sonogramQualityButtonBar.add(cleanButton);
			sonogramQualityButtonBar.add(otherBirdButton);
			sonogramQualityButtonBar.add(noisyButton);
			sonogramQualityButtonBar.add(noisyOtherBirdButton);
			add(sonogramQualityButtonBar);
		}

		void loadQuality(Sonogram sonogram) {
			sonogramQualityButtonGroup.clearSelection();;
			EnumSonogramQuality sonogramQuality = sonogram.getQuality();
			if (sonogramQuality == EnumSonogramQuality.CLEAN)
				cleanButton.setSelected(true);
			else if (sonogramQuality == EnumSonogramQuality.OTHER_BIRD)
				otherBirdButton.setSelected(true);
			else if (sonogramQuality == EnumSonogramQuality.NOISY)
				noisyButton.setSelected(true);
			else if (sonogramQuality == EnumSonogramQuality.NOISY_OTHER_BIRD)
				noisyOtherBirdButton.setSelected(true);
			invalidate();
		}
	}

	private class SonogramReviewListener implements ListSelectionListener, ActionListener {
		@Override
		public void valueChanged(ListSelectionEvent e) {
			if (e.getValueIsAdjusting()
					|| databaseCard.sonogramPreferenceAndReviewPanel.sonogramSet == null) return;
			if (sonogramReviewList.getSelectedIndex() == -1) return;
			Sonogram s = sonogramReviewList.getSelectedValue();
			sonogramReviewList.ensureIndexIsVisible(sonogramReviewList.getSelectedIndex());
			if (previousSonogram != null)
				databaseCard.sonogramPanel.markSonogram(previousSonogram);
			databaseCard.sonogramPanel.markSonogram(s);
			previousSonogram = s;
			buttonBar.loadQuality(s);
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			Sonogram sonogram = sonogramReviewList.getSelectedValue();
			String ac = e.getActionCommand();
			if (ac == "done") {
				if (previousSonogram != null) {
					databaseCard.sonogramPanel.markSonogram(previousSonogram);
					previousSonogram = null;
				}
				databaseCard.sonogramPreferenceAndReviewPanel.sonogramReviewDone();
				return;
			}
			if (ac == "clear") {
				buttonBar.sonogramQualityButtonGroup.clearSelection();
				sonogramReviewList.requestFocusInWindow();
				sonogram.setQuality(null);
			}
			else if (ac == "play") {
				sonogram.play();
				sonogramReviewList.requestFocusInWindow();
				return;
			}
			else if (ac == "clean")
				sonogram.setQuality(EnumSonogramQuality.CLEAN);
			else if (ac == "other bird")
				sonogram.setQuality(EnumSonogramQuality.OTHER_BIRD);
			else if (ac == "noisy")
				sonogram.setQuality(EnumSonogramQuality.NOISY);
			else if (ac == "noisy & other bird")
				sonogram.setQuality(EnumSonogramQuality.NOISY_OTHER_BIRD);
			int selectedIndex = sonogramReviewList.getSelectedIndex();
			if (selectedIndex < databaseCard.sonogramPreferenceAndReviewPanel.sonogramSet.size() - 1) {
		        sonogramReviewList.setSelectedIndex(selectedIndex + 1);
				sonogram = sonogramReviewList.getSelectedValue();
				buttonBar.loadQuality(sonogram);
			}
			sonogramReviewList.requestFocusInWindow();
		}
	}
}


text:
package com.snakerflow.framework.security.service;

import java.util.List;

import com.snakerflow.framework.orm.Page;
import com.snakerflow.framework.orm.PropertyFilter;
import com.snakerflow.framework.security.dao.RoleDao;
import com.snakerflow.framework.security.entity.Role;
import com.snakerflow.framework.security.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 角色管理类
 * @author yuqs
 * @since 0.1
 */
@Component
public class RoleManager {
	//注入角色持久化对象
	@Autowired
	private RoleDao roleDao;
	//注入用户管理对象
	@Autowired
	private UserManager userManager;

	/**
	 * 保存、更新角色实体
	 * @param entity
	 */
	public void save(Role entity) {
		roleDao.save(entity);
	}

	/**
	 * 根据主键ID删除对应的角色
	 * @param id
	 */
	public void delete(Long id) {
		List<User> users = userManager.getAll();
		for(User user : users) {
			for(Role role : user.getRoles()) {
				if(role.getId().longValue() == id.longValue()) {
					user.getRoles().remove(role);
					userManager.save(user);
					break;
				}
			}
		}
		roleDao.delete(id);
	}

	/**
	 * 根据主键ID获取角色实体
	 * @param id
	 * @return
	 */
	public Role get(Long id) {
		return roleDao.get(id);
	}

	/**
	 * 根据分页对象、过滤集合参数,分页查询角色列表
	 * @param page
	 * @param filters
	 * @return
	 */
	public Page<Role> findPage(final Page<Role> page, final List<PropertyFilter> filters) {
		return roleDao.findPage(page, filters);
	}

	/**
	 * 获取所有角色记录
	 * @return
	 */
	public List<Role> getAll() {
		return roleDao.getAll();
	}
}


text:
package madgik.exareme.common.schema.expression;

/**
 * @author herald
 */
public class SQLDMQuery extends SQLQuery {

    private static final long serialVersionUID = 1L;
    private String table = null;

    public SQLDMQuery() {
    }

    public String getTable() {
        return table;
    }

    public void setTable(String table) {
        this.table = table;
    }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="smack">

        <roleset framnet="-" id="smack.01" name="to give an indication, be suggestive of" vncls="-">
            <roles>
                <role descr="entity being suggestive" f="" n="0"/>
                <role descr="entity suggested of" f="" n="1"/>

                <note/>
            </roles>

            <example name="transitive" src="" type="">
                <inflection aspect="ns" form="full" person="ns" tense="ns" voice="active"/>
                <text>From the perspective of East Germany 's old guard , reforms that-1 [*T*-1] smack of capitalism and Western-style democracy could eliminate their country 's reason for being .</text>
                <arg f="" n="0">[*T*-1]     (= that)</arg>
                <arg f="slc" n="m">that ->  reforms</arg>
                <rel f="">smack</rel>
                <arg f="" n="1">of capitalism and Western-style democracy</arg>

                <note/>
            </example>

            <note>Based on WSJ. No appropriate VNcls. Updated by Julia, 11/2010.</note>
        </roleset>

        <note/>
        <roleset framnet="Cause_harm , Impact , Experience_bodily_harm , Cause_impact , Body_movement" id="smack.02" name="hit" vncls="18.1  18.4">
            <roles>
                <role descr="hitter" f="" n="0">
                    <vnrole vncls="18.1" vntheta="agent"/>
                    <vnrole vncls="18.4" vntheta="theme"/>
                </role>
                <note/>
                <role descr="thing hit" f="ppt" n="1">
                    <vnrole vncls="18.1" vntheta="patient"/>
                    <vnrole vncls="18.4" vntheta="location"/>
                </role>
                <role descr="instrument, if separate from arg0" f="mnr" n="2">
                    <vnrole vncls="18.1" vntheta="instrument"/>
                </role>
            </roles>
            <note>Added by Julia based on ULA. Member of VNcls hit-18.1-1, bump-18.4-1</note>
            <example name="I think I might have mentioned that I love ULA" src="ULA" type="-">
                <inflection aspect="ns" form="full" person="third" tense="future" voice="active"/>
                <text>Among Bessie 's numbers were Dying Gambler 's Blues , Sing Sing Prison Blues , and one I had never heard called Black Mountain Blues , which has the imcomparable lines , Home in Black Mountain a chile' will smack yo' face ;</text>
                <note/>
                <arg f="loc" n="m">Home in Black Mountain</arg>
                <arg f="" n="0">a chile'</arg>
                <arg f="mod" n="m">will</arg>
                <rel f="">smack</rel>
                <arg f="" n="1">yo' face</arg>
            </example>
            <example name="all args" src="internet" type="-">
                <inflection aspect="ns" form="participle" person="other" tense="past" voice="active"/>
                <text>So I smacked him with my lunch tray...</text>
                <note/>
                <arg f="dis" n="m">So</arg>
                <arg f="" n="0">I</arg>
                <rel f="">smacked</rel>
                <arg f="" n="1">him</arg>
                <arg f="" n="2">with my lunch tray</arg>
            </example>
            <example name="ergative" src="-" type="-">
                <inflection aspect="ns" form="participle" person="third" tense="past" voice="ns"/>
                <text>Mary's open hand smacked John's face.</text>
                <note/>
                <arg f="" n="0">Mary's open hand</arg>
                <rel f="">smacked</rel>
                <arg f="" n="1">John's face</arg>
            </example>
        </roleset>
    </predicate>

    <note/>
</frameset>


text:
var fs = require("fs");
var path = require("path");

// Allow plugins to be written in coffee-script
require("coffee-script");

// Load and export all plugins
var PLUGINS_PATH = path.join(__dirname, "./plugins");
fs.readdirSync(PLUGINS_PATH).forEach(function (file) {
  var pluginPath = path.join(PLUGINS_PATH, file);
  if(fs.statSync(pluginPath).isDirectory()) {
    exports[file] = require(pluginPath);
    exports[file].configFile = require(pluginPath + "/config");
  }
});


text:
#include <stdlib.h>
#include <check.h>
#include "../src/counter.h"
#include "../src/dot_writer.h"

START_TEST(test_counter_create)
{
	Counter *counter;

	counter = counter_create("type", "path");
	ck_assert_str_eq(counter_path(counter), "path");
	counter_free(counter);
}
END_TEST

Suite * preparation_suite(void); // could put to a seperate file
Suite * dot_suite(void);

//	TCase *tc_generate_report; // put into relating suites!!
//	TCase *tc_prepare_database;
//	TCase *tc_analysis;	// analysis the layer structure, get the parameters
Suite * counter_suite(void)
{
	Suite *s;
	TCase *tc_core;

	s = suite_create("Counter");

	/* Core test case */
	tc_core = tcase_create("Core");
	tcase_add_test(tc_core, test_counter_create);

	suite_add_tcase(s, tc_core);

	return s;
}
static void add_additional_suites(SRunner *sr)
{
//srunner_add_suite (sr, preparation_suite);
//srunner_add_suite (sr, dot_suite);
}
int main(void)
{
	int number_failed;
	Suite *s;
	SRunner *sr;

	s = counter_suite();
	sr = srunner_create(s);
	add_additional_suites(sr);
	srunner_run_all(sr, CK_NORMAL);
	number_failed = srunner_ntests_failed(sr);
	srunner_free(sr);

	return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}


text:
package com.v7lin.style.global;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.res.XmlResourceParser;
import android.text.TextUtils;

import com.v7lin.android.os.env.PathUtils;
import com.v7lin.style.app.StyleConst;

/**
 *
 *
 * @author v7lin Email:v7lin@qq.com
 */
public class GlobalManager implements StyleConst {

	/**
	 * 获取配置信息
	 */
	public static void ensureConfig(Context context, int configResid) {
		String rtlPath = null;
		XmlResourceParser parser = context.getResources().getXml(configResid);
		try {
			boolean eof = false;
			while (!eof) {
				switch (parser.getEventType()) {
				case XmlPullParser.START_TAG: {
					if (TextUtils.equals(parser.getName(), KEY_CONFIG_RTLPATH)) {
						rtlPath = parser.nextText();
					}
					break;
				}
				case XmlPullParser.END_DOCUMENT: {
					eof = true;
					break;
				}
				default: {
					break;
				}
				}
				parser.next();
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (TextUtils.isEmpty(rtlPath)) {
			rtlPath = DEFAULT_CONFIG_RTLPATH;
		}
		// 设置 APP 路径
		PathUtils.setAppRtlPath(rtlPath);
	}
}


text:
<?php

namespace Hal\Application\Score\Factor;

use Hal\Component\Bounds\Result\ResultInterface;
use Hal\Component\Result\ResultCollection;

/**
 * PrincipleInterface
 *
 * @author Jean-François Lépine <https://twitter.com/Halleck45>
 */
interface FactorInterface {

    /**
     * Give score for principle
     *
     * @param ResultCollection $collection
     * @param ResultCollection $groupedResults
     * @param ResultInterface $bound
     * @return mixed
     */
    public function calculate(ResultCollection $collection, ResultCollection $groupedResults, ResultInterface $bound);

    /**
     * Name of principle
     *
     * @çeturn string
     */
    public function getName();
}


text:
title: "Thomas Hoving, Met Chief and Journalist, Dies"
layout: page
old_permalink: thomas-hoving-dies-at-78
category: news
---
![Thomas Hoving (NYT)](/assets/img/popup.jpg)
Thomas Hoving (NYT)

Thomas Hoving, the former Met director who brought us King Tut and the Euphronios krater, has died. He was 78. Hoving loved an adventure. And he made the mummies dance.

[NYT: Hoving, Who Shook Up the Met, Dies at 78](http://www.nytimes.com/2009/12/11/arts/design/11hoving.html)


text:
package com.planet_ink.coffee_mud.Items.interfaces;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

public interface Coins extends Item
{
	public long getNumberOfCoins();
	public void setNumberOfCoins(long number);
	public boolean putCoinsBack();
	public double getDenomination();
	public void setDenomination(double valuePerCoin);
	public double getTotalValue();
	public String getCurrency();
	public void setCurrency(String named);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace nhs.itk.hl7v3.datatypes
{

    public enum HL7V3_NullType
    {
        NoInformation,
        Invalid,
        Other,
        Unencoded,
        Derived,
        Unknown,
        AskedNotKnown,
        TemporarilyUnavailable,
        NotAsked,
        Masked,
        NotApplicable
    }

    public static class HL7V3_NullTypeExtensions
    {
        public static string ToFriendlyString(this HL7V3_NullType me)
        {
            switch (me)
            {
                case HL7V3_NullType.NoInformation:
                    return "NI";
                case HL7V3_NullType.Invalid:
                    return "INV";
                case HL7V3_NullType.Other:
                    return "OTH";
                case HL7V3_NullType.Unencoded:
                    return "UNC";
                case HL7V3_NullType.Derived:
                    return "DER";
                case HL7V3_NullType.Unknown:
                    return "UNK";
                case HL7V3_NullType.AskedNotKnown:
                    return "ASKU";
                case HL7V3_NullType.TemporarilyUnavailable:
                    return "NAV";
                case HL7V3_NullType.NotAsked:
                    return "NASK";
                case HL7V3_NullType.Masked:
                    return "MSK";
                case HL7V3_NullType.NotApplicable:
                    return "NA";
                default:
                    return null;
            }
        }
    }

}


text:
layout: post
title: "The death of the generalist CRO agency"
date: "2020-02-12"
---

Here's an uncontroversial statement: purchasing $15,000 worth of furniture online is _different_ from signing up for a free trial of a project management app.

And both are different from clicking an article link, or subscribing to an email list.

But go searching for a Conversion Rate Optimization agency, and you'll find folks willing and ready to optimize your site for any and all of these actions.

You'll find a _ton_ of them.

![](/images/Screen-Shot-2020-02-11-at-1.28.27-PM.png)

This will change.

## CRO infancy

For years, the practice of using data, experimentation, and UX research to improve a website's conversion rate ... was new. Hip. Edgy.

Only the cool kids were doing it.

During this phase, there were a handful of tools, and a handful of practitioners.

"Doing CRO" was itself a niche pursuit.

As a business owner, you were lucky to find someone with the skills to run a successful experiment on your website.

But major players like Facebook and Amazon started experimenting aggressively. [Obama](https://blog.optimizely.com/2010/11/29/how-obama-raised-60-million-by-running-a-simple-experiment/) got into the game.

Then Google released a free experimentation tool, and things really took off.

![](/images/Screen-Shot-2020-02-11-at-1.37.21-PM.png)

## CRO puberty

Which brings us to present day. You can't swing a funnel without hitting a CRO agency, and apparently you can't open a marketing agency without asserting that you "do CRO".

But this stuff is hard. [7 out of 10 tests fail](https://blog.convert.com/seven-out-of-ten-of-all-ab-tests-fail.html). (Or is it [7 out of 8](https://vwo.com/blog/a-b-testing-tips/)?)

It's expensive, too. You're looking at 5 figures per month for a testing tool and an agency to run it.

The current boom in experimentation is letting businesses down. For every legitimate, measurable, data-driven improvement, there are tons of failed tests, inconclusive results, and false positives.

You can already see the fallout. A couple of points that almost every marketer will concede:

> We know that testing is important ...

and

> We want to be data driven ...

But the painful lesson they've learned:

> We tried, and it just didn't move the needle.

## CRO maturity (a prediction)

Where's all this heading?

The multitude of agencies and consultants who take a "throw stuff against the wall" approach will largely be culled.

Businesses will be much more reluctant to release budgets for testing "because it's important."

And specialists will win the day.

No doubt there are a handful of 🦄 unicorns whose analytical chops, UX insights, and empathy are so off the charts that they can successfully optimize a law firm's lead generation website on Tuesday and a media site's ad impressions on Thursday.

But they'll always be rare. The rest of us normal humans will win by focusing on specific user intentions, particular types of sites, and a subset of all conversions.

Optimizing a SaaS site for free trial signups doesn't really prepare you to optimize a high-ticket ecommerce site for revenue per visitor.

Know what does? Optimizing 10 other high-ticket ecommerce sites for revenue per visitor 😁

This evolution is already in progress. See, for example, [Draft](https://draft.nu/) - an agency that only serves ecommerce shops.

As a result of this focus, they're able to produce [_incredible_ research and insights _for ecommerce shops_](https://draft.nu/analysis/).

Got an ecommerce shop? You can seek help from an agency that's worked with Microsoft, Lyft, and InstaGram. They're clearly professionals, and they're clearly connected.

But ... WTF does optimizing for software purchases, rides, or screen time have to do with getting people to buy _your_ product? Me, I'd go with Draft.

In my career I've optimized ecommerce, lead generation, SaaS, and media sites.

I've optimized for ad views, affiliate link clicks, purchases, average order value, subscriptions, trial signups, and at least a dozen other things that make people money on the internet.

Moving forward, my focus is one one particular flavor of conversion: leads.

Filling out a form as an initial step in a larger purchase process.

Because it's _different_ from buying shoes, or upgrading from a free trial to a paid plan.

Because businesses trying to get more leads are _different_ from magazines and mobile apps.

Because this focus allows me to produce unique and valuable research for a specific type of marketer.

Because there are a ton of hideous lead forms, confusing (or entirely absent) value propositions, uninspired CTAs, and starving sales teams out there, just waiting for help.

Because I don't want anybody to pay me to run heat maps and experiments on their website; I want them to pay me for growing their business and getting them more customers.

Because once we're past CRO puberty, just knowing how to run tests on websites won't count for a thing. Generalist CRO agencies will have a hard time staying relevant.

But if you're optimizing your online publication for paid subscriptions, there will be a clear leader in the field.

If you're optimizing your SaaS app for upgrades, there will be a known name with a proven track record.

And if you're trying to get more leads from your website, well, 👋😁.


text:
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="1dp"
        android:color="@color/pubnative_call_to_action_background_color"/>
    <corners
        android:radius="4dp" />

    <padding
        android:left="1dp"
        android:right="1dp"
        android:top="1dp"
        android:bottom="1dp"/>

    <solid android:color="@color/pubnative_call_to_action_background_color"/>

</shape>


text:
from pyOpt import ALGENCAN
from pyOpt import ALPSO
from pyOpt import COBYLA
from pyOpt import CONMIN
from pyOpt import FILTERSD
from pyOpt import KSOPT
from pyOpt import MIDACO
from pyOpt import NSGA2
from pyOpt import Optimization
from pyOpt import PSQP
from pyOpt import SDPEN
from pyOpt import SLSQP
from pyOpt import SOLVOPT


text:
export function loggerResolver(action, next) {
  console.log("action", action.type, action);
  return next(null, action);
}


text:
ros::Publisher _pointcloud_pub;
laser_geometry::LaserProjection projection;

double min_dist, neighbor_dist;

void scanCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
  sensor_msgs::LaserScan scanData = *msg;

  auto rangeIsValid = [&scanData](float range) {
    return !std::isnan(range) && range > scanData.range_min && range < scanData.range_max;
  };

  for (unsigned int i = 0; i < scanData.ranges.size(); i++)
  {
    float& range = scanData.ranges[i];
    if (range > scanData.range_max || range < scanData.range_min)
      continue;
    // Too close
    if (range < min_dist)
      range = scanData.range_max + 1;
    // No valid neighbors
    else if ((i == 0 || !rangeIsValid(scanData.ranges[i - 1])) &&
             (i == (scanData.ranges.size() - 1) || !rangeIsValid(scanData.ranges[i + 1])))
      range = scanData.range_max + 1;
    // No close neighbors
    else if ((i == 0 || abs(scanData.ranges[i - 1] - range) > neighbor_dist) &&
             (i == (scanData.ranges.size() - 1) || abs(scanData.ranges[i + 1] - range) > neighbor_dist))
      range = scanData.range_max + 1;
  }

  sensor_msgs::PointCloud2 cloud;
  projection.projectLaser(scanData, cloud);
  cloud.header.frame_id = "/lidar";

  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_for_pub(new pcl::PointCloud<pcl::PointXYZ>());
  fromROSMsg(cloud, *cloud_for_pub);
  _pointcloud_pub.publish(*cloud_for_pub);
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "scan_to_pointcloud");

  ros::NodeHandle pNh("~");

  pNh.getParam("min_dist", min_dist);
  pNh.getParam("neighbor_dist", neighbor_dist);

  ros::NodeHandle nh;

  _pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ> >("/pc2", 1);

  ros::Subscriber scan_sub = nh.subscribe("/scan", 1, scanCallback);

  ros::spin();
}


text:
'use strict';

/**
 * @ngdoc directive
 * @name stockDogApp.directive:stkWatchlistPanel
 * @description
 * # stkWatchlistPanel
 */
angular.module('stockDogApp')
  .directive('stkWatchlistPanel', function ($location, $modal, $routeParams, WatchlistService) {
    return {
      templateUrl: 'views/templates/watchlist-panel.html',
      restrict: 'E',
      scope: {},
      link: function ($scope) {
        // [2] Initialize variables
        $scope.watchlist = {};
        var addListModal = $modal({
          scope: $scope,
          template: 'views/templates/addlist-modal.html',
          show: false
        });
        // [3] Bind model from service to this scope
        $scope.watchlists = WatchlistService.query();
        // [4] Display addlist modal
        $scope.showModal = function () {
          addListModal.$promise.then(addListModal.show);
        };
        // [5] Create a new list from fields in modal
        $scope.createList = function () {
          WatchlistService.save($scope.watchlist);
          addListModal.hide();
          $scope.watchlist = {};
        };
        // [6] Delete desired list and redirect to home
        $scope.deleteList = function (list) {
          WatchlistService.remove(list);
          $location.path('/');
        };
        $scope.currentList = $routeParams.listId;
        $scope.gotoList = function (listId) {
          $location.path('watchlist/' + listId);
        };
      }
    };
  });


text:
<?php defined('BX_DOL') or die('hack attempt');

bx_import('BxBaseModTextPageAuthor');

/**
 * Profile's entries page.
 */
class BxPostsPageAuthor extends BxBaseModTextPageAuthor
{
    public function __construct($aObject, $oTemplate = false)
    {
        parent::__construct($aObject, $oTemplate);
    }

}

/** @} */


text:
PYTHONIC_NS_BEGIN

namespace numpy
{

#define NUMPY_NARY_FUNC_NAME double_
#define NUMPY_NARY_FUNC_SYM details::float64
#include "pythonic/types/numpy_nary_expr.hpp"
}
PYTHONIC_NS_END

#endif


text:
module Rubocop
  module Cop
    module Style
      # This cop checks for redundant uses of `self`.
      #
      # `self` is only needed when:
      #
      # * Sending a message to same object with zero arguments in
      #   presence of a method name clash with an argument or a local
      #   variable.
      #
      #   Note, with using explicit self you can only send messages
      #   with public or protected scope, you cannot send private
      #   messages this way.
      #
      #   Example:
      #
      #   def bar
      #     :baz
      #   end
      #
      #   def foo(bar)
      #     self.bar # resolves name clash with argument
      #   end
      #
      #   def foo2
      #     bar = 1
      #     self.bar # resolves name class with local variable
      #   end
      #
      # * Calling an attribute writer to prevent an local variable assignment
      #
      #   attr_writer :bar
      #
      #   def foo
      #     self.bar= 1 # Make sure above attr writer is called
      #   end
      #
      # Special cases:
      #
      # We allow uses of `self` with operators because it would be awkward
      # otherwise.
      class RedundantSelf < Cop
        MSG = 'Redundant `self` detected.'

        def initialize(config = nil, options = nil)
          super
          @allowed_send_nodes = []
          @local_variables = []
        end

        # Assignment of self.x

        def on_or_asgn(node)
          lhs, _rhs = *node
          allow_self(lhs)
        end

        alias_method :on_and_asgn, :on_or_asgn

        def on_op_asgn(node)
          lhs, _op, _rhs = *node
          allow_self(lhs)
        end

        # Using self.x to distinguish from local variable x

        def on_def(node)
          @local_variables = []
        end

        def on_defs(node)
          @local_variables = []
        end

        def on_arg(node)
          on_argument(node)
        end

        def on_blockarg(node)
          on_argument(node)
        end

        def on_lvasgn(node)
          lhs, _rhs = *node
          @local_variables << lhs
        end

        # Detect offences

        def on_send(node)
          receiver, method_name, *_args = *node
          if receiver && receiver.type == :self
            unless operator?(method_name) || keyword?(method_name) ||
                @allowed_send_nodes.include?(node) ||
                @local_variables.include?(method_name)
              convention(node, :expression)
            end
          end
        end

        def autocorrect(node)
          @corrections << lambda do |corrector|
            corrector.replace(node.loc.expression,
                              node.loc.expression.source.gsub(/self\./, ''))
          end
        end

        private

        def on_argument(node)
          name, _ = *node
          @local_variables << name
        end

        def operator?(method_name)
          method_name.to_s =~ /\W/
        end

        def keyword?(method_name)
          [:alias, :and, :begin, :break, :case, :class, :def, :defined, :do,
           :else, :elsif, :end, :ensure, :false, :for, :if, :in, :module,
           :next, :nil, :not, :or, :redo, :rescue, :retry, :return, :self,
           :super, :then, :true, :undef, :unless, :until, :when, :while,
           :yield].include?(method_name)
        end

        def allow_self(node)
          if node.type == :send
            receiver, _method_name, *_args = *node
            @allowed_send_nodes << node if receiver && receiver.type == :self
          end
        end

      end
    end
  end
end


text:
using System.Threading.Tasks;
using GridDomain.Aggregates;
using GridDomain.Scenarios.Builders;
using Serilog;

namespace GridDomain.Scenarios.Runners
{
    public static class AggregateScenarioRunBuilderLocalRunnerExtensions
    {
        public static async Task<IAggregateScenarioRun<TAggregate>> Local<TAggregate>(this IAggregateScenarioRunBuilder<TAggregate> builder, ILogger log = null) where TAggregate : class, IAggregate
        {
            var runner = new AggregateScenarioLocalRunner<TAggregate>(log ?? Log.Logger);
            return await runner.Run(builder.Scenario);
        }
    }
}


text:
/* */
"format global";
"use strict";

var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };

exports.Program = Program;
exports.FunctionExpression = FunctionExpression;
exports.ThisExpression = ThisExpression;
exports.CallExpression = CallExpression;
exports.__esModule = true;

var messages = _interopRequireWildcard(require("../../../messages"));

var t = _interopRequireWildcard(require("../../../types"));

function Program(program, parent, scope, file) {
  var first = program.body[0];
  if (t.isExpressionStatement(first) && t.isLiteral(first.expression, { value: "use strict" })) {
    file.set("existingStrictDirective", program.body.shift());
  }
}

function FunctionExpression() {
  this.skip();
}

exports.FunctionDeclaration = FunctionExpression;

function ThisExpression() {
  return t.identifier("undefined");
}

function CallExpression(node, parent, scope, file) {
  if (t.isIdentifier(node.callee, { name: "eval" })) {
    throw file.errorWithNode(node, messages.get("evalInStrictMode"));
  }
}


text:
package compiler;
import java.io.IOException;

public class LexerTest {

public static void main(String[] args) throws IOException {

		Token t; 				  /*token*/
		RPLanguageTokenManager tm;/*lexer*/

		//apertura del file sorgente
		java.io.InputStream infile;
		infile = new java.io.FileInputStream("input/regole1.txt");

		//definizione del lexer (sul file sorgente)
		tm = new RPLanguageTokenManager(new SimpleCharStream(infile));

		//lettura dei token (e stampa a video dei tipi)
		t = tm.getNextToken();
		while (t.kind != RPLanguageConstants.EOF) {

			System.out.println(t.kind+" "+t.image);
			t = tm.getNextToken();
		}

		infile.close();
	}
}


text:
FragmentedKey
===========

tl;dr;
A php library for managing cache invalidation by tracking tag-value pair versions on memcache, apc or other storage device and generating derived cache keys based on those values.

For a Java port of this library please see (https://github.com/noizu/fragmented-keys-4java)

Overview
----------
Fragmented Keys provide a straightforward way to manage and invalidate composite cache keys.

It does this by persisting in memcache (or other back-end persistance layer of your choice)  tag-instance versionining information. When constructing composite/fragmented keys these tags and their versions are used to generate the final composite key.

Thus if you wanted to tie something to to the granularity of say a specific thing like username you can do the following:

```php
  $GlobalGreetingTag = new Tag\Standard("Global.Greeting", "global");
  $UserUserNameTag = new Tag\Standard("User.Username", $userId);
  $keyobj = new Key\Standard(
      "CacheDataThatInvalidatesWhenUserNamesAreChanged",
      array($UserUserNameTag, $GlobalGreetingTag)
  );
  $cacheKey = $keyObj->getKeyStr();
```

You can then Invalidate only items linked to your user's username by calling:
```php
  $UserUserNameTag = new Tag\Standard("User.Username", $userId);
  $UserUserNameTag->Increment();
```

Behind the scenes this looks something like blocking out everything below the [Targeted User] bucket.
```
  AllKey
    \
     \-[ ]Global.Greeting
            \
             \-[ ]Other User Cached Greeting
              \
               \-[x]Targeted User
```

Or you could just go crazy and invalidate all keys that rely on Global.Greating

```php
  $GlobalGreetingTag->Increment();
```

but amke sure your database is ready for it.
```
  AllKey
    \
     \-[x]Global.Greeting
            \
             \-[x]Other User Cached Greeting
              \
               \-[x]Target User
```

Setup & Installation
==

Installation
---
This project is available on composer, just add noizu-labs/fragmented-keys to your required list.
    "require": {
        "noizu-labs/fragmented-keys": "dev-master",
    }

Setup
-----
The code depends on a Memcached, Memcache or APC handle being available and configured along with a global prefix to
avoid collisions.

```php

$m = new \Memcached;
\NoizuLabs\FragmentedKeys\Configuration\setGlobalCacheHandler(new \NoizuLabs\FragmentedKeys\CacheHandler\Memcached($m));
\NoizuLabs\FragmentedKeys\Configuration\setGlobalPrefix("MyApp");

//you may override the handler per tag by calling
$tag->setCacheHandler($alternativeHandler);

//or by including a handler in you constructor.
$tag = new Tag\Standard("Users", 1234, null, CacheHandler\Apc());

```

Components
=================

Cache Handlers
-------
```php
$apcHandler = \NoizuLabs\FragmentedKeys\CacheHandler\Apc();
$inMemoryHandler = \NoizuLabs\FragmentedKeys\CacheHandler\Memory();
$memcachedHandler = \NoizuLabs\FragmentedKeys\CacheHandler\Memcached(new Memcached());
$memcacheHandler = \NoizuLabs\FragmentedKeys\CacheHandler\Memcache(new Memcache());
```

Tags
--------

Tags are a logical grouping that you would under certain circumstance invalidate assocaited cached data.

A User:$id pair,  a Site:$siteId, etc. This library takes they tag-instance pairs and appends @version fields to them so that when you want to invalidate a large swatch of related items you don't need to send dozens of invalidate requests to memcache, or apc. You just make a single $tag->increment() call and any associated keys that us that tag-instance (User:$userId) will generate new keys;

| Tag Class | Description|
|-----------|------------|
| Standard  | Basic Key. Persists version to specified cache handler                                                            |
| Delayed*   | Basic Key with built in Delay. Only internal key versions greater than the specified delay will cause a new  version to be returned. Allowing you to pull cached content that only updates every hours, 30 seconds, etc. |
| Constant    | Key with Constant associated Version. E.g. version can only be set once at construction time. useful for incorporating non version tag-instance details in large composite keys |

*Delayed is not yet implemented

Key Rings
---------
Key rings help may your life easier by letting you define common key structures one and then reuse him in your code as needed.
You can tweak settings in your config, or even define custom keys that always include some additional tag s *with out requiring your cache caller to manually include them!*

Example
```php
<?php
    //=================================================
    // Config stuff you only need to do this once
    //=================================================
    /* Somewhere in you bootstrap or wherever you instiatiate a KeyRing or KeyRing derived Class */
    $cacheHandlers = array(
        'memcache' => new \NoizuLabs\FragmentedKeys\CacheHandler\Memcached($this->container['memcache']),
        'memory' => new \NoizuLabs\FragmentedKeys\CacheHandler\Memory()
        );
    $globalOptions = array(
      'type' => 'standard'
    );
    $tagOptions = array(
        'universe' => array('type' => 'constant', 'version' => 5)
    );
    $ring = new FragmentedKeys\KeyRing($globalOptions,  $tagOptions, 'memcache', $cacheHandlers);

    /* define you keys */
    $ring->DefineKey("Users", array('universe', array('tag' => 'planet' , 'cacheHandler' => 'memory', 'version' => null, 'type'=>'standard'), 'city'));

    //==============================================
    // Need to check for some cached data? Generating you key now takes one line instead of 5;
    //===============================================
    $users = $ring->getUsersKeyObj('MilkyWay', 'Earth', 'Chicago')->getKeyStr();
    $users = $memcache->get($userKey);
    if(!users) {
          $users = query("select * from users where universe='MilkyWay' AND planet='Earth' AND 'city' => 'Chicago'");
          $memcache->set($userKey, $users);
    }

    /* Invalidate them */
    $universeTag = new Tag\Standard('universe', 'MilkyWay');
    $universeTag->increment();

    //===============================
    // Old Method
    //===============================
    $universeTag = new Tag\Constant("universe", "MilkyWay",5);
    $worldTag = new Tag\Standard("planet", "Earth");
    $cityTag = new Tag\Standard("city", "Chicago", null, new FragmentedKeys\CacheHandler\Memory());
    $key = new Key\Standard("Users", array($universeTag, $worldTag, $cityTag);
    $userKey = $key->getKeyStr();
    $users = $memcache->get($userKey);
    if(!users) {
          $users = query("select * from users where universe='MilkyWay' AND planet='Earth' AND 'city' => 'Chicago'");
          $memcache->set($userKey, $users);
    }

    /* Invalidate them */
    $universeTag->increment();
```

*The ability to auto include params isnt fully backed into the config process yet but you can emulate it easily by extending the base keyring class and doing the following

```php
class MyGames extends NoizuLabs\FragmentedKeys\KeyRing {
    public getGameDescriptionKeyObj($gameId) {
         /* Define Key in the usual manner  */

         /* . . . */

         $gameSiteId = $this->pimpleContainer['gameSite'];
         $userId = $this->getUserId();
         return $this->getKeyObj("GameDescription", array( $gameId, $gameSiteId, $userId, ... etc.));
    }
}

// Now your cache code looks simple
$gameDescCacheKey = $ring->getGameDescriptionKeyObj($gameId)->getKeyStr();

```


text:
package com.switchfly.compress.cli.task;

import java.io.IOException;
import com.switchfly.compress.cli.CompressCLI;
import com.switchfly.compress.cli.exceptions.CompressorException;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class CompressorTask extends Task {
    private CompressCLI _compressCLI;

    public CompressorTask() {
        _compressCLI = new CompressCLI();
    }

    public void setIsListOnly(boolean isListOnly) {
        _compressCLI.setIsListOnly(isListOnly);
    }

    public void setIsVerbose(boolean isVerbose) {
        _compressCLI.setIsVerbose(isVerbose);
    }

    public void setLineBreakPos(int breakPos) {
        _compressCLI.setLineBreakPos(breakPos);
    }

    public void setObfuscate(boolean obfuscate) {
        _compressCLI.setObfuscate(obfuscate);
    }

    public void setDisableMicroOptimizations(boolean disableMicroOptimizations) {
        _compressCLI.setDisableMicroOptimizations(disableMicroOptimizations);
    }

    public void setPreserveSemicolons(boolean preserveSemicolons) {
        _compressCLI.setPreserveUnecessarySemicolons(preserveSemicolons);
    }

    public void setOutputPath(String outputPath) {
        _compressCLI.setOutputPath(outputPath);
    }

    public void setConfigurationPath(String configurationPath) throws IOException, CompressorException {
        _compressCLI.setConfigurationFromFile(configurationPath);
    }

    public void setBaseInputPath(String baseInputPath) {
        _compressCLI.setBaseInputPath(baseInputPath);
    }

    public void setJsURIFragment(String fragment) {
        _compressCLI.setJsURIFragment(fragment);
    }

    public void setCssURIFragment(String fragment) {
        _compressCLI.setCssURIFragment(fragment);
    }

    public void execute() {
        try {
            _compressCLI.execute();
        } catch (Exception e) {
            throw new BuildException(e);
        }
    }
}


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

using WebsitePanel.Server.Utils;
using Microsoft.Win32;

namespace WebsitePanel.Providers.Mail
{
	public class AbilityMailServer : HostingServiceProviderBase, IMailServer
	{
		#region IMailServer Members

		public bool AccountExists(string mailboxName)
		{
			Tree users = AMSHelper.GetUsersConfig();
			AmsMailbox accnt = new AmsMailbox(mailboxName);

			return accnt.Load(users);
		}

		public void AddDomainAlias(string domainName, string aliasName)
		{
			Tree domains = AMSHelper.GetDomainsConfig();
			AmsDomain alias = new AmsDomain(aliasName);

			if (!alias.Load(domains))
			{
				alias.DomainConfig["enabled"] = "1";
				alias.DomainConfig["domain"] = aliasName;
				alias.DomainConfig["mode"] = "1"; // alias mode
				alias.DomainConfig["useconvertdomain"] = "1";
				alias.DomainConfig["convertdomain"] = domainName;

				if (!alias.Save(domains))
				{
					Log.WriteInfo("Couldn't save domains configuration.");
					throw new Exception("Couldn't add domain alias.");
				}
			}
			else
			{
				Log.WriteInfo("Alias already exists.");
				throw new Exception("Alias already exists.");
			}
		}

		public void CreateAccount(MailAccount mailbox)
		{
			Tree users = AMSHelper.GetUsersConfig();
			AmsMailbox accnt = new AmsMailbox(mailbox.Name);

			if (accnt.Load(users))
				throw new Exception("Mailbox is already registered.");

			accnt.Read(mailbox);

			if (!accnt.Save(users))
				throw new Exception("Couldn't create a mailbox.");
		}

		public void CreateDomain(MailDomain domain)
		{
			Tree domains = AMSHelper.GetDomainsConfig();
			AmsDomain amsDomain = new AmsDomain(domain.Name);

			if (amsDomain.Load(domains))
				throw new Exception("Domain is already registered.");

			amsDomain.Read(domain);

			if (!amsDomain.Save(domains))
				throw new Exception("Couldn't create a domain.");
		}

		public void CreateGroup(MailGroup group)
		{
			Tree users = AMSHelper.GetUsersConfig();
			AmsMailbox amsGroup = new AmsMailbox(group.Name);

			if (amsGroup.Load(users))
				throw new Exception("Mail group is already exists.");

			amsGroup.Read(group);

			if (!amsGroup.Save(users))
				throw new Exception("Couldn't create a mail group.");
		}

		public void CreateList(MailList maillist)
		{
			Tree config = AMSHelper.GetMailListsConfig();
			AmsMailList amsList = new AmsMailList(maillist.Name);

			if (amsList.Load(config))
				throw new Exception("Mail list is already exists.");

			amsList.Read(maillist);

			if (!amsList.Save(config))
				throw new Exception("Couldn't create a mail list.");
		}

		public void DeleteAccount(string mailboxName)
		{
			Tree config = AMSHelper.GetUsersConfig();
			AmsMailbox amsMailbox = new AmsMailbox(mailboxName);

			if (amsMailbox.Load(config))
			{
				if (!amsMailbox.Delete(config))
					throw new Exception("Couldn't delete a specified account.");
			}
			else
				throw new Exception("Couldn't load account settings.");
		}

	    public bool MailAliasExists(string mailAliasName)
	    {
	        throw new System.NotImplementedException();
	    }

	    public MailAlias[] GetMailAliases(string domainName)
	    {
	        throw new System.NotImplementedException();
	    }

	    public MailAlias GetMailAlias(string mailAliasName)
	    {
	        throw new System.NotImplementedException();
	    }

	    public void CreateMailAlias(MailAlias mailAlias)
	    {
	        throw new System.NotImplementedException();
	    }

	    public void UpdateMailAlias(MailAlias mailAlias)
	    {
	        throw new System.NotImplementedException();
	    }

	    public void DeleteMailAlias(string mailAliasName)
	    {
	        throw new System.NotImplementedException();
	    }

	    public void DeleteDomain(string domainName)
		{
			Tree config = AMSHelper.GetDomainsConfig();
			AmsDomain amsDomain = new AmsDomain(domainName);

			if (amsDomain.Load(config))
			{
				if (!amsDomain.Delete(config))
					throw new Exception("Couldn't delete specified domain.");
			}
			else
				throw new Exception("Couldn't find specified domain.");
		}

		public void DeleteDomainAlias(string domainName, string aliasName)
		{
			Tree config = AMSHelper.GetDomainsConfig();
			AmsDomain amsAlias = new AmsDomain(aliasName);

			if (amsAlias.Load(config))
			{
				string amsDomain = amsAlias.DomainConfig["convertdomain"];
				if (string.Compare(amsDomain, domainName, true) == 0)
				{
					if (!amsAlias.DeleteAlias(config))
						throw new Exception("Couldn't delete alias.");
				}
			}
			else
			{
				throw new Exception("Couldn't find specified alias.");
			}
		}

		public void DeleteGroup(string groupName)
		{
			Tree config = AMSHelper.GetUsersConfig();
			AmsMailbox amsGroup = new AmsMailbox(groupName);

			if (amsGroup.Load(config))
			{
				if (!amsGroup.Delete(config))
					throw new Exception("Couldn't delete specified mail group.");
			}
			else
			{
				throw new Exception("Couldn't find specified mail group.");
			}
		}

		public void DeleteList(string maillistName)
		{
			Tree config = AMSHelper.GetMailListsConfig();
			AmsMailList amsList = new AmsMailList(maillistName);

			if (amsList.Load(config))
			{
				if (!amsList.Delete(config))
					throw new Exception("Couldn't delete a mail list.");
			}
			else
			{
				throw new Exception("Couldn't find specified mail list.");
			}
		}

		public bool DomainAliasExists(string domainName, string aliasName)
		{
			Tree config = AMSHelper.GetDomainsConfig();
			AmsDomain amsAlias = new AmsDomain(aliasName);

			if (amsAlias.Load(config))
				if (string.Compare(amsAlias.DomainConfig["convertdomain"], domainName, true) == 0)
					return true;

			return false;
		}

		public bool DomainExists(string domainName)
		{
			Tree config = AMSHelper.GetDomainsConfig();
			AmsDomain amsDomain = new AmsDomain(domainName);

			return amsDomain.Load(config);
		}

		public MailAccount GetAccount(string mailboxName)
		{
			Tree config = AMSHelper.GetUsersConfig();
			AmsMailbox amsMailbox = new AmsMailbox(mailboxName);

			if (amsMailbox.Load(config))
			{
				amsMailbox.LoadAccountConfig();
				return amsMailbox.ToMailAccount();
			}

			return null;
		}

		public MailAccount[] GetAccounts(string domainName)
		{
			Tree config = AMSHelper.GetUsersConfig();
			List<MailAccount> accounts = new List<MailAccount>();

			AmsMailbox[] mbList = AmsMailbox.GetMailboxes(config, domainName);
			foreach (AmsMailbox mb in mbList)
				accounts.Add(mb.ToMailAccount());

			return accounts.ToArray();
		}

		public MailDomain GetDomain(string domainName)
		{
			Tree config = AMSHelper.GetDomainsConfig();
			AmsDomain amsDomain = new AmsDomain(domainName);

			if (amsDomain.Load(config))
				return amsDomain.ToMailDomain();

			return null;
		}

		public virtual string[] GetDomains()
		{
			Tree config = AMSHelper.GetDomainsConfig();

			return AmsDomain.GetDomains(config);
		}

		public string[] GetDomainAliases(string domainName)
		{
			Tree config = AMSHelper.GetDomainsConfig();

			return AmsDomain.GetDomainAliases(config, domainName);
		}

		public MailGroup GetGroup(string groupName)
		{
			Tree config = AMSHelper.GetUsersConfig();
			AmsMailbox amsGroup = new AmsMailbox(groupName);

			if (amsGroup.Load(config))
			{
				amsGroup.LoadAccountConfig();
				return amsGroup.ToMailGroup();
			}

			return null;
		}

		public MailGroup[] GetGroups(string domainName)
		{
			List<MailGroup> groups = new List<MailGroup>();
			Tree config = AMSHelper.GetUsersConfig();

			AmsMailbox[] amsGroups = AmsMailbox.GetMailGroups(config, domainName);

			foreach (AmsMailbox amsGroup in amsGroups)
				groups.Add(amsGroup.ToMailGroup());

			return groups.ToArray();
		}

		public MailList GetList(string maillistName)
		{
			Tree config = AMSHelper.GetMailListsConfig();
			AmsMailList amsList = new AmsMailList(maillistName);

			if (amsList.Load(config))
			{
				amsList.LoadListConfig();
				return amsList.ToMailList();
			}

			return null;
		}

		public MailList[] GetLists(string domainName)
		{
			List<MailList> lists = new List<MailList>();
			Tree config = AMSHelper.GetMailListsConfig();

			AmsMailList[] amsLists = AmsMailList.GetMailLists(config, domainName);

			foreach (AmsMailList amsList in amsLists)
				lists.Add(amsList.ToMailList());

			return lists.ToArray();
		}

		public bool GroupExists(string groupName)
		{
			Tree config = AMSHelper.GetUsersConfig();
			AmsMailbox amsGroup = new AmsMailbox(groupName);

			if (amsGroup.Load(config))
			{
				amsGroup.LoadAccountConfig();

				return amsGroup.IsMailGroup();
			}

			return false;
		}

		public bool ListExists(string maillistName)
		{
			Tree config = AMSHelper.GetMailListsConfig();
			AmsMailList amsList = new AmsMailList(maillistName);

			return amsList.Load(config);
		}

		public void UpdateAccount(MailAccount mailbox)
		{
			Tree config = AMSHelper.GetUsersConfig();
			AmsMailbox amsMailbox = new AmsMailbox(mailbox.Name);

			if (amsMailbox.Load(config))
			{
				amsMailbox.LoadAccountConfig();
				amsMailbox.Read(mailbox);

				if (!amsMailbox.Save(config))
					throw new Exception("Couldn't update specified mailbox.");
			}
			else
			{
				throw new Exception("Couldn't find specified mailbox.");
			}
		}

		public void UpdateDomain(MailDomain domain)
		{
			Tree config = AMSHelper.GetDomainsConfig();
			AmsDomain amsDomain = new AmsDomain(domain.Name);

			if (amsDomain.Load(config))
			{
				amsDomain.Read(domain);

				if (!amsDomain.Save(config))
					throw new Exception("Couldn't update specified domain.");
			}
			else
			{
				throw new Exception("Couldn't find specified domain.");
			}
		}

		public void UpdateGroup(MailGroup group)
		{
			Tree config = AMSHelper.GetUsersConfig();
			AmsMailbox amsGroup = new AmsMailbox(group.Name);

			if (amsGroup.Load(config))
			{
				amsGroup.LoadAccountConfig();
				amsGroup.Read(group);

				if (!amsGroup.Save(config))
					throw new Exception("Couldn't update specified mail group.");
			}
			else
			{
				throw new Exception("Couldn't find specified mail group.");
			}
		}

		public void UpdateList(MailList maillist)
		{
			Tree config = AMSHelper.GetMailListsConfig();
			AmsMailList amsList = new AmsMailList(maillist.Name);

			if (amsList.Load(config))
			{
				amsList.LoadListConfig();
				amsList.Read(maillist);

				if (!amsList.Save(config))
					throw new Exception("Couldn't update specified mail list.");
			}
			else
			{
				throw new Exception("Couldn't find specified mail list.");
			}
		}

		#endregion

		#region HostingServiceProviderBase members

		public override void DeleteServiceItems(ServiceProviderItem[] items)
		{
			foreach (ServiceProviderItem item in items)
			{
				if (item is MailDomain)
				{
					try
					{
						// delete mail domain
						DeleteDomain(item.Name);
					}
					catch (Exception ex)
					{
						Log.WriteError(String.Format("Error deleting '{0}' mail domain", item.Name), ex);
					}
				}
			}
		}

		public override void ChangeServiceItemsState(ServiceProviderItem[] items, bool enabled)
		{
			foreach (ServiceProviderItem item in items)
			{
				if (item is MailDomain)
				{
					try
					{
						MailDomain domain = GetDomain(item.Name);
						domain.Enabled = enabled;
						// update mail domain
						UpdateDomain(domain);
					}
					catch (Exception ex)
					{
						Log.WriteError(String.Format("Error switching '{0}' mail domain", item.Name), ex);
					}
				}
			}
		}

		#endregion

        public override bool  IsInstalled()
        {
            string name = null;
            string versionNumber = null;

            RegistryKey HKLM = Registry.LocalMachine;

            RegistryKey key = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Ability Mail Server 2_is1");

            if (key != null)
            {
                name = (string) key.GetValue("DisplayName");
                string[] parts = name.Split(new char[] {' '});
                versionNumber = parts[3];
            }
            else
            {
                key = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Ability Mail Server 2_is1");
                if (key != null)
                {
                    name = (string)key.GetValue("DisplayName");
                    string[] parts = name.Split(new char[] { ' ' });
                    versionNumber = parts[3];
                }
                else
                {
                    return false;
                }
            }

            string[] split = versionNumber.Split(new char[] {'.'});

            return split[0].Equals("2");
        }

	}
}


text:
from xml.etree.cElementTree import parse, tostring

def xmlpp(source):
    root = parse(source).getroot()
    indent(root)
    return tostring(root)

def indent(elem, level=0):
    i = "\n" + level*"  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
/// <reference path="../../../Scripts/endgate.d.ts" />
/// <reference path="BurningFlame.ts" />
/// <reference path="SmokePoofManager.ts" />
// Wrap in module to keep code out of global scope
var AudioHandling;
(function (AudioHandling) {
    var Game = (function (_super) {
        __extends(Game, _super);
        function Game(canvas) {
            _super.call(this, canvas);

            // Create the burning flame at the center of the canvas
            this._burningFlame = new AudioHandling.BurningFlame(canvas.width / 2, canvas.height / 2);

            // Add the burning flames graphic to the Scene (so it can be drawn)
            this.Scene.Add(this._burningFlame.Graphic);

            // We pass in the loaded AudioPlayer for the smoke poof sound
            // We provide two sound files so that it can play properly in all browsers. If one sound file fails to load/play
            // the other will be loaded and played.
            this._smokePoofManager = new AudioHandling.SmokePoofManager(this.Input.Mouse, this.Scene, this.Audio.Load("poof", ["/Content/Samples/AudioHandling/sounds/smokepoof.ogg", "/Content/Samples/AudioHandling/sounds/smokepoof.mp3"]));

            // Load our burning flame sound under the key "burning"
            // We provide two sound files for the same reason as detailed above
            this.Audio.Load("burning", ["/Content/Samples/AudioHandling/sounds/fireburning.ogg", "/Content/Samples/AudioHandling/sounds/fireburning.mp3"]);

            // Play our burning sound on repeat at 75% volume.  The this._burningSound allows for modification of the sound after
            // it has begun to play.  However, in this sample we do not do any modifications to the sound once we play it.
            // The reason why we still save the playing sound is to prevent it from being garbage collected.
            this._burningSound = this.Audio.Play("burning", new eg.Sound.AudioSettings(true, 75));
        }
        Game.prototype.Update = function (gameTime) {
            this._burningFlame.Update(gameTime);
            this._smokePoofManager.Update(gameTime);
        };
        return Game;
    })(eg.Game);
    AudioHandling.Game = Game;
})(AudioHandling || (AudioHandling = {}));
//@ sourceMappingURL=Game.js.map


text:
class EXPA::Surveys < ActiveEXPA::Base
  class << self

  end
end