text:
AJS.toInit(function () {
  var baseUrl = AJS.$("meta[name='application-base-url']").attr("content");

  //Atlassian's framework seems not completely bug free. the confluence-base-url is set as a fallback, which we set ourself in the admin.vm
  if (baseUrl == null || baseUrl == undefined) {
    baseUrl = AJS.$("meta[name='confluence-base-url']").attr("content");
  }

  function populateForm() {
    AJS.$.ajax({
      url: baseUrl + "/rest/surveyplugin/1.0/admin",
      dataType: "json",
      success: function (config) {
        AJS.$("#is-" + config.iconSet).attr("checked", "checked");
      }
    });
  }

  function updateConfig() {
    var upConfig = AJS.$.ajax({
      url: baseUrl + "/rest/surveyplugin/1.0/admin",
      type: "PUT",
      contentType: "application/json",
      data: '{ "iconSet": "' + AJS.$("input[name='is-rads']:checked").attr("id") + '" }',
      processData: false
    });
    upConfig.done(function () {
      var inlineDialog = AJS.InlineDialog(AJS.$("#iconset-submit-div"), "confirmationDialog",
        function (content, trigger, showPopup) {
          content.css({"padding": "20px"}).html('
' + AJS.I18n.getText('surveyplugin.admin.iconset.confirmation') + ': ' + AJS.$("label[for='" + AJS.$("input[name='is-rads']:checked").attr("id") + "']").text() + '
');
          showPopup();
          return false;
        }
      );
      inlineDialog.show();
    });
  }

  populateForm();

  AJS.$("#admin").submit(function (e) {
    e.preventDefault();
    updateConfig();
  });
});


text:
import { Component, ChangeDetectionStrategy, ViewChild, AfterViewInit } from '@angular/core';
import { DataService, Human } from '../data.service';
import { Observable } from 'rxjs';
import { Command, GridComponent, PaneComponent } from 'ng2-qgrid';

const EXAMPLE_TAGS = [
	'pane-trigger',
	'Pane for selected row can be opened by clicking on the triangle button'
];

@Component({
	selector: 'example-pane-trigger',
	templateUrl: 'example-pane-trigger.component.html',
	styleUrls: ['example-pane-trigger.component.scss'],
	providers: [DataService],
	changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExamplePaneTriggerComponent implements AfterViewInit {
	static tags = EXAMPLE_TAGS;
	title = EXAMPLE_TAGS[1];

	@ViewChild(GridComponent) grid: GridComponent;
	@ViewChild(PaneComponent) pane: PaneComponent;

	rows$: Observable<Human[]>;
	selectedRow: Human;

	openPane = new Command({
		execute: () => this.pane.open('right'),
		canExecute: () => !!this.selectedRow,
	});

	constructor(dataService: DataService) {
		this.rows$ = dataService.getPeople();
	}

	ngAfterViewInit() {
		const { model } = this.grid;
		model.selectionChanged.watch(e => {
			if (e.hasChanges('items')) {
				this.selectedRow = e.state.items[0];
				this.openPane.canExecuteCheck.next();
			}
		});
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.phoenix.util;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.coprocessor.MetaDataProtocol;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
import org.apache.phoenix.query.QueryConstants;
import org.apache.phoenix.schema.types.PInteger;
import org.apache.phoenix.schema.types.PLong;
import org.apache.phoenix.schema.PName;
import org.apache.phoenix.schema.PNameFactory;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.SaltingUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

public class UpgradeUtil {
    private static final Logger logger = LoggerFactory.getLogger(UpgradeUtil.class);
    private static final byte[] SEQ_PREFIX_BYTES = ByteUtil.concat(QueryConstants.SEPARATOR_BYTE_ARRAY, Bytes.toBytes("_SEQ_"));

    private UpgradeUtil() {
    }

    private static byte[] getSequenceSnapshotName() {
        return Bytes.toBytes("_BAK_" + PhoenixDatabaseMetaData.SEQUENCE_FULLNAME);
    }

    private static void createSequenceSnapshot(HBaseAdmin admin, PhoenixConnection conn) throws SQLException {
        byte[] tableName = getSequenceSnapshotName();
        HColumnDescriptor columnDesc = new HColumnDescriptor(PhoenixDatabaseMetaData.SEQUENCE_FAMILY_BYTES);
        HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
        desc.addFamily(columnDesc);
        try {
            admin.createTable(desc);
            copyTable(conn, PhoenixDatabaseMetaData.SEQUENCE_FULLNAME_BYTES, tableName);
        } catch (IOException e) {
            throw ServerUtil.parseServerException(e);
        }
    }

    private static void restoreSequenceSnapshot(HBaseAdmin admin, PhoenixConnection conn) throws SQLException {
        byte[] tableName = getSequenceSnapshotName();
        copyTable(conn, tableName, PhoenixDatabaseMetaData.SEQUENCE_FULLNAME_BYTES);
    }

    private static void deleteSequenceSnapshot(HBaseAdmin admin) throws SQLException {
        byte[] tableName = getSequenceSnapshotName();
        try {
            admin.disableTable(tableName);;
            admin.deleteTable(tableName);
        } catch (IOException e) {
            throw ServerUtil.parseServerException(e);
        }
    }

    @SuppressWarnings("deprecation")
    private static void copyTable(PhoenixConnection conn, byte[] sourceName, byte[] targetName) throws SQLException {
        int batchSizeBytes = 100 * 1024; // 100K chunks
        int sizeBytes = 0;
        List<Mutation> mutations =  Lists.newArrayListWithExpectedSize(10000);

        Scan scan = new Scan();
        scan.setRaw(true);
        scan.setMaxVersions(MetaDataProtocol.DEFAULT_MAX_META_DATA_VERSIONS);
        ResultScanner scanner = null;
        HTableInterface source = null;
        HTableInterface target = null;
        try {
            source = conn.getQueryServices().getTable(sourceName);
            target = conn.getQueryServices().getTable(targetName);
            scanner = source.getScanner(scan);
            Result result;
             while ((result = scanner.next()) != null) {
                for (KeyValue keyValue : result.raw()) {
                    sizeBytes += keyValue.getLength();
                    if (KeyValue.Type.codeToType(keyValue.getType()) == KeyValue.Type.Put) {
                        // Put new value
                        Put put = new Put(keyValue.getRow());
                        put.add(keyValue);
                        mutations.add(put);
                    } else if (KeyValue.Type.codeToType(keyValue.getType()) == KeyValue.Type.Delete){
                        // Copy delete marker using new key so that it continues
                        // to delete the key value preceding it that will be updated
                        // as well.
                        Delete delete = new Delete(keyValue.getRow());
                        delete.addDeleteMarker(keyValue);
                        mutations.add(delete);
                    }
                }
                if (sizeBytes >= batchSizeBytes) {
                    logger.info("Committing bactch of temp rows");
                    target.batch(mutations);
                    mutations.clear();
                    sizeBytes = 0;
                }
            }
            if (!mutations.isEmpty()) {
                logger.info("Committing last bactch of temp rows");
                target.batch(mutations);
            }
            logger.info("Successfully completed copy");
        } catch (SQLException e) {
            throw e;
        } catch (Exception e) {
            throw ServerUtil.parseServerException(e);
        } finally {
            try {
                if (scanner != null) scanner.close();
            } finally {
                try {
                    if (source != null) source.close();
                } catch (IOException e) {
                    logger.warn("Exception during close of source table",e);
                } finally {
                    try {
                        if (target != null) target.close();
                    } catch (IOException e) {
                        logger.warn("Exception during close of target table",e);
                    }
                }
            }
        }
    }

    private static void preSplitSequenceTable(PhoenixConnection conn, int nSaltBuckets) throws SQLException {
        HBaseAdmin admin = conn.getQueryServices().getAdmin();
        boolean snapshotCreated = false;
        boolean success = false;
        try {
            if (nSaltBuckets <= 0) {
                return;
            }
            logger.warn("Pre-splitting SYSTEM.SEQUENCE table " + nSaltBuckets + "-ways. This may take some time - please do not close window.");
            HTableDescriptor desc = admin.getTableDescriptor(PhoenixDatabaseMetaData.SEQUENCE_FULLNAME_BYTES);
            createSequenceSnapshot(admin, conn);
            snapshotCreated = true;
            admin.disableTable(PhoenixDatabaseMetaData.SEQUENCE_FULLNAME);
            admin.deleteTable(PhoenixDatabaseMetaData.SEQUENCE_FULLNAME);
            byte[][] splitPoints = SaltingUtil.getSalteByteSplitPoints(nSaltBuckets);
            admin.createTable(desc, splitPoints);
            restoreSequenceSnapshot(admin, conn);
            success = true;
            logger.warn("Completed pre-splitting SYSTEM.SEQUENCE table");
        } catch (IOException e) {
            throw new SQLException("Unable to pre-split SYSTEM.SEQUENCE table", e);
        } finally {
            try {
                if (snapshotCreated && success) {
                    try {
                        deleteSequenceSnapshot(admin);
                    } catch (SQLException e) {
                        logger.warn("Exception while deleting SYSTEM.SEQUENCE snapshot during pre-split", e);
                    }
                }
            } finally {
                try {
                    admin.close();
                } catch (IOException e) {
                    logger.warn("Exception while closing admin during pre-split", e);
                }
            }
        }
    }

    @SuppressWarnings("deprecation")
    public static boolean upgradeSequenceTable(PhoenixConnection conn, int nSaltBuckets, PTable oldTable) throws SQLException {
        logger.info("Upgrading SYSTEM.SEQUENCE table");

        byte[] seqTableKey = SchemaUtil.getTableKey(null, PhoenixDatabaseMetaData.SEQUENCE_SCHEMA_NAME, PhoenixDatabaseMetaData.SEQUENCE_TABLE_NAME);
        HTableInterface sysTable = conn.getQueryServices().getTable(PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME_BYTES);
        try {
            logger.info("Setting SALT_BUCKETS property of SYSTEM.SEQUENCE to " + SaltingUtil.MAX_BUCKET_NUM);
            KeyValue saltKV = KeyValueUtil.newKeyValue(seqTableKey,
                    PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES,
                    PhoenixDatabaseMetaData.SALT_BUCKETS_BYTES,
                    MetaDataProtocol.MIN_SYSTEM_TABLE_TIMESTAMP,
                    PInteger.INSTANCE.toBytes(nSaltBuckets));
            Put saltPut = new Put(seqTableKey);
            saltPut.add(saltKV);
            // Prevent multiple clients from doing this upgrade
            if (!sysTable.checkAndPut(seqTableKey,
                    PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES,
                    PhoenixDatabaseMetaData.SALT_BUCKETS_BYTES, null, saltPut)) {
                if (oldTable == null) { // Unexpected, but to be safe just run pre-split code
                    preSplitSequenceTable(conn, nSaltBuckets);
                    return true;
                }
                // We can detect upgrade from 4.2.0 -> 4.2.1 based on the timestamp of the table row
                if (oldTable.getTimeStamp() == MetaDataProtocol.MIN_SYSTEM_TABLE_TIMESTAMP-1) {
                    byte[] oldSeqNum = PLong.INSTANCE.toBytes(oldTable.getSequenceNumber());
                    KeyValue seqNumKV = KeyValueUtil.newKeyValue(seqTableKey,
                            PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES,
                            PhoenixDatabaseMetaData.TABLE_SEQ_NUM_BYTES,
                            MetaDataProtocol.MIN_SYSTEM_TABLE_TIMESTAMP,
                            PLong.INSTANCE.toBytes(oldTable.getSequenceNumber()+1));
                    Put seqNumPut = new Put(seqTableKey);
                    seqNumPut.add(seqNumKV);
                    // Increment TABLE_SEQ_NUM in checkAndPut as semaphore so that only single client
                    // pre-splits the sequence table.
                    if (sysTable.checkAndPut(seqTableKey,
                            PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES,
                            PhoenixDatabaseMetaData.TABLE_SEQ_NUM_BYTES, oldSeqNum, seqNumPut)) {
                        preSplitSequenceTable(conn, nSaltBuckets);
                        return true;
                    }
                }
                logger.info("SYSTEM.SEQUENCE table has already been upgraded");
                return false;
            }

            int batchSizeBytes = 100 * 1024; // 100K chunks
            int sizeBytes = 0;
            List<Mutation> mutations =  Lists.newArrayListWithExpectedSize(10000);

            boolean success = false;
            Scan scan = new Scan();
            scan.setRaw(true);
            scan.setMaxVersions(MetaDataProtocol.DEFAULT_MAX_META_DATA_VERSIONS);
            HTableInterface seqTable = conn.getQueryServices().getTable(PhoenixDatabaseMetaData.SEQUENCE_FULLNAME_BYTES);
            try {
                boolean committed = false;
                logger.info("Adding salt byte to all SYSTEM.SEQUENCE rows");
                ResultScanner scanner = seqTable.getScanner(scan);
                try {
                    Result result;
                     while ((result = scanner.next()) != null) {
                        for (KeyValue keyValue : result.raw()) {
                            KeyValue newKeyValue = addSaltByte(keyValue, nSaltBuckets);
                            if (newKeyValue != null) {
                                sizeBytes += newKeyValue.getLength();
                                if (KeyValue.Type.codeToType(newKeyValue.getType()) == KeyValue.Type.Put) {
                                    // Delete old value
                                    byte[] buf = keyValue.getBuffer();
                                    Delete delete = new Delete(keyValue.getRow());
                                    KeyValue deleteKeyValue = new KeyValue(buf, keyValue.getRowOffset(), keyValue.getRowLength(),
                                            buf, keyValue.getFamilyOffset(), keyValue.getFamilyLength(),
                                            buf, keyValue.getQualifierOffset(), keyValue.getQualifierLength(),
                                            keyValue.getTimestamp(), KeyValue.Type.Delete,
                                            ByteUtil.EMPTY_BYTE_ARRAY,0,0);
                                    delete.addDeleteMarker(deleteKeyValue);
                                    mutations.add(delete);
                                    sizeBytes += deleteKeyValue.getLength();
                                    // Put new value
                                    Put put = new Put(newKeyValue.getRow());
                                    put.add(newKeyValue);
                                    mutations.add(put);
                                } else if (KeyValue.Type.codeToType(newKeyValue.getType()) == KeyValue.Type.Delete){
                                    // Copy delete marker using new key so that it continues
                                    // to delete the key value preceding it that will be updated
                                    // as well.
                                    Delete delete = new Delete(newKeyValue.getRow());
                                    delete.addDeleteMarker(newKeyValue);
                                    mutations.add(delete);
                                }
                            }
                            if (sizeBytes >= batchSizeBytes) {
                                logger.info("Committing bactch of SYSTEM.SEQUENCE rows");
                                seqTable.batch(mutations);
                                mutations.clear();
                                sizeBytes = 0;
                                committed = true;
                            }
                        }
                    }
                    if (!mutations.isEmpty()) {
                        logger.info("Committing last bactch of SYSTEM.SEQUENCE rows");
                        seqTable.batch(mutations);
                    }
                    preSplitSequenceTable(conn, nSaltBuckets);
                    logger.info("Successfully completed upgrade of SYSTEM.SEQUENCE");
                    success = true;
                    return true;
                } catch (InterruptedException e) {
                    throw ServerUtil.parseServerException(e);
                } finally {
                    try {
                        scanner.close();
                    } finally {
                        if (!success) {
                            if (!committed) { // Try to recover by setting salting back to off, as we haven't successfully committed anything
                                // Don't use Delete here as we'd never be able to change it again at this timestamp.
                                KeyValue unsaltKV = KeyValueUtil.newKeyValue(seqTableKey,
                                        PhoenixDatabaseMetaData.TABLE_FAMILY_BYTES,
                                        PhoenixDatabaseMetaData.SALT_BUCKETS_BYTES,
                                        MetaDataProtocol.MIN_SYSTEM_TABLE_TIMESTAMP,
                                        PInteger.INSTANCE.toBytes(0));
                                Put unsaltPut = new Put(seqTableKey);
                                unsaltPut.add(unsaltKV);
                                try {
                                    sysTable.put(unsaltPut);
                                    success = true;
                                } finally {
                                    if (!success) logger.error("SYSTEM.SEQUENCE TABLE LEFT IN CORRUPT STATE");
                                }
                            } else { // We're screwed b/c we've already committed some salted sequences...
                                logger.error("SYSTEM.SEQUENCE TABLE LEFT IN CORRUPT STATE");
                            }
                        }
                    }
                }
            } catch (IOException e) {
                throw ServerUtil.parseServerException(e);
            } finally {
                try {
                    seqTable.close();
                } catch (IOException e) {
                    logger.warn("Exception during close",e);
                }
            }
        } catch (IOException e) {
            throw ServerUtil.parseServerException(e);
        } finally {
            try {
                sysTable.close();
            } catch (IOException e) {
                logger.warn("Exception during close",e);
            }
        }
    }

    @SuppressWarnings("deprecation")
    private static KeyValue addSaltByte(KeyValue keyValue, int nSaltBuckets) {
        byte[] buf = keyValue.getBuffer();
        int length = keyValue.getRowLength();
        int offset = keyValue.getRowOffset();
        boolean isViewSeq = length > SEQ_PREFIX_BYTES.length && Bytes.compareTo(SEQ_PREFIX_BYTES, 0, SEQ_PREFIX_BYTES.length, buf, offset, SEQ_PREFIX_BYTES.length) == 0;
        if (!isViewSeq && nSaltBuckets == 0) {
            return null;
        }
        byte[] newBuf;
        if (isViewSeq) { // We messed up the name for the sequences for view indexes so we'll take this opportunity to fix it
            if (buf[length-1] == 0) { // Global indexes on views have trailing null byte
                length--;
            }
            byte[][] rowKeyMetaData = new byte[3][];
            SchemaUtil.getVarChars(buf, offset, length, 0, rowKeyMetaData);
            byte[] schemaName = rowKeyMetaData[PhoenixDatabaseMetaData.SCHEMA_NAME_INDEX];
            byte[] unprefixedSchemaName = new byte[schemaName.length - MetaDataUtil.VIEW_INDEX_SEQUENCE_PREFIX_BYTES.length];
            System.arraycopy(schemaName, MetaDataUtil.VIEW_INDEX_SEQUENCE_PREFIX_BYTES.length, unprefixedSchemaName, 0, unprefixedSchemaName.length);
            byte[] tableName = rowKeyMetaData[PhoenixDatabaseMetaData.TABLE_NAME_INDEX];
            PName physicalName = PNameFactory.newName(unprefixedSchemaName);
            // Reformulate key based on correct data
            newBuf = MetaDataUtil.getViewIndexSequenceKey(tableName == null ? null : Bytes.toString(tableName), physicalName, nSaltBuckets).getKey();
        } else {
            newBuf = new byte[length + 1];
            System.arraycopy(buf, offset, newBuf, SaltingUtil.NUM_SALTING_BYTES, length);
            newBuf[0] = SaltingUtil.getSaltingByte(newBuf, SaltingUtil.NUM_SALTING_BYTES, length, nSaltBuckets);
        }
        return new KeyValue(newBuf, 0, newBuf.length,
                buf, keyValue.getFamilyOffset(), keyValue.getFamilyLength(),
                buf, keyValue.getQualifierOffset(), keyValue.getQualifierLength(),
                keyValue.getTimestamp(), KeyValue.Type.codeToType(keyValue.getType()),
                buf, keyValue.getValueOffset(), keyValue.getValueLength());
    }

}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Figo</title>
  <meta name="description" content="Write an awesome description for your new site here. You can edit this line in _config.yml. It will appear in your document head meta (for Google search results) and in your feed.xml site description.
">
  <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Tangerine">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://localhost:4000/">
  <link rel="alternate" type="application/rss+xml" title="Figo" href="http://localhost:4000/feed.xml" />
  <link href='http://fonts.googleapis.com/css?family=Roboto:400,300,700' rel='stylesheet' type='text/css'>

  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="/css/animate.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          Toggle navigation

        </button>

          P Vineet Souri

About

Portfolio

Skills

Contact

Parallax

Parallax is an effect where the background content or image in this case, is moved at a different speed than the foreground content while scrolling.

  © 2015 - Vineet Souri P


text:
package net.sf.jasperreports.data.cache;

import java.io.ObjectStreamException;
import java.io.Serializable;

import net.sf.jasperreports.engine.JRConstants;

/**
 * @author Lucian Chirita (lucianc@users.sourceforge.net)
 * @version $Id: NumberToShortTransformer.java 7199 2014-08-27 13:58:10Z teodord $
 */
public final class NumberToShortTransformer implements ValueTransformer, Serializable
{

	private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;

	private static final NumberToShortTransformer INSTANCE = new NumberToShortTransformer();

	public static NumberToShortTransformer instance()
	{
		return INSTANCE;
	}

	private NumberToShortTransformer()
	{
	}

	@Override
	public Class<?> getResultType()
	{
		return Short.class;
	}

	public Object get(Object value)
	{
		return ((Number) value).shortValue();
	}

	private Object readResolve() throws ObjectStreamException
	{
		return INSTANCE;
	}

}


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

<TITLE>
GLGraphTest
</TITLE>

<META NAME="date" CONTENT="2012-11-08">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.intel.hadoop.graphbuilder.test.graph

Class GLGraphTest

java.lang.Object
  com.intel.hadoop.graphbuilder.test.graph.GLGraphTest

public class GLGraphTest
extends java.lang.Object

Unit test for GLGraph.

Author:

Haijie Gu

Constructor Summary

GLGraphTest()

Method Summary

 void
buildGraphExample()

 void
testEmptyGraph()

 void
testGoogleGraph()

 void
testSmallGraph()

Methods inherited from class java.lang.Object

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

Constructor Detail

GLGraphTest

public GLGraphTest()

Method Detail

testEmptyGraph

public void testEmptyGraph()
                    throws java.lang.Exception

Throws:

java.lang.Exception

testSmallGraph

public void testSmallGraph()
                    throws java.lang.Exception

Throws:

java.lang.Exception

buildGraphExample

public void buildGraphExample()
                       throws java.lang.Exception

Throws:

java.lang.Exception

testGoogleGraph

public void testGoogleGraph()
                     throws java.lang.Exception

Throws:

java.lang.Exception

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
Release 0.6 ("Cannon Beach")

2013-12-25

Happy Holidays! Sorry, it's been over 3 months since our last release, but it's worth it. This release is awesome.

I'm giving this release the codename "Cannon Beach",
where I've done a bunch of hacking on Camlistore over the years, and in the past few months.

camlistore-0.6.zip

Or browse at Github: github.com/bradfitz/camlistore/tree/0.6

What is Camlistore?

See the docs and overview.

New in 0.6

New beautiful web UI with infinite scroll of photos

Search! Search by tag, photo location (using GPS info in JPEG EXIF + geocoding lookups), photo orientation, size, format, ...

Websocket-based live updating of search results (see new photos appear on the web as they're uploaded from Android or other clients)

Notable bug fixes: corruption fix for cznic/kv (for the "kvfile" index type), fd open/close race in diskpacked, etc.

camlistored --reindex

Start of OS X GUI and iPhone app. (no binary releases yet)

Bunch of internal cleanups

New publishing and templating system.

Faster, prettier thumbnails

Start of content importer framework & initial version of Flickr importer

18 unique contributors since 0.5

10 new contributors: Brian Marete, Daniel Pupius, Dustin Sallings, Jakub Brzeski, Robert Obryk, Salman Aljammaz, Steve Phillips, Tamás Gulácsi, Tony Chang, and Ulf Holm Nielsen.

434 non-merge commits

Screenshots

See http://imgur.com/a/NKje7.  We hope to soon be using Camlistore itself for publishing these, instead of using imgur.

My apologies if I forgot something in this summary.

Get involved!

We welcome feedback, feature requests, bug reports, and code
contributions!

Feel free to email us on our mailing
list, and/or file a bug (or
see existing
bugs).

While we welcome user bug reports, we also welcome code
contributions. See the Contributing
page for details. While most the codebase (the server and
command-line tools) are written in Go,
there's also a lot of JavaScript which needs love, as well as Java
(for Android) and Objective C (for OS X and iOS). Or anything useful you'd like
to contribute.


text:
package org.semanticweb.elk.loading;

import org.semanticweb.elk.util.concurrent.computation.InterruptMonitor;

/**
 * Returns axiom loader that is passed to the constructor. Ignores all
 * arguments of the factory method.
 *
 * @author Peter Skocovsky
 */
public class TestAxiomLoaderFactory implements AxiomLoader.Factory {

	private final TestAxiomLoader loader_;

	public TestAxiomLoaderFactory(final TestAxiomLoader loader) {
		this.loader_ = loader;
	}

	@Override
	public TestAxiomLoader getAxiomLoader(final InterruptMonitor interrupter) {
		return loader_;
	}

}


text:
"""
Module for running Louvain community detection algorithm.
"""

from __future__ import division, print_function, absolute_import
import six
range = six.moves.range
zip = six.moves.zip

import numpy as np
import subprocess
import tempfile
import threading
import os
import scipy.sparse as sp
from contextlib import closing

from . import qualityfuncs

def _edge_lines_iter(conn_mx, is_sparse):
    """
    Iterate over Pajek edge lines
    """
    if is_sparse:
        for ndx in range(conn_mx.shape[0]):
            conns = conn_mx.rows[ndx]
            weights = conn_mx.data[ndx]
            if not len(conns):
                yield ('%d %d %0.5f 0\n' % (ndx, 0, 0))
            else:
                for c, w in zip(conns, weights):
                    yield ('%d %d %0.5f 0\n' % (ndx, c, w))
    else:
        for ndx in range(conn_mx.shape[0]):
            r = conn_mx[ndx, :]
            conns = np.flatnonzero(r)
            weights = r[conns]
            if not len(conns):
                yield ('%d %d %0.5f 0\n' % (ndx, 0, 0))
            else:
                for c, w in zip(conns, weights):
                    yield ('%d %d %0.5f 0\n' % (ndx, c, w))

def optimize_modularity(conn_mx, rand_init=True, num_runs=1, debug=False, errortol=1e-2):
    """
    Optimize directed, weighted Newman's modularity
    using the Louvain algorithm. This uses C++ implementation from
    https://github.com/raldecoa/SurpriseMe/tree/master/src/CPM

    For example:

    >>> import networkx as nx
    >>> from graphy.louvain import optimize_modularity
    >>> G = nx.karate_club_graph()
    >>> best_membership, q = optimize_modularity(nx.to_numpy_matrix(G))
    >>> print(best_membership, q)   # doctest: +SKIP

    Parameters
    ----------
    conn_mx : 2-dimensional np.array or scipy.sparse matrix
        Connectivity matrix.

    rand_init : bool (default True)
        Whether to randomly shuffle order of nodes (makes results
        non-deterministic)

    num_runs : int (default 1)
        How many runs to perform (highest quality run returned).  Only allow if
        rand_init is True.

    debug : bool (default False)
        If True, prints various debugging information.

    Returns
    -------
    np.array
        Optimal membership vector indicating community membership of each node.

    float
        Modularity value corresponding to the optimal membership vector. Notice
        that because the modularity value is computed by adding up increments
        over many moves, this may only be accurate to a few decimal places.
    """
    # TODO: Implement multithreading?  Code seems to support it already

    # check inputs
    if num_runs > 1 and not rand_init:
        raise ValueError('Multiple runs only makes sense when initial order of'
                         'nodes is randomized')

    # check is sparse or not
    is_sparse = sp.isspmatrix(conn_mx)
    if is_sparse:
        # transform to list of lists
        conn_mx = conn_mx.tolil()
    else:
        conn_mx = np.asarray(conn_mx)

    # check is square matrix
    if conn_mx.shape[0] != conn_mx.shape[1]:
        raise ValueError('conn mx should be square')

    qObj = qualityfuncs.DirectedModularity(conn_mx)

    # create files
    DIR = tempfile.gettempdir()
    pfx = '%d_%d_' % (os.getpid(), hash(threading.current_thread().name))

    NETWORK_FILE = os.path.join(DIR, pfx+'net.txt')
    OUTPUT_FILE = os.path.join(DIR, pfx+'net.bin')
    NODEMAP_FILE = os.path.join(DIR, pfx+'nmap.bin')
    CONF_FILE = os.path.join(DIR, pfx+'conf.bin')

    with closing(open(NETWORK_FILE, 'w')) as f:
        f.write('>\n')
        N_nodes = conn_mx.shape[0]
        node_lines = ('%d %d\n' % (ndx, ndx) for ndx in range(N_nodes))
        f.writelines(node_lines)
        f.write('>\n0 0\n>\n')
        edges_lines = _edge_lines_iter(conn_mx, is_sparse)
        f.writelines(edges_lines)

    bin_dir = os.path.join(os.path.dirname(__file__), 'external',
                           'SurpriseMeCPM', 'bin')
    subprocess.call([os.path.join(bin_dir, 'slicer'),
                     '-i', NETWORK_FILE,
                     '-o', OUTPUT_FILE,
                     '-n', NODEMAP_FILE,
                     '-c', CONF_FILE], stderr=subprocess.PIPE)

    call_opts = [os.path.join(bin_dir, 'community'), ]
    if rand_init:
        call_opts.append('-r')
    call_opts.append(OUTPUT_FILE)
    call_opts.append(CONF_FILE)

    best_membership, best_q = None, None
    for run_ndx in range(num_runs):
        rand_seed_opt = [] # ['-s', str(1+run_ndx)]
        res = subprocess.Popen(call_opts + rand_seed_opt, stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)

        output, errors = map(lambda s: s.decode('ascii'), res.communicate())

        all_files = [NETWORK_FILE, OUTPUT_FILE, NODEMAP_FILE, CONF_FILE]
        if debug:
            print("******* RUN %d *******" % run_ndx)
            print("**** OUTPUT: ****")
            print(output)
            print()
            print("**** STDERR: ****")
            print(errors)
            print("*****************")
            print("Leaving files in place:")
            print(all_files)

        returned_q = float(errors.strip().split("\n")[-1].split(" ")[0])

        membership = np.zeros(conn_mx.shape[0], dtype='int')
        ndxs, vals = zip(*[map(int, l.strip().split("\t"))
                           for l in output.strip().split("\n")])
        membership[list(ndxs)] = vals

        accurate_q = qObj.quality(membership)
        if (np.abs(returned_q - accurate_q) > errortol):
            raise Exception('Quality returned by Louvain (%0.5f) does not match explicitly computed quality (%0.5f)' %
                (returned_q, accurate_q))

        if best_q is None or accurate_q > best_q:
            best_membership, best_q = membership, accurate_q

    if not debug:
        for fname in all_files:
            os.remove(fname)

    return best_membership, best_q