text:
package com.tikal.jenkins.plugins.multijob.counters;

import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

import hudson.model.Result;

/**
 * A manager for the different counters that can exist in a phase.
 *
A manager process the results of the jobs, the result of the phase
 * and transforms the counters and their values in the data structure
 * needed by the Multijob.injectEnvVars.

 *
These are the variables that will be injected:

 *
 *
The variables related to the last phase execution:

 *

 *
PHASE_RESULT: with the result (as string) of the previous phase.

 *
PHASE_SUCCESSFUL: the number of jobs with UNSTABLE or SUCCESS results.

 *
PHASE_STABLE: the number of jobs with SUCCESS results.

 *
PHASE_UNSTABLE: the number of jobs with UNSTABLE results.

 *
PHASE_FAILED: the number of jobs with FAILED results.

 *
PHASE_ABORTED: the number of jobs with ABORTED results.

 *
PHASE_SKIPPED: the number of jobs with has been skipped.

 *

 *
 *
The variables related to the phase name (in the following example, TRALL is the phase name):

 *

 *
TRALL_RESULT: with the result (as string) of the previous phase.

 *
TRALL_SUCCESSFUL: the number of jobs with UNSTABLE or SUCCESS results.

 *
TRALL_STABLE: the number of jobs with SUCCESS results.

 *
TRALL_UNSTABLE: the number of jobs with UNSTABLE results.

 *
TRALL_FAILED: the number of jobs with FAILED results.

 *
TRALL_ABORTED: the number of jobs with ABORTED results.

 *
TRALL_SKIPPED: the number of jobs with has been skipped.

 *

 *
 *
The variables related to current multijob execution:

 *

 *
MULTIJOB_RESULT: with the result (as string) of the previous phase.

 *
MULTIJOB_SUCCESSFUL: the number of jobs with UNSTABLE or SUCCESS results.

 *
MULTIJOB_STABLE: the number of jobs with SUCCESS results.

 *
MULTIJOB_UNSTABLE: the number of jobs with UNSTABLE results.

 *
MULTIJOB_FAILED: the number of jobs with FAILED results.

 *
MULTIJOB_ABORTED: the number of jobs with ABORTED results.

 *
MULTIJOB_SKIPPED: the number of jobs with has been skipped.

 *

 */
public final class CounterManager {
    /**
     * Name of the key that will be used to store, as an environment property, the result of the phase.
     *
We compute the result of the phase as the worse of the results of all triggered jobs.

     */
    public static final String PHASE_RESULT = "PHASE_RESULT";

    /**
     * We store all values of the counters as a Map.
     */
    private final Map<CounterKey, AtomicInteger> counters;

    /**
     * The phase result. It is computed as the worse of the results of all triggered jobs.
     */
    private Result phaseResult = Result.SUCCESS;

    public CounterManager() {
        final Map<CounterKey, AtomicInteger> counters = new HashMap<CounterKey, AtomicInteger>(CounterKey.values().length);
        for(final CounterKey key: CounterKey.values()) {
            counters.put(key, new AtomicInteger(0));
        }

        this.counters = counters;
    }

    /**
     * Process the result of the job.
     *
The processing of the result of the job is an operation that involucres two steps:

     *

     *
First, we increment all of the counters this result applies to.

     *
Second, we update the phaseResult variable if the result if worse than current.

     *

     *
     * @param result the result of the job to be processed.
     */
    public void process(Result result) {
        for(final CounterKey key: CounterKey.values()) {
            if (key.appliesTo(result)) {
                this.counters.get(key).incrementAndGet();
            }
        }
        if (result.isWorseThan(phaseResult)) {
            phaseResult = result;
        }
    }

    /**
     * A convenient way to process a skipped job.
     */
    public void processSkipped() {
        this.counters.get(CounterKey.SKIPPED).incrementAndGet();
    }

    /**
     * A convenient way to process an aborted job.
     */
    public void processAborted() {
        this.counters.get(CounterKey.ABORTED).incrementAndGet();
    }

    /**
     * Returns a map with the variables and their values, to be injected.
     * @return a map with the variables related to phase and multijob.
     */
    public Map<String, String> toMap() {
        final Map<String, String> map = new HashMap<String, String>(this.counters.size());
        map.put(PHASE_RESULT, phaseResult.toString());

        for(CounterKey key: CounterKey.values()) {
            map.put(key.name(), String.valueOf(this.counters.get(key)));
        }
        return map;
    }

    @Override
    public String toString() {
        return counters.toString();
    }
}


text:
namespace Core {

class Object {
public:

};

}

#endif //HTTP_CLIENT_OBJECT_H

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}
<!DOCTYPE html>

    <meta charset="UTF-8">

    {% block title %}
    <title>Registration Complete</title>
    {% endblock title %}

{% block main %}

Thank you, your account was successfully activated.

Sign In

{% endblock main %}


text:
function ThemeLoader() {

}

ThemeLoader.prototype.loadTheme = function(theme) {
	if (theme === 'hot-pink') {
		return;
	}

	this.fetchTheme(theme);
};

ThemeLoader.prototype.fetchTheme = function(theme) {
	var file = document.createElement("link");
	file.setAttribute("rel", "stylesheet");
	file.setAttribute("type", "text/css");
	file.setAttribute("href", 'css/themes/' + theme + '.css');

	if (typeof file !== "undefined") {
		document.getElementsByTagName("head")[0].appendChild(file)
	}
};


text:
declare module wijmo.grid.multirow {
    /**
     * Extends the @see:Row to provide additional information for multi-row records.
     */
    class _MultiRow extends Row {
        _idxData: number;
        _idxRecord: number;
        /**
         * Initializes a new instance of the @see:Row class.
         *
         * @param dataItem The data item that this row is bound to.
         * @param dataIndex The index of the record within the items source.
         * @param recordIndex The index of this row within the record (data item).
         */
        constructor(dataItem: any, dataIndex: number, recordIndex: number);
        /**
         * Gets the index of this row within the record (data item) it represents.
         */
        recordIndex: number;
        /**
         * Gets the index of this row within the data source collection.
         */
        dataIndex: number;
    }
}

declare module wijmo.grid.multirow {
    /**
     * Extends the @see:Column class to with a @see:colspan property to
     * describe a cell in a @see:_CellGroup.
     */
    class _Cell extends Column {
        _row: number;
        _col: number;
        _colspan: number;
        _rowspan: number;
        /**
         * Initializes a new instance of the @see:_Cell class.
         *
         * @param options JavaScript object containing initialization data for the @see:_Cell.
         */
        constructor(options?: any);
        /**
         * Gets or sets the number of physical columns spanned by this @see:_Cell.
         */
        colspan: number;
    }
}

declare module wijmo.grid.multirow {
    /**
     * Describes a group of cells that may span multiple rows and columns.
     */
    class _CellGroup extends _Cell {
        _g: MultiRow;
        _colstart: number;
        _cells: _Cell[];
        _rng: CellRange[];
        _cols: ColumnCollection;
        /**
         * Initializes a new instance of the @see:_CellGroup class.
         *
         * @param grid @see:MultiRow that owns this @see:_CellGroup.
         * @param options JavaScript object containing initialization data for the new @see:_CellGroup.
         */
        constructor(grid: MultiRow, options?: any);
        _copy(key: string, value: any): boolean;
        cells: _Cell[];
        closeGroup(rowsPerItem: number): void;
        getColumnWidth(c: number): any;
        getMergedRange(p: GridPanel, r: number, c: number): CellRange;
        getBindingColumn(p: GridPanel, r: number, c: number): Column;
    }
}

declare module wijmo.grid.multirow {
    /**
     * Provides custom merging for @see:MultiRow controls.
     */
    class _MergeManager extends MergeManager {
        /**
         * Gets a @see:CellRange that specifies the merged extent of a cell
         * in a @see:GridPanel.
         *
         * @param p The @see:GridPanel that contains the range.
         * @param r The index of the row that contains the cell.
         * @param c The index of the column that contains the cell.
         * @param clip Whether to clip the merged range to the grid's current view range.
         * @return A @see:CellRange that specifies the merged range, or null if the cell is not merged.
         */
        getMergedRange(p: GridPanel, r: number, c: number, clip?: boolean): CellRange;
    }
}

declare module wijmo.grid.multirow {
    /**
     * Manages the new row template used to add rows to the grid.
     */
    class _AddNewHandler extends wijmo.grid._AddNewHandler {
        /**
         * Initializes a new instance of the @see:_AddNewHandler class.
         *
         * @param grid @see:FlexGrid that owns this @see:_AddNewHandler.
         */
        constructor(grid: FlexGrid);
        /**
         * Updates the new row template to ensure it's visible only if the grid is
         * bound to a data source that supports adding new items, and that it is
         * in the right position.
         */
        updateNewRowTemplate(): void;
    }
}

/**
 * Defines the @see:MultiRow control and associated classes.
 */
