text:
fencepy
=======

|Development Status| |Latest Version| |Download Stats| |Python Versions| |Wheel Status|

Standardized fencing off of python virtual environments on a per-project
basis. The idea is to take a directory as an input and create and manage
a python virtual environment in a known location.

**Master on Linux**

|Travis Status| |Coveralls Status|

**Master on Windows**

|Appveyor Status|
This has proven to be an unstable build environment. Keeping it here for
ease of checking up on the status manually.

How does it work?
-----------------

`fencepy` is fairly simple. After parsing arguments, it calls out to the
correct copy of `virtualenv` (based on the location of the running python
interpreter) with a pre-generated base directory. Upon successful creation
of the virtual environment, it applies various modifications based on the
contents of the directory from which it was run.

Opinionated hooks
-----------------

The goal is to make this framework attractive to users of other
compatible products. For instance, as a user of git and sublime text, I
added functionality related to those.

git
~~~

If the directory provided as input (defaults to cwd) is part of a git
repository, the virtual environment created will be relative to the root
of that repository.

sublime text
~~~~~~~~~~~~

The sublime linter plugin is very easy to configure. Pointing it to a
particular installation of python is as simple as putting some json into
a configuration file. If there is a ``.sublime-project`` file in the
input directory, then it will be configured to respect the virtual
environment that is being created.

requirements.txt
~~~~~~~~~~~~~~~~

As a helpful shortcut, if there is a ``requirements.txt`` file in the
input directory, then those requirements will be installed upon
virtualenv creation.

oh-my-zsh
~~~~~~~~~

If you use ``oh-my-zsh``, when you set up your first fencepy environment, it will
configure some shortcuts for you::

    fpadd -> fencepy create
    fpnew -> fencepy create
    fpsrc -> . `fencepy activate`
    fpup  -> fencepy update
    fpdel -> fencepy erase

Quickstart
-----

``fencepy`` manages virtual environments based on the directory each environment is linked to.  So, in order to act on a virtual environment, you simply have to be in the directory that it applies to and run a ``fencepy`` command.  To get started, install ``fencepy`` with ``pip``:

.. code::

    $ sudo pip install fencepy

Then you can create and activate virtual environment with a few simple commands:

.. code::

    $ cd <project_dir>
    $ fencepy create
    $ . `fencepy activate`

These commands are universal, which is to say they never change, regardless of the project you're working on (and thus are *very* ``<ctrl-r>``-friendly).  Any time you want to get back to your virtual environment, it looks just the same, without the creation:

.. code::

    $ cd <project_dir>
    $ . `fencepy activate`

If, for any reason, you need to start fresh, simply blow it away and recreate:

.. code::

    $ cd <project_dir>
    $ fencepy erase
    $ fencepy create

See ``fencepy help`` for more information on these and all the other functions that ``fencepy`` has to offer!

Additional notes
----------------

Python versions
~~~~~~~~~~~~~~~

Both python 2 and 3 are supported. Additionally, both can be used for
one project, as they will be stored in separate directories.

Cross-platform support
~~~~~~~~~~~~~~~~~~~~~~

Both Windows and *nix shells are supported!

Extending fencepy
~~~~~~~~~~~~~~~~~

Additional functionality should be very easy to implement. Each of the hooks
mentioned above is implemented as a "plugin" that takes the full dict of parsed
arguments as input. Additionally, inverse cleanup methods are planned for the
future.

Alternatives
~~~~~~~~~~~~

* virtualenvwrapper_

.. _virtualenvwrapper: http://virtualenvwrapper.readthedocs.org/en/latest/

.. |Travis Status| image:: https://img.shields.io/travis/ajk8/fencepy/master.svg
    :target: https://travis-ci.org/ajk8/fencepy
    :alt: Travis-ci build status
.. |Coveralls Status| image:: https://img.shields.io/coveralls/ajk8/fencepy/master.svg
    :target: https://coveralls.io/r/ajk8/fencepy?branch=master
    :alt: Coveralls coverage (from travis)
.. |Appveyor Status| image:: https://img.shields.io/appveyor/ci/ajk8/fencepy/master.svg
    :target: https://ci.appveyor.com/project/ajk8/fencepy
    :alt: Appveyor build status
.. |Python Versions| image:: https://img.shields.io/pypi/pyversions/fencepy.svg
    :target: https://pypi.python.org/pypi/fencepy/
    :alt: Supported Python versions
.. |Latest Version| image:: https://img.shields.io/pypi/v/fencepy.svg
    :target: https://pypi.python.org/pypi/fencepy/
    :alt: Latest Version
.. |Download Stats| image:: https://img.shields.io/pypi/dm/fencepy.svg
    :target: https://pypi.python.org/pypi/fencepy/
    :alt: Downloads/month
.. |Wheel Status| image:: https://img.shields.io/pypi/wheel/fencepy.svg
    :target: https://pypi.python.org/pypi/fencepy/
    :alt: Wheel Status
.. |License| image:: https://img.shields.io/pypi/l/fencepy.svg
    :target: https://pypi.python.org/pypi/fencepy/
    :alt: License
.. |Development Status| image:: https://img.shields.io/pypi/status/fencepy.svg
    :target: https://pypi.python.org/pypi/fencepy/
    :alt: Development Status


text:
package de.tototec.cmdoption.handler;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import de.tototec.cmdoption.internal.I18n;
import de.tototec.cmdoption.internal.I18n.PreparedI18n;
import de.tototec.cmdoption.internal.I18nFactory;

/**
 * Apply an one-arg option to a {@link Byte} (or byte) field or
 * method.
 *
 * @since 0.6.0
 */
public class ByteHandler implements CmdOptionHandler {

	public ByteHandler() {}

	public boolean canHandle(final AccessibleObject element, final int argCount) {
		if (element instanceof Field && argCount == 1) {
			final Field field = (Field) element;
			return !Modifier.isFinal(field.getModifiers())
					&& (field.getType().equals(Byte.class) || field.getType().equals(byte.class));
		} else if (element instanceof Method && argCount == 1) {
			final Method method = (Method) element;
			if (method.getParameterTypes().length == 1) {
				final Class<?> type = method.getParameterTypes()[0];
				return byte.class.equals(type) || Byte.class.equals(type);
			}
		}
		return false;
	}

