text:
	<alm-dialog
		(pfDialogClick)="onButtonClick($event)"
		[dialog]='dialog'
  ></alm-dialog>

		<input type="checkbox" [checked]="checkedWI" (click)="toggleEntry($event)" />

       {{workItem.attributes['system.number']}}

{{workItem.attributes['system.title']}}

          {{workItem.attributes['system.description'] ? workItem.attributes['system.description'] : "No description available for this work item."}}

			<button class="btn btn-link workItemList_dropdownKebabBtn dropdown-toggle" type="button" id="dropdownKebabRight" aria-haspopup="true" aria-expanded="true" dropdownToggle>

			</button>

Move to Top

Move to Bottom

Associate with Iteration...

Open

Move to Backlog

<fab-planner-associate-iteration-modal
  [workItem]="workItem"
  #associateIterationModal>
</fab-planner-associate-iteration-modal>


text:
@interface SWPSimpleCategory : NSObject <SWPCategory>

@property (nonatomic, copy) NSString *name;

+ (SWPSimpleCategory *)categoryWithName:(NSString *)categoryName;

@end

redpajama_set_name: RedPajamaGithub


text:
@interface KIFTestStep (textField)

+ (id)stepToClearTextFieldWithLabel:(NSString *)label;

@end


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Management;
using Microsoft.WindowsAzure.Management.Models;

namespace Microsoft.WindowsAzure
{
    /// <summary>
    /// The Service Management API provides programmatic access to much of the
    /// functionality available through the Management Portal. The Service
    /// Management API is a REST API. All API operations are performed over
    /// SSL and are mutually authenticated using X.509 v3 certificates.  (see
    /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
    /// more information)
    /// </summary>
    public static partial class AffinityGroupOperationsExtensions
    {
        /// <summary>
        /// The Create Affinity Group operation creates a new affinity group
        /// for the specified subscription.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Create Affinity Group
        /// operation.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static OperationResponse Create(this IAffinityGroupOperations operations, AffinityGroupCreateParameters parameters)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IAffinityGroupOperations)s).CreateAsync(parameters);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// The Create Affinity Group operation creates a new affinity group
        /// for the specified subscription.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Create Affinity Group
        /// operation.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static Task<OperationResponse> CreateAsync(this IAffinityGroupOperations operations, AffinityGroupCreateParameters parameters)
        {
            return operations.CreateAsync(parameters, CancellationToken.None);
        }

        /// <summary>
        /// The Delete Affinity Group operation deletes an affinity group in
        /// the specified subscription.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <param name='affinityGroupName'>
        /// Required. The name of the affinity group.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static OperationResponse Delete(this IAffinityGroupOperations operations, string affinityGroupName)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IAffinityGroupOperations)s).DeleteAsync(affinityGroupName);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// The Delete Affinity Group operation deletes an affinity group in
        /// the specified subscription.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <param name='affinityGroupName'>
        /// Required. The name of the affinity group.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static Task<OperationResponse> DeleteAsync(this IAffinityGroupOperations operations, string affinityGroupName)
        {
            return operations.DeleteAsync(affinityGroupName, CancellationToken.None);
        }

        /// <summary>
        /// The Get Affinity Group Properties operation returns the system
        /// properties associated with the specified affinity group.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <param name='affinityGroupName'>
        /// Required. The name of the desired affinity group as returned by the
        /// name element of the List Affinity Groups operation.
        /// </param>
        /// <returns>
        /// The Get Affinity Group operation response.
        /// </returns>
        public static AffinityGroupGetResponse Get(this IAffinityGroupOperations operations, string affinityGroupName)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IAffinityGroupOperations)s).GetAsync(affinityGroupName);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// The Get Affinity Group Properties operation returns the system
        /// properties associated with the specified affinity group.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <param name='affinityGroupName'>
        /// Required. The name of the desired affinity group as returned by the
        /// name element of the List Affinity Groups operation.
        /// </param>
        /// <returns>
        /// The Get Affinity Group operation response.
        /// </returns>
        public static Task<AffinityGroupGetResponse> GetAsync(this IAffinityGroupOperations operations, string affinityGroupName)
        {
            return operations.GetAsync(affinityGroupName, CancellationToken.None);
        }

        /// <summary>
        /// The List Affinity Groups operation lists the affinity groups
        /// associated with the specified subscription.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <returns>
        /// The List Affinity Groups operation response.
        /// </returns>
        public static AffinityGroupListResponse List(this IAffinityGroupOperations operations)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IAffinityGroupOperations)s).ListAsync();
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// The List Affinity Groups operation lists the affinity groups
        /// associated with the specified subscription.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <returns>
        /// The List Affinity Groups operation response.
        /// </returns>
        public static Task<AffinityGroupListResponse> ListAsync(this IAffinityGroupOperations operations)
        {
            return operations.ListAsync(CancellationToken.None);
        }

        /// <summary>
        /// The Update Affinity Group operation updates the label and/or the
        /// description for an affinity group for the specified subscription.
        /// (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <param name='affinityGroupName'>
        /// Required. The name of the affinity group.
        /// </param>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Update Affinity Group
        /// operation.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static OperationResponse Update(this IAffinityGroupOperations operations, string affinityGroupName, AffinityGroupUpdateParameters parameters)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IAffinityGroupOperations)s).UpdateAsync(affinityGroupName, parameters);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <summary>
        /// The Update Affinity Group operation updates the label and/or the
        /// description for an affinity group for the specified subscription.
        /// (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx
        /// for more information)
        /// </summary>
        /// <param name='operations'>
        /// Reference to the
        /// Microsoft.WindowsAzure.Management.IAffinityGroupOperations.
        /// </param>
        /// <param name='affinityGroupName'>
        /// Required. The name of the affinity group.
        /// </param>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Update Affinity Group
        /// operation.
        /// </param>
        /// <returns>
        /// A standard service response including an HTTP status code and
        /// request ID.
        /// </returns>
        public static Task<OperationResponse> UpdateAsync(this IAffinityGroupOperations operations, string affinityGroupName, AffinityGroupUpdateParameters parameters)
        {
            return operations.UpdateAsync(affinityGroupName, parameters, CancellationToken.None);
        }
    }
}


text:
TEMPLATE="template/index.html"

function get_all_slides {
  slides_dir="arch java testing ops tasking"
  for i in $slides_dir; do
    echo $i
  done
}

function get_all_slides_markdown {
  for dir in `get_all_slides`; do
    for i in `find $dir -name '*.md'`; do
      echo $i
    done
  done
}

function process {
  mdfile=$1
  dirname=`dirname $mdfile`
  filename=`basename $mdfile`
  target=$dirname/index.html
  cp -fv $TEMPLATE $target
  gsed -i "s/\\\$filename\\\$/$filename/" "$target"

  title=`head -1 $mdfile | tr -d '#'`
  if [[ -n $title ]]; then
    gsed -i "s/\\\$title\\\$/$title/" "$target"
  fi
}

function process_all {
  for i in `get_all_slides_markdown`; do
    process $i
  done
}

process_all


text:
package com.packt.snake.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.packt.snake.SnakeGame;

public class DesktopLauncher {
	public static void main (String[] arg) {
		LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
		new LwjglApplication(new SnakeGame(), config);
	}
}


text:
quasardb benchmarking tool
--------------------------

`qdb-benchmark` is a performance testing tool for quasardb.
However it's been designed to be independent of quasardb and can be used to benchmark other engines.