declare module wijmo.grid.multirow {
    /**
     * Extends the @see:FlexGrid control to provide multiple rows per item.
     *
     * Use the @see:layoutDefinition property to define the layout of the rows
     * used to display each data item.
     *
     * A few @see:FlexGrid properties are disabled in the @see:MultiRow control
     * because they would interfere with the custom multi-row layouts.
     * The list of disabled properties includes @see:allowMerging and
     * @see:childItemsPath.
     */
    class MultiRow extends FlexGrid {
        _rowsPerItem: number;
        _layoutDef: any[];
        _cellBindingGroups: _CellGroup[];
        _cellGroupsByColumn: any;
        _centerVert: boolean;
        _collapsedHeaders: boolean;
        _btnCollapse: HTMLElement;
        /**
         * Initializes a new instance of the @see:MultiRow class.
         *
         * In most cases, the @see:options parameter will include the value for the
         * @see:layoutDefinition property.
         *
         * @param element The DOM element that will host the control, or a selector for the host element (e.g. '#theCtrl').
         * @param options JavaScript object containing initialization data for the control.
         */
        constructor(element: any, options?: any);
        /**
         * Gets or sets an array that defines the layout of the rows used to display each data item.
         *
         * The array contains a list of cell group objects which have the following properties:
         *
         *

         *
header: Group header (shown when the headers are collapsed)

         *
colspan: Number of grid columns spanned by the group

         *
cells: Array of cell objects, which extend @see:Column with a colspan property.

         *

         *
         * When the @see:layoutDefinition property is set, the grid scans the cells in each
         * group as follows:
         *
         *

         *
The grid calculates the group's colspan as the max between the group's own colspan
         * and the widest cell in the group.

         *
If the cell fits the current row within the group, it is added to the current row.

         *
If it doesn't fit, it is added to a new row.

         *

         *
         * When all groups are ready, the grid calculates the number of rows per record to the maximum
         * rowspan of all groups, and adds rows to each group to pad their height as needed.
         *
         * This scheme is simple and flexible. For example:
         *
{ header: 'Group 1', cells: [{ binding: 'c1' }, { bnding: 'c2'}, { binding: 'c3' }]}

         *
         * The group has colspan 1, so there will be one cell per column. The result is:
         *

         * | C1 |
         * | C2 |
         * | C3 |
         *

         *
         * To create a group with two columns, set the group's colspan property:
         *
         *
{ header: 'Group 1', colspan: 2, cells:[{ binding: 'c1' }, { binding: 'c2'}, { binding: 'c3' }]}

         *
         * The cells will wrap as follows:
         *

         * | C1  | C2 |
         * | C3       |
         *

         *
         * Note that the last cell spans two columns (to fill the group).
         *
         * You can also specify the colspan on individual cells rather than on the group:
         *
         *
{ header: 'Group 1', cells: [{binding: 'c1', colspan: 2 }, { bnding: 'c2'}, { binding: 'c3' }]}

         *
         * Now the first cell has colspan 2, so the result is:
         *

         * | C1       |
         * | C2 |  C3 |
         *

         *
         * Because cells extend the @see:Column class, you can add all the usual @see:Column
         * properties to any cells:
         *

         * { header: 'Group 1', cells: [
         *    { binding: 'c1', colspan: 2 },
         *    { bnding: 'c2'},
         *    { binding: 'c3', format: 'n0', required: false, etc... }
         * ]}

         */
        layoutDefinition: any[];
        /**
         * Gets the number of rows used do display each item.
         *
         * This value is calculated automatically based on the value
         * of the @see:layoutDefinition property.
         */
        rowsPerItem: number;
        /**
         * Gets the @see:Column object used to bind a data item to a grid cell.
         *
         * @param p @see:GridPanel that contains the cell.
         * @param r Index of the row that contains the cell.
         * @param c Index of the column that contains the cell.
         */
        getBindingColumn(p: GridPanel, r: number, c: number): Column;
        /**
         * Gets or sets a value that determines whether the content of cells
         * that span multiple rows should be vertically centered.
         */
        centerHeadersVertically: boolean;
        /**
         * Gets or sets a value that determines whether column headers
         * should be collapsed and displayed as a single row displaying
         * the group headers.
         *
         * If you set the @see:collapsedHeaders property to true,
         * remember to set the header property of every group in order
         * to avoid empty headers.
         */
        collapsedHeaders: boolean;
        /**
         * Gets or sets a value that determines whether the grid should display
         * a button in the column header panel to allow users to collapse and
         * expand the column headers.
         *
         * If the button is visible, clicking on it will cause the grid to
         * toggle the value of the @see:collapsedHeaders property.
         */
        showHeaderCollapseButton: boolean;
        _addBoundRow(items: any[], index: number): void;
        _addNode(items: any[], index: number, level: number): void;
        _bindColumns(): void;
        _updateColumnTypes(): void;
        _getBindingColumn(p: GridPanel, r: Number, c: Column): Column;
        _cvCollectionChanged(sender: any, e: collections.NotifyCollectionChangedEventArgs): void;
        _parseCellGroups(groups: any[]): _CellGroup[];
        _formatItem(s: MultiRow, e: FormatItemEventArgs): void;
        _updateButtonGlyph(): void;
    }
}


text:
declare namespace javax {
  namespace sound {
    namespace sampled {

      interface TargetDataLine extends javax.sound.sampled.DataLine {
        open(arg0: javax.sound.sampled.AudioFormat, arg1: number | java.lang.Integer): void
        open(arg0: javax.sound.sampled.AudioFormat): void
        read(arg0: number[] | java.lang.Byte[], arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number
      }

    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >
	    <LinearLayout
	        android:layout_width="match_parent"
	        android:layout_height="wrap_content"
	        android:orientation="horizontal"
	        >
	        <EditText android:id="@+id/host_ip_edittext"
	            android:layout_height="wrap_content"
	            android:layout_width="0sp"
	            android:layout_weight="1"
	            android:hint="请输入服务器的IP地址"
	            />
	        <Button android:id="@+id/host_ip_submit_button"
	            android:layout_height="wrap_content"
	            android:layout_width="wrap_content"
	            android:text="提交"
	            />

	    </LinearLayout>
    <Button android:id="@+id/httpclient_button_baidu"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="httpclient_BAIDU"/>

	    <Button android:id="@+id/httpclient_button"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="httpclient_xml"/>

	    <Button android:id="@+id/http_url_connection_button"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="http_url_connection_xml"/>

	    <Button android:id="@+id/http_client_json_button"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:text="http_client_json"/>

	    <TextView android:id="@+id/net_info_small_textview"
	        android:layout_width="match_parent"
	        android:layout_height="wrap_content"
	        android:text="小提示窗口"
	        />

	    <ScrollView
	        android:layout_height="match_parent"
	        android:layout_width="match_parent">
		    <TextView android:id="@+id/net_info_textview"
		        android:layout_width="match_parent"
		        android:layout_height="wrap_content"
		        android:text="this is info dialog"
		        />
	    </ScrollView>

</LinearLayout>


text:
/*
FUNCTION
<<fgetlen>>---get length of received data for this stream

INDEX
	fgetlen

ANSI_SYNOPSIS
	#include <stdio.h>
	int fgetlen(FILE *<[fp]>);

DESCRIPTION
Use <<fgetlen>> to get the amount of received data from the file or stream
identified by <[fp]>.

RETURNS
The amount of received data or -1 if there is no reception buffer

PORTABILITY
This function is not part of POSIX neither of ANSY

*/

#include "stdio.h"

int fgetlen(FILE *fp)
{
	// if (fp->r_buf!=NULL) return fp->r_len;
	// else return -1;
	return -1;
}


text:
from __future__ import unicode_literals

from django.contrib.auth.models import User
from django.db import models

# Create your models here.

class Notice(models.Model):
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    title = models.CharField(max_length=500, null=True)
    start_date = models.DateTimeField(auto_now=False, auto_now_add=False)
    end_date = models.DateTimeField(auto_now=False, auto_now_add=False)
    message = models.TextField(null=True)
    url = models.URLField(null=True)