	public void applyParams(final Object config, final AccessibleObject element, final String[] args,
			final String optionName) throws CmdOptionHandlerException {

		byte parsedValue = 0;

		try {
			final String arg = args[0];
			parsedValue = Byte.parseByte(arg);
		} catch (final NumberFormatException e) {
			final I18n i18n = I18nFactory.getI18n(ByteHandler.class);
			final PreparedI18n msg = i18n.preparetr("Could not read byte value \"{0}\".", args[0]);
			throw new CmdOptionHandlerException(msg.notr(), e, msg.tr());
		}

		try {
			if (element instanceof Field) {
				final Field field = (Field) element;
				field.set(config, parsedValue);
			} else {
				final Method method = (Method) element;
				method.invoke(config, parsedValue);
			}
		} catch (final Exception e) {
			final I18n i18n = I18nFactory.getI18n(ByteHandler.class);
			final PreparedI18n msg = i18n.preparetr("Could not apply argument \"{0}\".", args[0]);
			throw new CmdOptionHandlerException(msg.notr(), e, msg.tr());
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
package sqlite3

// Code generated by xo. DO NOT EDIT.

import (
	"context"
)

// AuthGroup represents a row from 'auth_group'.
type AuthGroup struct {
	ID   int    `json:"id"`   // id
	Name string `json:"name"` // name
	// xo fields
	_exists, _deleted bool
}

// Exists returns true when the AuthGroup exists in the database.
func (ag *AuthGroup) Exists() bool {
	return ag._exists
}

// Deleted returns true when the AuthGroup has been marked for deletion from
// the database.
func (ag *AuthGroup) Deleted() bool {
	return ag._deleted
}

// Insert inserts the AuthGroup to the database.
func (ag *AuthGroup) Insert(ctx context.Context, db DB) error {
	switch {
	case ag._exists: // already exists
		return logerror(&ErrInsertFailed{ErrAlreadyExists})
	case ag._deleted: // deleted
		return logerror(&ErrInsertFailed{ErrMarkedForDeletion})
	}
	// insert (primary key generated and returned by database)
	const sqlstr = `INSERT INTO auth_group (` +
		`id, name` +
		`) VALUES (` +
		`$1, $2` +
		`)`
	// run
	logf(sqlstr, ag.Name)
	res, err := db.ExecContext(ctx, sqlstr, ag.ID, ag.Name)
	if err != nil {
		return logerror(err)
	}
	// retrieve id
	id, err := res.LastInsertId()
	if err != nil {
		return logerror(err)
	} // set primary key
	ag.ID = int(id)
	// set exists
	ag._exists = true
	return nil
}

// Update updates a AuthGroup in the database.
func (ag *AuthGroup) Update(ctx context.Context, db DB) error {
	switch {
	case !ag._exists: // doesn't exist
		return logerror(&ErrUpdateFailed{ErrDoesNotExist})
	case ag._deleted: // deleted
		return logerror(&ErrUpdateFailed{ErrMarkedForDeletion})
	}
	// update with primary key
	const sqlstr = `UPDATE auth_group SET ` +
		`name = $1 ` +
		`WHERE id = $2`
	// run
	logf(sqlstr, ag.Name, ag.ID)
	if _, err := db.ExecContext(ctx, sqlstr, ag.Name, ag.ID); err != nil {
		return logerror(err)
	}
	return nil
}

// Save saves the AuthGroup to the database.
func (ag *AuthGroup) Save(ctx context.Context, db DB) error {
	if ag.Exists() {
		return ag.Update(ctx, db)
	}
	return ag.Insert(ctx, db)
}

// Upsert performs an upsert for AuthGroup.
func (ag *AuthGroup) Upsert(ctx context.Context, db DB) error {
	switch {
	case ag._deleted: // deleted
		return logerror(&ErrUpsertFailed{ErrMarkedForDeletion})
	}
	// upsert
	const sqlstr = `INSERT INTO auth_group (` +
		`id, name` +
		`) VALUES (` +
		`$1, $2` +
		`)` +
		` ON CONFLICT (id) DO ` +
		`UPDATE SET ` +
		`name = EXCLUDED.name `
	// run
	logf(sqlstr, ag.ID, ag.Name)
	if _, err := db.ExecContext(ctx, sqlstr, ag.ID, ag.Name); err != nil {
		return logerror(err)
	}
	// set exists
	ag._exists = true
	return nil
}

// Delete deletes the AuthGroup from the database.
func (ag *AuthGroup) Delete(ctx context.Context, db DB) error {
	switch {
	case !ag._exists: // doesn't exist
		return nil
	case ag._deleted: // deleted
		return nil
	}
	// delete with single primary key
	const sqlstr = `DELETE FROM auth_group ` +
		`WHERE id = $1`
	// run
	logf(sqlstr, ag.ID)
	if _, err := db.ExecContext(ctx, sqlstr, ag.ID); err != nil {
		return logerror(err)
	}
	// set deleted
	ag._deleted = true
	return nil
}

// AuthGroupByID retrieves a row from 'auth_group' as a AuthGroup.
//
// Generated from index 'auth_group_id_pkey'.
func AuthGroupByID(ctx context.Context, db DB, id int) (*AuthGroup, error) {
	// query
	const sqlstr = `SELECT ` +
		`id, name ` +
		`FROM auth_group ` +
		`WHERE id = $1`
	// run
	logf(sqlstr, id)
	ag := AuthGroup{
		_exists: true,
	}
	if err := db.QueryRowContext(ctx, sqlstr, id).Scan(&ag.ID, &ag.Name); err != nil {
		return nil, logerror(err)
	}
	return &ag, nil
}

// AuthGroupByName retrieves a row from 'auth_group' as a AuthGroup.
//
// Generated from index 'sqlite_autoindex_auth_group_1'.
func AuthGroupByName(ctx context.Context, db DB, name string) (*AuthGroup, error) {
	// query
	const sqlstr = `SELECT ` +
		`id, name ` +
		`FROM auth_group ` +
		`WHERE name = $1`
	// run
	logf(sqlstr, name)
	ag := AuthGroup{
		_exists: true,
	}
	if err := db.QueryRowContext(ctx, sqlstr, name).Scan(&ag.ID, &ag.Name); err != nil {
		return nil, logerror(err)
	}
	return &ag, nil
}


text:
package uk.gov.gchq.gaffer.hbasestore.operation.handler;

import com.google.common.collect.Lists;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;

import uk.gov.gchq.gaffer.commonutil.StreamUtil;
import uk.gov.gchq.gaffer.commonutil.TestGroups;
import uk.gov.gchq.gaffer.data.element.Edge;
import uk.gov.gchq.gaffer.data.element.Element;
import uk.gov.gchq.gaffer.data.element.Entity;
import uk.gov.gchq.gaffer.hbasestore.HBaseProperties;
import uk.gov.gchq.gaffer.hbasestore.HBaseStore;
import uk.gov.gchq.gaffer.hbasestore.serialisation.ElementSerialisation;
import uk.gov.gchq.gaffer.hbasestore.util.CellUtil;
import uk.gov.gchq.gaffer.operation.OperationException;
import uk.gov.gchq.gaffer.operation.impl.add.AddElements;
import uk.gov.gchq.gaffer.serialisation.implementation.StringSerialiser;
import uk.gov.gchq.gaffer.serialisation.implementation.raw.CompactRawIntegerSerialiser;
import uk.gov.gchq.gaffer.store.Context;
import uk.gov.gchq.gaffer.store.StoreException;
import uk.gov.gchq.gaffer.store.schema.Schema;
import uk.gov.gchq.gaffer.store.schema.SchemaEdgeDefinition;
import uk.gov.gchq.gaffer.store.schema.SchemaEntityDefinition;
import uk.gov.gchq.gaffer.store.schema.TypeDefinition;
import uk.gov.gchq.koryphe.impl.binaryoperator.StringConcat;
import uk.gov.gchq.koryphe.impl.binaryoperator.Sum;

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

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class AddElementsHandlerTest {
    private static final Schema SCHEMA = new Schema.Builder()
            .type("string", new TypeDefinition.Builder()
                    .clazz(String.class)
                    .serialiser(new StringSerialiser())
                    .build())
            .type("int", new TypeDefinition.Builder()
                    .clazz(Integer.class)
                    .serialiser(new CompactRawIntegerSerialiser())
                    .build())
            .type("type", Boolean.class)
            .edge(TestGroups.EDGE, new SchemaEdgeDefinition.Builder()
                    .source("string")
                    .destination("string")
                    .directed("true")
                    .property("prop1", "string")
                    .property("visibility", "string")
                    .property("count", "int")
                    .groupBy("prop1")
                    .aggregate(false)
                    .build())
            .entity(TestGroups.ENTITY, new SchemaEntityDefinition.Builder()
                    .vertex("string")
                    .property("prop1", "string")
                    .property("visibility", "string")
                    .property("count", "int")
                    .groupBy("prop1")
                    .aggregate(false)
                    .build())
            .visibilityProperty("visibility")
            .vertexSerialiser(new StringSerialiser())
            .build();

    private static final Schema SCHEMA_WITH_AGGREGATION = new Schema.Builder()
            .type("string", new TypeDefinition.Builder()
                    .clazz(String.class)
                    .serialiser(new StringSerialiser())
                    .aggregateFunction(new StringConcat())
                    .build())
            .type("int", new TypeDefinition.Builder()
                    .clazz(Integer.class)
                    .serialiser(new CompactRawIntegerSerialiser())
                    .aggregateFunction(new Sum())
                    .build())
            .type("type", Boolean.class)
            .edge(TestGroups.EDGE, new SchemaEdgeDefinition.Builder()
                    .source("string")
                    .destination("string")
                    .directed("true")
                    .property("prop1", "string")
                    .property("visibility", "string")
                    .property("count", "int")
                    .groupBy("prop1")
                    .build())
            .entity(TestGroups.ENTITY, new SchemaEntityDefinition.Builder()
                    .vertex("string")
                    .property("prop1", "string")
                    .property("visibility", "string")
                    .property("count", "int")
                    .groupBy("prop1")
                    .build())
            .visibilityProperty("visibility")
            .vertexSerialiser(new StringSerialiser())
            .build();

    @Test
    public void shouldAddElements() throws OperationException, StoreException, IOException {
        // Given
        final AddElementsHandler handler = new AddElementsHandler();
        final List<Element> elements = createElements();
        final List<Element> elementsWithNull = new ArrayList<>(elements);
        elementsWithNull.add(null); // null should be skipped

        final AddElements addElements = new AddElements.Builder()
                .input(elementsWithNull)
                .build();
        final Context context = mock(Context.class);
        final HBaseStore store = mock(HBaseStore.class);

        final HTable table = mock(HTable.class);
        given(store.getTable()).willReturn(table);

        final HBaseProperties properties = HBaseProperties.loadStoreProperties(StreamUtil.storeProps(getClass()));
        final int writeBufferSize = 5;
        properties.setWriteBufferSize(writeBufferSize);
        given(store.getProperties()).willReturn(properties);

        given(store.getSchema()).willReturn(SCHEMA);

        // When
        handler.doOperation(addElements, context, store);

        // Then
        final ArgumentCaptor<List<Put>> putsCaptor = (ArgumentCaptor) ArgumentCaptor.forClass(List.class);
        verify(table, times(2)).put(putsCaptor.capture());
        verify(table, times(2)).flushCommits();
        final List<List<Put>> allPuts = putsCaptor.getAllValues();
        assertThat(allPuts).hasSize(2);
        final List<Put> combinedPuts = new ArrayList<>();
        combinedPuts.addAll(allPuts.get(0));
        combinedPuts.addAll(allPuts.get(1));

        final List<Element> expectedElements = new ArrayList<>();
        for (final Element element : elements) {
            expectedElements.add(element);
            if (element instanceof Edge && !((Edge) element).getSource().equals(((Edge) element).getDestination())) {
                expectedElements.add(element);
            }
        }
        final Element[] expectedElementsArr = expectedElements.toArray(new Element[expectedElements.size()]);
        final List<Element> elementsAdded = CellUtil.getElements(combinedPuts, new ElementSerialisation(SCHEMA), false);
        assertEquals(expectedElements.size(), elementsAdded.size());
        assertThat(elementsAdded).contains(expectedElementsArr);
    }

    @Test
    public void shouldDoNothingIfNoElementsProvided() throws OperationException, StoreException, IOException {
        // Given
        final AddElementsHandler handler = new AddElementsHandler();
        final AddElements addElements = new AddElements();
        final Context context = mock(Context.class);
        final HBaseStore store = mock(HBaseStore.class);

        final Table table = mock(Table.class);
        given(store.getTable()).willReturn(table);

        final HBaseProperties properties = HBaseProperties.loadStoreProperties(StreamUtil.storeProps(getClass()));
        given(store.getProperties()).willReturn(properties);

        given(store.getSchema()).willReturn(SCHEMA);

        // When
        handler.doOperation(addElements, context, store);

        // Then
        verify(table, never()).put(any(Put.class));
    }

    private List<Element> createElements() {
        return Lists.newArrayList(
                new Edge.Builder()
                        .group(TestGroups.EDGE)
                        .source("vertexA")
                        .dest("vertexB")
                        .directed(true)
                        .property("prop1", "a")
                        .property("visibility", "public")
                        .property("count", 1)
                        .build(),
                new Edge.Builder()
                        .group(TestGroups.EDGE)
                        .source("vertexD")
                        .dest("vertexC")
                        .directed(true)
                        .property("prop1", "a")
                        .property("visibility", "public")
                        .property("count", 1)
                        .build(),
                new Edge.Builder()
                        .group(TestGroups.EDGE)
                        .source("vertexE")
                        .dest("vertexE")
                        .directed(true)
                        .property("prop1", "a")
                        .property("visibility", "public")
                        .property("count", 1)
                        .build(),
                new Edge.Builder()
                        .group(TestGroups.EDGE)
                        .source("vertexF")
                        .dest("vertexG")
                        .directed(false)
                        .property("prop1", "a")
                        .property("visibility", "public")
                        .property("count", 1)
                        .build(),
                new Edge.Builder()
                        .group(TestGroups.EDGE)
                        .source("vertexH")
                        .dest("vertexH")
                        .directed(false)
                        .property("prop1", "a")
                        .property("visibility", "public")
                        .property("count", 1)
                        .build(),
                new Entity.Builder()
                        .group(TestGroups.ENTITY)
                        .vertex("vertexI")
                        .property("prop1", "a")
                        .property("visibility", "public")
                        .property("count", 1)
                        .build()
        );
    }

    @Test
    public void shouldThrowNoExceptionsWhenValidateFlagSetToFalse() throws OperationException, StoreException {
        final AddElements addElements = new AddElements.Builder()
                .input(new Edge("Unknown group", "source", "dest", true))
                .validate(false)
                .build();

        final AddElementsHandler handler = new AddElementsHandler();
        final Context context = mock(Context.class);
        final HBaseStore store = mock(HBaseStore.class);

        final Table table = mock(Table.class);
        given(store.getTable()).willReturn(table);

        final HBaseProperties properties = HBaseProperties.loadStoreProperties(StreamUtil.storeProps(getClass()));
        given(store.getProperties()).willReturn(properties);

        given(store.getSchema()).willReturn(SCHEMA);

        // When / Then - no exceptions
        handler.doOperation(addElements, context, store);
    }
}


text:
#pragma once

#include <map>

#include "trace_model.hpp"

namespace retrace {

/**
 * Handle map.
 *
 * It is just like a regular std::map<T, T> container, but lookups of missing
 * keys return the key instead of default constructor.
 *
 * This is necessary for several GL named objects, where one can either request
 * the implementation to generate an unique name, or pick a value never used
 * before.
 *
 * XXX: In some cases, instead of returning the key, it would make more sense
 * to return an unused data value (e.g., container count).
 */
template <class T>
class map
{
private:
    typedef std::map<T, T> base_type;
    base_type base;

public:
    typedef typename base_type::const_iterator const_iterator;

    const_iterator end(void) const {
        return base.end();
    }

    const_iterator find(const T & key) const {
        return base.find(key);
    }

    T & operator[] (const T &key) {
        typename base_type::iterator it;
        it = base.find(key);
        if (it == base.end()) {
            return (base[key] = key);
        }
        return it->second;
    }

    const T & operator[] (const T &key) const {
        typename base_type::const_iterator it;
        it = base.find(key);
        if (it == base.end()) {
            return (base[key] = key);
        }
        return it->second;
    }

    /*
     * Handle situations where the application declares an array like
     *
     *   uniform vec4 myMatrix[4];
     *
     * then calls glGetUniformLocation(..., "myMatrix") and then infer the slot
     * numbers rather than explicitly calling glGetUniformLocation(...,
     * "myMatrix[0]"), etc.
     */
    T lookupUniformLocation(const T &key) {
        typename base_type::const_iterator it;
        it = base.upper_bound(key);
        if (it != base.begin()) {
            --it;
        } else {
            return (base[key] = key);
        }
        T t = it->second + (key - it->first);
        return t;
    }
};

void
addRegion(trace::Call &call, unsigned long long address, void *buffer, unsigned long long size);

void
delRegionByPointer(void *ptr);

void
toRange(trace::Value &value, void * & ptr, size_t & len);

void *
toPointer(trace::Value &value, bool bind = false);

void
addObj(trace::Call &call, trace::Value &value, void *obj);

void
delObj(trace::Value &value);

void *
toObjPointer(trace::Call &call, trace::Value &value);

template< class T >
inline T *
asObjPointer(trace::Call &call, trace::Value &value) {
    return static_cast<T *>(toObjPointer(call, value));
}

} /* namespace retrace */


text:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { blue500, blue700, grey400, pinkA200, grey100, grey500, darkBlack, blue800 } from 'material-ui/styles/colors';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';

const muiTheme = getMuiTheme({
  fontFamily: 'Roboto, sans-serif',
});

// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();

ReactDOM.render(
  <MuiThemeProvider muiTheme={muiTheme}>
    <App />
  </MuiThemeProvider>, document.getElementById('root')
);


text:
from xhtml2pdf.context import pisaContext
from xhtml2pdf.default import DEFAULT_CSS
from xhtml2pdf.parser import pisaParser
from reportlab.platypus.flowables import Spacer
from reportlab.platypus.frames import Frame
from xhtml2pdf.xhtml2pdf_reportlab import PmlBaseDoc, PmlPageTemplate
from xhtml2pdf.util import pisaTempFile, getBox, pyPdf
import cgi
import logging
import copy

# Copyright 2010 Dirk Holtwick, holtwick.it
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

log = logging.getLogger("xhtml2pdf")

def pisaErrorDocument(dest, c):
    out = pisaTempFile(capacity=c.capacity)
    out.write("
%d error(s) occured:
" % c.err)
    for mode, line, msg, _ in c.log:
        if mode == "error":
            out.write("
%s in line %d: %s
" % (mode, line, cgi.escape(msg)))

    out.write("
%d warning(s) occured:
" % c.warn)
    for mode, line, msg, _ in c.log:
        if mode == "warning":
            out.write("
%s in line %d: %s
" % (mode, line, cgi.escape(msg)))

    return pisaDocument(out.getvalue(), dest, raise_exception=False)

def pisaStory(src, path=None, link_callback=None, debug=0, default_css=None,
              xhtml=False, encoding=None, context=None, xml_output=None,
              **kw):
    # Prepare Context
    if not context:
        context = pisaContext(path, debug=debug)
        context.pathCallback = link_callback

    # Use a default set of CSS definitions to get an expected output
    if default_css is None:
        default_css = DEFAULT_CSS

    # Parse and fill the story
    pisaParser(src, context, default_css, xhtml, encoding, xml_output)

    # Avoid empty documents
    if not context.story:
        context.story = [Spacer(1, 1)]

    if context.indexing_story:
        context.story.append(context.indexing_story)

    # Remove anchors if they do not exist (because of a bug in Reportlab)
    for frag, anchor in context.anchorFrag:
        if anchor not in context.anchorName:
            frag.link = None
    return context

def pisaDocument(src, dest=None, path=None, link_callback=None, debug=0,
                 default_css=None, xhtml=False, encoding=None, xml_output=None,
                 raise_exception=True, capacity=100 * 1024, **kw):
    log.debug("pisaDocument options:\n  src = %r\n  dest = %r\n  path = %r\n  link_callback = %r\n  xhtml = %r",
              src,
              dest,
              path,
              link_callback,
              xhtml)

    # Prepare simple context
    context = pisaContext(path, debug=debug, capacity=capacity)
    context.pathCallback = link_callback

    # Build story
    context = pisaStory(src, path, link_callback, debug, default_css, xhtml,
                        encoding, context=context, xml_output=xml_output)

    # Buffer PDF into memory
    out = pisaTempFile(capacity=context.capacity)

    doc = PmlBaseDoc(
        out,
        pagesize=context.pageSize,
        author=context.meta["author"].strip(),
        subject=context.meta["subject"].strip(),
        keywords=[x.strip() for x in
                  context.meta["keywords"].strip().split(",") if x],
        title=context.meta["title"].strip(),
        showBoundary=0,
        allowSplitting=1)

    # Prepare templates and their frames
    if "body" in context.templateList:
        body = context.templateList["body"]
        del context.templateList["body"]
    else:
        x, y, w, h = getBox("1cm 1cm -1cm -1cm", context.pageSize)
        body = PmlPageTemplate(
            id="body",
            frames=[
                Frame(x, y, w, h,
                      id="body",
                      leftPadding=0,
                      rightPadding=0,
                      bottomPadding=0,
                      topPadding=0)],
            pagesize=context.pageSize)

    doc.addPageTemplates([body] + context.templateList.values())

    # Use multibuild e.g. if a TOC has to be created
    if context.multiBuild:
        doc.multiBuild(context.story)
    else:
        doc.build(context.story)

    # Add watermarks
    if pyPdf:
        for bgouter in context.pisaBackgroundList:
            # If we have at least one background, then lets do it
            if bgouter:
                istream = out

                output = pyPdf.PdfFileWriter()
                input1 = pyPdf.PdfFileReader(istream)
                duplicate_input1 = copy.copy(input1)
                ctr = 0
                # TODO: Why do we loop over the same list again?
                # see bgouter at line 137
                for bg in context.pisaBackgroundList:
                    page = input1.getPage(ctr)
                    if (bg and not bg.notFound()
                        and (bg.mimetype == "application/pdf")):
                        bginput = pyPdf.PdfFileReader(bg.getFile())
                        pagebg = bginput.getPage(0)
                        original_page = duplicate_input1.getPage(ctr)
                        page.mergePage(pagebg)
                        page.mergePage(original_page)
                    else:
                        log.warn(context.warning(
                            "Background PDF %s doesn't exist.", bg))
                    output.addPage(page)
                    ctr += 1
                out = pisaTempFile(capacity=context.capacity)
                output.write(out)
                # data = sout.getvalue()
                # Found a background? So leave loop after first occurence
                break
    else:
        log.warn(context.warning("pyPDF not installed!"))

    # Get the resulting PDF and write it to the file object
    # passed from the caller

    if dest is None:
        # No output file was passed - Let's use a pisaTempFile
        dest = pisaTempFile(capacity=context.capacity)
    context.dest = dest

    data = out.getvalue()  # TODO: That load all the tempfile in RAM - Why bother with a swapping tempfile then?
    context.dest.write(data)  # TODO: context.dest is a tempfile as well...

    return context


text:
from Tkinter import *

class Dialog:

    command  = None

    def __init__(self, master=None, **options):

        # FIXME: should this be placed on the module level instead?
        if TkVersion < 4.2:
            raise TclError, "this module requires Tk 4.2 or newer"

        self.master  = master
        self.options = options
        if not master and options.get('parent'):
            self.master = options['parent']

    def _fixoptions(self):
        pass # hook

    def _fixresult(self, widget, result):
        return result # hook

    def show(self, **options):

        # update instance options
        for k, v in options.items():
            self.options[k] = v

        self._fixoptions()

        # we need a dummy widget to properly process the options
        # (at least as long as we use Tkinter 1.63)
        w = Frame(self.master)

        try:

            s = w.tk.call(self.command, *w._options(self.options))

            s = self._fixresult(w, s)

        finally:

            try:
                # get rid of the widget
                w.destroy()
            except:
                pass

        return s


text:
//  -------------------------------------------------------------------------------------------------
//  <copyright file="SpecificationTypeExtensions.cs" company="RHEA System S.A.">
//
//    Copyright 2017-2022 RHEA System S.A.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
//  </copyright>
//  -------------------------------------------------------------------------------------------------

namespace ReqIFSharp.Extensions.ReqIFExtensions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using ReqIFSharp;

    /// <summary>
    /// The <see cref="SpecificationTypeExtensions"/> class provides a number of extension methods for the <see cref="SpecificationType"/> class
    /// </summary>
    public static class SpecificationTypeExtensions
    {
        /// <summary>
        /// Queries the <see cref="Specification"/>s that are referencing the <see cref="SpecificationType"/>
        /// </summary>
        /// <param name="specificationType">
        /// The subject <see cref="SpecificationType"/>
        /// </param>
        /// <returns>
        /// An <see cref="IEnumerable{Specification}"/> that are referencing the <see cref="SpecificationType"/>
        /// </returns>
        public static IEnumerable<Specification> QueryReferencingSpecifications(this SpecificationType specificationType)
        {
            if (specificationType.ReqIFContent == null)
            {
                throw new InvalidOperationException("The owning ReqIFContent of the SpecificationType is not set.");
            }

            var specifications = specificationType.ReqIFContent.Specifications;

            var result = specifications.Where(x => x.Type == specificationType);

            return result;
        }
    }
}


text:
$(document).ready(function() {
	// If there is a query string, this form was submitted
	if(location.search) {
		$("#savedAlert").show();
	}
});


text:
class Game < ActiveRecord::Base
  # Remember to create a migration!
  belongs_to :player, class_name: "User"

end


text:
'use strict';
var Buffer = require('../../').Buffer;

const common = require('./common');
const assert = require('assert');

const b = Buffer.alloc(1, 'a');
const c = Buffer.alloc(1, 'c');
const d = Buffer.alloc(2, 'aa');
const e = new Uint8Array([ 0x61, 0x61 ]); // ASCII 'aa', same as d

assert.strictEqual(b.compare(c), -1);
assert.strictEqual(c.compare(d), 1);
assert.strictEqual(d.compare(b), 1);
assert.strictEqual(d.compare(e), 0);
assert.strictEqual(b.compare(d), -1);
assert.strictEqual(b.compare(b), 0);

assert.strictEqual(Buffer.compare(b, c), -1);
assert.strictEqual(Buffer.compare(c, d), 1);
assert.strictEqual(Buffer.compare(d, b), 1);
assert.strictEqual(Buffer.compare(b, d), -1);
assert.strictEqual(Buffer.compare(c, c), 0);
assert.strictEqual(Buffer.compare(e, e), 0);
assert.strictEqual(Buffer.compare(d, e), 0);
assert.strictEqual(Buffer.compare(d, b), 1);

assert.strictEqual(Buffer.compare(Buffer.alloc(0), Buffer.alloc(0)), 0);
assert.strictEqual(Buffer.compare(Buffer.alloc(0), Buffer.alloc(1)), -1);
assert.strictEqual(Buffer.compare(Buffer.alloc(1), Buffer.alloc(0)), 1);

const errMsg = common.expectsError({
  code: 'ERR_INVALID_ARG_TYPE',
  type: TypeError,
  message: 'The "buf1", "buf2" arguments must be one of ' +
             'type Buffer or Uint8Array'
}, 2);
assert.throws(() => Buffer.compare(Buffer.alloc(1), 'abc'), errMsg);

assert.throws(() => Buffer.compare('abc', Buffer.alloc(1)), errMsg);

common.expectsError(() => Buffer.alloc(1).compare('abc'), {
  code: 'ERR_INVALID_ARG_TYPE',
  type: TypeError,
  message: 'The "target" argument must be one of ' +
           'type Buffer or Uint8Array. Received type string'
});


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fab_margin">16dp</dimen>

    <!-- margin & padding -->
    <dimen name="margin_xxlarge">30dp</dimen>
    <dimen name="margin_xlarge">20dp</dimen>
    <dimen name="margin_large">15dp</dimen>
    <dimen name="margin_xmiddle">12dp</dimen>
    <dimen name="margin_middle">10dp</dimen>
    <dimen name="margin_xxsmall">8dp</dimen>
    <dimen name="margin_small">5dp</dimen>
    <dimen name="margin_xsmall">3dp</dimen>
    <dimen name="item_height_default">43dp</dimen>
    <dimen name="item_height_small">35dp</dimen>
    <dimen name="item_height_large">50dp</dimen>

    <dimen name="image_size_default">25dp</dimen>
    <dimen name="image_size_small">20dp</dimen>
</resources>


text:
package com.networknt.light.rule.config;

import com.networknt.light.rule.Rule;

/**
 * Created by steve on 28/02/16.
 *
 * AccessLevel R [owner, admin, configAdmin]
 */
public class DelHostConfigRule extends AbstractConfigRule implements Rule {
    public boolean execute (Object ...objects) throws Exception {
        return delHostConfig(objects);
    }
}


text:
<?php

// First of all, we make sure we are accessing the source file via SMF so that people can not directly access the file.
if (!defined('SMF'))
  die('Hack Attempt...');

$txt['rpg_cal_desc'] = 'From here you can add, remove, and edit events for the RPG Calendar and create BBCode calendars.';
$txt['rpg_cal_events_desc']=&$txt['rpg_cal_desc'];
$txt['rpg_cal_label'] = 'RPG Date and Calendar';
$txt['rpg_cal_manage_events'] = 'Manage Events & Dates';
$txt['rpg_start_date'] = 'Begining of Current Date Range';
$txt['rpg_end_date'] = 'End of Current Date Range';
$txt['rpg_cal_color'] = 'Color';
$txt['rpg_cal_bbcode_date'] = 'BBCode Calendar for';
$txt['rpg_cal_bbcode_desc'] = 'Create Calendar with BBCode';
$txt['rpg_cal_bbcode'] = 'BBCode Calendar';
$txt['rpg_cal_calendar_year'] ='Year';
$txt['rpg_cal_calendar_month'] = 'Month';
$txt['rpg_cal_calendar_day'] = 'Day';
$txt['rpg_cal_title_label'] = 'Title';
$txt['rpg_cal_every_year'] = 'Every Year';
$txt['rpg_cal_button_add'] = 'Add';
$txt['rpg_cal_button_edit'] = 'Edit';
$txt['rpg_cal_button_remove'] = 'Remove';
$txt['rpg_cal_submit_bbcode'] = 'Create BBCode Calendar';
$txt['rpg_cal_manage_events_desc'] = 'From here you can add, remove, and edit events on the AO Calendar.';
$txt['rpg_cal_current_events'] = 'Current Events';
$txt['rpg_cal_no_entries'] = 'There are currently no events configured.';
$txt['rpg_cal_event_title'] = 'Event';
$txt['rpg_cal_event_add'] = 'Add New Event';
$txt['rpg_cal_event_edit'] = 'Edit Existing Event';
$txt['rpg_cal_bbcode_title'] = 'Create BBCode Calendar';
$txt['rpg_cal_current_date_settings'] = 'Current Date Settings';
$txt['rpg_cal_page_title']= 'Calendar';
$txt['rpg_cal'] = 'Calendar';

$txt['rpg_cal_short_headings']=array('Su','Mo','Tu','We','Th','Fr','Sa');
$txt['rpg_cal_long_headings']=array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

$txt['sp_function_sp_rpgCal_label'] = 'RPG Calendar Block';
$txt['sp_function_sp_rpgCal_desc'] = 'Displays a calendar in a block based on the current dates of the RPG Date and Calendar Mod.';
$txt['sp_param_sp_rpgCal_content_above'] = 'Enter the custom HTML content for above the calendar in this box.';
$txt['sp_param_sp_rpgCal_content_below'] = 'Enter the custom HTML content for below the calendar in this box.';
?>


text:
import * as React from "react";

import {connect} from "react-redux";
import {Redirect, RouteComponentProps, RouteProps} from "react-router";
import {Grid, Card, Checkbox, Form, Header, Input, Message} from "semantic-ui-react";
import * as actions from "../store/auth/actions";
import {
    Formik,
    FormikActions,
    FormikProps,
    Form as FormikForm,
    Field,
    FieldProps,
    Label,
    withFormik,
    FormikBag
} from "formik";
import { Button } from "formik-semantic-ui";
import {RootState} from "../reducers";
import {ApiError} from "redux-api-middleware";
import * as Yup from "yup";

interface IFormValues {
    email: string;
    password: string;
}

interface IReduxDispatchProps {
    logout: actions.TokenActionRequestCreator;
}

export interface ILogoutPageProps extends IReduxDispatchProps {
    apiError?: ApiError;
    access_token?: string;
    loading: boolean;
}

export interface IRouteProps {
    from?: string;
}

const UnconnectedLogoutPage: React.FC = (
    props: ILogoutPageProps & RouteComponentProps<IRouteProps>) => {

    return (
        <Grid textAlign="center" style={{height: '100vh'}} verticalAlign="middle">
            <Grid.Column style={{maxWidth: 450}}>
                <Card>
                    <Card.Content>
                        <Card.Header>Logging Out</Card.Header>
                        <Card.Description>
                            Hold on while we log you out...
                        </Card.Description>
                    </Card.Content>
                </Card>
            </Grid.Column>}
        </Grid>
    );
};

export const LogoutPage = connect(
    (state: RootState) => ({
        access_token: state.auth.access_token,
        apiError: state.auth.error,
        loading: state.auth.loading,
    }),
    {Logout: actions.logout})(UnconnectedLogoutPage);


text:
(function(global) {
  "use strict";

  var GOVUK = global.GOVUK || {};

  GOVUK.analyticsPlugins = GOVUK.analyticsPlugins || {};
  GOVUK.analyticsPlugins.downloadLinkTracker = function (options) {
    var options = options || {},
        downloadLinkSelector = options.selector;

    if (downloadLinkSelector) {
      $('body').on('click', downloadLinkSelector, trackDownload);
    }

    function trackDownload(evt) {
      var $link = getLinkFromEvent(evt),
          href = $link.attr('href'),
          evtOptions = {transport: 'beacon'},
          linkText = $.trim($link.text());

      if (linkText) {
        evtOptions.label = linkText;
      }

      GOVUK.analytics.trackEvent('Download Link Clicked', href, evtOptions);
    }

    function getLinkFromEvent(evt) {
      var $target = $(evt.target);

      if (!$target.is('a')) {
        $target = $target.parents('a');
      }

      return $target;
    }
  }

  global.GOVUK = GOVUK;
})(window);


text:
package com.jerrellmardis.amphitheatre.model.tvdb;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name = "Series", strict = false)
public class Series extends BaseResponse {

    @Element(name = "seriesid", required = false)
    private int mSeriesId;

    @Element(name = "SeriesName", required = false)
    private String mSeriesName;

    @Element(name = "banner", required = false)
    private String mImageUrl;

    @Element(name = "posters", required = false)
    private String mPosters;

    public int getSeriesId() {
        return mSeriesId;
    }

    public String getSeriesName() {
        return mSeriesName;
    }

    public String getImageUrl() {
        return mImageUrl;
    }

    public String getPosters() {
        return mPosters;
    }

    @Override
    public String toString() {
        return "Series{" +
                "mSeriesId=" + mSeriesId +
                ", mSeriesName='" + mSeriesName + '\'' +
                ", mImageUrl='" + mImageUrl + '\'' +
                ", mPosters='" + mPosters + '\'' +
                '}';
    }
}


text:
'use strict';

function _spID(id){
  var object = {};
  object = document.getElementById(id);
  return object;
}

function _spCL(cl){
  var object = {};
  object = document.getElementsByClassName(cl);
  return object;
}

var map, marker, clientLoc, outputData;
// Try HTML5 geolocation
if(navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    clientLoc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

     var options = {
      location: {},
      radius: '500',
      types: []
    };
    var data = nearbySearch(clientLoc, options);
    console.log(data);
    refreshView('results', renderListView(data), false);
    console.log("map loaded");

    marker = new google.maps.Marker({
      map: map,
      draggable: true,
      animation: google.maps.Animation.DROP,
      position: clientLoc,
      visible: true
    });

    google.maps.event.addListener(marker, 'click', toggleBounce);

    google.maps.event.addListener(marker, 'click', function(event){
      console.log("marker clicked!");
    }, true);
    //event at the end of a marker drag
    google.maps.event.addListener(marker, "dragend", function(event) {
      clientLoc = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
    });

    map.setCenter(clientLoc);

  }, function() {
    handleNoGeolocation(true);
  });
} else {
  // Browser doesn't support Geolocation
  handleNoGeolocation(false);
}

function initialize() {
  var mapOptions = {
    zoom: 15
  };

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

}

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}

google.maps.event.addDomListener(window, 'load', initialize);

$(document).ready(function () {
  initialize();
  $('#dest').focus();
});

$('#dest').keyup(function (e) {
  if (e.keyCode === 13) {
    $('#dirs').click();
  }
});


text:
require 'time'

module EasyTimers