`qdb-benchmark` contains a pool of predefined tests. It prepares a set of tests in various configuration and runs them one after the other.

A "test" is a code that performs a basic operation running in a loop.
When a test requires some kind of preparation before running, it's done in its "setup" phase.
Similarly, when a test requires some home keeping, it's done in its "cleanup" phase.

Tests leaves the database in the same state as before: unique keys are used that should not conflict with existing data. Added entries are removed at the end of each test.
Altough it's not recommended, `qdb-benchmark` can be used on a production database.

Depending on the options provided on the command line, `qdb-benchmark` will run one or more tests. Each test is run against one or more threading configuration. Each test is run against one or more input size.

`qdb-benchmark` samples the number of iterations at a regular pace, the resulting data is saved in a `results.jsonp` in the current folder. When running quasardb tests, it also samples information from the nodes, like the memory load for example.

There is an HTML report template that can be used to view the tests results in a web browser.
To use it, just copy `results.jsonp` in the `html_report/` folder and open `index.html` in your browser.

# Usage

## Basic usage

    qdb-benchmark -c qdb://127.0.0.1:2836 --tests qdb_blob_put,qdb_blob_get --threads 1,2,4 --sizes 1K,1M

This will run 12 tests:

1. `qdb_blob_put`, with a content of 1KB, running on 1 thread
2. `qdb_blob_put`, with a content of 1KB, running on 2 threads
3. `qdb_blob_put`, with a content of 1KB, running on 4 threads
4. `qdb_blob_put`, with a content of 1MB, running on 1 thread
5. `qdb_blob_put`, with a content of 1MB, running on 2 threads
6. `qdb_blob_put`, with a content of 1MB, running on 4 threads
7. `qdb_blob_get`, with a content of 1KB, running on 1 thread
8. `qdb_blob_get`, with a content of 1KB, running on 2 threads
9. `qdb_blob_get`, with a content of 1KB, running on 4 threads
10. `qdb_blob_get`, with a content of 1MB, running on 1 thread
11. `qdb_blob_get`, with a content of 1MB, running on 2 threads
12. `qdb_blob_get`, with a content of 1MB, running on 4 threads

Each test will run during approximately 4 seconds, and there will be a pause of 1 second between each test.

## Options

#### `--cluster` or `-c`

Sets the cluster's address.

When testing a quasardb cluster, the value must have the form `qdb://ip:port`.

The default value is `qdb://127.0.0.1:2836`.

#### `--pause` or `-p`

Sets the delay between each test, in seconds.

The default value is `1` second.

#### `--duration` or `-d`

Sets the duration of each test, in seconds.

Tests are not bound to a number of iteration, instead they are executed until this timeout is reached.
Some tests have a long running setup; in that case the timeout is used to limit the duration of the setup, and the test is executed according to the number of iteration prepared during the setup.

The default value is `4` seconds.

#### `--threads` or `-t`

Sets the number of threads to run each test.

The default is `1,2,4`, therefore running each test 3 times: a first time with 1 thread, then with 2 and a last time with 4 threads.

#### `--sizes`

Sets the contents sizes for each test.