    def __str__(self):
        return self.title


text: console.log(isNaN("q"));


text:
function TranslationCollection(headers, translations) {
    this.headers = headers || {};
    this.translations = translations || {};
}

TranslationCollection.prototype.hasHeader = function(name) {
    return name in this.headers;
};

TranslationCollection.prototype.getHeaders = function() {
    return this.headers;
};

TranslationCollection.prototype.getHeader = function(name) {
    return this.headers[name];
};

TranslationCollection.prototype.hasTranslation = function(key) {
    return key in this.translations;
};

TranslationCollection.prototype.getTranslations = function(key) {
    if(!key) {
        return this.translations;
    }

    if(this.hasTranslation(key)) {
        return this.translations[key];
    }
};

module.exports = TranslationCollection;


text:
wget https://s3.amazonaws.com/erin-data/higgs/higgs_test_5k.csv
#wget https://s3.amazonaws.com/erin-data/higgs/higgs_train_5k.csv
wget https://s3.amazonaws.com/erin-data/higgs/higgs_train_10k.csv
#wget https://s3.amazonaws.com/erin-data/higgs/higgs_train_50k.csv
#wget https://s3.amazonaws.com/erin-data/higgs/higgs_train_100k.csv
#wget https://s3.amazonaws.com/erin-data/higgs/higgs_train_1M.csv


text:
/**
 */
package microserviceMetamodel.impl;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;

import org.eclipse.emf.ecore.impl.EFactoryImpl;

import org.eclipse.emf.ecore.plugin.EcorePlugin;

import microserviceMetamodel.*;

/**
 * <!-- begin-user-doc -->
 * An implementation of the model <b>Factory</b>.
 * <!-- end-user-doc -->
 * @generated
 */
public class AnotherMicroserviceMetamodelFactoryImpl extends EFactoryImpl implements AnotherMicroserviceMetamodelFactory {
	/**
	 * Creates the default factory implementation.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public static AnotherMicroserviceMetamodelFactory init() {
		try {
			AnotherMicroserviceMetamodelFactory theAnotherMicroserviceMetamodelFactory = (AnotherMicroserviceMetamodelFactory)EPackage.Registry.INSTANCE.getEFactory(AnotherMicroserviceMetamodelPackage.eNS_URI);
			if (theAnotherMicroserviceMetamodelFactory != null) {
				return theAnotherMicroserviceMetamodelFactory;
			}
		}
		catch (Exception exception) {
			EcorePlugin.INSTANCE.log(exception);
		}
		return new AnotherMicroserviceMetamodelFactoryImpl();
	}

	/**
	 * Creates an instance of the factory.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public AnotherMicroserviceMetamodelFactoryImpl() {
		super();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public EObject create(EClass eClass) {
		switch (eClass.getClassifierID()) {
			case AnotherMicroserviceMetamodelPackage.MICROSERVICE: return createMicroservice();
			case AnotherMicroserviceMetamodelPackage.CONFIGURATION: return createConfiguration();
			case AnotherMicroserviceMetamodelPackage.VERSION: return createVersion();
			case AnotherMicroserviceMetamodelPackage.ENDPOINT: return createEndpoint();
			case AnotherMicroserviceMetamodelPackage.REST_OPERATION: return createRESTOperation();
			case AnotherMicroserviceMetamodelPackage.MICROSERVICE_TYPE: return createMicroserviceType();
			case AnotherMicroserviceMetamodelPackage.MICROSERVICE_REPOSITORY: return createMicroserviceRepository();
			case AnotherMicroserviceMetamodelPackage.VIRTUAL_HOST: return createVirtualHost();
			case AnotherMicroserviceMetamodelPackage.PHYSICAL_HOST: return createPhysicalHost();
			case AnotherMicroserviceMetamodelPackage.INFRASTRUCTURE_MODEL: return createInfrastructureModel();
			case AnotherMicroserviceMetamodelPackage.DEPENDENCY_MODEL: return createDependencyModel();
			case AnotherMicroserviceMetamodelPackage.OPERATION_TO_OPERATION_CALLING_DEPENDENCY: return createOperationToOperationCallingDependency();
			case AnotherMicroserviceMetamodelPackage.TIME_SERIES: return createTimeSeries();
			case AnotherMicroserviceMetamodelPackage.TIME_SERIES_POINT: return createTimeSeriesPoint();
			case AnotherMicroserviceMetamodelPackage.MICROSERVICE_OPERATION_TIME_SERIES_POINT: return createMicroserviceOperationTimeSeriesPoint();
			case AnotherMicroserviceMetamodelPackage.META_MODEL_STRUCTURE: return createMetaModelStructure();
			default:
				throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
		}
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public Object createFromString(EDataType eDataType, String initialValue) {
		switch (eDataType.getClassifierID()) {
			case AnotherMicroserviceMetamodelPackage.REST_VERB:
				return createRESTVerbFromString(eDataType, initialValue);
			default:
				throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
		}
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	public String convertToString(EDataType eDataType, Object instanceValue) {
		switch (eDataType.getClassifierID()) {
			case AnotherMicroserviceMetamodelPackage.REST_VERB:
				return convertRESTVerbToString(eDataType, instanceValue);
			default:
				throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
		}
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public Microservice createMicroservice() {
		MicroserviceImpl microservice = new MicroserviceImpl();
		return microservice;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public Configuration createConfiguration() {
		ConfigurationImpl configuration = new ConfigurationImpl();
		return configuration;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public Version createVersion() {
		VersionImpl version = new VersionImpl();
		return version;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public Endpoint createEndpoint() {
		EndpointImpl endpoint = new EndpointImpl();
		return endpoint;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public RESTOperation createRESTOperation() {
		RESTOperationImpl restOperation = new RESTOperationImpl();
		return restOperation;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public MicroserviceType createMicroserviceType() {
		MicroserviceTypeImpl microserviceType = new MicroserviceTypeImpl();
		return microserviceType;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public MicroserviceRepository createMicroserviceRepository() {
		MicroserviceRepositoryImpl microserviceRepository = new MicroserviceRepositoryImpl();
		return microserviceRepository;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public VirtualHost createVirtualHost() {
		VirtualHostImpl virtualHost = new VirtualHostImpl();
		return virtualHost;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public PhysicalHost createPhysicalHost() {
		PhysicalHostImpl physicalHost = new PhysicalHostImpl();
		return physicalHost;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public InfrastructureModel createInfrastructureModel() {
		InfrastructureModelImpl infrastructureModel = new InfrastructureModelImpl();
		return infrastructureModel;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public DependencyModel createDependencyModel() {
		DependencyModelImpl dependencyModel = new DependencyModelImpl();
		return dependencyModel;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public OperationToOperationCallingDependency createOperationToOperationCallingDependency() {
		OperationToOperationCallingDependencyImpl operationToOperationCallingDependency = new OperationToOperationCallingDependencyImpl();
		return operationToOperationCallingDependency;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public TimeSeries createTimeSeries() {
		TimeSeriesImpl timeSeries = new TimeSeriesImpl();
		return timeSeries;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public TimeSeriesPoint createTimeSeriesPoint() {
		TimeSeriesPointImpl timeSeriesPoint = new TimeSeriesPointImpl();
		return timeSeriesPoint;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public MicroserviceOperationTimeSeriesPoint createMicroserviceOperationTimeSeriesPoint() {
		MicroserviceOperationTimeSeriesPointImpl microserviceOperationTimeSeriesPoint = new MicroserviceOperationTimeSeriesPointImpl();
		return microserviceOperationTimeSeriesPoint;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public MetaModelStructure createMetaModelStructure() {
		MetaModelStructureImpl metaModelStructure = new MetaModelStructureImpl();
		return metaModelStructure;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public RESTVerb createRESTVerbFromString(EDataType eDataType, String initialValue) {
		RESTVerb result = RESTVerb.get(initialValue);
		if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
		return result;
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public String convertRESTVerbToString(EDataType eDataType, Object instanceValue) {
		return instanceValue == null ? null : instanceValue.toString();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	public AnotherMicroserviceMetamodelPackage getAnotherMicroserviceMetamodelPackage() {
		return (AnotherMicroserviceMetamodelPackage)getEPackage();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @deprecated
	 * @generated
	 */
	@Deprecated
	public static AnotherMicroserviceMetamodelPackage getPackage() {
		return AnotherMicroserviceMetamodelPackage.eINSTANCE;
	}

} //AnotherMicroserviceMetamodelFactoryImpl


text:
import json
import logging
import os
import subprocess

import pandas as pd
import psycopg2
from six import string_types
from six.moves import cStringIO, range, urllib
from sqlalchemy import func
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.orm import Query

from .database import database as db, CreateTableAs
from .utils import load_config, logf

# Set up logging system.
logging.basicConfig()
logger = logging.getLogger(__name__)

# Import from GDAL if available.
try:
    from osgeo import osr
except ImportError:
    logger.warn("GDAL bindings not available. No custom projection support.")
    gdal = False
else:
    gdal = True

class TableLoader(object):
    """Table loader class with support for shapefiles and GeoAlchemy.

    Some example usage:

        loader = TableLoader()

        # Load shapefile.
        loader.load_shp('parcel/Alameda.shp', 'staging.alameda')

        # Load multiple shapefiles.
        loader.load_shp_map({'staging.alameda': 'parcel/Alameda.shp'})

        # Run SQL command.
        with loader.database.cursor() as cur:
            cur.execute("SELECT DISTINCT luc_desc FROM staging.alameda;")
            for desc in cur:
                print(desc)

        # Run ORM command.
        session = loader.database.session
        alameda = loader.tables.staging.alameda
        for desc in session.query(alameda.luc_desc).distinct():
            print(desc)

        # Refresh ORM if schema was modified.
        loader.database.refresh()

        # Close all connection(s).
        loader.close()

    Methods:
        duplicate:       Duplicate a PostgreSQL table, including indexes.
        close:           Close managed PostgreSQL connection(s).
        get_attributes:  Export shapefile attributes as a pandas DataFrame.
        get_encoding:    Identify shapefile attribute encoding.
        get_srid:        Identify shapefile EPSG SRID.
        load_shp:        Load a shapefile into a PostGIS table.
        load_shp_map:    Load multiple shapefiles into PostGIS tables.

    Attributes:
        database:        PostgreSQL database connection manager class.
        directory:       Path to the directory containing the shapefiles.
        srid:            Default Spatial Reference System Identifier (SRID).
        tables:          PostgreSQL table objects, namespaced by schema.

    Attributes can be passed as additional constructor arguments and override
    configuration.

    Constructor arguments:
        config_filename: Path to additional configuration file.
                         If None, configuration must be provided in default
                         locations, or attributes must be passed as
                         constructor arguments in place of configuration.

    """
    def __init__(self, config_filename=None, database=None, directory=None,
                 srid=None):
        # Attempt to load configuration.
        config = load_config(config_filename)

        # Define arguments from configuration, unless overridden.
        if not database:
            database = db
        if not directory:
            directory = config.get('data', 'directory')
        if not srid:
            srid = config.get('data', 'srid')

        # Create new connection(s) using configuration, unless already
        # connected.
        try:
            database.assert_connected()
        except psycopg2.DatabaseError:
            db_config = dict(config.items('database'))
            database.connect(**db_config)

        # Assign arguments to attributes.
        self.database = database
        self.tables = self.database.tables
        if os.path.exists(directory):
            self.directory = directory
        else:
            raise IOError("Directory does not exist: %s" % directory)
        self.srid = int(srid)

    def duplicate(self, table, new_table_name, schema_name='public'):
        """
        Duplicate a PostgreSQL table, including indexes and constraints.

        Parameters
        ----------
        table : sqlalchemy.ext.declarative.api.DeclarativeMeta
            Table ORM class to duplicate.
        new_table_name : str
            Name of new table.
        schema_name : str, optional
            Name of schema to contain the new table. Default is 'public'.

        Returns
        -------
        new_table : sqlalchemy.ext.declarative.api.DeclarativeMeta
            Duplicated ORM table class.

        """
        # Copy schema including constraints and indexes, then insert values.
        # This may be inefficient, unfortunately.
        t = table.__table__
        with db.cursor() as cur:
            cur.execute("""
                CREATE TABLE {nschema}.{ntable}
                    (LIKE {oschema}.{otable} INCLUDING ALL);
                INSERT INTO {nschema}.{ntable}
                    SELECT * FROM {oschema}.{otable};
            """.format(nschema=schema_name, ntable=new_table_name,
                       oschema=t.schema, otable=t.name))

        # Refresh ORM and return table class.
        db.refresh()
        return getattr(getattr(db.tables, schema_name), new_table_name)

    def close(self):
        """Close managed PostgreSQL connection(s)."""
        return self.database.close()

    def get_path(self, filename):
        """
        Get the absolute path to a file in the data directory.

        Parameters
        ----------
        filename: str
            File path, relative to the data directory.

        Returns
        -------
        filepath : str
            Absolute file path.

        """
        filepath = os.path.join(self.directory, filename)
        return filepath