  # Wraps a timer
  class Timer
    attr_reader :time, :name, :interval, :recurring, :callback

    # Create a new instance
    # @param time [Float] Seconds since epoch.
    # @param name [Symbol] A name for this timer; generated from the current clock time if nil.
    # @param interval [Float] Seconds.
    # @param recurring [Boolean]
    # @param callback [Callable]
    def initialize(time, name, interval, recurring, callback)
      @time = time
      @name = name
      @interval = interval
      @recurring = recurring
      @callback = callback
      @cancelled = false

      if @name == nil
        @name = Time.now.gmtime.to_f.to_s.to_sym
      end
    end

    # Cancel the timer by overwriting the callback
    def cancel()
      @callback = nil
      @cancelled = true
    end

    # Check if this timer has been cancelled.
    def cancelled?
      return @cancelled
    end

  end
end


text:
    <button type="submit" class="btn btn-sm-back" ng-click="back()">

        {{getLocalizedString('back')}}
    </button>

{{getLocalizedString('appointmentsViewReservations')}}

                {{getLocalizedString('patientAppointmentsViewFacility')}}
                {{getLocalizedString('patientAppointmentsViewDate')}}
                {{getLocalizedString('patientAppointmentsViewTijdstip')}}
                {{getLocalizedString('patientAppointmentsViewType')}}
                {{getLocalizedString('patientAppointmentsViewUnit')}}

