text:
package com.google.uzaygezen.core;

import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Comparator;

import com.google.uzaygezen.core.ranges.LongRange;

/**
 * @author Daniel Aioanei
 */
public class TestUtils {

  public static final LongRange ZERO_ONE = LongRange.of(0, 1);
  public static final LongRange ZERO_TWO = LongRange.of(0, 2);
  public static final LongRange ZERO_FOUR = LongRange.of(0, 4);
  public static final LongRange ZERO_TEN = LongRange.of(0, 10);
  public static final LongRange ONE_TEN = LongRange.of(1, 10);
  public static final LongRange TWO_FOUR = LongRange.of(2, 4);
  public static final LongRange TWO_SIX = LongRange.of(2, 6);
  public static final LongRange TWO_TEN = LongRange.of(2, 10);
  public static final LongRange THREE_FOUR = LongRange.of(3, 4);
  public static final LongRange FOUR_EIGHT = LongRange.of(4, 8);
  public static final LongRange THREE_SEVEN = LongRange.of(3, 7);
  public static final LongRange SIX_SEVEN = LongRange.of(6, 7);
  public static final LongRange SIX_TEN = LongRange.of(6, 10);
  public static final LongRange EIGHT_TEN = LongRange.of(8, 10);

  public static final long SEED = computeSeed();

  private static class ImmutableLongContent extends LongContent {

    public ImmutableLongContent(long v) {
      super(v);
    }

    @Override
    public void add(LongContent other) {
      throw new IllegalStateException("Cannot modify shared instance.");
    }
  }

  public static final LongContent ZERO_LONG_CONTENT = new ImmutableLongContent(0);
  public static final LongContent ONE_LONG_CONTENT = new ImmutableLongContent(1);

  private TestUtils() {}

  public static BitSet unsignedIntToLittleEndianBitSet(int i) {
    BitSet bs = new BitSet(32);
    for (int j = 0; j < 32; ++j) {
      if ((i & 1) == 1) {
        bs.set(j);
      }
      i >>>= 1;
    }
    return bs;
  }

  /**
   * Generates all possible multidimensional specifications with at most {@code
   * maxDimensions} dimensions, and the sum of all bits for all dimensions at
   * most {@code maxDimBitsSum}. For each such multidimensional space
   * specification it calls {@code callback}.
   * <p>
   * This method is used for exhaustive space search testing.
   * </p>
   *
   * @param maxDimensions maximum number of dimensions
   * @param maxDimBitsSum maximum sum of the number of bits
   * @param callback will be called once for each different multidimensional
   * space specification
   */
  public static void generateSpec(int maxDimensions, int maxDimBitsSum, IntArrayCallback callback) {
    generateSpec(maxDimensions, maxDimBitsSum, false, callback);
  }

  /**
   * Like {@link #generateSpec(int, int, IntArrayCallback)}, but the sum must be exact.
   */
  public static void generateSpecWithExactSum(
      int maxDimensions, int dimBitsSum, IntArrayCallback callback) {
    generateSpec(maxDimensions, dimBitsSum, true, callback);
  }

  private static void generateSpec(
      int maxDimensions, int maxDimBitsSum, boolean exactSum, IntArrayCallback callback) {
    // mSum = sum of all dimensions.
    // n = number of dimensions
    for (int n = 0; n <= maxDimensions; ++n) {
      int[] m = new int[n];
      Arrays.fill(m, -1);
      // Generate all possible n dimensions with sum == mSum.
      int sum = 0;
      for (int k = 0; k >= 0;) {
        if (k == n) {
          if (sum <= maxDimBitsSum & (!exactSum | sum == maxDimBitsSum)) {
              callback.call(m);
          }
          --k;
          if (k >= 0) {
            sum -= m[k];
          }
        } else {
          ++m[k];
          if (sum + m[k] <= maxDimBitsSum) {
            sum += m[k];
            ++k;
          } else {
            m[k] = -1;
            --k;
            if (k >= 0) {
              sum -= m[k];
            }
          }
        }
      }
    }
  }

  /**
   * Callback for {@link #generateSpec(int, int, IntArrayCallback)} and
   * {@link #generateSpecWithExactSum(int, int, IntArrayCallback)}.
   */
  public interface IntArrayCallback {
    /**
     * Called for each multidimensional space specification.
     *
     * @param m the bit count for each dimension
     */
    void call(int[] m);
  }

  /**
   * Lexicographical comparator of {@code int[]}.
   */
  public enum IntArrayComparator implements Comparator<int[]> {

    INSTANCE;

    @Override
    public int compare(int[] a, int[] b) {
      int minLen = Math.min(a.length, b.length);
      for (int i = 0; i < minLen; ++i) {
        int cmp = Integer.compare(a[i], b[i]);
        if (cmp != 0) {
          return cmp;
        }
      }
      return Integer.compare(a.length, b.length);
    }
  }

  private static long computeSeed() {
    String s = System.getProperty("test.compactHilbertCurve.seed");
    return s == null ? Calendar.getInstance().get(Calendar.DAY_OF_MONTH) : Long.parseLong(s);
  }

  /**
   * To be used by those tests methods which don't care about which type of bit
   * vector is instantiated.
   */
  public static BitVector createBitVector(long initialValue, int bitCount) {
    BitVector bitVector = BitVectorFactories.OPTIMAL.apply(bitCount);
    if (initialValue != 0) {
      bitVector.copyFrom(initialValue);
    }
    return bitVector;
  }
}


text:
package org.apache.camel.cdi;

import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.Predicate;
import java.util.stream.Stream;

import static java.security.AccessController.doPrivileged;
import static java.util.Comparator.comparing;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toSet;

import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.AnnotatedConstructor;
import javax.enterprise.inject.spi.AnnotatedField;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.util.Nonbinding;

import static org.apache.camel.cdi.AnyLiteral.ANY;
import static org.apache.camel.cdi.DefaultLiteral.DEFAULT;

@Vetoed
final class CdiSpiHelper {

    private CdiSpiHelper() {
    }

    static Predicate<Bean> hasType(Type type) {
        requireNonNull(type);
        return bean -> bean.getTypes().contains(type);
    }

    static Predicate<Annotation> isAnnotationType(Class<? extends Annotation> clazz) {
        requireNonNull(clazz);
        return annotation -> clazz.equals(annotation.annotationType());
    }

    static Class<?> getRawType(Type type) {
        if (type instanceof Class<?>) {
            return Class.class.cast(type);
        } else if (type instanceof ParameterizedType) {
            return getRawType(ParameterizedType.class.cast(type).getRawType());
        } else if (type instanceof TypeVariable<?>) {
            return getBound(TypeVariable.class.cast(type).getBounds());
        } else if (type instanceof WildcardType) {
            return getBound(WildcardType.class.cast(type).getUpperBounds());
        } else if (type instanceof GenericArrayType) {
            Class<?> rawType = getRawType(GenericArrayType.class.cast(type).getGenericComponentType());
            if (rawType != null) {
                return Array.newInstance(rawType, 0).getClass();
            }
        }
        throw new UnsupportedOperationException("Unable to retrieve raw type for [" + type + "]");
    }

    private static Class<?> getBound(Type[] bounds) {
        if (bounds.length == 0) {
            return Object.class;
        } else {
            return getRawType(bounds[0]);
        }
    }

    @SafeVarargs
    static boolean hasAnnotation(AnnotatedType<?> type, Class<? extends Annotation>... annotations) {
        return Stream.of(annotations)
            .anyMatch(annotation -> hasAnnotation(type, annotation));
    }

    static boolean hasAnnotation(AnnotatedType<?> type, Class<? extends Annotation> annotation) {
        if (type.isAnnotationPresent(annotation)) {
            return true;
        }
        for (AnnotatedMethod<?> method : type.getMethods()) {
            if (method.isAnnotationPresent(annotation)) {
                return true;
            }
        }
        for (AnnotatedConstructor<?> constructor : type.getConstructors()) {
            if (constructor.isAnnotationPresent(annotation)) {
                return true;
            }
        }
        for (AnnotatedField<?> field : type.getFields()) {
            if (field.isAnnotationPresent(annotation)) {
                return true;
            }
        }
        return false;
    }

    static Set<Annotation> getQualifiers(Annotated annotated, BeanManager manager) {
        return annotated.getAnnotations().stream()
            .filter(annotation -> manager.isQualifier(annotation.annotationType()))
            .collect(collectingAndThen(toSet(),
                qualifiers -> {
                    if (qualifiers.isEmpty()) {
                        qualifiers.add(DEFAULT);
                    }
                    qualifiers.add(ANY);
                    return qualifiers;
                })
            );
    }

    /**
     * Generates a unique signature for {@link Bean}.
     */
    static String createBeanId(Bean<?> bean) {
        return Stream.of(bean.getName(),
            bean.getScope().getName(),
            createAnnotationCollectionId(bean.getQualifiers()),
            createTypeCollectionId(bean.getTypes()))
            .filter(Objects::nonNull)
            .collect(joining(","));
    }

    /**
     * Generates a unique signature of a collection of types.
     */
    private static String createTypeCollectionId(Collection<Type> types) {
        return types.stream()
            .sorted(comparing(CdiSpiHelper::createTypeId))
            .map(CdiSpiHelper::createTypeId)
            .collect(joining(",", "[", "]"));
    }

    /**
     * Generates a unique signature for a {@link Type}.
     */
    private static String createTypeId(Type type) {
        if (type instanceof Class<?>) {
            return Class.class.cast(type).getName();
        }

        if (type instanceof ParameterizedType) {
            return createTypeId(((ParameterizedType) type).getRawType())
                + Stream.of(((ParameterizedType) type).getActualTypeArguments())
                .map(CdiSpiHelper::createTypeId)
                .collect(joining(",", "<", ">"));
        }

        if (type instanceof TypeVariable<?>) {
            return TypeVariable.class.cast(type).getName();
        }

        if (type instanceof GenericArrayType) {
            return createTypeId(GenericArrayType.class.cast(type).getGenericComponentType());
        }

        throw new UnsupportedOperationException("Unable to create type id for type [" + type + "]");
    }

    /**
     * Generates a unique signature for a collection of annotations.
     */
    private static String createAnnotationCollectionId(Collection<Annotation> annotations) {
        if (annotations.isEmpty()) {
            return "";
        }

        return annotations.stream()
            .sorted(comparing(a -> a.annotationType().getName()))
            .map(CdiSpiHelper::createAnnotationId)
            .collect(joining(",", "[", "]"));
    }