    def get_attributes(self, filename):
        """
        Export shapefile attributes as a pandas DataFrame.

        Uses OGR's ESRI Shapefile driver to read records from the file.

        Parameters
        ----------
        filename : str
            Shapefile or dBase/xBase file, relative to the data directory.

        Returns
        -------
        df : pd.DataFrame

        """
        splitext = os.path.splitext(filename)
        if splitext[1].lower() == '.shp':
            filename = splitext[0] + '.dbf'
        filepath = self.get_path(filename)
        return dbf_to_df(filepath)

    def get_encoding(self, filename):
        """Identify shapefile attribute table encoding.

        Use encoding specified by cpg or cst file, before falling back to
        LATIN1.

        Args:
            filename: Shapefile, relative to the data directory.

        Returns:
            encoding: Character encoding (str).

        """
        # Read encoding from shapefile cpg and cst file.
        filepath = self.get_path(filename)
        encoding = None
        for extension in ['.cpg', '.cst']:
            encoding_filepath = os.path.splitext(filepath)[0] + extension
            try:
                with open(encoding_filepath) as encoding_file:
                    encoding = encoding_file.read().strip()
                logger.debug("%s file reported %s encoding: %s"
                             % (extension, encoding, filename))
                break
            except IOError:
                continue

        if not encoding or encoding.lower() == "system":
            # No encoding found. Fall back to LATIN1.
            encoding = "LATIN1"
            logger.debug("Assuming %s attribute encoding: %s"
                         % (encoding, filename))

        return encoding

    def get_srid(self, filename):
        """Identify shapefile SRID using GDAL and prj2EPSG API.

        Try to identify the SRID of a shapefile by reading the
        projection information of the prj file and matching to an
        EPSG SRID using GDAL and the prj2EPSG API.

        If the prj file cannot be read, warn and return 0,
        which is the default SRID in PostGIS 2.0+.

        If no match is found, define a custom projection in the
        spatial_ref_sys table and return its SRID.

        Args:
            filename: Shapefile, relative to the data directory.

        Returns:
            srid: EPSG, custom SRID, or 0.

        """
        # Read projection information from shapefile prj file.
        filepath = self.get_path(filename)
        prj_filepath = os.path.splitext(filepath)[0] + '.prj'
        try:
            with open(prj_filepath) as prj_file:
                wkt = prj_file.read().strip()
        except IOError:
            logger.warn("Unable to open projection information: %s"
                        % filename)
            return 0

        # Attempt to identify EPSG SRID using GDAL.
        if gdal:
            sr = osr.SpatialReference()
            sr.ImportFromESRI([wkt])
            res = sr.AutoIdentifyEPSG()
            if res == 0:
                # Successfully identified SRID.
                srid = int(sr.GetAuthorityCode(None))
                logger.debug("GDAL returned SRID %s: %s" % (srid, filename))
                return srid

        # Try querying prj2EPSG API.
        params = urllib.parse.urlencode({'terms': wkt, 'mode': 'wkt'})
        resp = urllib.request.urlopen('http://prj2epsg.org/search.json?'
                                      + params)
        data = json.load(resp)
        if data['exact']:
            # Successfully identified SRID.
            srid = int(data['codes'][0]['code'])
            logger.debug("prj2EPSG API returned SRID %s: %s"
                         % (srid, filename))
            return srid

        # Unable to identify EPSG SRID. Use custom SRID.
        srs = self.tables.public.spatial_ref_sys
        with self.database.session() as sess:
            srid = sess.query(srs.srid).filter(srs.srtext == wkt).first()
        if srid:
            return srid[0]
        else:
            if gdal:
                # Need to define custom projection since not in database.
                logger.warn("Defining custom projection: %s" % filename)
                proj4 = sr.ExportToProj4().strip()
                if not proj4:
                    raise RuntimeError("Unable to project: %s" % filename)
                with self.database.session() as sess:
                    srid = sess.query(func.max(srs.srid)).one()[0] + 1
                    projection = srs(srid=srid,
                                     auth_name="custom", auth_srid=srid,
                                     srtext=wkt, proj4text=proj4)
                    sess.add(projection)
                srid = projection.srid
            else:
                raise RuntimeError("No GDAL: unable to define projection.")
        logger.debug("Using custom SRID %s: %s" % (srid, filename))
        return srid

    def load_shp(self, filename, table, srid=None, encoding=None,
                 drop=False, append=False):
        """Load a shapefile from the directory into a PostGIS table.

        This is a Python wrapper for shp2gpsql. shp2pgsql is spawned by
        subprocess. Commands generated by shp2pgsql are executed on a
        psycopg2 cursor object. For performance, the PostgreSQL "dump"
        format is used instead of the default "insert" SQL format.

        Args:
            filename: Shapefile, relative to the data directory.
            table:    PostGIS table name (optionally schema-qualified).
            srid:     Spatial Reference System Identifier (SRID).
                      If None, attempt to identify SRID from projection
                      information before falling back to default.
            encoding: Shapefile attribute table encoding.
                      If None, attempt to identify encoding from cpg or cst
                      file before falling back to default.
            drop:     Whether to drop a table that already exists.
                      Defaults to False.
            append:   Whether to append to an existing table, instead of
                      creating one. Defaults to False.

        """
        filepath = self.get_path(filename)

        # Make sure that shapefile exists and is readable.
        with open(filepath):
            pass

        # If SRID not provided, identify from projection information.
        if not srid:
            srid = self.get_srid(filename)

        # If encoding not provided, try to identify from cpg or cst file
        # before falling back to default encoding.
        if not encoding:
            encoding = self.get_encoding(filename)

        logger.info("Loading table %s (SRID: %s) from file %s (encoding: %s)."
                    % (table, srid, filename, encoding))
        with self.database.cursor() as cur:

            if drop:
                # Drop the existing table.
                cur.execute('DROP TABLE IF EXISTS %s' % table)

            if not append:
                # Create the new table itself without adding actual data.
                create_table = subprocess.Popen(['shp2pgsql', '-p', '-I',
                                                 '-s', str(srid),
                                                 '-W', encoding,
                                                 filepath, table],
                                                stdout=subprocess.PIPE,
                                                stderr=subprocess.PIPE,
                                                universal_newlines=True)
                try:
                    command = ""
                    for line in create_table.stdout:
                        if line and not (line.startswith("BEGIN") or
                                         line.startswith("COMMIT")):
                            command += line
                    cur.execute(command)
                finally:
                    logf(logging.WARN, create_table.stderr)
                create_table.wait()

            # Append data to existing or newly-created table.
            append_data = subprocess.Popen(['shp2pgsql', '-a', '-D', '-I',
                                            '-s', str(srid),
                                            '-W', encoding,
                                            filepath, table],
                                           stdout=subprocess.PIPE,
                                           stderr=subprocess.PIPE,
                                           universal_newlines=True)
            try:
                while True:
                    line = append_data.stdout.readline()
                    if line.startswith("COPY"):
                        break
                cur.copy_expert(line, append_data.stdout)
            finally:
                logf(logging.WARN, append_data.stderr)
            append_data.wait()

        # Refresh ORM.
        self.database.refresh()

    def load_shp_map(self, mapping):
        """Load multiple shapefiles by mapping tables to filenames or kwargs.

        The shapefile dictionary should map each database table name to:

            - a shapefile filename to load, or
            - dict-like keyword arguments to pass to the load_shp method,
              other than the table name.

        By default, existing tables will be dropped (drop=True).

        """
        for (table, value) in mapping.items():
            if isinstance(value, string_types):
                self.load_shp(filename=value, table=table, drop=True)
            else:
                if 'drop' not in value:
                    value['drop'] = True
                self.load_shp(table=table, **value)

class TableFrame(object):
    """
    DataFrame-like object for read-only access to a database table.

    TableFrame wraps a SQLAlchemy ORM table for queries using syntax
    similar to key and attribute access on a pandas DataFrame.
    These DataFrame-like operations are supported:

        my_tableframe = TableFrame(table, index_col='gid')
        my_series1 = my_tableframe['col1']
        my_dataframe = my_tableframe[['col1', 'col2']]
        my_series2 = my_tableframe.col2
        num_rows = len(my_tableframe)

    Caching is enabled by default. As columns are queried, they will
    be cached as individual Series objects for future lookups.
    The cache can be emptied by calling the `clear` method.
    Caching can be enabled and disabled with the `cache` parameter or
    by reassigning to the `cache` attribute.

    Unlike a DataFrame, TableFrame is read-only.

    TableFrame instances can be registered as tables in the
    UrbanSim simulation framework using the `sim.add_table` function.

    Parameters
    ----------
    table : sqlalchemy.ext.declarative.DeclarativeMeta
        Table ORM class to wrap.
    index_col : str, optional
        Name of column to use as DataFrame and Series index.
    cache : bool, optional
        Whether to cache columns as they are queried.

    Attributes
    ----------
    cache : bool
        Whether caching is enabled. Can be reassigned to enable/disable.
    columns : list of str
        List of column names in database table.
    index : pandas.Index
        DataFrame and Series index

    """
    def __init__(self, table, index_col=None, cache=True):
        super(TableFrame, self).__init__()
        super(TableFrame, self).__setattr__('_table', table)
        super(TableFrame, self).__setattr__('_index_col', index_col)
        super(TableFrame, self).__setattr__('cache', cache)
        super(TableFrame, self).__setattr__('_cached', {})
        super(TableFrame, self).__setattr__('_index', pd.Index([]))

    @property
    def columns(self):
        return self._table.__table__.columns.keys()

    @property
    def index(self):
        if not self.cache or len(self._index) == 0:
            if self._index_col:
                index_column = getattr(self._table, self._index_col)
                index = db_to_df(index_column,
                                 index_col=self._index_col).index
            else:
                index = pd.Index(range(len(self)))
            super(TableFrame, self).__setattr__('_index', index)
        return self._index

    def clear(self):
        """Clear column cache."""
        self._cached.clear()

    def copy(self):
        """Object is read-only, so the same object is returned."""
        return self

    def __dir__(self):
        """Support IPython tab-completion of column names."""
        return self.__dict__.keys() + self.columns