                    {{reservation.hosp_short_name}} {{reservation.location_name}}

                    {{formatShortDate(reservation.the_date)}}

                    {{reservation.time_from}}

                    {{reservation.title}}

                    {{reservation.unit_name}}

 0" ng-repeat="server in currentServers">
            {{server.hosp_short_name}}: {{server.hosp_full_name}}

{{ getLocalizedString('patientAppointmentsViewNoReservations')}}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <title>Grace Smith Vidaurre</title>

    <link rel="stylesheet" href="/stylesheets/styles.css">
    <link rel="stylesheet" href="/stylesheets/pygment_trac.css">
    <link rel="stylesheet" href="/stylesheets/bootstrap-social.css">
    <link rel="stylesheet" href="/static/bootstrap-3.3.5-dist/css/bootstrap.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

Grace Smith Vidaurre

       Born in Rhode Island; raised in RI and Nicaragua; studied Biology and Spanish outside Philadelphia; working on PhD research with invasive parakeet populations

	15 February 2016

	Trellis maps in R with raster layers

	15 February 2016

	Make a time lapse map

	15 February 2016

	ggmapping

	15 February 2016

	Download GBIF data for mapping

	15 February 2016

	Parakeet invaders and fun with R


text:
SET FOREIGN_KEY_CHECKS = 0;

DROP TABLE IF EXISTS t_data;
CREATE TABLE t_data (
  `data_id` int NOT NULL  auto_increment
  ,`date` datetime DEFAULT NULL
  ,`value` int DEFAULT NULL
  ,`string` varchar(64) DEFAULT NULL
  ,`text` text DEFAULT NULL
  ,`enum` enum('red','black') DEFAULT 'red'
  ,`blob` blob DEFAULT NULL
  ,`real` float DEFAULT NULL
  ,`dictionary_id` int DEFAULT NULL

  ,INDEX ix_t_data_dictionary_id(`dictionary_id` )

  ,CONSTRAINT c_t_data_data_id PRIMARY KEY(`data_id`)

  ,CONSTRAINT c_t_data_dictionary_id FOREIGN KEY(`dictionary_id`)
    REFERENCES t_dictionary(`dictionary_id`)

  ) ENGINE=InnoDB CHARSET cp1251;

DROP TABLE IF EXISTS t_dictionary;
CREATE TABLE t_dictionary (
  `dictionary_id` int NOT NULL  auto_increment
  ,`text` varchar(64) DEFAULT NULL

  ,CONSTRAINT c_t_dictionary_dictionary_id PRIMARY KEY(`dictionary_id`)

  ) ENGINE=InnoDB CHARSET cp1251;

DROP TABLE IF EXISTS t_link;
CREATE TABLE t_link (
  `link_id` int NOT NULL  auto_increment
  ,`data_id` int NOT NULL
  ,`dictionary_id` int NOT NULL

  ,INDEX ix_t_link_data_id(`data_id` )
  ,INDEX ix_t_link_dictionary_id(`dictionary_id` )

  ,CONSTRAINT c_t_link_link_id PRIMARY KEY(`link_id`)

  ,CONSTRAINT c_t_link_data_id FOREIGN KEY(`data_id`)
    REFERENCES t_data(`data_id`)
  ,CONSTRAINT c_t_link_dictionary_id FOREIGN KEY(`dictionary_id`)
    REFERENCES t_dictionary(`dictionary_id`) ON DELETE set null

  ) ENGINE=InnoDB CHARSET cp1251;

DROP TABLE IF EXISTS t_another_link;
CREATE TABLE t_another_link (
  `another_link_id` int NOT NULL  auto_increment
  ,`owner_id` int NOT NULL
  ,`child_id` int NOT NULL

  ,INDEX ix_t_another_link_owner_id(`owner_id` )
  ,INDEX ix_t_another_link_child_id(`child_id` )

  ,CONSTRAINT c_t_another_link_another_link_id PRIMARY KEY(`another_link_id`)

  ,CONSTRAINT c_t_another_link_owner_id FOREIGN KEY(`owner_id`)
    REFERENCES t_data(`data_id`)
  ,CONSTRAINT c_t_another_link_child_id FOREIGN KEY(`child_id`)
    REFERENCES t_dictionary(`dictionary_id`) ON DELETE CASCADE

  ) ENGINE=InnoDB CHARSET cp1251;

DROP TABLE IF EXISTS t_base;
CREATE TABLE t_base (
  `base_id` int NOT NULL  auto_increment
  ,`baseData` int DEFAULT NULL

  ,CONSTRAINT c_t_base_base_id PRIMARY KEY(`base_id`)

  ) ENGINE=InnoDB CHARSET cp1251;

DROP TABLE IF EXISTS t_details;
CREATE TABLE t_details (
  `details_id` int NOT NULL  auto_increment
  ,`base_id` int NOT NULL
  ,`detailsData` int DEFAULT NULL

  ,INDEX ix_t_details_base_id(`base_id` )

  ,CONSTRAINT c_t_details_details_id PRIMARY KEY(`details_id`)

  ,CONSTRAINT c_t_details_base_id FOREIGN KEY(`base_id`)
    REFERENCES t_base(`base_id`) ON DELETE CASCADE

  ) ENGINE=InnoDB CHARSET cp1251;

DROP TABLE IF EXISTS t_propertiesOne;
CREATE TABLE t_propertiesOne (
  `propertiesOne_id` int NOT NULL  auto_increment
  ,`base_id` int NOT NULL
  ,`propertiesOneData` int DEFAULT NULL

  ,INDEX ix_t_propertiesOne_base_id(`base_id` )

  ,CONSTRAINT c_t_propertiesOne_propertiesOne_id PRIMARY KEY(`propertiesOne_id`)

  ,CONSTRAINT c_t_propertiesOne_base_id FOREIGN KEY(`base_id`)
    REFERENCES t_base(`base_id`) ON DELETE CASCADE

  ) ENGINE=InnoDB CHARSET cp1251;

DROP TABLE IF EXISTS t_propertiesTwo;
CREATE TABLE t_propertiesTwo (
  `propertiesTwo_id` int NOT NULL  auto_increment
  ,`base_id` int NOT NULL
  ,`propertiesTwoData` int DEFAULT NULL

  ,INDEX ix_t_propertiesTwo_base_id(`base_id` )

  ,CONSTRAINT c_t_propertiesTwo_propertiesTwo_id PRIMARY KEY(`propertiesTwo_id`)

  ,CONSTRAINT c_t_propertiesTwo_base_id FOREIGN KEY(`base_id`)
    REFERENCES t_base(`base_id`) ON DELETE CASCADE

  ) ENGINE=InnoDB CHARSET cp1251;

SET FOREIGN_KEY_CHECKS = 1;


text:
using System.Collections;

namespace System.ComponentModel.Design
{
    public class DesignerVerbCollection : CollectionBase
    {
        public DesignerVerbCollection()
        {
        }