    /**
     * Generates a unique signature for an {@link Annotation}.
     */
    static String createAnnotationId(Annotation annotation) {
        Method[] methods = doPrivileged(
            (PrivilegedAction<Method[]>) () -> annotation.annotationType().getDeclaredMethods());

        return Stream.of(methods)
            .filter(method -> !method.isAnnotationPresent(Nonbinding.class))
            .sorted(comparing(Method::getName))
            .collect(() -> new StringJoiner(",", "@" + annotation.annotationType().getCanonicalName() + "(", ")"),
                (joiner, method) -> {
                    try {
                        joiner.add(method.getName() + "=" + method.invoke(annotation).toString());
                    } catch (NullPointerException | IllegalArgumentException | IllegalAccessException | InvocationTargetException cause) {
                        throw new RuntimeException(
                            "Error while accessing member [" + method.getName() + "]"
                                + " of annotation [" + annotation.annotationType().getName() + "]", cause);
                    }
                },
                StringJoiner::merge)
            .toString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package cdi

import (
	"sync"

	cdi "github.com/container-orchestrated-devices/container-device-interface/specs-go"
	oci "github.com/opencontainers/runtime-spec/specs-go"
)

//
// Registry keeps a cache of all CDI Specs installed or generated on
// the host. Registry is the primary interface clients should use to
// interact with CDI.
//
// The most commonly used Registry functions are for refreshing the
// registry and injecting CDI devices into an OCI Spec.
//
type Registry interface {
	RegistryResolver
	RegistryRefresher
	DeviceDB() RegistryDeviceDB
	SpecDB() RegistrySpecDB
}

// RegistryRefresher is the registry interface for refreshing the
// cache of CDI Specs and devices.
//
// Configure reconfigures the registry with the given options.
//
// Refresh rescans all CDI Spec directories and updates the
// state of the cache to reflect any changes. It returns any
// errors encountered during the refresh.
//
// GetErrors returns all errors encountered for any of the scanned
// Spec files during the last cache refresh.
//
// GetSpecDirectories returns the set up CDI Spec directories
// currently in use. The directories are returned in the scan
// order of Refresh().
//
// GetSpecDirErrors returns any errors related to the configured
// Spec directories.
type RegistryRefresher interface {
	Configure(...Option) error
	Refresh() error
	GetErrors() map[string][]error
	GetSpecDirectories() []string
	GetSpecDirErrors() map[string]error
}

// RegistryResolver is the registry interface for injecting CDI
// devices into an OCI Spec.
//
// InjectDevices takes an OCI Spec and injects into it a set of
// CDI devices given by qualified name. It returns the names of
// any unresolved devices and an error if injection fails.
type RegistryResolver interface {
	InjectDevices(spec *oci.Spec, device ...string) (unresolved []string, err error)
}

// RegistryDeviceDB is the registry interface for querying devices.
//
// GetDevice returns the CDI device for the given qualified name. If
// the device is not GetDevice returns nil.
//
// ListDevices returns a slice with the names of qualified device
// known. The returned slice is sorted.
type RegistryDeviceDB interface {
	GetDevice(device string) *Device
	ListDevices() []string
}

// RegistrySpecDB is the registry interface for querying CDI Specs.
//
// ListVendors returns a slice with all vendors known. The returned
// slice is sorted.
//
// ListClasses returns a slice with all classes known. The returned
// slice is sorted.
//
// GetVendorSpecs returns a slice of all Specs for the vendor.
//
// GetSpecErrors returns any errors for the Spec encountered during
// the last cache refresh.
//
// WriteSpec writes the Spec with the given content and name to the
// last Spec directory.
type RegistrySpecDB interface {
	ListVendors() []string
	ListClasses() []string
	GetVendorSpecs(vendor string) []*Spec
	GetSpecErrors(*Spec) []error
	WriteSpec(raw *cdi.Spec, name string) error
}

type registry struct {
	*Cache
}

var _ Registry = &registry{}

var (
	reg      *registry
	initOnce sync.Once
)

// GetRegistry returns the CDI registry. If any options are given, those
// are applied to the registry.
func GetRegistry(options ...Option) Registry {
	var new bool
	initOnce.Do(func() {
		reg, _ = getRegistry(options...)
		new = true
	})
	if !new && len(options) > 0 {
		reg.Configure(options...)
		reg.Refresh()
	}
	return reg
}

// DeviceDB returns the registry interface for querying devices.
func (r *registry) DeviceDB() RegistryDeviceDB {
	return r
}

// SpecDB returns the registry interface for querying Specs.
func (r *registry) SpecDB() RegistrySpecDB {
	return r
}

func getRegistry(options ...Option) (*registry, error) {
	c, err := NewCache(options...)
	return &registry{c}, err
}


text:
package org.apodhrad.p2diff.html;

import static org.apodhrad.p2diff.util.ResourceUtils.getResourceFile;
import static org.junit.Assert.assertEquals;

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

import org.apache.commons.io.FileUtils;
import org.apodhrad.p2diff.file.Delta;
import org.junit.Before;
import org.junit.Test;

public class HTMLGeneratorTest {

	@Before
	public void deleteTargetDiffFolder() {
		FileUtils.deleteQuietly(new File("target/diff-reports"));
	}

	@Test
	public void testConvertingToHtml() throws Exception {
		List<String> diff = FileUtils.readLines(getResourceFile("/diff.txt"));
		List<String> expectedHtml = FileUtils.readLines(getResourceFile("/html_diff.txt"));

		assertEquals(expectedHtml, HTMLGenerator.convertToHTML(diff));
	}

	@Test
	public void testGeneratingDiffReport() throws Exception {
		File target = new File("target");

		List<String> diff = FileUtils.readLines(getResourceFile("/diff_jar.txt"));
		new HTMLGenerator(target).generateDiffReport(diff);

		String expectedHtml = FileUtils.readFileToString(getResourceFile("/report_diff.html"));
		assertEquals(expectedHtml, FileUtils.readFileToString(new File(target, "diff-reports/index.html")));
	}

	@Test
	public void testGeneratingDeltaReport() throws Exception {
		File target = new File("target");

		List<Delta> deltas = new ArrayList<Delta>();
		deltas.add(new Delta("test0.txt", new File("test0_1.2.2.txt"), new File("test0_1.2.3.txt")));
		deltas.add(new Delta("dir1/test1.txt", new File("test1.txt"), new File("test1.txt")));
		deltas.add(new Delta("dir2/test2.txt", new File("test2_1.2.2.txt"), null));
		deltas.add(new Delta("dir3/test3.txt", null, new File("test3_1.2.3.txt")));

		new HTMLGenerator(target).generateDeltaReport(deltas);

		String expectedHtml = FileUtils.readFileToString(getResourceFile("/report_delta.html"));
		assertEquals(expectedHtml, FileUtils.readFileToString(new File(target, "diff-reports/index.html")));
	}

	@Test
	public void testGeneratingComplexReport() throws Exception {

	}

}


text:
test_description="Test get command"

. lib/test-lib.sh

test_init_ipfs

test_ipfs_get_flag() {
    ext="$1"; shift
    tar_flag="$1"; shift
    flag="$@"

    test_expect_success "ipfs get $flag succeeds" '
        ipfs get "$HASH" '"$flag"' >actual
    '

    test_expect_success "ipfs get $flag output looks good" '
		printf "%s\n\n" "Saving archive to $HASH$ext" >expected &&
		test_cmp expected actual
	'

    test_expect_success "ipfs get $flag archive output is valid" '
		tar "$tar_flag" "$HASH$ext" &&
		test_cmp "$HASH" data &&
		rm "$HASH$ext" &&
		rm "$HASH"
	'
}

# we use a function so that we can run it both offline + online
test_get_cmd() {

	test_expect_success "'ipfs get --help' succeeds" '
		ipfs get --help >actual
	'

	test_expect_success "'ipfs get --help' output looks good" '
		egrep "ipfs get.*<ipfs-path>" actual >/dev/null ||
		test_fsh cat actual
	'

	test_expect_success "ipfs get succeeds" '
		echo "Hello Worlds!" >data &&
		HASH=`ipfs add -q data` &&
		ipfs get "$HASH" >actual
	'

	test_expect_success "ipfs get output looks good" '
		printf "%s\n\n" "Saving file(s) to $HASH" >expected &&
		test_cmp expected actual
	'

	test_expect_success "ipfs get file output looks good" '
		test_cmp "$HASH" data
	'

	test_expect_success "ipfs get DOES NOT error when trying to overwrite a file" '
		ipfs get "$HASH" >actual &&
		rm "$HASH"
	'

    test_ipfs_get_flag ".tar" "-xf" -a

    test_ipfs_get_flag ".tar.gz" "-zxf" -a -C

    test_ipfs_get_flag ".tar.gz" "-zxf" -a -C -l 9

	test_expect_success "ipfs get succeeds (directory)" '
		mkdir -p dir &&
		touch dir/a &&
		mkdir -p dir/b &&
		echo "Hello, Worlds!" >dir/b/c &&
		HASH2=`ipfs add -r -q dir | tail -n 1` &&
		ipfs get "$HASH2" >actual
	'

	test_expect_success "ipfs get output looks good (directory)" '
		printf "%s\n\n" "Saving file(s) to $HASH2" >expected &&
		test_cmp expected actual
	'

	test_expect_success "ipfs get output is valid (directory)" '
		test_cmp dir/a "$HASH2"/a &&
		test_cmp dir/b/c "$HASH2"/b/c &&
		rm -r "$HASH2"
	'

	test_expect_success "ipfs get -a -C succeeds (directory)" '
		ipfs get "$HASH2" -a -C >actual
	'

	test_expect_success "ipfs get -a -C output looks good (directory)" '
		printf "%s\n\n" "Saving archive to $HASH2.tar.gz" >expected &&
		test_cmp expected actual
	'

	test_expect_success "gzipped tar archive output is valid (directory)" '
		tar -zxf "$HASH2".tar.gz &&
		test_cmp dir/a "$HASH2"/a &&
		test_cmp dir/b/c "$HASH2"/b/c &&
		rm -r "$HASH2"
	'

	test_expect_success "ipfs get ../.. should fail" '
		echo "Error: invalid ipfs ref path" >expected &&
		test_must_fail ipfs get ../.. 2>actual &&
		test_cmp expected actual
	'
}

# should work offline
test_get_cmd

# should work online
test_launch_ipfs_daemon
test_get_cmd
test_kill_ipfs_daemon

test_done


text:
cask 'tableau' do
  version '2018.3.0'
  sha256 '54ca0044f342b91130a496788c0d9cf7796787bd72128d57bba56ea2e9094ffa'

  url "https://downloads.tableau.com/tssoftware/TableauDesktop-#{version.dots_to_hyphens}.dmg"
  name 'Tableau Desktop'
  homepage 'https://www.tableau.com/products/desktop/download'

  depends_on macos: '>= :yosemite'

  pkg 'Tableau Desktop.pkg'

  uninstall pkgutil: [
                       'com.amazon.redshiftodbc',
                       'simba.sparkodbc',
                       'com.simba.sparkodbc',
                       'com.simba.sqlserverodbc',
                       'com.tableausoftware.Desktop.app',
                       'com.tableausoftware.DesktopShortcut',
                       'com.tableausoftware.FLEXNet.11.*',
                       'com.tableausoftware.mysql',
                       'com.tableausoftware.oracle',
                       'com.tableausoftware.postgresql',
                     ]
end


text:
Router.configure({
    notFoundTemplate: '404',
    loadingTemplate: 'loading',
    layoutTemplate: 'layout',
    yieldTemplates: {
        'header': {to: 'header'}
    }
});

Router.map(function () {
    this.route('home', {
        path: '/',
        template: 'graphList'
    });

    this.route('graphAdd', {
        path: '/graphs/add'
    });

    this.route('graphEdit', {
        path: '/graphs/:_id',
        before: function () {
            Session.set('currentGraphId', this.params._id);
        }
    });

    this.route('dashboardList', {
        path: '/dashboards'
    });

    this.route('dashboardViewFullScreen', {
        path: '/dashboards/:_id/fullscreen',
        before: function () {
            Session.set('currentDashboardId', this.params._id);
        },
        yieldTemplates: {
            '': {to: 'header'}
        }
    });

    this.route('dashboardView', {
        path: '/dashboards/:_id',
        before: function () {
            Session.set('currentDashboardId', this.params._id);
        }
    });

    this.route('userList', {
        path: '/users',
        before: function () {
            if (!isAdmin()) {
                this.render('users403');
                this.stop();
            }
        }
    });
});

Router.addHook('before', function () {
    Session.set('graphDateRange', {
        type: 'relative',
        from: '-1d',
        until: '-0d'
    });
    Session.set('graphAutoRefreshEnabled', false);

    if (!Meteor.user()) {
        this.render('401');
        return this.stop();
    }

    if (!isUser()) {
        this.render('403');
        return this.stop();
    }
});


text:
# SoftDeleteable behavior extension for Doctrine 2

**SoftDeleteable** behavior allows to "soft delete" objects, filtering them
at SELECT time by marking them as with a timestamp, but not explicitly removing them from the database.

Features:

- Works with DQL DELETE queries (using a Query Hint).
- All SELECT queries will be filtered, not matter from where they are executed (Repositories, DQL SELECT queries, etc).
- For now, it works only with the ORM
- Can be nested with other behaviors
- Annotation, Yaml and Xml mapping support for extensions
- Support for 'timeAware' option: When creating an entity set a date of deletion in the future and never worry about cleaning up at expiration time.

Content:

- [Including](#including-extension) the extension
- Entity [example](#entity-mapping)
- [Yaml](#yaml-mapping) mapping example
- [Xml](#xml-mapping) mapping example
- Usage [examples](#usage)
- Using [Traits](#traits)

## Setup and autoloading

Read the [documentation](http://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/annotations.md#em-setup)
or check the [example code](http://github.com/l3pp4rd/DoctrineExtensions/tree/master/example)
on how to setup and use the extensions in most optimized way.

With SoftDeleteable there's one more step you need to do. You need to add the filter to your configuration:

``` php

$config = new Doctrine\ORM\Configuration;

// Your configs..

$config->addFilter('soft-deleteable', 'Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter');
```

And then you can access the filter from your EntityManager to enable or disable it with the following code:

``` php
// This will enable the SoftDeleteable filter, so entities which were "soft-deleted" will not appear
// in results
// You should adapt the filter name to your configuration (ex: softdeleteable)
$em->getFilters()->enable('soft-deleteable');

// This will disable the SoftDeleteable filter, so entities which were "soft-deleted" will appear in results
$em->getFilters()->disable('soft-deleteable');
```

Or from your DocumentManager (ODM):

``` php
// This will enable the SoftDeleteable filter, so entities which were "soft-deleted" will not appear
// in results
// You should adapt the filter name to your configuration (ex: softdeleteable)
$em->getFilterCollection()->enable('soft-deleteable');

// This will disable the SoftDeleteable filter, so entities which were "soft-deleted" will appear in results
$em->getFilterCollection()->disable('soft-deleteable');
```

**NOTE:** by default all filters are disabled, so you must explicitly enable **soft-deleteable** filter in your setup
or whenever you need it.

## SoftDeleteable Entity example:

### SoftDeleteable annotations:
- **@Gedmo\Mapping\Annotation\SoftDeleteable** this class annotation tells if a class is SoftDeleteable. It has a
mandatory parameter "fieldName", which is the name of the field to be used to hold the known "deletedAt" field. It
must be of any of the date types.

Available configuration options:
- **fieldName** - The name of the field that will be used to determine if the object is removed or not (NULL means
it's not removed. A date value means it was removed). NOTE: The field MUST be nullable.

- **timeAware** - Defaults to false. If set to true, softDeletable will also return results where the value of
`fieldName` is in the future. This is very handy if at the time of creation you already know when an item should be deleted.

**Note:** that SoftDeleteable interface is not necessary, except in cases where
you need to identify entity as being SoftDeleteable. The metadata is loaded only once then
cache is activated.

``` php
<?php
namespace Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
 */
class Article
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @ORM\Column
     */
    private $title;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $deletedAt;

    public function getId()
    {
        return $this->id;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function getDeletedAt()
    {
        return $this->deletedAt;
    }

    public function setDeletedAt($deletedAt)
    {
        $this->deletedAt = $deletedAt;
    }
}
```

## Yaml mapping example:

Yaml mapped Article: **/mapping/yaml/Entity.Article.dcm.yml**

```
---
Entity\Article:
  type: entity
  table: articles
  gedmo:
    soft_deleteable:
      field_name: deletedAt
      time_aware: false
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    title:
      type: string
    deletedAt:
      type: date
      nullable: true
```

## Xml mapping example

``` xml
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:gedmo="http://Atlantic18.github.io/DoctrineExtensions/schemas/orm/doctrine-extensions-3.0.xsd">

    <entity name="Mapping\Fixture\Xml\Timestampable" table="timestampables">
        <id name="id" type="integer" column="id">
            <generator strategy="AUTO"/>
        </id>

        <field name="title" type="string" />

        <field name="deletedAt" type="datetime" nullable="true" />

        <gedmo:soft-deleteable field-name="deletedAt" time-aware="false" />
    </entity>

</doctrine-mapping>
```

## Usage:

``` php
<?php
$article = new Article;
$article->setTitle('My Article');

$em->persist($article);
$em->flush();

// Now if we remove it, it will set the deletedAt field to the actual date
$em->remove($article);
$em->flush();

$repo = $em->getRepository('Article');
$art = $repo->findOneBy(array('title' => 'My Article'));

// It should NOT return the article now
$this->assertNull($art);

// But if we disable the filter, the article should appear now
$em->getFilters()->disable('soft-deleteable');

$art = $repo->findOneBy(array('title' => 'My Article'));

$this->assertTrue(is_object($art));

// Enable / Disable filter filter, for specified entity (default is enabled for all)
$filter = $em->getFilters()->enable('soft-deleteable');
$filter->disableForEntity('Entity\Article');
$filter->enableForEntity('Entity\Article');

// Undelete the entity by setting the deletedAt field to null
$article->setDeletedAt(null);
```

Easy like that, any suggestions on improvements are very welcome.

## Traits

You can use softDeleteable traits for quick **deletedAt** timestamp definitions
when using annotation mapping.
There is also a trait without annotations for easy integration purposes.

**Note:** this feature is only available since php **5.4.0**. And you are not required
to use the Traits provided by extensions.

``` php
<?php
namespace SoftDeleteable\Fixture;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;

/**
 * @ORM\Entity
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
 */
class UsingTrait
{
    /**
     * Hook SoftDeleteable behavior
     * updates deletedAt field
     */
    use SoftDeleteableEntity;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(length=128)
     */
    private $title;
}
```

Traits are very simple and if you use different field names I recommend to simply create your
own ones based per project. These ones are standing as an example.

## Extra

By default it is too complicated to manage extension dependencies so you may have issues when combining some of the extensions. You can how ever create your own listeners to help you out.

Here is an example of a soft delete listener to move your item to the end of the list when you delete it, so you prevent later collision.

*Services.yml*

```
app.soft_delete_listener:
    class: AppBundle\Events\SoftDeleteListener
    tags:
        - { name: doctrine.event_listener, event: preRemove, priority: 10 }
```

*SoftDeleteListener.php*

```
<?php

namespace AppBundle\Events;

use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Gedmo\Sortable\Sortable;

class SoftDeleteListener
{
    public function preRemove(LifecycleEventArgs $event)
    {
        $entity = $event->getObject();

        if ($entity instanceof Sortable) {
            $entity->setPosition(-1);

            $om = $event->getObjectManager();
            $om->persist($entity);
            $om->flush();
        }
    }
}
```

By setting the position to -1 you will send the entity to the last position before it will be removed. See [sortable](https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/sortable.md) documentation for more information.


text:
require 'kcmo_datasets/crime'

class NeighborhoodServices::Crime
  def initialize(neighborhood_id, options = {})
    @neighborhood_id = neighborhood_id
    @options = options
  end

  def grouped_totals
    @dataset ||= KcmoDatasets::Crime.new(Neighborhood.find(@neighborhood_id), @options)
    CrimeMapper.convert_crime_key_to_application_key(@dataset.grouped_totals)
  end

  def mapped_coordinates
    @dataset ||= KcmoDatasets::Crime.new(Neighborhood.find(@neighborhood_id), @options)
    @dataset.query_data
      .map{ |coordinate| ::Entities::Crime.deserialize(coordinate) }
      .select(&::Entities::GeoJson::MAPPABLE_ITEMS)
      .map(&:to_h)
  end
end


text:
<?php
    include '../Modelo/conexion.php';
    session_start();
    $uActivo = $_SESSION['usuario'];
    $conexion=new conexion();

    include '../Modelo/validadorAcceso.php';
    $objValidador = new ControladorAccesoVistasPorUsuario(' ');
    $urlActual = substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
    $objValidador->puedeAcceder($urlActual, $uActivo);
?>
 <!DOCTYPE html>

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

    <title>Sistema de Apoyo a la Empresa TIS</title>

    <link href="../Librerias/icheck/skins/square/green.css" rel="stylesheet">

    <link rel="stylesheet" href="../Librerias/css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="../Librerias/lib/css/docs.css">

    <link rel="stylesheet" type="text/css" href="../Librerias/font-awesome/css/font-awesome.css">

    <link rel="stylesheet" type="text/css" href="../Librerias/lib/css/bootstrap-datetimepicker.css">

    <link rel="stylesheet" type="text/css" href="../Librerias/lib/css/bootstrap-multiselect.css">

    <link rel="stylesheet" type="text/css" href="../Librerias/lib/css/bootstrapValidator.css">

    <link href="../Librerias/css/plugins/timeline/timeline.css" rel="stylesheet">

    <link href="../Librerias/css/sb-admin.css" rel="stylesheet">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-collapse">
                Toggle navigation

            </button>
            Inicio

                        Repositorio

                 Foro

                    <?php echo $uActivo.' '; ?>

                         Modificar Datos personales

                        Salir

                         Administrar Grupo Empresas

                         Documentos

                                Contratos Emitidos

                                Documentos Subidos

                                Documentos Recibidos

                         Tareas

                                Registrar Proyecto

                                Subir Documentos

                                Registrar Documentos Requeridos

                                Configurar Fechas para la Recepción de Documentos

                                Crear Publicación

                                Emitir Orden de Cambio

                                Emitir Notificación de Conformidad

                                Emitir Adenda

                                Emitir Contrato

                         Seguimiento Semanal

                         Evaluacion

                                Evaluacion 2 Fase

                                Evaluacion 3 Fase

                                        Criterio de Evaluación

                                        Criterio de Calificación

                                                 Crear Criterio de Calificación

                                                 Eliminar Criterio de Calificación

                                        Formulario de Evaluacion

                                                Crear Formulario de Evaluacion

                                                 Habilitar Formulario de Evaluacion

                                                Eliminar Formulario de Evaluacion

                                        Evaluar Grupo Empresa

                                Evaluacion Final

                         Publicaciones

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Asistencia

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Seguimiento Semanal

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Ver Seguimientos

                                    <fieldset class="campos-border">

                                                      Actividad
                                                      Grupo Empresa
                                                      Estado
                                                      Acciones
                                                      Modificar Fecha

                                            <?php
                                                    date_default_timezone_set('America/Puerto_Rico');
                                                    $fechaAct = date('Y-m-j');
                                                    $stampFechaA = strtotime($fechaAct);
                                                    $anuncio="";
                                                    $clase="";
                                                    $estado="";

                                                   $peticion= $conexion->consulta("SELECT `NOMBRE_R`, NOMBRE_U, ID_R FROM `registro`, inscripcion WHERE `TIPO_T`='actividad planificacion' and `NOMBRE_UA`='$uActivo' and  `NOMBRE_UGE`=`NOMBRE_U`");
                                                   while($fila = mysql_fetch_array($peticion))
                                                    {
                                                        if(!empty($fila[0]))
                                                        {
                                                            $codigo=$fila['ID_R'];
                                                            $peticion1= $conexion->consulta("SELECT f.FECHA_FR FROM  fecha_realizacion as f, registro as a WHERE f.ID_R=a.ID_R and f.ID_R='$codigo'");
                                                            while ($correo = mysql_fetch_array($peticion1))
                                                            {
                                                                $fechaFin=$correo["FECHA_FR"];
                                                            }
                                                            $peticion2= $conexion->consulta("SELECT `NOTA_E` FROM evaluacion where `ID_R`='$codigo'");
                                                            $tamano=mysql_num_rows($peticion2);

                                                            $stampFechaF = strtotime($fechaFin);
                                                            if($stampFechaA<=$stampFechaF)
                                                            {
                                                                if($tamano==0)
                                                                {
                                                                    $anuncio="En Proceso";
                                                                    $estado="En Proceso";
                                                                    $clase="label label-warning";

                                                                }
                                                                else
                                                                {
                                                                    $anuncio=" Evaluado  ";
                                                                    $estado="Registrado";
                                                                    $clase="label label-success";
                                                                }
                                                            }
                                                            else
                                                            {

                                                                if($tamano==0)
                                                                {
                                                                $anuncio=" Retrasado ";
                                                                 $estado="Retraso";
                                                                $clase="label label-danger";

                                                                }
                                                                else
                                                                {
                                                                    $anuncio=" Evaluado  ";
                                                                     $estado="Registrado";
                                                                    $clase="label label-success";
                                                                }

                                                            }

                                                           $peticion6=$conexion->consulta("SELECT grupo_empresa.NOMBRE_LARGO_GE FROM grupo_empresa, registro WHERE registro.ID_R='$codigo' and grupo_empresa.NOMBRE_U=registro.NOMBRE_U");
                                                           while ($correo1 = mysql_fetch_array($peticion6))
                                                           { $nLargoGE=$correo1["NOMBRE_LARGO_GE"];}

                                                              $consulta="SELECT DISTINCT NOMBRE_R FROM `registro` AS r,`receptor` AS w WHERE  r.`ID_R` = w.`ID_R` AND r.`TIPO_T` LIKE 'Contrato' AND w.`RECEPTOR_R` = '$nLargoGE'";
                                                              $contrato= $conexion->consulta($consulta);
                                                              $cantC= mysql_num_rows($contrato);

                                                            if ($tamano==0)
                                                            {     if ($cantC == 0)
                                                                    {
                                                                     $btnEvaluacion= 'Evaluacion';
                                                                     $btnReportes = 'Reportes';
                                                                    }
                                                                    else
                                                                    {
                                                                     $btnEvaluacion= 'Evaluacion';
                                                                     $btnReportes = 'Reportes';
                                                                    }

                                                            }
                                                            else
                                                            {
                                                            $btnEvaluacion= 'Evaluacion';
                                                            $btnReportes = 'Reportes';
                                                            }

                                                            if ($estado=="Retraso")
                                                            {
                                                             $btnModificar= 'Modificar';
                                                            }
                                                            else
                                                            {
                                                            $btnModificar= 'Modificar';

                                                            }

                                                            echo
                                                            '

                                                                '.$fila['NOMBRE_R'].'
                                                                '.$fila['NOMBRE_U'].'
                                                                '.$anuncio.'
                                                                '.$btnEvaluacion.'   '.$btnReportes.'
                                                                '.$btnModificar.'

';
                                                        }
                                                    }

                                            ?>

                                    </fieldset>

                                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Buscador


text:
package uk.co.streefland.rhys.finalyearproject.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.co.streefland.rhys.finalyearproject.operation.user.FindUserOperation;
import uk.co.streefland.rhys.finalyearproject.operation.user.LoginUserOperation;
import uk.co.streefland.rhys.finalyearproject.operation.user.RegisterUserOperation;

import java.io.IOException;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Represents the set of user objects stored on the local node and the operations to manage them
 */
public class Users implements Serializable {

    private static final long serialVersionUID = 1L;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final HashMap<String, User> users;
    private final HashMap<String, User> cache;
    private transient LocalNode localNode;
    private User localUser;

    public Users(LocalNode localNode) {
        this.users = new HashMap<>();
        this.cache = new HashMap<>();
        init(localNode);
    }

    /**
     * Used to set the transient objects when a saved state has been read
     */
    public void init(LocalNode localNode) {
        this.localNode = localNode;
    }

    /**
     * Invokes the register user operation to register the user on the network and returns whether it was successful
     *
     * @param userName The user object to register on the network
     * @return True if the user was registered successfully
     * @throws IOException
     */
    public boolean registerUser(String userName) throws IOException, NoSuchAlgorithmException {
        /* Prepare a new public/private keypair */
        localNode.getEncryption().generateKeyPair();

        /* Create and prepare the user object */
        User user = new User(userName, localNode.getEncryption().getPublicKey().getEncoded());
        user.addAssociatedNode(localNode.getNode()); // add the local node as an associated node
        user.setRegisterTime();

        /* Invoke RegisterUserOperation */
        RegisterUserOperation ruo = new RegisterUserOperation(localNode, user, true);
        ruo.execute();

        /* Set the local user object */
        if (ruo.isRegisteredSuccessfully()) {
            localUser = user; // set the local user object
            users.put(userName, user); // add the local user to the list of users
        }

        localNode.getEncryption().updateUsername(userName);
        return ruo.isRegisteredSuccessfully();
    }

    /**
     * Invokes the login user operation to log an existing user into the network on this node
     *
     * @param userName
     * @return
     * @throws IOException
     */
    public boolean loginUser(String userName) throws IOException {

        /* Create the user object */
        User user = new User(userName, localNode.getEncryption().getPublicKey().getEncoded());

        /* Invoke LoginUserOperation */
        LoginUserOperation luo = new LoginUserOperation(localNode, user);
        luo.execute();

        /* Update the rest of the nodes on the network with the last login time */
        if (luo.isLoggedIn()) {
            user.setLastActiveTime(); // set the last login time
            user.addAssociatedNode(localNode.getNode()); // add the local node as the associated node

            /* Run the RegisterUserOperation to update other nodes on the network with the new user object*/
            RegisterUserOperation ruo = new RegisterUserOperation(localNode, user, true);
            ruo.execute();

            localUser = user; // set the local user object
            users.put(userName, user); // add the user to the list of users
        }
        return luo.isLoggedIn();
    }

    /**
     * Stores a user on the local node
     * Replaces the existing one based on the logic in the comments
     *
     * @param newUser The user to store on the local node
     * @return False if the user already exists on the network
     */
    public synchronized boolean addUser(User newUser) {

        User user = users.get(newUser.getUserName());

        if (user != null) {
            if ((user.getLastActiveTime() < newUser.getLastActiveTime()) && newUser.getRegisterTime() != 0L) {
                logger.debug("New user object has newer last active timestamp - replacing the old one");
                replaceUser(user, newUser);
                return false;
            }

            /* If new user has an older registration time that isn't zero - replace the existing user */
            if (user.getRegisterTime() > newUser.getRegisterTime() && newUser.getRegisterTime() != 0L) {
                logger.debug("New user has an older registration timestamp - replacing the old one");
                replaceUser(user, newUser);
                return false;
            }

            /* If existing user has older registration time then do nothing */
            if ((user.getRegisterTime() < newUser.getRegisterTime())) {
                logger.debug("User with the same name exists - discarding");
                return false;
            }

            /* Users are exactly the same - do nothing */
            if (user.getRegisterTime() == newUser.getRegisterTime()) {
                logger.debug("User objects are the same, doing nothing");
                return false;
            }
        }

        /* User doesn't exist in our memory - add it */
        users.put(newUser.getUserName(), newUser);
        logger.debug("New user added to users: {}", newUser.getUserName());
        return true;
    }

    /**
     * Replaces a user and updates the routing table if required
     *
     * @param oldUser The user object to replace
     * @param newUser The new user object
     */
    private void replaceUser(User oldUser, User newUser) {

        users.replace(newUser.getUserName(), oldUser, newUser);

        /* Update the associated node if it's present in the local routing table */
        if (!oldUser.getAssociatedNode().equals(newUser.getAssociatedNode())) {
            localNode.getRoutingTable().setUnresponsiveContact(oldUser.getAssociatedNode());
            localNode.getRoutingTable().insert(newUser.getAssociatedNode());
        }
    }

    /**
     * Adds a user object to the cache and updates the routing table if required
     *
     * @param newUser
     * @param resetNodeStaleCount
     */
    public synchronized void addUserToCache(User newUser, boolean resetNodeStaleCount) {

        /* Update the associated node if it's present in the local routing table */
        localNode.getRoutingTable().refreshContact(newUser.getAssociatedNode(), resetNodeStaleCount);

        User oldUser = users.get(newUser.getUserName());

        /* User object is present in users therefore we don't need to bother with the cache */
        if (oldUser != null) {
            users.replace(newUser.getUserName(), oldUser, newUser);
            return;
        }

        /* Replace the user object in the cache */
        cache.remove(newUser.getUserName());
        cache.put(newUser.getUserName(), newUser);
    }

    /**
     * Looks for a user with a specified userName on the local node and returns the user object if it was found
     *
     * @param userName
     * @return
     */
    public synchronized User findUser(String userName) {

        /* Look in users first */
        User user = users.get(userName);
        if (user != null) {
            return user;
        }

        /* Look in cache if not found in users */
        user = cache.get(userName);
        return user;
    }

    public synchronized User findUser(User user) {
        return findUser(user.getUserName());
    }

    /**
     * Looks for a user object on the network
     *
     * @param userName The username to search for
     * @return The user object or null if the user couldn't be found
     * @throws IOException
     */
    public synchronized User findUserOnNetwork(String userName) throws IOException {

        /* Look on the local node first */
        User user = findUser(userName);

        /* Look on the network if not found locally */
        if (findUser(userName) == null) {
            FindUserOperation fuo = new FindUserOperation(localNode, new User(userName));
            fuo.execute();
            user = fuo.getFoundUser();
            if (user != null) {
                addUserToCache(user, false);
            }
        }

        return user;
    }

    /**
     * Cleans up cached user objects that are older than the value specified in Configuration.USER_CACHE_EXPIRY
     */
    public synchronized void cleanUp() {
        long currentTime = new Date().getTime() / 1000; // current time in seconds

        for (Map.Entry<String, User> entry : cache.entrySet()) {
            if (currentTime >= entry.getValue().getLastActiveTime() + Configuration.USER_CACHE_EXPIRY) {
                cache.remove(entry.getKey());
            }
        }
    }

    @Override
    public synchronized final String toString() {
        StringBuilder sb = new StringBuilder("\n****** Users ******");

        sb.append("\nUsers on local node: ");

        for (Map.Entry user : users.entrySet()) {
            sb.append("\n");
            sb.append(user.getValue().toString());
        }

        sb.append("\nUsers in cache: ");

        for (Map.Entry user : cache.entrySet()) {
            sb.append("\n");
            sb.append(user.getValue().toString());
        }

        sb.append("\n");
        sb.append("****** Users Ended ******\n");
        return sb.toString();
    }

    public User getLocalUser() {
        return localUser;
    }

    public Map<String, User> getUsers() {
        return users;
    }
}


text:
/**
 * Define the standard SimTK compliant "version" and "about" routines.
 */

#include "About.h"
#include <cstring>
#include <cstdio>
#include <stdio.h>
#include <stdlib.h>

#define STR(var) #var
#define MAKE_VERSION_STRING(maj,min,build)  STR(maj.min.build)
#define MAKE_COPYRIGHT_STRING(y,a) \
    "Copyright (c) " STR(y) " Stanford University, " STR(a)
#define MAKE_STRING(a) STR(a)

#define GET_VERSION_STRING  \
    MAKE_VERSION_STRING(OPENSIM_COMMON_MAJOR_VERSION,  \
                        OPENSIM_COMMON_MINOR_VERSION,  \
                        OPENSIM_COMMON_BUILD_VERSION)

#define GET_COPYRIGHT_STRING \
    MAKE_COPYRIGHT_STRING(OPENSIM_COMMON_COPYRIGHT_YEARS, \
                          OPENSIM_COMMON_AUTHORS)

#define GET_AUTHORS_STRING \
    MAKE_STRING(OPENSIM_COMMON_AUTHORS)

#define GET_LIBRARY_STRING \
    MAKE_STRING(OPENSIM_COMMON_LIBRARY_NAME)

#define GET_TYPE_STRING \
    MAKE_STRING(OPENSIM_COMMON_TYPE)

#define GET_SYSTEM_INFO \
    MAKE_STRING(OSIM_SYS_INFO)

#define GET_COMPILER_INFO \
    MAKE_STRING(OSIM_COMPILER_INFO)

#define GET_OS_NAME \
    MAKE_STRING(OSIM_OS_NAME)

#define GET_OSIM_VERSION \
    MAKE_STRING(OSIM_VERSION)

#ifndef NDEBUG
    #define GET_DEBUG_STRING "debug"
#else
    #define GET_DEBUG_STRING "release"
#endif

using namespace std;

extern "C" {

void opensim_version_common(int* major, int* minor, int* build) {
    static const char* l = "OPENSIM library="   GET_LIBRARY_STRING;
    static const char* t = "OPENSIM type="      GET_TYPE_STRING;
    static const char* d = "OPENSIM debug="     GET_DEBUG_STRING;
    static const char* v = "OPENSIM version="   GET_VERSION_STRING;
    static const char* c = "OPENSIM copyright=" GET_COPYRIGHT_STRING;

    if (major) *major = OPENSIM_COMMON_MAJOR_VERSION;
    if (minor) *minor = OPENSIM_COMMON_MINOR_VERSION;
    if (build) *build = OPENSIM_COMMON_BUILD_VERSION;

    // Force statics to be present in the binary (Release mode otherwise
    // optimizes them away).
    volatile int i=0;
    if (i) { // never true, but compiler doesn't know ...
        *major = *l + *t + *d + *v + *c;
    }
}

void opensim_about_common(const char* key, int maxlen, char* value) {
    if (maxlen <= 0 || value==0) return;
    value[0] = '\0'; // in case we don't find a match
    if (key==0) return;

    // downshift the key
    std::string skey(key);
    for (size_t i=0; i<skey.size(); ++i)
        skey[i] = tolower(skey[i]);

    const char* v = 0;
    if      (skey == "version")   v = GET_VERSION_STRING;
    else if (skey == "library")   v = GET_LIBRARY_STRING;
    else if (skey == "type")      v = GET_TYPE_STRING;
    else if (skey == "copyright") v = GET_COPYRIGHT_STRING;
    else if (skey == "authors")   v = GET_AUTHORS_STRING;
    else if (skey == "debug")     v = GET_DEBUG_STRING;

    if (v) {
        strncpy(value,v,maxlen-1);
        value[maxlen-1] = '\0'; // in case we ran out of room
    }
}

} // extern "C"

namespace OpenSim {

static const char* OpenSimVersion = GET_OSIM_VERSION;

std::string GetVersionAndDate() {
    char buffer[256];
    sprintf(buffer,"version %s, build date %s %s",
            OpenSimVersion, __TIME__, __DATE__);
    return std::string(buffer);
}

std::string GetVersion() {
    return OpenSimVersion;
}

std::string GetOSInfoVerbose() {
    const char * str = GET_SYSTEM_INFO;
    return str;
}

std::string GetOSInfo() {
    const char * str = GET_OS_NAME;
    return str;
}

std::string GetCompilerVersion() {
    std::string os = GetOSInfo();
    std::string str = "(Unknown)";

    if( 0 == os.compare("Windows")) {
        const int MSVCVersion = atoi(GET_COMPILER_INFO);
        if( MSVCVersion >= 1910 ) {
            // With Visual Studio 2017, the versioning of the Visual C++
            // compiler became more fine-grained, so we can no longer use
            // a switch statement.
            // Also, Visual Studio 2017 decouples the Visual Studio IDE
            // from the C++ toolset (compiler), so providing the IDE year
            // does not indicate the compiler version (it may be possible
            // to use the Visual Studio 2019 IDE, or whatever is next,
            // with the same C++ toolset that came with Visual Studio 2017.
            // Therefore, we no longer provide the Visual Studio year.
            // https://blogs.msdn.microsoft.com/vcblog/2016/10/05/visual-c-compiler-version/
            // https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B
            if (1910 <= MSVCVersion && MSVCVersion < 2000) {
                str = "Microsoft Visual C++ 14.1";
            }
            str += " (MSC_VER " + std::to_string(MSVCVersion) + ")";
        } else {
            switch( MSVCVersion ) {
                case 1900:
                    str = "Visual Studio 2015";
                    break;
                case 1800:
                    str = "Visual Studio 2013";
                    break;
                case 1700:
                    str = "Visual Studio 2011";
                    break;
                case 1600:
                    str = "Visual Studio 2010";
                    break;
                case 1500:
                    str = "Visual Studio 2008";
                    break;
                case 1400:
                    str = "Visual Studio 2005";
                    break;
                case 1310:
                    str = "Visual Studio 2003";
                    break;
                case 1300:
                    str = "Visual Studio 2002";
                    break;
            }
        }
    } else if( 0 == os.compare("Darwin")) {
        str = "Mac OS X :";
        str += GET_COMPILER_INFO;
    } else if( 0 == os.compare("Linux")){
        str = "Linux :";
        str = GET_COMPILER_INFO;
    } else {
        str = GET_COMPILER_INFO;
    }

    return str;
}

}


text:
extern crate protobuf_macros;

use std::env;
use std::path::PathBuf;

fn main() {
    let out = PathBuf::from(env::var("OUT_DIR").unwrap());

    protobuf_macros::expand("src/lib.in.rs", &out.join("lib.rs")).unwrap();

    println!("cargo:rerun-if-changed=src/lib.in.rs");
    println!("cargo:rerun-if-changed=src/spirc.rs");

}


text:
package org.ixmas.machinelearning.supervised.knn;

import org.ixmas.machinelearning.supervised.Example;
import org.ixmas.machinelearning.supervised.ExampleSet;
import org.ixmas.machinelearning.supervised.input.position.Position;
import org.ixmas.machinelearning.supervised.input.position.PositionNeighborhoodComputer;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.collect.ImmutableList.of;
import static org.assertj.core.api.Assertions.assertThat;

public class PositionNeighborhoodComputerTest {

    private PositionNeighborhoodComputer m_positionNeighborhoodComputer;

    @BeforeMethod
    public void beforeMethod() {
        m_positionNeighborhoodComputer = new PositionNeighborhoodComputer();
    }

    @Test
    public void should() {
        Position[] positions = new Position[]{new Position(0., 0.), new Position(1., 1.), new Position(2., 2.), new Position(3., 3.), new Position(4., 4.), new Position(5., 5.)};
        ExampleSet<Position, Integer> trainingSet = new ExampleSet<>();
        List<Example<Position, Integer>> examples = new ArrayList<>();
        int idx = 0;
        for (Position position : positions) {
            Example<Position, Integer> example = new Example<>(position, idx / 2);
            examples.add(example);
            trainingSet.addExample(example);
            idx++;
        }
        Position position = new Position(3.2);
        ExampleSet<Position, Integer> neighborhood = m_positionNeighborhoodComputer.compute(position, trainingSet, 3);
        assertThat(neighborhood).containsAll(of(examples.get(3), examples.get(4), examples.get(2)));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<infinispan
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="urn:infinispan:config:7.0 http://www.infinispan.org/schemas/infinispan-config-7.0.xsd"
        xmlns="urn:infinispan:config:7.0">

    <jgroups>
        <stack-file name="jgroupsStack" path="jgroups-site2.xml"/>
    </jgroups>

    <cache-container name="default" default-cache="testCacheSite2">
        <transport stack="jgroupsStack" lock-timeout="600000" cluster="default" />
        <serialization></serialization>
        <jmx>
            <property name="enabled">true</property>
        </jmx>
        <distributed-cache name="testCacheSite2" mode="SYNC" remote-timeout="60000" statistics="true" l1-lifespan="-1" owners="2" segments="512" >
            <locking acquire-timeout="3000" concurrency-level="1000" />
            <backups>
                <backup site="SITE1"/>
            </backups>
            <state-transfer timeout="60000" />
        </distributed-cache>

        <distributed-cache name="testCacheSite1_backup" mode="SYNC" remote-timeout="60000" statistics="true" l1-lifespan="-1" owners="2" segments="512">
            <locking acquire-timeout="3000" concurrency-level="1000" />
            <backup-for remote-cache="testCacheSite1" remote-site="SITE1"/>
            <state-transfer timeout="60000" />
        </distributed-cache>
    </cache-container>

</infinispan>


text:
<?php

declare(strict_types=1);

namespace Arrayy\Type;

use Arrayy\Collection\Collection;

/**
 * @extends Collection<array-key,bool[]>
 */
final class BoolArrayCollection extends Collection implements TypeInterface
{
    /**
     * The type (FQCN) associated with this collection.
     *
     * @return string
     */
    public function getType()
    {
        return 'bool[]';
    }
}


text:
#ifndef GENERIC_BASIS_DISCRETIZATION_MODULE_H
#define GENERIC_BASIS_DISCRETIZATION_MODULE_H

#include "discretization_module_base.h"
#include "misc/interval_bases_list.h"
#include "methods/basis/list.h"

#include "WaveletTL/galerkin/cached_problem.h"

template<unsigned int jmax_standard, class LIST_1D_BASES = IntervalBasesList_all, class METHOD_LIST = methods::basis::List>
class GenericBasisDiscretizationModule
        : public DiscretizationModuleBase<jmax_standard, LIST_1D_BASES, METHOD_LIST>
{

public:

    static QString getDiscretizationTypeName()
    {
        return QStringLiteral("Wavelet Riesz Basis");
    }

protected:

    template<class EQUATION>
    using SimpleSolution = GenericSolution< InfiniteVector<double, typename EQUATION::Index>,
                                            SampledMapping<EQUATION::space_dimension>,
                                            typename EQUATION::WaveletBasis >;

    template<class EQUATION, class RAW_PROBLEM>
    using BasisDiscretizedProblem
    = GenericDiscretizedProblem<WaveletTL::CachedProblem, EQUATION, RAW_PROBLEM,
                                SimpleSolution<EQUATION>, METHOD_LIST>;

    // For more complex domains like the L-domain:

    template<class EQUATION>
    using MultiPatchSolution = GenericSolution< InfiniteVector<double, typename EQUATION::Index>,
                                              Array1D<SampledMapping<EQUATION::space_dimension> >,
                                              typename EQUATION::WaveletBasis >;

    template<class EQUATION, class RAW_PROBLEM>
    using MultiPatchBasisDiscretizedProblem
    = GenericDiscretizedProblem<WaveletTL::CachedProblem, EQUATION, RAW_PROBLEM,
                                MultiPatchSolution<EQUATION>, METHOD_LIST>;
};

#endif // GENERIC_BASIS_DISCRETIZATION_MODULE_H


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

<title>AbstractLayoutCache (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="javax.swing.tree.AbstractLayoutCache class">
<meta name="keywords" content="nodeDimensions">
<meta name="keywords" content="treeModel">
<meta name="keywords" content="treeSelectionModel">
<meta name="keywords" content="rootVisible">
<meta name="keywords" content="rowHeight">
<meta name="keywords" content="setNodeDimensions()">
<meta name="keywords" content="getNodeDimensions()">
<meta name="keywords" content="setModel()">
<meta name="keywords" content="getModel()">
<meta name="keywords" content="setRootVisible()">
<meta name="keywords" content="isRootVisible()">
<meta name="keywords" content="setRowHeight()">
<meta name="keywords" content="getRowHeight()">
<meta name="keywords" content="setSelectionModel()">
<meta name="keywords" content="getSelectionModel()">
<meta name="keywords" content="getPreferredHeight()">
<meta name="keywords" content="getPreferredWidth()">
<meta name="keywords" content="isExpanded()">
<meta name="keywords" content="getBounds()">
<meta name="keywords" content="getPathForRow()">
<meta name="keywords" content="getRowForPath()">
<meta name="keywords" content="getPathClosestTo()">
<meta name="keywords" content="getVisiblePathsFrom()">
<meta name="keywords" content="getVisibleChildCount()">
<meta name="keywords" content="setExpandedState()">
<meta name="keywords" content="getExpandedState()">
<meta name="keywords" content="getRowCount()">
<meta name="keywords" content="invalidateSizes()">
<meta name="keywords" content="invalidatePathBounds()">
<meta name="keywords" content="treeNodesChanged()">
<meta name="keywords" content="treeNodesInserted()">
<meta name="keywords" content="treeNodesRemoved()">
<meta name="keywords" content="treeStructureChanged()">
<meta name="keywords" content="getRowsForPaths()">
<meta name="keywords" content="isFixedRowHeight()">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.swing.tree

Class AbstractLayoutCache

java.lang.Object

javax.swing.tree.AbstractLayoutCache

All Implemented Interfaces:

RowMapper

Direct Known Subclasses:

FixedHeightLayoutCache, VariableHeightLayoutCache

public abstract class AbstractLayoutCache
extends Object
implements RowMapper

Warning:
 Serialized objects of this class will not be compatible with
 future Swing releases. The current serialization support is
 appropriate for short term storage or RMI between applications running
 the same version of Swing.  As of 1.4, support for long term storage
 of all JavaBeansTM
 has been added to the java.beans package.
 Please see XMLEncoder.

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
AbstractLayoutCache.NodeDimensions

Used by AbstractLayoutCache to determine the size
 and x origin of a particular node.

Field Summary

Fields

Modifier and Type
Field and Description

protected AbstractLayoutCache.NodeDimensions
nodeDimensions

Object responsible for getting the size of a node.

protected boolean
rootVisible

True if the root node is displayed, false if its children are
 the highest visible nodes.

protected int
rowHeight

Height to use for each row.

protected TreeModel
treeModel

Model providing information.

protected TreeSelectionModel
treeSelectionModel

Selection model.

Constructor Summary

Constructors

Constructor and Description

AbstractLayoutCache()

Method Summary

Methods

Modifier and Type
Method and Description

abstract Rectangle
getBounds(TreePath path,
         Rectangle placeIn)

Returns a rectangle giving the bounds needed to draw path.

abstract boolean
getExpandedState(TreePath path)

Returns true if the path is expanded, and visible.

TreeModel
getModel()

Returns the TreeModel that is providing the data.

AbstractLayoutCache.NodeDimensions
getNodeDimensions()

Returns the object that renders nodes in the tree, and which is
 responsible for calculating the dimensions of individual nodes.

protected Rectangle
getNodeDimensions(Object value,
                 int row,
                 int depth,
                 boolean expanded,
                 Rectangle placeIn)

Returns, by reference in placeIn,
 the size needed to represent value.

abstract TreePath
getPathClosestTo(int x,
                int y)

Returns the path to the node that is closest to x,y.

abstract TreePath
getPathForRow(int row)

Returns the path for passed in row.

int
getPreferredHeight()

Returns the preferred height.

int
getPreferredWidth(Rectangle bounds)

Returns the preferred width for the passed in region.

abstract int
getRowCount()

Number of rows being displayed.

abstract int
getRowForPath(TreePath path)

Returns the row that the last item identified in path is visible
 at.

int
getRowHeight()

Returns the height of each row.

int[]
getRowsForPaths(TreePath[] paths)

Returns the rows that the TreePath instances in
 path are being displayed at.

TreeSelectionModel
getSelectionModel()

Returns the model used to maintain the selection.

abstract int
getVisibleChildCount(TreePath path)

Returns the number of visible children for row.

abstract Enumeration<TreePath>
getVisiblePathsFrom(TreePath path)

Returns an Enumerator that increments over the visible
 paths starting at the passed in location.

abstract void
invalidatePathBounds(TreePath path)

Instructs the LayoutCache that the bounds for
 path are invalid, and need to be updated.

abstract void
invalidateSizes()

Informs the TreeState that it needs to recalculate
 all the sizes it is referencing.

abstract boolean
isExpanded(TreePath path)

Returns true if the value identified by row is currently expanded.

protected boolean
isFixedRowHeight()

Returns true if the height of each row is a fixed size.

boolean
isRootVisible()

Returns true if the root node of the tree is displayed.

abstract void
setExpandedState(TreePath path,
                boolean isExpanded)

Marks the path path expanded state to
 isExpanded.

void
setModel(TreeModel newModel)

Sets the TreeModel that will provide the data.

void
setNodeDimensions(AbstractLayoutCache.NodeDimensions nd)

Sets the renderer that is responsible for drawing nodes in the tree
 and which is threfore responsible for calculating the dimensions of
 individual nodes.

void
setRootVisible(boolean rootVisible)

Determines whether or not the root node from
 the TreeModel is visible.

void
setRowHeight(int rowHeight)

Sets the height of each cell.

void
setSelectionModel(TreeSelectionModel newLSM)

Sets the TreeSelectionModel used to manage the
 selection to new LSM.

abstract void
treeNodesChanged(TreeModelEvent e)

 Invoked after a node (or a set of siblings) has changed in some
 way.

abstract void
treeNodesInserted(TreeModelEvent e)

Invoked after nodes have been inserted into the tree.

abstract void
treeNodesRemoved(TreeModelEvent e)

Invoked after nodes have been removed from the tree.

abstract void
treeStructureChanged(TreeModelEvent e)

Invoked after the tree has drastically changed structure from a
 given node down.

Methods inherited from class java.lang.Object

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

Field Detail

nodeDimensions

protected AbstractLayoutCache.NodeDimensions nodeDimensions

Object responsible for getting the size of a node.

treeModel

protected TreeModel treeModel

Model providing information.

treeSelectionModel

protected TreeSelectionModel treeSelectionModel

Selection model.

rootVisible

protected boolean rootVisible

True if the root node is displayed, false if its children are
 the highest visible nodes.

rowHeight

protected int rowHeight

Height to use for each row.  If this is <= 0 the renderer will be
 used to determine the height for each row.

Constructor Detail

AbstractLayoutCache

public AbstractLayoutCache()

Method Detail

setNodeDimensions

public void setNodeDimensions(AbstractLayoutCache.NodeDimensions nd)

Sets the renderer that is responsible for drawing nodes in the tree
 and which is threfore responsible for calculating the dimensions of
 individual nodes.

Parameters:

nd - a NodeDimensions object

getNodeDimensions

public AbstractLayoutCache.NodeDimensions getNodeDimensions()

Returns the object that renders nodes in the tree, and which is
 responsible for calculating the dimensions of individual nodes.

Returns:

the NodeDimensions object

setModel

public void setModel(TreeModel newModel)

Sets the TreeModel that will provide the data.

Parameters:

newModel - the TreeModel that is to
          provide the data

getModel

public TreeModel getModel()

Returns the TreeModel that is providing the data.

Returns:

the TreeModel that is providing the data

setRootVisible

public void setRootVisible(boolean rootVisible)

Determines whether or not the root node from
 the TreeModel is visible.

Parameters:

rootVisible - true if the root node of the tree is to be displayed

See Also:

rootVisible

isRootVisible

public boolean isRootVisible()

Returns true if the root node of the tree is displayed.

Returns:

true if the root node of the tree is displayed

See Also:

rootVisible

setRowHeight

public void setRowHeight(int rowHeight)

Sets the height of each cell.  If the specified value
 is less than or equal to zero the current cell renderer is
 queried for each row's height.

Parameters:

rowHeight - the height of each cell, in pixels

getRowHeight

public int getRowHeight()

Returns the height of each row.  If the returned value is less than
 or equal to 0 the height for each row is determined by the
 renderer.

setSelectionModel

public void setSelectionModel(TreeSelectionModel newLSM)

Sets the TreeSelectionModel used to manage the
 selection to new LSM.

Parameters:

newLSM - the new TreeSelectionModel

getSelectionModel

public TreeSelectionModel getSelectionModel()

Returns the model used to maintain the selection.

Returns:

the treeSelectionModel

getPreferredHeight

public int getPreferredHeight()

Returns the preferred height.

Returns:

the preferred height

getPreferredWidth

public int getPreferredWidth(Rectangle bounds)

Returns the preferred width for the passed in region.
 The region is defined by the path closest to
 (bounds.x, bounds.y) and
 ends at bounds.height + bounds.y.
 If bounds is null,
 the preferred width for all the nodes
 will be returned (and this may be a VERY expensive
 computation).

Parameters:

bounds - the region being queried

Returns:

the preferred width for the passed in region

isExpanded

public abstract boolean isExpanded(TreePath path)

Returns true if the value identified by row is currently expanded.

getBounds

public abstract Rectangle getBounds(TreePath path,
                  Rectangle placeIn)

Returns a rectangle giving the bounds needed to draw path.

Parameters:

path - a TreePath specifying a node

placeIn - a Rectangle object giving the
          available space

Returns:

a Rectangle object specifying the space to be used

getPathForRow

public abstract TreePath getPathForRow(int row)

Returns the path for passed in row.  If row is not visible
 null is returned.

Parameters:

row - the row being queried

Returns:

the TreePath for the given row

getRowForPath

public abstract int getRowForPath(TreePath path)

Returns the row that the last item identified in path is visible
 at.  Will return -1 if any of the elements in path are not
 currently visible.

Parameters:

path - the TreePath being queried

Returns:

the row where the last item in path is visible or -1
         if any elements in path aren't currently visible

getPathClosestTo

public abstract TreePath getPathClosestTo(int x,
                        int y)

Returns the path to the node that is closest to x,y.  If
 there is nothing currently visible this will return null,
 otherwise it'll always return a valid path.
 If you need to test if the
 returned object is exactly at x, y you should get the bounds for
 the returned path and test x, y against that.

Parameters:

x - the horizontal component of the desired location

y - the vertical component of the desired location

Returns:

the TreePath closest to the specified point

getVisiblePathsFrom

public abstract Enumeration<TreePath> getVisiblePathsFrom(TreePath path)

Returns an Enumerator that increments over the visible
 paths starting at the passed in location. The ordering of the
 enumeration is based on how the paths are displayed.
 The first element of the returned enumeration will be path,
 unless it isn't visible,
 in which case null will be returned.

Parameters:

path - the starting location for the enumeration

Returns:

the Enumerator starting at the desired location

getVisibleChildCount

public abstract int getVisibleChildCount(TreePath path)

Returns the number of visible children for row.

Parameters:

path - the path being queried

Returns:

the number of visible children for the specified path

setExpandedState

public abstract void setExpandedState(TreePath path,
                    boolean isExpanded)

Marks the path path expanded state to
 isExpanded.

Parameters:

path - the path being expanded or collapsed

isExpanded - true if the path should be expanded, false otherwise

getExpandedState

public abstract boolean getExpandedState(TreePath path)

Returns true if the path is expanded, and visible.

Parameters:

path - the path being queried

Returns:

true if the path is expanded and visible, false otherwise

getRowCount

public abstract int getRowCount()

Number of rows being displayed.

Returns:

the number of rows being displayed

invalidateSizes

public abstract void invalidateSizes()

Informs the TreeState that it needs to recalculate
 all the sizes it is referencing.

invalidatePathBounds

public abstract void invalidatePathBounds(TreePath path)

Instructs the LayoutCache that the bounds for
 path are invalid, and need to be updated.

Parameters:

path - the path being updated

treeNodesChanged

public abstract void treeNodesChanged(TreeModelEvent e)

 Invoked after a node (or a set of siblings) has changed in some
 way. The node(s) have not changed locations in the tree or
 altered their children arrays, but other attributes have
 changed and may affect presentation. Example: the name of a
 file has changed, but it is in the same location in the file
 system.

e.path() returns the path the parent of the changed node(s).

e.childIndices() returns the index(es) of the changed node(s).

Parameters:

e - the TreeModelEvent

treeNodesInserted

public abstract void treeNodesInserted(TreeModelEvent e)

Invoked after nodes have been inserted into the tree.

e.path() returns the parent of the new nodes

e.childIndices() returns the indices of the new nodes in
 ascending order.

Parameters:

e - the TreeModelEvent

treeNodesRemoved

public abstract void treeNodesRemoved(TreeModelEvent e)

Invoked after nodes have been removed from the tree.  Note that
 if a subtree is removed from the tree, this method may only be
 invoked once for the root of the removed subtree, not once for
 each individual set of siblings removed.

e.path() returns the former parent of the deleted nodes.

e.childIndices() returns the indices the nodes had before they were deleted in ascending order.

Parameters:

e - the TreeModelEvent

treeStructureChanged

public abstract void treeStructureChanged(TreeModelEvent e)

Invoked after the tree has drastically changed structure from a
 given node down.  If the path returned by e.getPath()
 is of length one and the first element does not identify the
 current root node the first element should become the new root
 of the tree.

e.path() holds the path to the node.

e.childIndices() returns null.

Parameters:

e - the TreeModelEvent

getRowsForPaths

public int[] getRowsForPaths(TreePath[] paths)

Returns the rows that the TreePath instances in
 path are being displayed at.
 This method should return an array of the same length as that passed
 in, and if one of the TreePaths
 in path is not valid its entry in the array should
 be set to -1.

Specified by:

getRowsForPaths in interface RowMapper

Parameters:

paths - the array of TreePaths being queried

Returns:

an array of the same length that is passed in containing
          the rows that each corresponding where each
          TreePath is displayed; if paths
          is null, null is returned

getNodeDimensions

protected Rectangle getNodeDimensions(Object value,
                          int row,
                          int depth,
                          boolean expanded,
                          Rectangle placeIn)

Returns, by reference in placeIn,
 the size needed to represent value.
 If inPlace is null, a newly created
 Rectangle should be returned, otherwise the value
 should be placed in inPlace and returned. This will
 return null if there is no renderer.

Parameters:

value - the value to be represented

row - row being queried

depth - the depth of the row

expanded - true if row is expanded, false otherwise

placeIn - a Rectangle containing the size needed
          to represent value

Returns:

a Rectangle containing the node dimensions,
          or null if node has no dimension

isFixedRowHeight

protected boolean isFixedRowHeight()

Returns true if the height of each row is a fixed size.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>{$cur_title}</title>
<meta name="author" content="OEdev">

<link type="text/css" rel="stylesheet" href="__ROOT__/Public/Admin/css/admin.css">

<link rel="stylesheet" href="__PUBLIC__/Admin/css/jquery.msgbox.css"/>

{$cur_menu}

        {$cur_title}

	<form id="" name="formfind" action="" method="GET">

	</form>

	<form action="" method="POST" name="orgtype" />

ID

用户名称

联系电话

操作

	  <foreach name="user_list" item="name">

	        {$name.user_id}

	    {$name.username}
	    {$name.tel}
	    审核通过

	  </foreach>

	  </form>

		{$page}


text:
/*
 * WidgetRoster Messages
 *
 * This contains all the text for the Roster component.
 */
import {defineMessages} from 'react-intl';

export default defineMessages({
  addPeople: {
    id: 'ciscospark.container.roster.message.addPeople',
    defaultMessage: 'Add people'
  },
  addPlaceholder: {
    id: 'ciscospark.container.roster.message.addPeople.placeholder',
    defaultMessage: 'Who are you looking for?'
  },
  cancelDetails: {
    id: 'ciscospark.container.roster.message.cancelDetails',
    defaultMessage: 'Cancel'
  },
  removeParticipant: {
    id: 'ciscospark.container.roster.message.removeParticipant',
    defaultMessage: 'Remove'
  },
  noResults: {
    id: 'ciscospark.container.roster.message.addPeople.noResults',
    defaultMessage: 'No Results'
  },
  externalParticipants: {
    id: 'ciscospark.container.roster.message.externalParticipants',
    defaultMessage: 'People outside your company are included in this space'
  },
  moderators: {
    id: 'ciscospark.container.roster.title.moderators',
    defaultMessage: 'Moderators'
  },
  participants: {
    id: 'ciscospark.container.roster.title.participants',
    defaultMessage: 'Participants'
  },
  inMeeting: {
    id: 'ciscospark.container.roster.title.inMeeting',
    defaultMessage: 'In Meeting'
  },
  notInMeeting: {
    id: 'ciscospark.container.roster.title.notInMeeting',
    defaultMessage: 'Not in Meeting'
  }
});


text:
using System;
using System.Globalization;
using System.Text.RegularExpressions;

namespace Correios.NET.Extensions
{
    public static class StringExtensions
    {
        public const char SPACE = ' ';
        public const string HYPHEN = "-";

        public static string RemoveLineEndings(this string text)
        {
            return Regex.Replace(text, @"(\r\n?|\n|\t)", SPACE.ToString()).Trim();
        }

        public static string RemoveHyphens(this string text)
        {
            return text.Replace(HYPHEN, string.Empty).Trim();
        }

        public static string[] SplitSpaces(this string text, int count = 1)
        {
            var separator = new string(SPACE, count);
            return text.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
        }

        public static DateTime ExtractDateTime(this string text, string pattern)
        {
            var regex = new Regex(pattern);
            var match = regex.Match(text);
            if (match.Success)
            {
                var matchValue = $"{match.Groups[1]} {match.Groups[2]}";
                var dateTime = DateTime.ParseExact(matchValue, "dd/MM/yyyy HH:mm", CultureInfo.GetCultureInfo("pt-BR"));
                return dateTime;
            }

            return DateTime.MinValue;
        }
    }
}


text:
function [mistakes, timerz, h_loss] = ofs_boosting(data, labels, opts)
% OFS_BOOSTING Online Boosting using Online Feature Selection
%
%  [mistakes, timerz] = OFS_BOOSTING(data, labels, opts)
%
%  @data: feature vectors (observations by features)
%  @labels: class labels (+/-1)
%  @opt: options structure
%     @opts.ensemble_size: ensemble size (required)
%     @opts.epsilon: search term
%     @opts.eta: learning rate
%     @opts.R: max l2-norm
%     @opts.truncate: l0-norm (required)
%     @opts.verbose: print evaulation round (mod(t,1000)==0)
%
%  See also
%  OFS_BAGGING, OFS_BOOSTING_AVG, OFS_BOOSTING_RANDTRUC_AVG

% perform some error checking
if ~isfield(opts, 'ensemble_size')
  error('opts.ensemble size must be specified');
end
if ~isfield(opts, 'truncate')
  error('opts.truncate must be specified');
end
if ~isfield(opts, 'fixed_partial')
  opts.fixed_partial = false;
end
if ~isfield(opts, 'epsilon')
  opts.epsilon = .1;
end
if ~isfield(opts, 'eta')
  opts.eta = .1;
end
if ~isfield(opts, 'verbose')
  opts.verbose = 0;
end
if ~isfield(opts, 'partial_test')
  opts.partial_test = 0;
end
if length(opts.truncate) == 1
  opts.truncate = opts.truncate*ones(1, opts.ensemble_size+1);
end
if length(opts.truncate) ~= (opts.ensemble_size+1)
  error('opts.truncate must be of length opts.ensemble_size+1.')
end
if ~isfield(opts, 'anneal')
  opts.anneal = 1;
end

[T, opts.n_features] = size(data);

% split the data into train/testing sequences assuing
data_tr = data(1:T-1, :);
data_te = data(2:T, :);
labels_tr = labels(1:T-1);
labels_te = labels(2:T);

% initialize the OFS models to be sampled from a Gaussian distribution then
% truncate out the vectors. no need to truncate the ensemble model yet
opts.models = randn(opts.n_features, opts.ensemble_size+1);
mistakes = zeros(length(labels_te), opts.ensemble_size+1);
h_loss = zeros(length(labels_te), opts.ensemble_size+1);

for i = 1:opts.ensemble_size
  opts.models(:, i) = truncate(opts.models(:, i), opts.truncate(i));
end

lambda_sc = zeros(opts.ensemble_size, 1);
lambda_sw = zeros(opts.ensemble_size, 1);
timerz = 0;

for t = 1:T-1

  if opts.verbose
    if mod(t, 1000) == 0
      disp(['Timestep ', num2str(t), ' of ', num2str(T-1)]);
    end
  end

  % if we are testing on partial information then we should create a mask
  % for the features that are available to us
  if opts.partial_test
    mask = zeros(1, opts.n_features);
    q = randperm(opts.n_features);
    mask(q(1:opts.truncate(end))) = 1;
  end

  if opts.fixed_partial
    if random('Binomial', 1, opts.epsilon) == 1,
      perm_t = randperm(size(opts.models(:, 1), 1));
      c_t = perm_t(1:opts.truncate(1)-1);
      v_idx = zeros(size(opts.models(:, end),1),1);
      v_idx(c_t) = 1;
    else
      v_idx = (opts.models(:, 1)~=0);
    end
  end

  lambda_t = 1;  % set current instance weight

  for k = 1:opts.ensemble_size

    % perform the online bagging update the to `k`th ensmeble member
    lambda_k = poissrnd(lambda_t);
    for j = 1:lambda_k
      if opts.fixed_partial
        opts.models(:,k) = update_ofs(data_tr(t, :), labels_tr(t), opts, k, v_idx);
      else
        opts.models(:,k) = update_ofs(data_tr(t, :), labels_tr(t), opts, k);
      end
    end

    % predict the output of the `k`th ensmeble member on the testing
    % sequence and update the mistakes if needed.

    if opts.partial_test
      f_t = opts.models(:,k)'*(data_te(t, :).*mask)';
      if ((f_t)*labels_te(t)) < 0
        mistakes(t, k) = 1;
        lambda_sw(k) = lambda_sw(k) + lambda_t;
        lambda_t = lambda_t*t/(2*lambda_sw(k));
      else
        lambda_sc(k) = lambda_sc(k) + lambda_t;
        lambda_t = lambda_t*t/(2*lambda_sc(k));
      end
    else
      f_t = opts.models(:,k)'*data_te(t, :)';
      if ((f_t)*labels_te(t)) < 0
        mistakes(t, k) = 1;
        lambda_sw(k) = lambda_sw(k) + lambda_t;
        lambda_t = lambda_t*t/(2*lambda_sw(k));
      else
        lambda_sc(k) = lambda_sc(k) + lambda_t;
        lambda_t = lambda_t*t/(2*lambda_sc(k));
      end
    end
    h_loss(t, k) = hinge(f_t, labels_te(t));

  end

  % update the weights for combining the ensemble models together.
  new_weights = zeros(opts.n_features, 1);
  for k = 1:opts.ensemble_size
    epsilon = lambda_sw(k)/(lambda_sw(k) + lambda_sc(k));
    beta = epsilon/(1-epsilon);
    vote_weight = log(1/beta);
    new_weights = new_weights + vote_weight*opts.models(:, k);
  end

  % for bagging, average the ensemble models then perform the truncation
  % step, and update the number of mistakes made by the ensemble.
  opts.models(:, end) = truncate(new_weights, opts.truncate(end));

  %tic;
  if opts.partial_test
    f_t = opts.models(:, end)'*(data_te(t, :).*mask)';
    if ((f_t)*labels_te(t)) < 0
      mistakes(t, end) = 1;
    end
  else
    f_t = opts.models(:, end)'*data_te(t, :)';
    if ((f_t)*labels_te(t)) < 0
      mistakes(t, end) = 1;
    end
  end
  timerz = timerz + toc;

  h_loss(t, end) = hinge(f_t, labels_te(t));
  opts.epsilon = opts.epsilon*opts.anneal^t;
end