    def __getitem__(self, key):
        """
        Return column(s) as a pandas Series or DataFrame.

        Like pandas, if the key is an iterable, a DataFrame will be
        returned containing the column(s) named in the iterable.
        Otherwise a Series will be returned.

        """
        # Collect column name(s).
        if hasattr(key, '__iter__') and not isinstance(key, string_types):
            # Argument is list-like. Later return DataFrame.
            return_dataframe = True
            column_names = key
        else:
            # Argument is scalar. Later return Series.
            return_dataframe = False
            column_names = [key]

        if self.cache:
            # Collect cached columns and exclude from query.
            cached = []
            query_columns = []
            for name in column_names:
                if name in self._cached:
                    cached.append(self._cached[name])
                else:
                    query_columns.append(getattr(self._table, name))
        else:
            # Caching disabled, so query all columns.
            query_columns = [getattr(self._table, n) for n in column_names]

        if query_columns:
            # Query uncached columns including column used as index.
            if self._index_col:
                query_columns.append(self._index_col)
            query_df = db_to_df(query_columns, index_col=self._index_col)
            if self.cache:
                # Join queried columns to cached columns.
                df = pd.concat([query_df] + cached, axis=1, copy=False)
                for (column_name, series) in query_df.iteritems():
                    self._cached[column_name] = series
            else:
                # Caching disabled, so no join.
                df = query_df
        else:
            # All columns were cached, so join them.
            df = pd.concat(cached, axis=1, copy=False)

        if return_dataframe:
            # Return DataFrame with specified column order.
            return df.reindex_axis(column_names, axis=1, copy=False)
        else:
            # Return Series.
            return df[key]

    def __getattr__(self, key):
        """Return column as a pandas Series."""
        return self.__getitem__(key)

    def __len__(self):
        """Calculate length from number of rows in database table."""
        with db.session() as sess:
            return sess.query(self._table).count()

    def __setattr__(self, name, value):
        """No attribute assignment, except to enable/disable cache."""
        if name == 'cache':
            super(TableFrame, self).__setattr__('cache', value)
        else:
            raise TypeError("TableFrame is read-only.")

def update_df(df, column, table):
    """
    Add or update column in DataFrame from database table.

    Database table must contain column with the same name as
    DataFrame's index (df.index.name).

    Parameters
    ----------
    df : pandas.DataFrame
        DataFrame to return an updated copy of.
    column : sqlalchemy.orm.attributes.InstrumentedAttribute
        Column ORM object to update DataFrame with.
    table : sqlalchemy.ext.declarative.DeclarativeMeta
        Table ORM class containing columns to update with and index on.

    Returns
    -------
    df : pandas.DataFrame

    """
    # Get table column to use as index based on DataFrame index name.
    index_column = getattr(table, df.index.name)

    # Query index column and column to update DataFrame with.
    with db.session() as sess:
        q = sess.query(index_column, column)

    # Update DataFrame column.
    new_df = db_to_df(q, index_col=df.index.name)
    df[column.name] = new_df[column.name]
    return df

def add_column(table, column_name, type_name, default=None):
    """
    Add column to table.

    Parameters
    ----------
    table : sqlalchemy.ext.declarative.DeclarativeMeta
        Table ORM class to add column to.
    column_name : str
        Name of column to add to table.
    type_name : str
        Name of column type.
    default : str, optional
        Default value for column. Must include quotes if string.

    Returns
    -------
    column : sqlalchemy.orm.attributes.InstrumentedAttribute
        Column ORM object that was added.

    """
    if default:
        default_str = "DEFAULT {}".format(default)
    else:
        default_str = ""

    t = table.__table__
    with db.cursor() as cur:
        cur.execute("""
            ALTER TABLE {schema}.{table}
            ADD COLUMN {column} {type} {default_str};
        """.format(
            schema=t.schema, table=t.name,
            column=column_name, type=type_name, default_str=default_str))
    db.refresh()
    return getattr(table, column_name)

def remove_column(column):
    """Remove column from table."""
    col = column.property.columns[0]
    t = col.table
    with db.cursor() as cur:
        cur.execute("""
            ALTER TABLE {schema}.{table}
            DROP COLUMN {column};
        """.format(schema=t.schema, table=t.name, column=col.name))
    db.refresh()

def exec_sql(query, params=None):
    """Execute SQL query."""
    with db.cursor() as cur:
        cur.execute(query, params)

def db_to_query(orm):
    """Convert table or list of ORM objects to a query."""
    if isinstance(orm, Query):
        # Assume input is Query object.
        return orm
    elif hasattr(orm, '__iter__') and not isinstance(orm, string_types):
        # Assume input is list of ORM objects.
        with db.session() as sess:
            return sess.query(*orm)
    else:
        # Assume input is single ORM object.
        with db.session() as sess:
            return sess.query(orm)

def db_to_db(query, table_name, schema=None, view=False, pk='id'):
    """
    Create a table or view from Query, table, or ORM objects, like columns.

    Do not use to duplicate a table. The new table will not contain
    the same indexes or constraints.

    Parameters
    ----------
    query : sqlalchemy.orm.Query, sqlalchemy.ext.declarative.DeclarativeMeta,
            or iterable
        Query ORM object, table ORM class, or list of ORM objects to query,
        like columns.
    table_name : str
        Name of table or view to create.
    schema : schema class, optional
        Schema of table to create. Defaults to public.
    view : bool, optional
        Whether to create a view instead of a table. Defaults to False.

    Returns
    -------
    None

    """
    if schema:
        schema_name = schema.__name__
    else:
        schema_name = 'public'
    qualified_name = schema_name + "." + table_name

    q = db_to_query(query)

    # Create new table from results of the query.
    with db.session() as sess:
        sess.execute(CreateTableAs(qualified_name, q, view))
        if pk:
            sess.execute("""
                ALTER TABLE {} ADD COLUMN {} serial PRIMARY KEY;
            """.format(qualified_name, pk))
    db.refresh()

def db_to_df(query, index_col=None):
    """
    Return DataFrame from Query, table, or ORM objects, like columns.

    Parameters
    ----------
    query : sqlalchemy.orm.Query, sqlalchemy.ext.declarative.DeclarativeMeta,
            or iterable
        Query ORM object, table ORM class, or list of ORM objects to query,
        like columns.
    index_col : str, optional
        Name of column to use as DataFrame index. If provided, column
        must be contained in query.

    Returns
    -------
    df : pandas.DataFrame

    """
    q = db_to_query(query)

    # Get list of column names.
    entities = q.column_descriptions
    if (len(entities) == 1 and
            isinstance(entities[0]['type'], DeclarativeMeta)):
        # If we query a table, column_descriptions refers to the table itself,
        # not its columns.
        table = q.column_descriptions[0]['type']
        column_names = table.__table__.columns.keys()
    else:
        column_names = [desc['name'] for desc in q.column_descriptions]

    # Convert Query object to DataFrame.
    data = (rec.__dict__ for rec in q.all())
    df = pd.DataFrame.from_records(data, columns=column_names,
                                   coerce_float=True)

    if index_col:
        df.set_index(index_col, inplace=True)
    return df

def df_to_db(df, table_name, schema=None, pk='id'):
    # Does not sanitize DataFrame input. Will fail if values contain
    # the escape character, backslash (\). Binary format COPY would be
    # faster and might be more robust.
    if schema:
        schema_name = schema.__name__
        qualified_name = "{}.{}".format(schema_name, table_name)
    else:
        schema_name = None
        qualified_name = table_name
    df.columns = [s.lower() for s in df.columns]
    empty_df = df.iloc[[0]]
    with db.cursor() as cur:
        empty_df.to_sql(table_name, db._engine, schema=schema_name,
                        index=True, if_exists='replace')
        cur.execute("DELETE FROM {}".format(qualified_name))
        buf = cStringIO()
        df.to_csv(buf, sep='\t', na_rep=r'\N', header=False, index=True)
        buf.seek(0)
        cur.copy_from(buf, qualified_name,
                      columns=tuple([df.index.name] +
                                    df.columns.values.tolist()))
        if pk:
            cur.execute("""
                ALTER TABLE {} ADD COLUMN {} serial PRIMARY KEY;
            """.format(qualified_name, pk))
    db.refresh()

def dbf_to_df(path):
    """
    Return DataFrame from attributes stored in dBase/xBase format.

    Uses OGR's ESRI Shapefile driver to read records from the file.

    Parameters
    ----------
    path : str
        File path to the dBase/xBase file.

    Returns
    -------
    df : pandas.DataFrame

    """
    import ogr

    # Open the file and collect information on fields.
    dbf = ogr.Open(path)
    table = dbf.GetLayer()
    header = table.GetLayerDefn()
    ncolumns = header.GetFieldCount()
    column_names = [header.GetFieldDefn(i).GetName() for i in range(ncolumns)]
    column_types = [header.GetFieldDefn(i).GetType() for i in range(ncolumns)]

    def read(row, i):
        """Return i-th field of a record."""
        # For performance, use the appropriate field type function.
        fld_type = column_types[i]
        if fld_type == ogr.OFTInteger:
            return row.GetFieldAsInteger(i)
        elif fld_type == ogr.OFTReal:
            return row.GetFieldAsDouble(i)
        elif fld_type == ogr.OFTStringList:
            return row.GetFieldAsStringList(i)
        elif fld_type == ogr.OFTIntegerList:
            return row.GetFieldAsIntegerList(i)
        elif fld_type == ogr.OFTRealList:
            return row.GetFieldAsDoubleList(i)
        else:
            return row.GetFieldAsString(i)

    # Represent records with memory-efficient generators.
    values = lambda row: (read(row, i) for i in range(ncolumns))
    records = (values(row) for row in table)