        public DesignerVerbCollection(DesignerVerb[] value) => AddRange(value);

        public DesignerVerb this[int index]
        {
            get => (DesignerVerb)(List[index]);
            set => List[index] = value;
        }

        public int Add(DesignerVerb value) => List.Add(value);

        public void AddRange(DesignerVerb[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            for (int i = 0; i < value.Length; i++)
            {
                Add(value[i]);
            }
        }

        public void AddRange(DesignerVerbCollection value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            int currentCount = value.Count;
            for (int i = 0; i < currentCount; i++)
            {
                Add(value[i]);
            }
        }

        public void Insert(int index, DesignerVerb value) => List.Insert(index, value);

        public int IndexOf(DesignerVerb value) => List.IndexOf(value);

        public bool Contains(DesignerVerb value) => List.Contains(value);

        public void Remove(DesignerVerb value) => List.Remove(value);

        public void CopyTo(DesignerVerb[] array, int index) => List.CopyTo(array, index);

        protected override void OnValidate(object value)
        {
            // Dont perform any argument validation.
        }
    }
}


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'nom_nom'
require 'spec'
require 'spec/autorun'

Spec::Runner.configure do |config|

end


text:
package com.brandonjenniges.metro.Route;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.brandonjenniges.metro.R;

import butterknife.Bind;
import butterknife.ButterKnife;

public class RouteViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public @Bind(R.id.route_tv) TextView routeTextView;