Most tests (for example `qdb_blob_put`) have different results depending on the size of the input. Some tests, like ``qdb_int_add`, don't depend on the size.

The default value is `1,1K,1M`, therefore running each test 3 times: a first time with an input of 1 byte, then with 1 kilobyte and a last time with 1 megabyte.

#### `--iterations` or `-i`

Sets the number of iterations done for each test.

It silences the (default) duration option.

The default value is `0`, meaning it's not active and the tests will run until the specified duration has elapsed.

#### `--tests`

Sets the names of the tests to run. You can use `*` at the beginning or end of a test name to select multiple tests at once.

To know the list of supported tests, just run `qdb-benchmark --help` or `qdb-benchmark --show-tests`.

The current list of supported tests is:

1. qdb_blob_attach_tag
1. qdb_blob_get
1. qdb_blob_get_noalloc
1. qdb_blob_put
1. qdb_blob_remove
1. qdb_blob_update
1. qdb_int_add
1. qdb_int_get
1. qdb_int_put
1. qdb_int_remove
1. qdb_int_update
1. qdb_stream_write
1. std_atomic
1. std_fread
1. std_fwrite
1. std_mutex

The default is to run all tests, which can be quite long.


text:
<?php

namespace Goetas\Mail\ToSwiftMailParser\Exception;

class InvalidMessageFormatException extends \Exception
{
}


text:
package org.apache.beam.sdk.extensions.euphoria.core.client.operator;

import static java.util.Objects.requireNonNull;

import org.apache.beam.sdk.extensions.euphoria.core.annotation.audience.Audience;
import org.apache.beam.sdk.extensions.euphoria.core.annotation.operator.Derived;
import org.apache.beam.sdk.extensions.euphoria.core.annotation.operator.StateComplexity;
import org.apache.beam.sdk.extensions.euphoria.core.client.functional.UnaryPredicate;
import org.apache.beam.sdk.extensions.euphoria.core.client.io.Collector;
import org.apache.beam.sdk.extensions.euphoria.core.client.operator.base.Builders;
import org.apache.beam.sdk.extensions.euphoria.core.client.operator.base.Operator;
import org.apache.beam.sdk.extensions.euphoria.core.client.util.PCollectionLists;
import org.apache.beam.sdk.extensions.euphoria.core.translate.OperatorTransform;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionList;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * Operator performing a filter operation.
 *
 *
Output elements that pass given condition.
 *
 *
Builders:

 *
 *

 *
{@code [named] ..................} give name to the operator [optional]
 *
{@code of .......................} input dataset
 *
{@code by .......................} apply {@link UnaryPredicate} to input elements
 *
{@code output ...................} build output dataset
 *

 */
@Audience(Audience.Type.CLIENT)
@Derived(state = StateComplexity.ZERO, repartitions = 0)
@SuppressWarnings({
  "rawtypes", // TODO(https://issues.apache.org/jira/browse/BEAM-10556)
  "nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public class Filter<InputT> extends Operator<InputT> implements CompositeOperator<InputT, InputT> {

  /**
   * Starts building a nameless {@link Filter} operator to process the given input dataset.
   *
   * @param <InputT> the type of elements of the input dataset
   * @param input the input data set to be processed
   * @return a builder to complete the setup of the new operator
   * @see #named(String)
   * @see OfBuilder#of(PCollection)
   */
  public static <InputT> ByBuilder<InputT> of(PCollection<InputT> input) {
    return named(null).of(input);
  }

  /**
   * Starts building a named {@link Filter} operator.
   *
   * @param name a user provided name of the new operator to build
   * @return a builder to complete the setup of the new operator
   */
  public static OfBuilder named(@Nullable String name) {
    return new Builder(name);
  }

  /** Builder for the 'of' step. */
  public interface OfBuilder extends Builders.Of {

    @Override
    <InputT> ByBuilder<InputT> of(PCollection<InputT> input);
  }

  /** Builder for the 'by' step. */
  public interface ByBuilder<InputT> {

    /**
     * Specifies the function that is capable of input elements filtering.
     *
     * @param predicate the function that filters out elements if the return value for the element
     *     is false
     * @return the next builder to complete the setup of the operator
     */
    Builders.Output<InputT> by(UnaryPredicate<InputT> predicate);
  }

  private static class Builder<InputT>
      implements OfBuilder, ByBuilder<InputT>, Builders.Output<InputT> {

    private final @Nullable String name;
    private PCollection<InputT> input;
    private UnaryPredicate<InputT> predicate;

    private Builder(@Nullable String name) {
      this.name = name;
    }

    @Override
    public <T> ByBuilder<T> of(PCollection<T> input) {
      @SuppressWarnings("unchecked")
      final Builder<T> cast = (Builder) this;
      cast.input = requireNonNull(input);
      return cast;
    }

    @Override
    public Builders.Output<InputT> by(UnaryPredicate<InputT> predicate) {
      this.predicate = requireNonNull(predicate);
      return this;
    }

    @Override
    public PCollection<InputT> output() {
      final Filter<InputT> filter = new Filter<>(name, predicate, input.getTypeDescriptor());
      return OperatorTransform.apply(filter, PCollectionList.of(input));
    }
  }

  private final UnaryPredicate<InputT> predicate;

  private Filter(
      @Nullable String name,
      UnaryPredicate<InputT> predicate,
      @Nullable TypeDescriptor<InputT> outputType) {
    super(name, outputType);
    this.predicate = predicate;
  }

  public UnaryPredicate<InputT> getPredicate() {
    return predicate;
  }

  @Override
  public PCollection<InputT> expand(PCollectionList<InputT> inputs) {
    return FlatMap.named(getName().orElse(null))
        .of(PCollectionLists.getOnlyElement(inputs))
        .using(
            (InputT element, Collector<InputT> collector) -> {
              if (getPredicate().apply(element)) {
                collector.collect(element);
              }
            },
            getOutputType().orElse(null))
        .output();
  }
}


text:
extern "C"
{
#include "clang-c/Index.h"
}

#include <iostream>

enum CXChildVisitResult visitNode(CXCursor cursor, CXCursor /*parent*/,
                                  CXClientData /*client_data*/)
{
    if (clang_getCursorKind(cursor) == CXCursor_CXXMethod or
        clang_getCursorKind(cursor) == CXCursor_FunctionDecl)
    {
        CXString name = clang_getCursorSpelling(cursor);
        CXSourceLocation loc = clang_getCursorLocation(cursor);
        CXString fName;
        unsigned line = 0;
        unsigned col = 0;
        clang_getPresumedLocation(loc, &fName, &line, &col);
        std::cout << clang_getCString(fName) << ":"
                  << line << ":" << col << " declares "
                  << clang_getCString(name) << '\n';
        return CXChildVisit_Continue;
    }
    return CXChildVisit_Recurse;
}

int main(int argc, char** argv)
{
    if (argc != 2)
    {
        return -1;
    }
    std::string fileName{argv[1]};
    CXIndex index = clang_createIndex(0, 0);
    const char *args[] = { "-I/usr/include", "-I." };
    CXTranslationUnit translationUnit =
        clang_parseTranslationUnit(index, fileName.c_str(), args, 2,
                                   nullptr, 0, CXTranslationUnit_None);
    CXCursor cur = clang_getTranslationUnitCursor(translationUnit);
    clang_visitChildren(cur, &visitNode, nullptr);

    clang_disposeTranslationUnit(translationUnit);
    clang_disposeIndex(index);
    return 0;
}


text:
package e2e

import (
	"encoding/json"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"github.com/pkg/errors"
	rbacv1 "k8s.io/api/rbac/v1"
	"kpt.dev/configsync/e2e/nomostest"
	"kpt.dev/configsync/e2e/nomostest/metrics"
	nomostesting "kpt.dev/configsync/e2e/nomostest/testing"
	"kpt.dev/configsync/pkg/api/configsync"
	"kpt.dev/configsync/pkg/core"
	"kpt.dev/configsync/pkg/kinds"
	"kpt.dev/configsync/pkg/testing/fake"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

// sortPolicyRules sorts PolicyRules lexicographically by JSON representation.
func sortPolicyRules(l, r rbacv1.PolicyRule) bool {
	jsnL, _ := json.Marshal(l)
	jsnR, _ := json.Marshal(r)
	return string(jsnL) < string(jsnR)
}

func clusterRoleHasRules(rules []rbacv1.PolicyRule) nomostest.Predicate {
	return func(o client.Object) error {
		cr, ok := o.(*rbacv1.ClusterRole)
		if !ok {
			return nomostest.WrongTypeErr(cr, &rbacv1.ClusterRole{})
		}

		// Ignore the order of the policy rules.
		if diff := cmp.Diff(rules, cr.Rules, cmpopts.SortSlices(sortPolicyRules)); diff != "" {
			return errors.New(diff)
		}
		return nil
	}
}

func managerFieldsNonEmpty() nomostest.Predicate {
	return func(o client.Object) error {
		fields := o.GetManagedFields()
		if len(fields) == 0 {
			return errors.New("expect non empty manager fields")
		}
		return nil
	}
}

// TestRevertClusterRole ensures that we revert conflicting manually-applied
// changes to cluster-scoped objects.
func TestRevertClusterRole(t *testing.T) {
	nt := nomostest.New(t, nomostesting.DriftControl)

	crName := "e2e-test-clusterrole"

	err := nt.ValidateNotFound(crName, "", fake.ClusterRoleObject())
	if err != nil {
		nt.T.Fatal(err)
	}

	// Declare the ClusterRole.
	declaredRules := []rbacv1.PolicyRule{
		{
			APIGroups: []string{""},
			Resources: []string{kinds.Deployment().Kind},
			Verbs:     []string{"get", "list", "create"},
		},
	}
	declaredCr := fake.ClusterRoleObject(core.Name(crName))
	declaredCr.Rules = declaredRules
	nt.RootRepos[configsync.RootSyncName].Add("acme/cluster/clusterrole.yaml", declaredCr)
	nt.RootRepos[configsync.RootSyncName].CommitAndPush("add get/list/create ClusterRole")
	nt.WaitForRepoSyncs()

	err = nt.Validate(crName, "", &rbacv1.ClusterRole{},
		clusterRoleHasRules(declaredRules))
	if err != nil {
		nt.T.Fatalf("validating ClusterRole precondition: %v", err)
	}

	// Apply a conflicting ClusterRole.
	appliedRules := []rbacv1.PolicyRule{
		{
			APIGroups: []string{""},
			Resources: []string{kinds.Deployment().Kind},
			Verbs:     []string{"get", "list"}, // missing "create"
		},
	}
	appliedCr := fake.ClusterRoleObject(core.Name(crName))
	appliedCr.Rules = appliedRules
	err = nt.Update(appliedCr)
	// The admission webhook should deny the conflicting change.
	if err == nil {
		nt.T.Fatal("got Update error = nil, want admission webhook to deny conflicting update")
	}

	// Ensure the conflict is reverted.
	d, err := nomostest.Retry(30*time.Second, func() error {
		return nt.Validate(crName, "", &rbacv1.ClusterRole{},
			clusterRoleHasRules(declaredRules))
	})

	if err != nil {
		// err is non-nil about 1% of the time, making this a flaky test.
		// So, wait for up to ten minutes for the ClusterRole to be reverted.
		// If it doesn't after ten minutes, this is definitely a bug.
		d2, err := nomostest.Retry(20*time.Minute, func() error {
			return nt.Validate(crName, "", &rbacv1.ClusterRole{},
				clusterRoleHasRules(declaredRules))
		})
		if err == nil {
			// This was probably a flake. Consider increasing test resources or
			// reducing test parallelism.
			nt.T.Fatalf("reverted ClusterRole conflict after %v: %v", d+d2, err)
		}

		// There is definitely some sort of bug in ACM.
		nt.T.Errorf("bug alert: did not revert ClusterRole conflict after %v: %v", d+d2, err)
	}

	err = nt.ValidateMetrics(nomostest.SyncMetricsToLatestCommit(nt), func() error {
		return nt.ValidateErrorMetricsNotFound()
	})
	if err != nil {
		nt.T.Error(err)
	}
}

// TestClusterRoleLifecycle ensures we can add/update/delete cluster-scoped
// resources.
func TestClusterRoleLifecycle(t *testing.T) {
	nt := nomostest.New(t, nomostesting.Reconciliation1)

	crName := "e2e-test-clusterrole"

	err := nt.ValidateNotFound(crName, "", fake.ClusterRoleObject())
	if err != nil {
		nt.T.Fatal(err)
	}

	// Declare the ClusterRole in repo.
	declaredRules := []rbacv1.PolicyRule{
		{
			APIGroups: []string{""},
			Resources: []string{kinds.Deployment().Kind},
			Verbs:     []string{"get", "list", "create"},
		},
	}
	declaredCr := fake.ClusterRoleObject(core.Name(crName))
	declaredCr.Rules = declaredRules
	nt.RootRepos[configsync.RootSyncName].Add("acme/cluster/clusterrole.yaml", declaredCr)
	nt.RootRepos[configsync.RootSyncName].CommitAndPush("add get/list/create ClusterRole")
	nt.WaitForRepoSyncs()

	err = nt.Validate(crName, "", &rbacv1.ClusterRole{},
		clusterRoleHasRules(declaredRules), managerFieldsNonEmpty())
	if err != nil {
		nt.T.Fatalf("validating ClusterRole precondition: %v", err)
	}

	// Validate multi-repo metrics.
	err = nt.ValidateMetrics(nomostest.SyncMetricsToLatestCommit(nt), func() error {
		err := nt.ValidateMultiRepoMetrics(nomostest.DefaultRootReconcilerName,
			nt.DefaultRootSyncObjectCount()+1, // 1 for the test ClusterRole
			metrics.ResourceCreated("ClusterRole"))
		if err != nil {
			return err
		}
		return nt.ValidateErrorMetricsNotFound()
	})
	if err != nil {
		nt.T.Error(err)
	}

	// Update the ClusterRole in the SOT.
	updatedRules := []rbacv1.PolicyRule{
		{
			APIGroups: []string{""},
			Resources: []string{kinds.Deployment().Kind},
			Verbs:     []string{"get", "list"}, // missing "create"
		},
	}
	updatedCr := fake.ClusterRoleObject(core.Name(crName))
	updatedCr.Rules = updatedRules
	nt.RootRepos[configsync.RootSyncName].Add("acme/cluster/clusterrole.yaml", updatedCr)
	nt.RootRepos[configsync.RootSyncName].CommitAndPush("update ClusterRole to get/list")
	nt.WaitForRepoSyncs()

	// Ensure the resource is updated.
	if err = nt.Validate(crName, "", &rbacv1.ClusterRole{}, clusterRoleHasRules(updatedRules), managerFieldsNonEmpty()); err != nil {
		nt.T.Errorf("updating ClusterRole: %v", err)
	}

	// Validate multi-repo metrics.
	err = nt.ValidateMetrics(nomostest.SyncMetricsToLatestCommit(nt), func() error {
		err := nt.ValidateMultiRepoMetrics(nomostest.DefaultRootReconcilerName,
			nt.DefaultRootSyncObjectCount()+1, // 1 for the test ClusterRole
			metrics.ResourcePatched("ClusterRole", 2))
		if err != nil {
			return err
		}
		return nt.ValidateErrorMetricsNotFound()
	})
	if err != nil {
		nt.T.Error(err)
	}

	// Delete the ClusterRole from the SOT.
	nt.RootRepos[configsync.RootSyncName].Remove("acme/cluster/clusterrole.yaml")
	nt.RootRepos[configsync.RootSyncName].CommitAndPush("deleting ClusterRole")
	nt.WaitForRepoSyncs()

	err = nt.ValidateNotFound(crName, "", &rbacv1.ClusterRole{})
	if err != nil {
		nt.T.Errorf("deleting ClusterRole: %v", err)
	}

	// Validate multi-repo metrics.
	err = nt.ValidateMetrics(nomostest.SyncMetricsToLatestCommit(nt), func() error {
		err := nt.ValidateMultiRepoMetrics(nomostest.DefaultRootReconcilerName,
			nt.DefaultRootSyncObjectCount(),
			metrics.ResourceDeleted("ClusterRole"))
		if err != nil {
			return err
		}
		return nt.ValidateErrorMetricsNotFound()
	})
	if err != nil {
		nt.T.Error(err)
	}
}


text:
package org.kitfox.mvel;

public class Role {
    String role;

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Role [role=" + role + "]";
    }

}


text:
/**
 * Created by wQ on 2017/4/19.
 */
import { Component ,OnInit} from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import {Http} from '@angular/http';
import {FormGroup} from "@angular/forms";
import {Router} from '@angular/router';

import {RegisterService} from '../../../core/services/register.service';
import {UserService} from '../../../core/services/user.service';
import {FieldBase} from '../field/field-base';

import { Response } from '@angular/http';

@Component({
  moduleId:module.id,
  selector:'register',
  templateUrl:'register.component.html',
  styleUrls:['register.component.css']
})
export class RegisterComponent implements OnInit{
  form:FormGroup;
  registered=false;
  fields:FieldBase<any>[]=[];
  alert:any={msg:'注册成功',type:'success',closable:true,src:'success.png'};
  username:string;
  password:string;

  constructor(private rs:RegisterService,
              private router:Router,
              private us:UserService,
              private http:Http){
    this.fields=rs.getFields();
  }
  //组件初始化
  ngOnInit(){
    this.form=this.rs.toFormGroup(this.fields);
    document.querySelector('section').style.height=document.documentElement.clientHeight+'px';
  }
  showPassword(){
    this.fields.forEach((field:any)=>{
      if(field.key === 'password'){
        field.type=field.type === 'password' ? 'text' : 'password';
      }
    });
  }
  //表单重置
  resetForm(){
    this.form.reset();
  }
  register(){
    //提交注册信息  subscribe()方法的第二个参数来处理错误信息
    this.rs.addUser(this.form.value).subscribe((res:Response) => {
      //json()方法把服务器返回的数据转换成JSON对象
      let body=res.json();
      this.registered=true;
      new Observable((observer:Observer<any>)=>{
        this.alert.msg= body.message || '注册成功';
        this.alert.type=body.success ? "success" : "danger";
        this.alert.src=body.success ? "success.png" : "fail.png";
        this.registered=true;
        observer.next(true);
      }).subscribe(data => {  //操作提示,1.5秒后跳转到首页 有.subscribe()函数,bosy.seccess,this.alert.type,this.alert.mag值正确,没有的话会出错(注册过的用户名还会注册成功)
        var This=this;
        setTimeout(function () {
          if(body.success){
            This.us.isLogin=true;
            This.router.navigate(['']); //跳到首页
            This.us.userInfo = { username: This.form.value.username,createDate:new Date().toLocaleString()}  // 缓存用户信息,显示在导航栏上
          }
          This.registered=false;
        },1500);

      });

    },error=>{
      console.error(error);
    });
  }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Fasterflect;

namespace GraphicsMagick
{
	public static class Quantum
	{
		static Quantum()
		{
		}
		public static Int32 Depth
		{
			get
			{
				object result;
				try
				{
					result = Types.Quantum.GetPropertyValue("Depth");
				}
				catch (Exception ex)
				{
					throw ExceptionHelper.Create(ex);
				}
				return (Int32)result;
			}
		}
		public static Byte Max
		{
			get
			{
				object result;
				try
				{
					result = Types.Quantum.GetPropertyValue("Max");
				}
				catch (Exception ex)
				{
					throw ExceptionHelper.Create(ex);
				}
				return (Byte)result;
			}
		}
	}
}


text:
// Copyright (c) by advancedfx.org
//
// Last changes:
// 2010-03-20 dominik.matrixstorm.com
//
// First changes
// 2010-03-20 dominik.matrixstorm.com

#include <shared/com/PipeCom.h>
#include <shared/com/AfxGoldSrcComDefs.h>

using namespace AfxGoldSrcCom;

class AfxGoldSrcComClient;

typedef void (* AfxGoldSrcComClientEvent)(AfxGoldSrcComClient * com);

class AfxGoldSrcComClient : public PipeCom
{
public:
	/// <summary> Creates and starts the com client. </summary>
	AfxGoldSrcComClient();

	~AfxGoldSrcComClient();

	/// <summary> Closes the communication client. </summary>
	void Close();

	/// <summary> full screen mode? </summary>
	bool GetFullScreen();

	/// <summary> force alpha bit planes request? </summary>
	bool GetForceAlpha8();

	int GetHeight();

	/// <summary> GameWindow parent (for docked mode) </summary>
	HWND GetParentWindow();

	int GetWidth();

	/// <summary> Desired render mode. </summary>
	ComRenderMode GetRenderMode();

	/// <summary> Whether to optimize window visibility for capturing (to
	/// make as much pixels visible as possible to prevent undefined pixel
	/// content. </summary>
	bool GetOptimizeCaptureVis();

	void OnRecordEnded();

	void OnRecordStarting();

	void OnHostFrame();

	ServerMessage RecvMessage(void);

	void SendMessage(ClientMessage message);

	/// <summary> Update Parent Window with new GameWindow size. </summary>
	void UpdateWindowSize(int x, int y);

	//
	// Events:

private:
	bool m_Connected;
	bool m_ForceAlpha8;
	bool m_FullScreen;
	int m_Height;
	bool m_OptimizeCaptureVis;
	int m_ParentWindow;
	ComRenderMode m_RenderMode;
	int m_Width;
};

/// <summary> global static singleton instance. </summary>
extern AfxGoldSrcComClient g_AfxGoldSrcComClient;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.github.lxyscls.jvmjava.classfile.constant;

import com.github.lxyscls.jvmjava.classfile.ClassReader;

/**
 *
 * @author sk-xinyilong
 */
public class ConstantDoubleInfo extends ConstantInfo {
    private final double val;

    ConstantDoubleInfo(ClassReader reader) {
        val = reader.readUint64().doubleValue();
    }

    public Double getValue() {
        return val;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/day_tag_photo"
        android:orderInCategory="100"
        android:title="@string/Photo"
        />
    <item
        android:id="@+id/day_tag_insert"
        android:orderInCategory="100"
        android:title="@string/PhotoImport"
        />
</menu>


text:
package com.microsoft.azure.management.datafactory.v2018_06_01;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.microsoft.rest.serializer.JsonFlatten;

/**
 * This activity executes inner activities until the specified boolean
 * expression results to true or timeout is reached, whichever is earlier.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = UntilActivity.class)
@JsonTypeName("Until")
@JsonFlatten
public class UntilActivity extends ControlActivity {
    /**
     * An expression that would evaluate to Boolean. The loop will continue
     * until this expression evaluates to true.
     */
    @JsonProperty(value = "typeProperties.expression", required = true)
    private Expression expression;

    /**
     * Specifies the timeout for the activity to run. If there is no value
     * specified, it takes the value of TimeSpan.FromDays(7) which is 1 week as
     * default. Type: string (or Expression with resultType string), pattern:
     * ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). Type: string (or
     * Expression with resultType string), pattern:
     * ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
     */
    @JsonProperty(value = "typeProperties.timeout")
    private Object timeout;

    /**
     * List of activities to execute.
     */
    @JsonProperty(value = "typeProperties.activities", required = true)
    private List<Activity> activities;

    /**
     * Get an expression that would evaluate to Boolean. The loop will continue until this expression evaluates to true.
     *
     * @return the expression value
     */
    public Expression expression() {
        return this.expression;
    }

    /**
     * Set an expression that would evaluate to Boolean. The loop will continue until this expression evaluates to true.
     *
     * @param expression the expression value to set
     * @return the UntilActivity object itself.
     */
    public UntilActivity withExpression(Expression expression) {
        this.expression = expression;
        return this;
    }

    /**
     * Get specifies the timeout for the activity to run. If there is no value specified, it takes the value of TimeSpan.FromDays(7) which is 1 week as default. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
     *
     * @return the timeout value
     */
    public Object timeout() {
        return this.timeout;
    }

    /**
     * Set specifies the timeout for the activity to run. If there is no value specified, it takes the value of TimeSpan.FromDays(7) which is 1 week as default. Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])). Type: string (or Expression with resultType string), pattern: ((\d+)\.)?(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9])).
     *
     * @param timeout the timeout value to set
     * @return the UntilActivity object itself.
     */
    public UntilActivity withTimeout(Object timeout) {
        this.timeout = timeout;
        return this;
    }

    /**
     * Get list of activities to execute.
     *
     * @return the activities value
     */
    public List<Activity> activities() {
        return this.activities;
    }

    /**
     * Set list of activities to execute.
     *
     * @param activities the activities value to set
     * @return the UntilActivity object itself.
     */
    public UntilActivity withActivities(List<Activity> activities) {
        this.activities = activities;
        return this;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$/src/com/illescasDaniel/ClientServer/ClientServer.java" charset="UTF-8" />
  </component>
</project>


text:
package ubic.gemma.core.genome.gene.service;

import gemma.gsec.SecurityService;
import org.apache.commons.lang3.StringUtils;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ubic.gemma.core.genome.gene.GeneSetValueObjectHelper;
import ubic.gemma.core.genome.gene.SessionBoundGeneSetValueObject;
import ubic.gemma.core.search.GeneSetSearch;
import ubic.gemma.model.genome.Gene;
import ubic.gemma.model.genome.Taxon;
import ubic.gemma.model.genome.TaxonValueObject;
import ubic.gemma.model.genome.gene.*;
import ubic.gemma.persistence.service.genome.gene.GeneSetDao;
import ubic.gemma.persistence.service.genome.taxon.TaxonService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

/**
 * Service for managing gene sets
 *
 * @author kelsey
 */
@Service
public class GeneSetServiceImpl implements GeneSetService {

    private static final Double DEFAULT_SCORE = 0.0;

    @Autowired
    private GeneService geneService;

    @Autowired
    private GeneSetDao geneSetDao = null;

    @Autowired
    private GeneSetSearch geneSetSearch;

    @Autowired
    private GeneSetValueObjectHelper geneSetValueObjectHelper;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private TaxonService taxonService;

    @SuppressWarnings("unchecked")
    @Override
    @Transactional
    public Collection<GeneSet> create( Collection<GeneSet> sets ) {
        return this.geneSetDao.create( sets );
    }

    @Override
    @Transactional
    public GeneSet create( GeneSet geneset ) {
        return this.geneSetDao.create( geneset );
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> findByGene( Gene gene ) {
        return this.geneSetDao.findByGene( gene );
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<? extends DatabaseBackedGeneSetValueObject> loadValueObjectsLite( Collection<Long> ids ) {
        return this.geneSetDao.loadValueObjectsLite( ids );
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<? extends DatabaseBackedGeneSetValueObject> loadValueObjects( Collection<Long> ids ) {
        return this.geneSetDao.loadValueObjects( ids );

    }

    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> findByName( String name ) {
        return this.geneSetDao.findByName( name );
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> findByName( String name, Taxon taxon ) {
        return this.geneSetDao.findByName( name, taxon );
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> load( Collection<Long> ids ) {
        return this.geneSetDao.load( ids );

    }

    @Override
    @Transactional(readOnly = true)
    public GeneSet load( Long id ) {
        return this.geneSetDao.load( id );
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> loadAll() {
        return this.geneSetDao.loadAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> loadAll( Taxon tax ) {
        return this.geneSetDao.loadAll( tax );
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> loadMyGeneSets() {
        return this.geneSetDao.loadMyGeneSets();
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> loadMyGeneSets( Taxon tax ) {
        return ( Collection<GeneSet> ) this.geneSetDao.loadMyGeneSets( tax );
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> loadMySharedGeneSets() {
        return ( Collection<GeneSet> ) this.geneSetDao.loadMySharedGeneSets();
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> loadMySharedGeneSets( Taxon tax ) {
        return ( Collection<GeneSet> ) this.geneSetDao.loadMySharedGeneSets( tax );
    }

    @Override
    @Transactional
    public void remove( Collection<GeneSet> sets ) {
        this.geneSetDao.remove( sets );
    }

    @Override
    @Transactional
    public void remove( GeneSet geneset ) {
        this.geneSetDao.remove( geneset );
    }

    @Override
    @Transactional
    public void update( Collection<GeneSet> sets ) {
        this.geneSetDao.update( sets );

    }

    @Override
    @Transactional
    public void update( GeneSet geneset ) {
        this.geneSetDao.update( geneset );

    }

//    @Override
//    @Transactional
//    public void addGene(GeneSet geneset, Gene gene) {
//        this.geneSetDao.addGeneToSet(geneset, gene);
//    }
//
//    @Override
//    @Transactional
//    public void removeGene(GeneSet geneset, Gene gene) {
//        this.geneSetDao.removeGeneFromSet(geneset, gene);
//    }

    @Override
    @Transactional(readOnly = true)
    public DatabaseBackedGeneSetValueObject getValueObject( Long id ) {
        GeneSet geneSet = this.load( id );
        return geneSetValueObjectHelper.convertToValueObject( geneSet );
    }

    @Override
    @Transactional
    public GeneSetValueObject createDatabaseEntity( GeneSetValueObject geneSetVo ) {
        GeneSet newGeneSet = GeneSet.Factory.newInstance();
        newGeneSet.setName( geneSetVo.getName() );
        newGeneSet.setDescription( geneSetVo.getDescription() );

        Collection<Long> geneIds = geneSetVo.getGeneIds();

        // If no gene Ids just create group and return.
        if ( geneIds != null && !geneIds.isEmpty() ) {
            Collection<Gene> genes = geneService.load( geneIds );

            if ( geneIds.size() != genes.size() ) {
                Log.warn( "Not all genes were found by id: " + geneIds.size() + " ids, " + genes.size()
                        + " genes fetched" );
            }

            Collection<GeneSetMember> geneMembers = new HashSet<>();
            for ( Gene g : genes ) {
                GeneSetMember gmember = GeneSetMember.Factory.newInstance();
                gmember.setGene( g );
                gmember.setScore( GeneSetServiceImpl.DEFAULT_SCORE );
                geneMembers.add( gmember );
            }

            newGeneSet.setMembers( geneMembers );
        }

        GeneSet gset = this.create( newGeneSet );

        // make groups private by default
        // can't do this to newGeneSet variable because the entity's id needs to be non-null
        if ( geneSetVo.getIsPublic() ) {
            securityService.makePublic( gset );
        } else {
            securityService.makePrivate( gset );
        }

        return geneSetValueObjectHelper.convertToValueObject( this.load( gset.getId() ) );
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSetValueObject> findGeneSetsByGene( Long geneId ) {

        Gene gene = geneService.load( geneId );

        Collection<GeneSet> genesets = geneSetSearch.findByGene( gene );

        Collection<GeneSetValueObject> gsvos = new ArrayList<>();
        //noinspection CollectionAddAllCanBeReplacedWithConstructor // not possible safely
        gsvos.addAll( geneSetValueObjectHelper.convertToValueObjects( genesets, false ) );
        return gsvos;
    }

    @Override
    @Transactional
    public DatabaseBackedGeneSetValueObject updateDatabaseEntityNameDesc( DatabaseBackedGeneSetValueObject geneSetVO ) {

        Long groupId = geneSetVO.getId();
        GeneSet gset = this.load( groupId );
        if ( gset == null ) {
            throw new IllegalArgumentException( "No gene set with id=" + groupId + " could be loaded" );
        }

        gset.setDescription( geneSetVO.getDescription() );
        if ( geneSetVO.getName() != null && geneSetVO.getName().length() > 0 )
            gset.setName( geneSetVO.getName() );
        this.update( gset );

        return geneSetValueObjectHelper.convertToValueObject( gset );

    }

    @Override
    @Transactional
    public void updateDatabaseEntityMembers( Long groupId, Collection<Long> geneIds ) {

        GeneSet gSet = this.load( groupId );
        if ( gSet == null ) {
            throw new IllegalArgumentException( "No gene set with id=" + groupId + " could be loaded" );
        }
        Collection<GeneSetMember> updatedGenelist = new HashSet<>();

        if ( geneIds.isEmpty() ) {
            throw new IllegalArgumentException( "No gene ids provided. Cannot save an empty set." );
        }

        Collection<Gene> genes = geneService.load( geneIds );

        if ( genes.isEmpty() ) {
            throw new IllegalArgumentException(
                    "None of the gene ids were valid (out of " + geneIds.size() + " provided)" );
        }
        if ( genes.size() < geneIds.size() ) {
            throw new IllegalArgumentException(
                    "Some of the gene ids were invalid: only found " + genes.size() + " out of " + geneIds.size()
                            + " provided)" );
        }

        assert genes.size() == geneIds.size();

        this.checkGeneList( gSet, updatedGenelist, genes );

        gSet.getMembers().clear();
        gSet.getMembers().addAll( updatedGenelist );

        this.update( gSet );
    }

    @Override
    @Transactional
    public Collection<DatabaseBackedGeneSetValueObject> updateDatabaseEntity(
            Collection<DatabaseBackedGeneSetValueObject> geneSetVos ) {

        Collection<GeneSet> updated = new HashSet<>();
        for ( DatabaseBackedGeneSetValueObject geneSetVo : geneSetVos ) {

            Long groupId = geneSetVo.getId();
            GeneSet gset = this.load( groupId );
            if ( gset == null ) {
                throw new IllegalArgumentException( "No gene set with id=" + groupId + " could be loaded" );
            }
            Collection<GeneSetMember> updatedGenelist = new HashSet<>();

            Collection<Long> geneIds = geneSetVo.getGeneIds();

            if ( geneIds.isEmpty() ) {
                throw new IllegalArgumentException( "No gene ids provided. Cannot save an empty set." );

            }
            Collection<Gene> genes = geneService.load( geneIds );

            if ( genes.isEmpty() ) {
                throw new IllegalArgumentException(
                        "None of the gene ids were valid (out of " + geneIds.size() + " provided)" );
            }
            if ( genes.size() < geneIds.size() ) {
                throw new IllegalArgumentException(
                        "Some of the gene ids were invalid: only found " + genes.size() + " out of " + geneIds.size()
                                + " provided)" );
            }

            assert genes.size() == geneIds.size();

            this.checkGeneList( gset, updatedGenelist, genes );

            gset.getMembers().clear();
            gset.getMembers().addAll( updatedGenelist );
            gset.setDescription( geneSetVo.getDescription() );
            gset.setName( geneSetVo.getName() );
            this.update( gset );

            /*
             * Make sure we return the latest.
             */
            updated.add( this.load( gset.getId() ) );
        }
        return geneSetValueObjectHelper.convertToValueObjects( updated );

    }

    @Override
    @Transactional
    public void deleteDatabaseEntity( DatabaseBackedGeneSetValueObject geneSetVO ) {
        GeneSet gset = this.load( geneSetVO.getId() );
        if ( gset != null )
            this.remove( gset );
    }

    @Override
    @Transactional
    public void deleteDatabaseEntities( Collection<DatabaseBackedGeneSetValueObject> vos ) {
        for ( DatabaseBackedGeneSetValueObject geneSetValueObject : vos ) {
            this.deleteDatabaseEntity( geneSetValueObject );
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSet> getUsersGeneGroups( boolean privateOnly, Long taxonId, boolean sharedPublicOnly ) {

        Taxon tax = null;
        if ( taxonId != null ) {
            tax = taxonService.load( taxonId );
            if ( tax == null ) {
                throw new IllegalArgumentException( "No such taxon with id=" + taxonId );
            }
        }

        Collection<GeneSet> geneSets;

        if ( privateOnly ) {
            // gets all groups user can see (includes: owned by user, shared with user & public)
            geneSets = this.loadAll( tax );

            // this filtering is to filter out public sets
            try {
                if ( !geneSets.isEmpty() ) {
                    geneSets.retainAll( securityService.choosePrivate( geneSets ) );
                }
            } catch ( AccessDeniedException e ) {
                // okay, they just aren't allowed to see those.
            }
        } else if ( sharedPublicOnly ) {
            // gets all groups shared with the user and all groups owned by the user, except public ones
            geneSets = this.loadMySharedGeneSets( tax );
        } else {
            geneSets = this.loadAll( tax );
        }

        return geneSets;
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<DatabaseBackedGeneSetValueObject> getUsersGeneGroupsValueObjects( boolean privateOnly,
            Long taxonId ) {
        Collection<GeneSet> geneSets = this.getUsersGeneGroups( privateOnly, taxonId, false );
        return geneSetValueObjectHelper.convertToValueObjects( geneSets );
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<GeneValueObject> getGenesInGroup( GeneSetValueObject object ) {

        Collection<GeneValueObject> results;

        GeneSet gs = this.load( object.getId() );
        if ( gs == null )
            return null;

        results = GeneValueObject.convertMembers2GeneValueObjects( gs.getMembers() );

        return results;

    }

    @Override
    public Collection<Long> getGeneIdsInGroup( GeneSetValueObject object ) {
        return this.getValueObject( object.getId() ).getGeneIds();
    }

    @Override
    @Transactional(readOnly = true)
    public int getSize( GeneSetValueObject object ) {
        return this.geneSetDao.getGeneCount( object.getId() );
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<GeneSetValueObject> findGeneSetsByName( String query, Long taxonId ) {

        if ( StringUtils.isBlank( query ) ) {
            return new HashSet<>();
        }
        Collection<GeneSet> foundGeneSets;
        Taxon tax = null;
        if ( taxonId == null ) {
            // throw new IllegalArgumentException( "Taxon must not be null" );
            foundGeneSets = geneSetSearch.findByName( query );
        } else {

            tax = taxonService.load( taxonId );

            if ( tax == null ) {
                // throw new IllegalArgumentException( "Can't locate taxon with id=" + taxonId );
                foundGeneSets = geneSetSearch.findByName( query );
            } else {
                foundGeneSets = geneSetSearch.findByName( query, tax );
            }
        }

        /*
         * Behaviour implemented here (easy to change): If we have a match in our system we stop here. Otherwise, we go
         * on to search the Gene Ontology.
         */

        // need taxon ID to be set for now, easy to change in Gene2GOAssociationDaoImpl.handleFindByGoTerm(String,
        // Taxon)

        if ( foundGeneSets.isEmpty() && tax != null ) {
            if ( query.toUpperCase().startsWith( "GO" ) ) {
                GeneSet goSet = this.geneSetSearch.findByGoId( query, tax );
                if ( goSet != null )
                    foundGeneSets.add( goSet );
            } else {
                foundGeneSets.addAll( geneSetSearch.findByGoTermName( query, tax ) );
            }
        }

        Collection<GeneSetValueObject> gsvos = new ArrayList<>();
        //noinspection CollectionAddAllCanBeReplacedWithConstructor // Not possible safely
        gsvos.addAll( geneSetValueObjectHelper.convertToValueObjects( foundGeneSets ) );
        return gsvos;
    }

    @Override
    @Transactional(readOnly = true)
    public TaxonValueObject getTaxonVOforGeneSetVO( SessionBoundGeneSetValueObject geneSetVO ) {

        if ( geneSetVO == null )
            return null;

        TaxonValueObject taxonVO = null;
        // get taxon from members
        for ( Long l : geneSetVO.getGeneIds() ) {
            Gene gene = geneService.load( l );

            if ( gene != null && gene.getTaxon() != null ) {
                taxonVO = TaxonValueObject.fromEntity( gene.getTaxon() );
                break;// assuming that the taxon will be the same for all genes in the set so no need to load all genes
                // from set
            }
        }

        return taxonVO;
    }

    @Override
    @Transactional(readOnly = true)
    public Taxon getTaxon( GeneSet geneSet ) {
        if ( geneSet == null )
            return null;
        Taxon tmpTax;
        tmpTax = geneSetDao.getTaxon( geneSet.getId() );

        return tmpTax;
    }

    @Override
    @Transactional(readOnly = true)
    public Collection<DatabaseBackedGeneSetValueObject> getValueObjects( Collection<Long> ids ) {
        Collection<DatabaseBackedGeneSetValueObject> vos = new ArrayList<>();
        for ( Long id : ids ) {
            vos.add( this.getValueObject( id ) );
        }
        return vos;
    }

    private void checkGeneList( GeneSet gset, Collection<GeneSetMember> updatedGenelist, Collection<Gene> genes ) {
        for ( Gene g : genes ) {

            GeneSetMember gsm = GeneSet.containsGene( g, gset );

            // Gene not in list create memember and add it.
            if ( gsm == null ) {
                GeneSetMember gmember = GeneSetMember.Factory.newInstance();
                gmember.setGene( g );
                gmember.setScore( GeneSetServiceImpl.DEFAULT_SCORE );
                gset.getMembers().add( gmember );
                updatedGenelist.add( gmember );
            } else {
                updatedGenelist.add( gsm );
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see ubic.gemma.core.genome.gene.service.GeneSetService#thaw(ubic.gemma.model.genome.gene.GeneSet)
     */
    @Override
    public void thaw( GeneSet geneSet ) {
        this.geneSetDao.thaw( geneSet );
    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.monitor.implementation;

import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.monitor.fluent.MetricNamespacesClient;
import com.azure.resourcemanager.monitor.fluent.models.MetricNamespaceInner;
import com.azure.resourcemanager.monitor.models.MetricNamespaceCollection;
import reactor.core.publisher.Mono;

/** An instance of this class provides access to all the operations defined in MetricNamespacesClient. */
public final class MetricNamespacesClientImpl implements MetricNamespacesClient {
    private final ClientLogger logger = new ClientLogger(MetricNamespacesClientImpl.class);

    /** The proxy service used to perform REST calls. */
    private final MetricNamespacesService service;

    /** The service client containing this operation class. */
    private final MonitorClientImpl client;

    /**
     * Initializes an instance of MetricNamespacesClientImpl.
     *
     * @param client the instance of the service client containing this operation class.
     */
    MetricNamespacesClientImpl(MonitorClientImpl client) {
        this.service =
            RestProxy.create(MetricNamespacesService.class, client.getHttpPipeline(), client.getSerializerAdapter());
        this.client = client;
    }

    /**
     * The interface defining all the services for MonitorClientMetricNamespaces to be used by the proxy service to
     * perform REST calls.
     */
    @Host("{$host}")
    @ServiceInterface(name = "MonitorClientMetricN")
    private interface MetricNamespacesService {
        @Headers({"Accept: application/json", "Content-Type: application/json"})
        @Get("/{resourceUri}/providers/microsoft.insights/metricNamespaces")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<MetricNamespaceCollection>> list(
            @HostParam("$host") String endpoint,
            @PathParam(value = "resourceUri", encoded = true) String resourceUri,
            @QueryParam("api-version") String apiVersion,
            @QueryParam("startTime") String startTime,
            Context context);
    }

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @param startTime The ISO 8601 conform Date start time from which to query for metric namespaces.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<MetricNamespaceInner>> listSinglePageAsync(String resourceUri, String startTime) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceUri == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null."));
        }
        final String apiVersion = "2017-12-01-preview";
        return FluxUtil
            .withContext(
                context -> service.list(this.client.getEndpoint(), resourceUri, apiVersion, startTime, context))
            .<PagedResponse<MetricNamespaceInner>>map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), null, null))
            .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext())));
    }

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @param startTime The ISO 8601 conform Date start time from which to query for metric namespaces.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<PagedResponse<MetricNamespaceInner>> listSinglePageAsync(
        String resourceUri, String startTime, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (resourceUri == null) {
            return Mono.error(new IllegalArgumentException("Parameter resourceUri is required and cannot be null."));
        }
        final String apiVersion = "2017-12-01-preview";
        context = this.client.mergeContext(context);
        return service
            .list(this.client.getEndpoint(), resourceUri, apiVersion, startTime, context)
            .map(
                res ->
                    new PagedResponseBase<>(
                        res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), null, null));
    }

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @param startTime The ISO 8601 conform Date start time from which to query for metric namespaces.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedFlux<MetricNamespaceInner> listAsync(String resourceUri, String startTime) {
        return new PagedFlux<>(() -> listSinglePageAsync(resourceUri, startTime));
    }

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedFlux<MetricNamespaceInner> listAsync(String resourceUri) {
        final String startTime = null;
        return new PagedFlux<>(() -> listSinglePageAsync(resourceUri, startTime));
    }

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @param startTime The ISO 8601 conform Date start time from which to query for metric namespaces.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    private PagedFlux<MetricNamespaceInner> listAsync(String resourceUri, String startTime, Context context) {
        return new PagedFlux<>(() -> listSinglePageAsync(resourceUri, startTime, context));
    }

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @param startTime The ISO 8601 conform Date start time from which to query for metric namespaces.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<MetricNamespaceInner> list(String resourceUri, String startTime, Context context) {
        return new PagedIterable<>(listAsync(resourceUri, startTime, context));
    }

    /**
     * Lists the metric namespaces for the resource.
     *
     * @param resourceUri The identifier of the resource.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return represents collection of metric namespaces.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    public PagedIterable<MetricNamespaceInner> list(String resourceUri) {
        final String startTime = null;
        return new PagedIterable<>(listAsync(resourceUri, startTime));
    }
}


text:
'use strict';

import { test } from 'tape';
import TableSelect from '../../../src';
import KeyCodeEvent from '../../helper/key-code-event';

let rows = null;
let table = null;
let tableSelect = null;

test('pre dispatch', t => {
  rows = Array.from(document.querySelectorAll('tr'));
  table = document.querySelector('table');
  tableSelect = new TableSelect(table);

  t.end();
});

test('before and after select event', t => {
  function select(event) {
    t.equal(event.detail.row, rows[0]);
  }

  t.plan(3);

  table.addEventListener('beforeSelect', select);
  table.addEventListener('afterSelect', select);

  tableSelect.selectRow(rows[0]);

  setTimeout(() => {
    table.removeEventListener('beforeSelect', select);
    table.removeEventListener('afterSelect', select);
    t.ok(true);
  });
});

test('before and after deselect event', t => {
  function deselect(event) {
    t.equal(event.detail.row, rows[0]);
  }

  t.plan(3);

  table.addEventListener('beforeDeselect', deselect);
  table.addEventListener('afterDeselect', deselect);

  tableSelect.deselectRow(rows[0]);

  setTimeout(() => {
    table.removeEventListener('beforeDeselect', deselect);
    table.removeEventListener('afterDeselect', deselect);
    t.ok(true);
  });
});

test('action', t => {
  function action(event) {
    t.equal(event.detail.rows.length, 1);
  }

  t.plan(2);

  table.addEventListener('action', action);

  tableSelect.selectRow(rows[0]);
  tableSelect.action();
  tableSelect.deselectRow(rows[0]);

  setTimeout(() => {
    table.removeEventListener('action', action);
    t.ok(true);
  });
});

test('action on double click', t => {
  function action(event) {
    t.equal(event.detail.rows.length, 1);
  }

  t.plan(2);

  table.addEventListener('action', action);

  tableSelect.selectRow(rows[1]);
  rows[1].dispatchEvent(new MouseEvent('dblclick'));

  setTimeout(() => {
    table.removeEventListener('action', action);
    tableSelect.deselectAll();
    t.ok(true);
  });
});

test('action on enter', t => {
  function action(event) {
    t.equal(event.detail.rows.length, 2);
  }

  t.plan(2);

  table.addEventListener('action', action);

  tableSelect.selectRow(rows[1]);
  tableSelect.selectRow(rows[2], true);
  table.dispatchEvent(new KeyCodeEvent('keydown', 13));

  setTimeout(() => {
    table.removeEventListener('action', action);
    tableSelect.deselectAll();
    t.ok(true);
  });
});

test('post dispatch', t => {
  tableSelect.destroy();
  t.end();
});