    df = pd.DataFrame.from_records(records, columns=column_names,
                                   coerce_float=False)
    return df

def vacuum(table):
    """
    VACUUM and then ANALYZE table.

    VACUUM reclaims storage from deleted or obselete tuples.
    ANALYZE updates statistics used by the query planner to determine the most
    efficient way to execute a query.

    Parameters
    ----------
    table : sqlalchemy.ext.declarative.DeclarativeMeta
        Table ORM class to vacuum.

    Returns
    -------
    None

    """
    # Vacuum
    t = table.__table__
    with db.connection() as conn:
        assert conn.autocommit is False
        conn.autocommit = True
        try:
            with conn.cursor() as cur:
                cur.execute("VACUUM ANALYZE {schema}.{table};".format(
                    schema=t.schema, table=t.name))
        finally:
            conn.autocommit = False


text:
scalejs.tabs-jqueryui
=====================

Adds boundable tabs (basedon jquery UI) control to scalejs app


text:
using System;
using System.IO;
using System.Text;

namespace Apache.Geode.DUnitFramework
{
  /// <summary>
  /// Class to do logging.
  /// </summary>
  public class UnitLog : IDisposable
  {
    #region Private members

    private string m_file;
    private FileStream m_stream;
    private bool m_append;

    #endregion

    public string File
    {
      get
      {
        return m_file;
      }
      set
      {
        Close();
        m_file = value;
        Init();
      }
    }

    public bool Append
    {
      get
      {
        return m_append;
      }
      set
      {
        m_append = value;
      }
    }

    public UnitLog(string file)
    {
      m_file = file;
      m_stream = null;
      m_append = true;
    }

    public UnitLog(string file, bool append)
    {
      m_file = file;
      m_stream = null;
      m_append = append;
    }

    /// <summary>
    /// Initialize the log file.
    /// </summary>
    private void Init()
    {
      if (m_stream == null)
      {
        try
        {
          string dirName = Path.GetDirectoryName(m_file);
          if (dirName != null && dirName.Length > 0 && !Directory.Exists(dirName))
          {
            Directory.CreateDirectory(dirName);
          }
          m_stream = new FileStream(m_file, (m_append ? FileMode.Append :
            FileMode.Create), FileAccess.Write, FileShare.ReadWrite);
        }
        catch (Exception)
        {
          m_stream = null;
        }
      }
    }

    /// <summary>
    /// Write the given message to the log file with default encoding.
    /// </summary>
    /// <param name="message">The message to write.</param>
    public void Write(string message)
    {
      Write(message, Encoding.Default);
    }

    /// <summary>
    /// Write the given message to the log file with the given encoding.
    /// </summary>
    /// <param name="message">The message to write.</param>
    /// <param name="encoding">The encoding of the message.</param>
    public void Write(string message, Encoding encoding)
    {
      Init();
      if (m_stream != null)
      {
        byte[] messageBytes = encoding.GetBytes(message);
        int numTries = 3;
        while (numTries-- > 0)
        {
          try
          {
            m_stream.Seek(0, SeekOrigin.End);
            m_stream.Write(messageBytes, 0, messageBytes.Length);
            m_stream.Flush();
            break;
          }
          catch
          {
            System.Threading.Thread.Sleep(50);
          }
        }
      }
    }

    /// <summary>
    /// Close the client side log.
    /// </summary>
    private void Close()
    {
      if (m_stream != null)
      {
        try
        {
          m_stream.Close();
        }
        catch
        {
        }
        m_stream = null;
      }
    }

    #region IDisposable Members

    /// <summary>
    /// Disposer closes the log properly.
    /// </summary>
    public void Dispose()
    {
      Close();
      GC.SuppressFinalize(this);
    }

    #endregion

    /// <summary>
    /// Finalizer for the case when the Disposer is not called.
    /// </summary>
    ~UnitLog()
    {
      Close();
    }
  }
}


text:
BookingsyncPortal::Engine.routes.draw do
  namespace :admin do
    resources :rentals, only: [:index, :show]
    resources :connections, only: [:create, :destroy]
    resources :remote_accounts, only: [:new, :create]
    get 'help', to: 'help#index'
    root to: 'rentals#index'
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta name="generator" content="HTML Tidy for Mac OS X (vers 31 October 2006 - Apple Inc. build 15.15), see www.w3.org" />

  <title></title>

Create a Data Loop (only on MarathonITE)

Based on Marathon, Jalian Systems provides a commercial version with extra features and support. You can use MarathonITE and reduce
     the effort required for creating resilient test suites. Use the included extract method refactoring to reuse your test scripts.
     Perform exploratory or semi-automatic testing through MarathonITE and share the test scripts with the development team.

For those cases, where you would like to execute the same steps in a test script for different data, MarathonITE provides a data loop
      refactoring. Using this refactoring, you can convert a set of statements from a test script to execute multiple times while
      accessing the data from a CSV file.

More info:

   Learn more about MarathonITE


text:
module.exports = {
  one: true,
  output: 'dist/' + process.env.REMAX_PLATFORM
};


text:
// Copyright 2010 Google Inc. All Rights Reserved.

package com.crawljax.browser;

import org.junit.Assume;
import org.junit.Before;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.firefox.FirefoxDriver;

import java.io.IOException;

/**
 * This is the base class for WebDriver based Firefox 'Crash' Tests running on Linux only. It's a
 * Linux only implementation because of its 'killall' statement. Caution: This test based on this
 * class will most-likely KILL all your running firefox instances.
 *
 * @version $Id: FirefoxLinuxCrash.java 449 2010-09-16 12:30:19Z slenselink@google.com $
 * @author slenselink@google.com (Stefan Lenselink)
 */
public abstract class FirefoxLinuxCrash {

	private static final int DEFAULT_SLEEP_TIMEOUT = 1000;
	private WebDriver driver;

	private boolean onPosix() {
		Platform current = Platform.getCurrent();
		switch (current) {
			case LINUX:
			case MAC:
			case UNIX:
				return true;
			case ANY:
			case VISTA:
			case WINDOWS:
			case XP:
			case ANDROID:
			default:
				return false;
		}
	}

	/**
     * Start a browser, than kill it hard!
     * @throws InterruptedException
     *             when the Thread.sleep can not be executed.
     */
    @Before
	public void setUp() throws InterruptedException {
		Assume.assumeTrue(onPosix());

		try {
			driver = new FirefoxDriver();
		} catch (WebDriverException e) {
			Assume.assumeNoException(e);
		}

		Assume.assumeNotNull(driver);

    	Thread.sleep(DEFAULT_SLEEP_TIMEOUT);

    	try {
			Runtime.getRuntime().exec("/usr/bin/killall firefox-bin --verbose");
		} catch (IOException e) {
			Assume.assumeNoException(e);
		}

    	Thread.sleep(DEFAULT_SLEEP_TIMEOUT);
    }

    /**
	 * @return the 'crashed'-driver
	 */
	public WebDriver getCrashedDriver() {
		return driver;
	}

}


text:
// Copyright 2017 DAIMTO ([Linda Lawton](https://twitter.com/LindaLawtonDK)) :  [www.daimto.com](http://www.daimto.com/)
//
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by DAIMTO-Google-apis-Sample-generator 1.0.0
//     Template File Name:  methodTemplate.tt
//     Build date: 2017-10-08
//     C# generater version: 1.0.0
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// About
//
// Unoffical sample for the Shoppingcontent v2 API for C#.
// This sample is designed to be used with the Google .Net client library. (https://github.com/google/google-api-dotnet-client)
//
// API Description: Manages product items, inventory, and Merchant Center accounts for Google Shopping.
// API Documentation Link https://developers.google.com/shopping-content
//
// Discovery Doc  https://www.googleapis.com/discovery/v1/apis/Shoppingcontent/v2/rest
//
//------------------------------------------------------------------------------
// Installation
//
// This sample code uses the Google .Net client library (https://github.com/google/google-api-dotnet-client)
//
// NuGet package:
//
// Location: https://www.nuget.org/packages/Google.Apis.Shoppingcontent.v2/
// Install Command: PM>  Install-Package Google.Apis.Shoppingcontent.v2
//
//------------------------------------------------------------------------------
using Google.Apis.Shoppingcontent.v2;
using Google.Apis.Shoppingcontent.v2.Data;
using System;

namespace GoogleSamplecSharpSample.Shoppingcontentv2.Methods
{

    public static class DatafeedsSample
    {

        public class DatafeedsCustombatchOptionalParms
        {
            /// Flag to run the request in dry-run mode.
            public bool? DryRun { get; set; }

        }

        /// <summary>
        /// NA
        /// Documentation https://developers.google.com/shoppingcontent/v2/reference/datafeeds/custombatch
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Shoppingcontent service.</param>
        /// <param name="body">A valid Shoppingcontent v2 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>DatafeedsCustomBatchResponseResponse</returns>
        public static DatafeedsCustomBatchResponse Custombatch(ShoppingcontentService service, DatafeedsCustomBatchRequest body, DatafeedsCustombatchOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (body == null)
                    throw new ArgumentNullException("body");

                // Building the initial request.
                var request = service.Datafeeds.Custombatch(body);

                // Applying optional parameters to the request.
                request = (DatafeedsResource.CustombatchRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Datafeeds.Custombatch failed.", ex);
            }
        }
        public class DatafeedsDeleteOptionalParms
        {
            /// Flag to run the request in dry-run mode.
            public bool? DryRun { get; set; }

        }

        /// <summary>
        /// Deletes a datafeed configuration from your Merchant Center account. This method can only be called for non-multi-client accounts.
        /// Documentation https://developers.google.com/shoppingcontent/v2/reference/datafeeds/delete
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Shoppingcontent service.</param>
        /// <param name="merchantId">NA</param>
        /// <param name="datafeedId">NA</param>
        /// <param name="optional">Optional paramaters.</param>
        public static void Delete(ShoppingcontentService service, string merchantId, string datafeedId, DatafeedsDeleteOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (merchantId == null)
                    throw new ArgumentNullException(merchantId);
                if (datafeedId == null)
                    throw new ArgumentNullException(datafeedId);

                // Building the initial request.
                var request = service.Datafeeds.Delete(merchantId, datafeedId);

                // Applying optional parameters to the request.
                request = (DatafeedsResource.DeleteRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                 request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Datafeeds.Delete failed.", ex);
            }
        }