    private Callback callback;

    public RouteViewHolder(View view, Callback callback) {
        super(view);
        ButterKnife.bind(this, view);
        view.setOnClickListener(this);
        this.callback = callback;
    }

    @Override
    public void onClick(View view) {
        callback.selectedLocationRow(getLayoutPosition());
    }

    public interface Callback {
        void selectedLocationRow(int row);
    }
}


text:
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.intention.impl;

import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.java.JavaBundle;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.util.LambdaRefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ig.psiutils.CommentTracker;
import com.siyeh.ig.psiutils.ExpressionUtils;
import com.siyeh.ig.psiutils.ParenthesesUtils;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Set;

public class InlineStreamMapAction extends PsiElementBaseIntentionAction {
  private static final Logger LOG = Logger.getInstance(InlineStreamMapAction.class.getName());
  public static final class Holder {
    private static final Set<String> MAP_METHODS =
      StreamEx.of("map", "mapToInt", "mapToLong", "mapToDouble", "mapToObj", "boxed", "asLongStream", "asDoubleStream").toSet();

    public static final Set<String> NEXT_METHODS = StreamEx
      .of("flatMap", "flatMapToInt", "flatMapToLong", "flatMapToDouble", "forEach", "forEachOrdered", "anyMatch", "noneMatch", "allMatch")
      .append(MAP_METHODS).toSet();
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull final PsiElement element) {
    if (!(element instanceof PsiIdentifier)) return false;
    final PsiElement parent = element.getParent();
    if (!(parent instanceof PsiReferenceExpression)) return false;
    final PsiElement gParent = parent.getParent();
    if (!(gParent instanceof PsiMethodCallExpression)) return false;
    PsiMethodCallExpression curCall = (PsiMethodCallExpression)gParent;
    if (!isMapCall(curCall)) return false;
    PsiMethodCallExpression nextCall = getNextExpressionToMerge(curCall);
    if(nextCall == null) return false;
    String key = curCall.getArgumentList().isEmpty() || nextCall.getArgumentList().isEmpty() ?
                 "intention.inline.map.merge.text" : "intention.inline.map.inline.text";
    setText(JavaBundle.message(key, element.getText(), nextCall.getMethodExpression().getReferenceName()));
    return true;
  }

  private static boolean isMapCall(@NotNull PsiMethodCallExpression methodCallExpression) {
    String name = methodCallExpression.getMethodExpression().getReferenceName();
    if (name == null || !Holder.MAP_METHODS.contains(name)) return false;

    final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
    final PsiExpression[] expressions = argumentList.getExpressions();
    if (!name.startsWith("map") && expressions.length == 0) return true;
    if (expressions.length != 1) return false;
    if (!StreamRefactoringUtil.isRefactoringCandidate(expressions[0], true)) return false;

    final PsiMethod method = methodCallExpression.resolveMethod();
    if (method == null) return false;
    final PsiClass containingClass = method.getContainingClass();
    return InheritanceUtil.isInheritor(containingClass, CommonClassNames.JAVA_UTIL_STREAM_BASE_STREAM);
  }

  @Nullable
  private static PsiMethodCallExpression getNextExpressionToMerge(PsiMethodCallExpression methodCallExpression) {
    PsiMethodCallExpression nextCall = ExpressionUtils.getCallForQualifier(methodCallExpression);
    if (nextCall == null) return null;
    String nextName = nextCall.getMethodExpression().getReferenceName();
    if (nextName == null || !Holder.NEXT_METHODS.contains(nextName) || translateName(methodCallExpression, nextCall) == null) return null;
    PsiExpressionList argumentList = (nextCall).getArgumentList();
    PsiExpression[] expressions = argumentList.getExpressions();
    if(expressions.length == 0) {
      if (!nextName.equals("boxed") && !nextName.equals("asLongStream") && !nextName.equals("asDoubleStream")) return null;
      return nextCall;
    }
    if (expressions.length != 1 || !StreamRefactoringUtil.isRefactoringCandidate(expressions[0], false)) return null;

    return nextCall;
  }