        /// <summary>
        /// Retrieves a datafeed configuration from your Merchant Center account. This method can only be called for non-multi-client accounts.
        /// Documentation https://developers.google.com/shoppingcontent/v2/reference/datafeeds/get
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Shoppingcontent service.</param>
        /// <param name="merchantId">NA</param>
        /// <param name="datafeedId">NA</param>
        /// <returns>DatafeedResponse</returns>
        public static Datafeed Get(ShoppingcontentService service, string merchantId, string datafeedId)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (merchantId == null)
                    throw new ArgumentNullException(merchantId);
                if (datafeedId == null)
                    throw new ArgumentNullException(datafeedId);

                // Make the request.
                return service.Datafeeds.Get(merchantId, datafeedId).Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Datafeeds.Get failed.", ex);
            }
        }
        public class DatafeedsInsertOptionalParms
        {
            /// Flag to run the request in dry-run mode.
            public bool? DryRun { get; set; }

        }

        /// <summary>
        /// Registers a datafeed configuration with your Merchant Center account. This method can only be called for non-multi-client accounts.
        /// Documentation https://developers.google.com/shoppingcontent/v2/reference/datafeeds/insert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Shoppingcontent service.</param>
        /// <param name="merchantId">NA</param>
        /// <param name="body">A valid Shoppingcontent v2 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>DatafeedResponse</returns>
        public static Datafeed Insert(ShoppingcontentService service, string merchantId, Datafeed body, DatafeedsInsertOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (body == null)
                    throw new ArgumentNullException("body");
                if (merchantId == null)
                    throw new ArgumentNullException(merchantId);

                // Building the initial request.
                var request = service.Datafeeds.Insert(body, merchantId);

                // Applying optional parameters to the request.
                request = (DatafeedsResource.InsertRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Datafeeds.Insert failed.", ex);
            }
        }
        public class DatafeedsListOptionalParms
        {
            /// The maximum number of products to return in the response, used for paging.
            public int? MaxResults { get; set; }
            /// The token returned by the previous request.
            public string PageToken { get; set; }

        }

        /// <summary>
        /// Lists the datafeeds in your Merchant Center account. This method can only be called for non-multi-client accounts.
        /// Documentation https://developers.google.com/shoppingcontent/v2/reference/datafeeds/list
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Shoppingcontent service.</param>
        /// <param name="merchantId">The ID of the managing account.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>DatafeedsListResponseResponse</returns>
        public static DatafeedsListResponse List(ShoppingcontentService service, string merchantId, DatafeedsListOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (merchantId == null)
                    throw new ArgumentNullException(merchantId);

                // Building the initial request.
                var request = service.Datafeeds.List(merchantId);

                // Applying optional parameters to the request.
                request = (DatafeedsResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Datafeeds.List failed.", ex);
            }
        }
        public class DatafeedsPatchOptionalParms
        {
            /// Flag to run the request in dry-run mode.
            public bool? DryRun { get; set; }

        }

        /// <summary>
        /// Updates a datafeed configuration of your Merchant Center account. This method can only be called for non-multi-client accounts. This method supports patch semantics.
        /// Documentation https://developers.google.com/shoppingcontent/v2/reference/datafeeds/patch
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Shoppingcontent service.</param>
        /// <param name="merchantId">NA</param>
        /// <param name="datafeedId">NA</param>
        /// <param name="body">A valid Shoppingcontent v2 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>DatafeedResponse</returns>
        public static Datafeed Patch(ShoppingcontentService service, string merchantId, string datafeedId, Datafeed body, DatafeedsPatchOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (body == null)
                    throw new ArgumentNullException("body");
                if (merchantId == null)
                    throw new ArgumentNullException(merchantId);
                if (datafeedId == null)
                    throw new ArgumentNullException(datafeedId);

                // Building the initial request.
                var request = service.Datafeeds.Patch(body, merchantId, datafeedId);

                // Applying optional parameters to the request.
                request = (DatafeedsResource.PatchRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Datafeeds.Patch failed.", ex);
            }
        }
        public class DatafeedsUpdateOptionalParms
        {
            /// Flag to run the request in dry-run mode.
            public bool? DryRun { get; set; }

        }

        /// <summary>
        /// Updates a datafeed configuration of your Merchant Center account. This method can only be called for non-multi-client accounts.
        /// Documentation https://developers.google.com/shoppingcontent/v2/reference/datafeeds/update
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Shoppingcontent service.</param>
        /// <param name="merchantId">NA</param>
        /// <param name="datafeedId">NA</param>
        /// <param name="body">A valid Shoppingcontent v2 body.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>DatafeedResponse</returns>
        public static Datafeed Update(ShoppingcontentService service, string merchantId, string datafeedId, Datafeed body, DatafeedsUpdateOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (body == null)
                    throw new ArgumentNullException("body");
                if (merchantId == null)
                    throw new ArgumentNullException(merchantId);
                if (datafeedId == null)
                    throw new ArgumentNullException(datafeedId);

                // Building the initial request.
                var request = service.Datafeeds.Update(body, merchantId, datafeedId);

                // Applying optional parameters to the request.
                request = (DatafeedsResource.UpdateRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Datafeeds.Update failed.", ex);
            }
        }

        }

        public static class SampleHelpers
        {

        /// <summary>
        /// Using reflection to apply optional parameters to the request.
        ///
        /// If the optonal parameters are null then we will just return the request as is.
        /// </summary>
        /// <param name="request">The request. </param>
        /// <param name="optional">The optional parameters. </param>
        /// <returns></returns>
        public static object ApplyOptionalParms(object request, object optional)
        {
            if (optional == null)
                return request;

            System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();

            foreach (System.Reflection.PropertyInfo property in optionalProperties)
            {
                // Copy value from optional parms to the request.  They should have the same names and datatypes.
                System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
				if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
					piShared.SetValue(request, property.GetValue(optional, null), null);
            }

            return request;
        }
    }
}


text:
@class PSPDFPageInfo, PSPDFAnnotation;

// PDF rendering options.
extern NSString *const kPSPDFPageColor;               // Multiplies a color used to color a page.
extern NSString *const kPSPDFContentOpacity;          // Opacity of the pdf content can be adjusted.
extern NSString *const kPSPDFInvertRendering;         // Inverts the rendering output. Default is NO.
extern NSString *const kPSPDFInterpolationQuality;    // Set custom interpolation quality. Defaults to kCGInterpolationHigh.
extern NSString *const kPSPDFDisablePageRendering;    // Set to YES to NOT draw page content. (Use to just draw an annotation)
extern NSString *const kPSPDFRenderOverlayAnnotations;// Set to YES to render annotations that have isOverlay = YES set.
extern NSString *const kPSPDFIgnorePageClip;          // If YES, will draw outside of page area.
extern NSString *const kPSPDFAllowAntiAliasing;       // Enabled/Disables antialiasing. Defaults to YES.
extern NSString *const kPSPDFBackgroundFillColor;     // Allows custom render color. Default is white.
extern NSString *const kPSPDFPDFBox;                  // Allows custom PDF box (if pageInfo is nil)

// Can be used to use a custom subclass of the PSPDFPageRenderer. Defaults to nil, which will use PSPDFPageRenderer.class.
// Set very early (in your AppDelegate) before you access PSPDFKit. Will be used to create the singleton.
extern Class PSPDFPageRendererClass;

/// PDF rendering code.
@interface PSPDFPageRenderer : NSObject

/// Access the style manager singleton.
+ (instancetype)sharedPageRenderer;

/// Setup the graphics context to the current PDF.
- (void)setupGraphicsContext:(CGContextRef)context inRectangle:(CGRect)displayRectangle pageInfo:(PSPDFPageInfo *)pageInfo;

/// Renders a page inside a rectangle. Set context CTM and ClipRect to control rendering.
/// Returns the renderingRectangle.
- (CGRect)renderPageRef:(CGPDFPageRef)page inContext:(CGContextRef)context inRectangle:(CGRect)rectangle pageInfo:(PSPDFPageInfo *)pageInfo withAnnotations:(NSArray *)annotations options:(NSDictionary *)options;

/// Render a page; defined by point and zoom. Use zoom=100 and point = CGPointMake(0, 0) for defaults.
- (CGSize)renderPage:(CGPDFPageRef)page inContext:(CGContextRef)context atPoint:(CGPoint)point withZoom:(double)zoom pageInfo:(PSPDFPageInfo *)pageInfo withAnnotations:(NSArray *)annotations options:(NSDictionary *)options;

/// Renders a particular appearance stream (A PDF within a PDF) into a context.
/// Will return NO if rendering failed.
- (BOOL)renderAppearanceStream:(PSPDFAnnotation *)annotation inContext:(CGContextRef)context error:(NSError **)error;

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Öst. bot. Z. 70: 91 (1921)

#### Original name
Cephalosporium herpetiforme Lingelsh.

### Remarks
null


text:
package com.esri.core.geometry;

//This is a stub
class OperatorProjectLocal extends OperatorProject {

	@Override
	public GeometryCursor execute(GeometryCursor inputGeoms,
			ProjectionTransformation transform, ProgressTracker progressTracker) {
		throw new GeometryException("not implemented");
	}

	public Geometry execute(Geometry inputGeom,
			ProjectionTransformation transform, ProgressTracker progressTracker) {
		throw new GeometryException("not implemented");
	}

	@Override
	public int transform(ProjectionTransformation transform, Point[] pointsIn,
			int count, Point[] pointsOut) {
		throw new GeometryException("not implemented");
	}

	public double[] transform(ProjectionTransformation transform,
			double[] coordsSrc, int pointCount) {
		throw new GeometryException("not implemented");
	}

}


text:
package liquibase.statement.core;

import liquibase.statement.AbstractSqlStatement;

public class CreateIndexStatement extends AbstractSqlStatement {

    private String tableCatalogName;
    private String tableSchemaName;
    private String indexName;
    private String tableName;
    private String[] columns;
    private String tablespace;
    private Boolean unique;
	// Contain associations of index
	// for example: foreignKey, primaryKey or uniqueConstraint
	private String associatedWith;