  /**
   * Generate name of joint method call which combines two given calls
   *
   * @param prevCall previous call (assumed to be in MAP_METHODS)
   * @param nextCall next call (assumed to be in NEXT_METHODS)
   * @return a name of the resulting method
   */
  @Nullable
  private static String translateName(@NotNull PsiMethodCallExpression prevCall, @NotNull PsiMethodCallExpression nextCall) {
    PsiMethod nextMethod = nextCall.resolveMethod();
    if (nextMethod == null) return null;
    String nextName = nextMethod.getName();
    PsiMethod method = prevCall.resolveMethod();
    if (method == null) return null;
    PsiClass prevClass = method.getContainingClass();
    if (prevClass == null) return null;
    String prevClassName = prevClass.getQualifiedName();
    if (prevClassName == null) return null;
    String prevName = method.getName();
    if (nextName.endsWith("Match") || nextName.startsWith("forEach")) return nextName;
    if (nextName.equals("map")) {
      return translateMap(prevName);
    }
    if (prevName.equals("map")) {
      return translateMap(nextName);
    }
    if(Holder.MAP_METHODS.contains(nextName)) {
      PsiType type = nextMethod.getReturnType();
      if(!(type instanceof PsiClassType)) return null;
      PsiClass nextClass = ((PsiClassType)type).resolve();
      if(nextClass == null) return null;
      String nextClassName = nextClass.getQualifiedName();
      if(nextClassName == null) return null;
      if(prevClassName.equals(nextClassName)) return "map";
      switch(nextClassName) {
        case CommonClassNames.JAVA_UTIL_STREAM_INT_STREAM:
          return "mapToInt";
        case CommonClassNames.JAVA_UTIL_STREAM_LONG_STREAM:
          return "mapToLong";
        case CommonClassNames.JAVA_UTIL_STREAM_DOUBLE_STREAM:
          return "mapToDouble";
        case CommonClassNames.JAVA_UTIL_STREAM_STREAM:
          return "mapToObj";
        default:
          return null;
      }
    }
    if(nextName.equals("flatMap") && prevClassName.equals(CommonClassNames.JAVA_UTIL_STREAM_STREAM)) {
      return mapToFlatMap(prevName);
    }
    return null;
  }

  @Contract(pure = true)
  @Nullable
  private static String mapToFlatMap(String mapMethod) {
    switch (mapMethod) {
      case "map":
        return "flatMap";
      case "mapToInt":
        return "flatMapToInt";
      case "mapToLong":
        return "flatMapToLong";
      case "mapToDouble":
        return "flatMapToDouble";
    }
    // Something unsupported passed: ignore
    return null;
  }

  @Contract(pure = true)
  @NotNull
  private static String translateMap(String nextMethod) {
    switch (nextMethod) {
      case "boxed":
        return "mapToObj";
      case "asLongStream":
        return "mapToLong";
      case "asDoubleStream":
        return "mapToDouble";
      default:
        return nextMethod;
    }
  }

  @Override
  @NotNull
  public String getFamilyName() {
    return JavaBundle.message("intention.inline.map.family");
  }

  @Override
  public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
    PsiMethodCallExpression mapCall = PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class);
    if(mapCall == null) return;

    PsiMethodCallExpression nextCall = getNextExpressionToMerge(mapCall);
    if(nextCall == null) return;

    PsiReferenceExpression nextRef = nextCall.getMethodExpression();
    PsiExpression nextQualifier = nextRef.getQualifierExpression();
    if(nextQualifier == null) return;

    String newName = translateName(mapCall, nextCall);
    if(newName == null) return;

    PsiLambdaExpression previousLambda = getLambda(mapCall);

    LOG.assertTrue(previousLambda != null);
    PsiExpression previousBody = LambdaUtil.extractSingleExpressionFromBody(previousLambda.getBody());
    LOG.assertTrue(previousBody != null);

    PsiLambdaExpression lambda = getLambda(nextCall);
    LOG.assertTrue(lambda != null);

    CommentTracker ct = new CommentTracker();

    if(!lambda.isPhysical()) {
      lambda = (PsiLambdaExpression)nextCall.getArgumentList().add(lambda);
    }
    PsiElement body = lambda.getBody();
    LOG.assertTrue(body != null);
    ct.markUnchanged(body);

    PsiParameter[] nextParameters = lambda.getParameterList().getParameters();
    LOG.assertTrue(nextParameters.length == 1);
    PsiParameter[] prevParameters = previousLambda.getParameterList().getParameters();
    LOG.assertTrue(prevParameters.length == 1);
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
    for(PsiReference ref : ReferencesSearch.search(nextParameters[0], new LocalSearchScope(body)).findAll()) {
      PsiElement e = ref.getElement();
      PsiExpression replacement = ct.markUnchanged(previousBody);
      if (e.getParent() instanceof PsiExpression &&
          ParenthesesUtils.areParenthesesNeeded(previousBody, (PsiExpression)e.getParent(), false)) {
        replacement = factory.createExpressionFromText("(a)", e);
        PsiExpression parenthesized = ((PsiParenthesizedExpression)replacement).getExpression();
        LOG.assertTrue(parenthesized != null);
        parenthesized.replace(previousBody);
      }
      ct.replace(e, replacement);
    }
    ct.replace(lambda.getParameterList(), previousLambda.getParameterList());
    ExpressionUtils.bindReferenceTo(nextRef, newName);
    PsiExpression prevQualifier = mapCall.getMethodExpression().getQualifierExpression();
    if(prevQualifier == null) {
      ct.deleteAndRestoreComments(nextQualifier);
    } else {
      ct.replaceAndRestoreComments(nextQualifier, prevQualifier);
    }
    CodeStyleManager.getInstance(project).reformat(lambda);
  }

  @Nullable
  private static PsiLambdaExpression getLambda(PsiMethodCallExpression call) {
    PsiExpression[] expressions = call.getArgumentList().getExpressions();
    if(expressions.length == 1) {
      PsiExpression expression = expressions[0];
      if(expression instanceof PsiLambdaExpression) return (PsiLambdaExpression)expression;
      if(expression instanceof PsiMethodReferenceExpression) {
        return LambdaRefactoringUtil.convertMethodReferenceToLambda((PsiMethodReferenceExpression)expression, false, true);
      }
      return null;
    }
    if(expressions.length != 0) return null;
    PsiMethod method = call.resolveMethod();
    if(method == null) return null;
    PsiClass containingClass = method.getContainingClass();
    if(containingClass == null) return null;
    String className = containingClass.getQualifiedName();
    if(className == null) return null;
    String varName;
    String type;
    switch (className) {
      case CommonClassNames.JAVA_UTIL_STREAM_INT_STREAM:
        varName = "i";
        type = CommonClassNames.JAVA_LANG_INTEGER;
        break;
      case CommonClassNames.JAVA_UTIL_STREAM_LONG_STREAM:
        varName = "l";
        type = CommonClassNames.JAVA_LANG_LONG;
        break;
      case CommonClassNames.JAVA_UTIL_STREAM_DOUBLE_STREAM:
        varName = "d";
        type = CommonClassNames.JAVA_LANG_DOUBLE;
        break;
      default:
        return null;
    }
    varName = JavaCodeStyleManager.getInstance(call.getProject()).suggestUniqueVariableName(varName, call, true);
    String expression;
    if("boxed".equals(method.getName())) {
      expression = varName+" -> ("+type+")"+varName;
    } else if("asLongStream".equals(method.getName())) {
      expression = varName+" -> (long)"+varName;
    } else if("asDoubleStream".equals(method.getName())) {
      expression = varName+" -> (double)"+varName;
    } else return null;
    PsiElementFactory factory = JavaPsiFacade.getElementFactory(call.getProject());
    return (PsiLambdaExpression)factory.createExpressionFromText(expression, call);
  }
}