    public CreateIndexStatement(String indexName, String tableCatalogName, String tableSchemaName, String tableName, Boolean isUnique, String associatedWith, String... columns) {
        this.indexName = indexName;
        this.tableCatalogName = tableCatalogName;
        this.tableSchemaName = tableSchemaName;
        this.tableName = tableName;
        this.columns = columns;
        this.unique = isUnique;
	    this.associatedWith = associatedWith;
    }

    public String getTableCatalogName() {
        return tableCatalogName;
    }

    public String getTableSchemaName() {
        return tableSchemaName;
    }

    public String getIndexName() {
        return indexName;
    }

    public String getTableName() {
        return tableName;
    }

    public String[] getColumns() {
        return columns;
    }

    public String getTablespace() {
        return tablespace;
    }

    public CreateIndexStatement setTablespace(String tablespace) {
        this.tablespace = tablespace;

        return this;
    }

    public Boolean isUnique() {
        return unique;
    }

	public String getAssociatedWith() {
		return associatedWith;
	}

	public void setAssociatedWith(String associatedWith) {
		this.associatedWith = associatedWith;
	}
}


text:
#pragma once

#include <QFrame>
#include "Code/Interface/QRDInterface.h"

class PythonContext;
class ScintillaEdit;
class QTextEdit;

namespace Ui
{
class PythonShell;
}

struct CaptureContextInvoker;

class PythonShell : public QFrame, public IPythonShell
{
  Q_OBJECT

public:
  explicit PythonShell(ICaptureContext &ctx, QWidget *parent = 0);

  ~PythonShell();

  // for UI-forwarding helper classes
  PythonContext *GetScriptContext();

  // IPythonShell
  QWidget *Widget() override { return this; }
private slots:
  // automatic slots
  void on_execute_clicked();
  void on_clear_clicked();
  void on_newScript_clicked();
  void on_openScript_clicked();
  void on_saveScript_clicked();
  void on_runScript_clicked();
  void on_abortRun_clicked();

  // manual slots
  void interactive_keypress(QKeyEvent *e);
  void helpSearch_keypress(QKeyEvent *e);
  void traceLine(const QString &file, int line);
  void exception(const QString &type, const QString &value, int finalLine, QList<QString> frames);
  void textOutput(bool isStdError, const QString &output);
  void editor_contextMenu(const QPoint &pos);

private:
  Ui::PythonShell *ui;
  ICaptureContext &m_Ctx;
  CaptureContextInvoker *m_ThreadCtx = NULL;

  ScintillaEdit *scriptEditor;

  static const int CURRENT_MARKER = 0;

  PythonContext *interactiveContext, *scriptContext;

  QList<QString> history;
  int historyidx = -1;

  QString m_storedLines;

  QString getDottedWordAtPoint(int scintillaPos);

  PythonContext *newContext();
  PythonContext *newImportedDummyContext();
  void setGlobals(PythonContext *ret);

  void startAutocomplete();
  void selectedHelp(QString word);
  void refreshCurrentHelp();

  QString scriptHeader();
  void appendText(QTextEdit *output, const QString &text);
  void enableButtons(bool enable);
};


text:
<?php

namespace Ojs\LocationBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class OjsLocationBundle extends Bundle
{
}


text:
/*
 * Datentypen.c
 * Einschränkungen der Verschiedenen Datentypen
 *  Created on: 17 Oct 2017
 *      Author: brauni
 */

#include <stdio.h>

int main(void) {
	setbuf(stdout, NULL); // Damit die Eclipse-Konsole funktioniert
	char buchstabe = 'x';
	unsigned short kurze_zahl = 100;
	printf("Ausgabe des Buchstaben 'x' in verschiedenen Formaten: \n");
	printf("%c\n", buchstabe);
	printf("%d\n", buchstabe);
	printf("Ausgabe der Zahl 100 in verschiedenen Formaten: \n");
	printf("dezimal: ");
	printf("%d\n", kurze_zahl);
	printf("hexadezimal: ");
	printf("%x\n", kurze_zahl);
	printf("oktal: ");
	printf("%o\n", kurze_zahl);
	kurze_zahl = -100;
	printf("Ausgabe von - 100: ");
	printf("%d\n", kurze_zahl);  //Fehler da unasigned short nur positiv sein kann
	return 0;
}


text:
layout: default
title: Red Wine Vinaigrette
---


text:
layout: page
title: Sub Foundation Award Ceremony
date: 2016-05-24
author: Robert Mccarty
tags: weekly links, java
status: published
summary: Suspendisse eget ultrices elit. Pellentesque euismod varius ipsum, sit.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 02/27/2019
  endDate: 03/04/2019
  ctyhocn: CSNHSHX
  groupCode: SFAC
published: true
---
Sed risus enim, lobortis a neque sit amet, rutrum pellentesque libero. Maecenas sit amet massa dapibus, rhoncus felis ut, aliquet erat. Quisque eu molestie metus. Nullam eget lorem mattis, placerat nibh ac, rhoncus magna. Sed erat enim, bibendum nec facilisis eget, gravida vel erat. Nulla a leo interdum, euismod est id, semper odio. Aliquam et metus in lacus semper dictum non eu leo. Nunc interdum magna nec arcu ultrices placerat. Etiam ac molestie neque. Aenean non gravida libero, ac feugiat turpis. Fusce sollicitudin turpis quis lacus placerat commodo. Vestibulum suscipit libero vel ultrices porttitor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lobortis enim tellus, porta egestas nisl facilisis ac.

1 Donec vel velit ut nunc mollis malesuada vitae nec nunc
1 Curabitur dignissim dui quis augue ultrices efficitur
1 Nunc quis sapien lobortis, pulvinar arcu vitae, commodo ipsum
1 Vivamus vitae velit finibus, imperdiet turpis et, pharetra ipsum
1 Vivamus dignissim risus eu sem blandit tincidunt
1 Pellentesque eu est id nibh dignissim commodo ut eu metus.

Praesent at lectus orci. Nulla mattis, leo porttitor malesuada rhoncus, dui augue eleifend quam, id ultrices risus justo id enim. Nulla sed neque nec elit vehicula pretium at sit amet tellus. Praesent gravida maximus risus et congue. Cras ultricies massa eget sem semper dignissim. Vivamus finibus imperdiet augue, nec consequat erat mattis id. Nunc ut blandit ante.


text:
'use strict';

describe('AdminScriptEditor', function() {
    beforeEach(function() {
        module('sovi.controllers');
    });

    it('should have correct editor defaults', inject(function($controller) {
        var scope = {};
        $controller('AdminScriptEditor', { $scope: scope });
        expect(scope.currentTheme).toBe('Monokai');
    }));
});


text:
import json
import os

DEBUG = False

SLEEP_TIME_SECONDS = 60
MAX_PROCASTINATION_TIME_DAY_MIN = 120

SHOW_NOTIFICATION = True
NOTIFICATION_INTERVAL_MIN = 10

DB_NAME = os.environ.get('DB_NAME', 'procastimeter')
DB_USER = os.environ.get('DB_USER', 'root')
DB_PASSWORD = os.environ.get('DB_PASSWORD', '')

BROWSER_APP_NAME = os.environ.get('BROWSER_APP_NAME', 'Google Chrome')


text:
<?php

/*
 * wrinche. Modern, powerful and user friendly CMS.
 * Connection model. Manages database connections.
 * Version: 0.1.5
 * Authors: lamka02sk
 */

namespace App\Models;

use App\Helpers\Config;

class ConnectionsModel extends MainModel {

    private $host,
            $database,
            $user,
            $pass;

    public $connections = [];

    public function start() {

        // Load current connections file
        $this->loadConnections();

        return $this;

    }

    private function loadConnections() {

        new Config('database');
        $this->connections = Config::$file['database'];

    }

    public function setConnection($host, $database, $user, $pass) {

        $this->host = $host;
        $this->database = $database;
        $this->user = $user;
        $this->pass = $pass;

        return $this;

    }

    public function getConnection() {

        return [
            $this->host, $this->database, $this->user, $this->pass
        ];

    }

    public function addConnection() {

        // If isset Default Connection, create another one
        if(isset($this->connections["default"]) && !empty($this->connections["default"])) {

            $this->connections[] = [
                "host" => $this->host,
                "database" => $this->database,
                "user" => $this->user,
                "pass" => $this->pass
            ];

        } else {

            $this->connections["default"] = [
                "host" => $this->host,
                "database" => $this->database,
                "user" => $this->user,
                "pass" => $this->pass
            ];

        }

        return $this;

    }

    public function saveConnections() {

        $json = json_encode($this->connections);
        file_put_contents(ROOT . '/app/Config/database.json', $json, LOCK_EX);

        return $this;

    }

}


text:
'''
LNDB.py
Handles all LNDB information
'''

import difflib

import aiohttp
from pyquery import PyQuery as pq

session = aiohttp.ClientSession()

async def getLightNovelURL(searchText):
    try:
        searchText = searchText.replace(' ', '+')
        async with session.get('http://lndb.info/search?text=' + searchText,
                               timeout=10) as resp:
            html = await resp.text()

        lndb = pq(html)

        lnList = []

        if 'light_novel' in html.url:
            # we've immediately hit a result
            return html.url
        else:
            # scan the search page for stuff

            lnList = []

            for thing in lndb.find('#bodylightnovelscontentid table tr'):
                title = pq(thing).find('a').text()
                url = pq(thing).find('a').attr('href')

                if title:
                    data = {'title': title,
                            'url': url}
                    lnList.append(data)

            closest = findClosestLightNovel(searchText, lnList)
            return closest['url']

    except Exception as e:
        return None

def findClosestLightNovel(searchText, lnList):
    try:
        nameList = []

        for ln in lnList:
            nameList.append(ln['title'].lower())

        closestNameFromList = difflib.get_close_matches(searchText.lower(),
                                                        nameList, 1, 0.80)

        for ln in lnList:
            if ln['title'].lower() == closestNameFromList[0].lower():
                return ln

        return None
    except:
        return None

def getLightNovelById(lnId):
    return 'http://lndb.info/light_novel/' + str(lnId)