text:
var QueryBase = function() {
};

QueryBase.prototype = new SSBase();

QueryBase.prototype._drawTable = function(id, columns, data) {
    if (columns == null || columns.length == 0) {
        return;
    }
    if (data == null) {
        return;
    }

    var column_defs = [];
    var column_names = [];

    var max_col = columns.length;
    if (max_col > SQLShare.Constants.MAX_PREVIEW_COLS) {
        max_col = SQLShare.Constants.MAX_PREVIEW_COLS;
        Solstice.Message.setInfo(Solstice.Lang.getMessage('SQLShare', 'max_preview_cols_exceeded', {
            shown: SQLShare.Constants.MAX_PREVIEW_COLS,
            total: columns.length
        }));
    }

    var column_keys = [];
    for (var i = 0; i < max_col; i++) {
        column_keys[i] = 'col_'+i;
        column_defs.push({
            key: column_keys[i], label: columns[i], sortable: false, resizeable: true
        });
    }

    var structured = [];
    for (var i = 0; i < data.length; i++) {
        var row_data = {};
        var row = data[i];
        for (var j = 0; j < row.length; j++) {
            row_data[column_keys[j]] = row[j];
        }
        structured.push(row_data);
    }

    var data_source = new YAHOO.util.DataSource(structured);
    data_source.responseType =  YAHOO.util.DataSource.TYPE_JSARRAY;
    data_source.responseSchema = {
        fields: column_keys
    };

    var options = {};
    if (data.length > 20) {
        options.paginator =  new YAHOO.widget.Paginator({ rowsPerPage : 20});
    }

    options.renderLoopSize = 1;

    var data_table = new YAHOO.widget.ScrollingDataTable(id, column_defs, data_source, options);
};

QueryBase.prototype._downloadFile = function(query, error_callback) {
    this._createNewIFrame();
    var iframe = this._getDownloadIFrame();
    YAHOO.util.Event.removeListener(iframe, "load");
    if (error_callback) {
        YAHOO.util.Event.addListener(iframe, "load", error_callback, this, true);
    }
    var download_url = this._getDownloadURL(query);
    iframe.location.href = download_url;
};

QueryBase.prototype._getDownloadError = function() {
    var iframe = this._getDownloadIFrame();
    return iframe.document.body;
};

QueryBase.prototype._createNewIFrame = function() {
    var iframe_name = 'query_download_iframe_'+(new Date()).getTime();
    try {
        new_iframe = document.createElement('<iframe name="'+iframe_name+'">');
        new_iframe.style.display = 'none';
    }
    catch (e) {
        new_iframe = document.createElement('iframe');
        new_iframe.setAttribute('name', iframe_name);
        new_iframe.style.width  = '1px';
        new_iframe.style.height = '1px';
        new_iframe.style.border = '0px';
        new_iframe.style.left = '-1000px';
        new_iframe.style.position = 'absolute';
    }
    new_iframe.setAttribute('src', Solstice.getDocumentBase() + '/content/blank.html');
    new_iframe.setAttribute('tabindex', '-1');
    document.getElementById('solstice_app_form').appendChild(new_iframe);

    iframe = window[iframe_name];

    this._current_iframe = iframe;
};

QueryBase.prototype._getDownloadIFrame = function() {
    var iframe = this._current_iframe;

    return iframe;
};

QueryBase.prototype._highlightName = function(ev) {
    YAHOO.util.Dom.addClass(this.id+"_name_container", "hover");
};

QueryBase.prototype._removeNameHighlight = function(ev) {
    YAHOO.util.Dom.removeClass(this.id+"_name_container", "hover");
};

QueryBase.prototype._resetNameContainer = function() {
    // This is to prevent table renaming until we sort out behavior post release 1
    return;
    YAHOO.util.Dom.removeClass(this.id+"_name_container", "hover");
    YAHOO.util.Dom.removeClass(this.id+"_name", "error_input");
    Solstice.Element.hide(this.id+'_name_required');
    YAHOO.util.Event.addListener(this.id+'_name_container', "mouseover", this._highlightName, this, true);
    YAHOO.util.Event.addListener(this.id+'_name_container', "mouseout", this._removeNameHighlight, this, true);
    YAHOO.util.Event.addListener(this.id+'_name_container', "click", this._openNameDialog, this, true);

};

QueryBase.prototype._openNameDialog = function(ev) {
    var query = this._model;
    YAHOO.util.Event.removeListener(this.id+'_name_container', "mouseover");
    YAHOO.util.Event.removeListener(this.id+'_name_container', "mouseout");
    YAHOO.util.Event.removeListener(this.id+'_name_container', "click");

    this._renderTo(this.id+'_name_container', this._getRenameView());

    YAHOO.util.Event.addListener(this.id+'_save_name', "click", this._beginNameSave, this, true);
    YAHOO.util.Event.addListener(this.id+'_cancel_name', "click", this._cancelNameSave, this, true);

};

QueryBase.prototype._cancelNameSave = function(ev) {
    YAHOO.util.Event.stopEvent(ev);
    var container = document.getElementById(this.id+'_name_container');

    var obj_name = this._getObjectName();
    container.innerHTML = obj_name.encodeHTML();

    this._resetNameContainer();
};

QueryBase.prototype._beginNameSave = function(ev) {
    var new_name = document.getElementById(this.id+'_name').value;

    Solstice.Element.hide(this.id+'_name_required');
    YAHOO.util.Dom.removeClass(this.id+"_name", "error_input");

    if (!new_name.match(/[\w]/)) {
        Solstice.Element.show(this.id+'_name_required');
        YAHOO.util.Dom.addClass(this.id+"_name", "error_input");
        return;
    }

    if (new_name == this._getObjectName()) {
        this._cancelNameSave(ev);
        return;
    }
_
    // Temporary approach to get around .net bug w/ encode ? in url components
    new_name = new_name.replace(/\?/g, '');
    this._new_name = new_name;

    this.AsyncGET(this._getRestRoot()+"/proxy/REST.svc/v2/db/"+this._getObjectType()+"/"+this._model.owner+'/'+new_name, this._postNameCheck);

};

QueryBase.prototype._postNameCheck = function(o) {
    if (o.code == 200) {
        if (!this._overwrite_panel) {
            var overwrite_panel = new YAHOO.widget.Panel(this.id+"_overwrite_panel", { visible: false, width: "500px", fixedcenter:true, draggable: false, modal: true });
            overwrite_panel.setBody("");
            overwrite_panel.setHeader("");
            overwrite_panel.render(document.body);
            Solstice.Element.show(this.id+"_overwrite_panel");
            this._overwrite_panel = overwrite_panel;
        }
        this._overwrite_panel.show();
        this._renderTo(this.id+'_overwrite_panel', 'saved_query/overwrite_panel.html', { id: this.id });

        YAHOO.util.Event.addListener(this.id+'_replace_table', "click", this._replaceTable, this, true);
        YAHOO.util.Event.addListener(this.id+'_cancel_replace', "click", this._cancelReplace, this, true);
    }
    else {
        this._saveNewName();
    }
};

QueryBase.prototype._cancelReplace = function() {
    this._overwrite_panel.hide();
};

QueryBase.prototype._replaceTable = function() {
    this._saveNewName();
    this._overwrite_panel.hide();
};

QueryBase.prototype._saveNewName = function() {
    var original_name = this._getObjectName();
    this._setObjectName(this._new_name);
    var name = this._getObjectName();
    this._new_name = null;
    this.AsyncPOST(this._getRestRoot()+"/proxy/REST.svc/v2/db/"+this._getObjectType()+"/"+this._model.owner+"/"+name, this._model, this._postSaveName);
}

QueryBase.prototype._postSaveName = function(o) {
    var obj_type = this._getObjectType();
    if (o.code == 201) {
        var owner = this._model.owner;
        var name = this._model.name;

        YAHOO.util.History.navigate('s', obj_type+'/'+owner+'/'+name);
        Solstice.Message.setSuccess(Solstice.Lang.getMessage('SQLShare', obj_type+'_renamed'));
    }
    else {
        Solstice.Message.setError(Solstice.Lang.getMessage('SQLShare', obj_type+'_rename_failed'));
        if (window.console) {
            window.console.log(o);
        }
    }
};

QueryBase.prototype._resetDescriptionContainer = function() {
    if (!document.getElementById("js-description-container")) {
        return;
    }

    var view = new SQLShare.View.SavedQuery.DescriptionArea(this._model);
    document.getElementById('js-description-container').innerHTML = view.toString();
    view.postRender();

    YAHOO.util.Dom.removeClass(this.id+"_description_container", "hover");
    YAHOO.util.Event.addListener(this.id+'_description_container', "mouseover", this._highlightDescription, this, true);
    YAHOO.util.Event.addListener(this.id+'_description_container', "mouseout", this._removeDescriptionHighlight, this, true);
    YAHOO.util.Event.addListener(this.id+'_description_container', "click", this._openDescriptionDialog, this, true);

    Solstice.YahooUI.PopIn.lower('edit_description_tags');
};

QueryBase.prototype._highlightDescription = function(ev) {
    YAHOO.util.Dom.addClass(this.id+"_description_container", "hover");
};

QueryBase.prototype._removeDescriptionHighlight = function(ev) {
    YAHOO.util.Dom.removeClass(this.id+"_description_container", "hover");
};

QueryBase.prototype._openDescriptionDialog = function(ev) {
    var query = this._model;
    YAHOO.util.Event.removeListener(this.id+'_description_container', "mouseover");
    YAHOO.util.Event.removeListener(this.id+'_description_container', "mouseout");
    YAHOO.util.Event.removeListener(this.id+'_description_container', "click");

    var popin = Solstice.YahooUI.PopIn.init('edit_description_tags', true);
    popin.cfg.setProperty('width', '640px');

    popin.setHeader(Solstice.Lang.getString('SQLShare', 'edit_dataset_description_tags'));

    var view = this._getChangeDescriptionView();
    var body = view.toString();

    this._removeDescriptionHighlight();
    popin.setBody(body);
    popin.show();
    view.postRender();

    this._buildTagger();

    this._description_popin = popin;

    YAHOO.util.Event.addListener(this.id+'_save_description', "click", this._beginDescriptionSave, this, true);
    YAHOO.util.Event.addListener(this.id+'_cancel_description', "click", this._cancelDescriptionSave, this, true);
};

QueryBase.prototype._buildTagger = function() {
    var is_dataset_owner = false;
    if (this._model.owner == solstice_user.login_name) {
        is_dataset_owner = true;
    }

    var raw_tags = this._model.tags;

    var tag_hash = {};
    for (var pc = 0; pc < raw_tags.length; pc++) {
        var person_tags = raw_tags[pc].tags;
        var owner = raw_tags[pc].name;

        var view_only = true;
        if (owner == solstice_user.login_name || is_dataset_owner) {
            view_only = false;
        }

        for (var t = 0; t < person_tags.length; t++) {
            tag_hash[person_tags[t]] = {
                view_only: view_only
            };

        }
    }

    var tag_set = SQLShare._ALL_TAGS || {};
    var datasource = [];
    for (tag in tag_set) {
        datasource.push(tag);
    }

    var me = this;
    YUI().use('tagger', function(Y) {
        var tags = new Y.Tagger('tag_container', {
            tags: tag_hash,
            datasource: datasource
        });
        tags.initialize();
        me._tagger = tags;
    });

};

QueryBase.prototype._cancelDescriptionSave = function(ev) {
    YAHOO.util.Event.stopEvent(ev);
    var container = document.getElementById(this.id+'_description_container');

    var obj_name = this._getObjectDescription();
    container.innerHTML = obj_name.encodeHTML();

    this._resetDescriptionContainer();
};

QueryBase.prototype._beginDescriptionSave = function(ev) {
    if (this._model.owner == solstice_user.login_name) {
        var new_description = document.getElementById(this.id+'_description').value;

        if (new_description == this._getObjectDescription()) {
            this._saveTags();
            return;
        }

        this._setObjectDescription(new_description);

        var container = document.getElementById(this.id+'_description_container');
        container.innerHTML = new_description.encodeHTML();
        this.AsyncPUT(this._getRestRoot()+"/proxy/REST.svc/v2/db/"+this._getURIFragment(), this._model, this._saveTags);
    }
    else {
        this._saveTags();
    }
};

QueryBase.prototype._saveTags = function(o) {
    var data = this._getNewTagData();

    if (data.is_changed) {
        this.AsyncPUT(this._getRestRoot()+"/proxy/REST.svc/v2/db/"+this._getURIFragment()+"/tags", data.tags, this._postSaveDescription, data.tags);
    }
    else {
        return this._postSaveDescription({ code: 200 }, data.tags);
    }

};

QueryBase.prototype._postSaveDescription = function(o, tags) {
    if (o.code == 200) {
        this._model.tags = tags;
        (new SQLShare()).drawSidebarLists();
    }
    this._resetDescriptionContainer();
};

QueryBase.prototype._togglePublic = function() {
    this._model.is_public = !this._model.is_public;
    this.AsyncPUT(this._getRestRoot()+"/proxy/REST.svc/v2/db/"+this._getURIFragment(), this._model, this._postTogglePublic);

    this._renderTo(this.id+'_is_public', 'table/toggling_public.html', {});
};

QueryBase.prototype._postTogglePublic = function(o) {
    // override in subclasses...
}

QueryBase.prototype._processQuery = function() {
    this.abortCurrentRequest();
    var query = this._editor.getCode();
    Solstice.Element.show('new_query_preview_panel');
    Solstice.Element.hide('dataset_preview_header');

    SQLShare.onChangeContent.fire();

    this._renderTo(this.id+"_results", 'query/running.html', {});
    // Should this be configurable anywhere?
    var max_rows = SQLShare.Constants.MAX_PREVIEW_ROWS;
    this.setCurrentRequest(this.AsyncPOST(this._getRestRoot()+"/proxy/REST.svc/v2/db", { sql: query, max_records: max_rows, sleep: 0 }, this._postQuery));
};

QueryBase.prototype._postQuery = function(o) {
    if (o.code == 202) {
        var new_location = o.conn.getResponseHeader['Location'];
        var full_url = new_location;
        this._full_url = full_url;
        this.AsyncGET(full_url, this._postInitialRedirect);
    }
    else {
        var error;
        if (o.data) {
            error = Solstice.String.encodeHTML(o.data.error);
        }
        if (o.code == 414) {
            error = Solstice.Lang.getString('SQLShare', 'error_query_too_long');
        }
        if (error == "") {
            error = Solstice.Lang.getString('SQLShare', 'error_query_generic');
        }
        this._renderTo(this.id+"_results", "query/error.html", { error: error });
    }
};

QueryBase.prototype._postInitialRedirect = function(o) {
    var query = this;
    var full_url = this._full_url;
    if (o.code == 202) {
        this.setResultsTimeout(window.setTimeout(function() { query._waitForQueryResults(full_url, 1) }, 2000));
    }
    else if (o.code == 200) {
        this._finishQuery(o.data);
    }
    else {
        if (o.data) {
            error = Solstice.String.encodeHTML(o.data.error);
        }
        if (o.code == 414) {
            error = Solstice.Lang.getString('SQLShare', 'error_query_too_long');
        }
        if (error == "") {
            error = Solstice.Lang.getString('SQLShare', 'error_query_generic');
        }
        this._renderTo(this.id+"_results", "query/error.html", { error: error });
    }

}

QueryBase.prototype._waitForQueryResults = function(full_url, count) {
    this.AsyncGET(full_url, this._postWaitForQueryResults, { count: count });
};

QueryBase.prototype._cancelQuery = function(ev) {
    var matches = this._full_url.match(/([0-9]+)$/);
    var process_id = matches[0];

    this.AsyncDELETE(this._getRestRoot()+'/proxy/REST.svc/v2/db/process/'+process_id, this._postDelete);
};

QueryBase.prototype._postDelete = function(o) {
    if (o.code == 410) {
        this.clearResultsTimeout();
        Solstice.Element.hide('new_query_preview_panel');

        Solstice.Message.setSuccess(Solstice.Lang.getMessage('SQLShare', 'queued_query_cancelled'));
    }
};

QueryBase.prototype._postWaitForQueryResults = function(o, args) {
    var count = args.count;
    if (count == 1) {
        Solstice.Element.show('query_in_queue');
        YAHOO.util.Event.addListener('cancel_query', "click", this._cancelQuery, this, true);
    }
    var full_url = this._full_url;
    if (o.code == 202) {
        var query = this;
         this.setResultsTimeout(window.setTimeout(function() { query._waitForQueryResults(full_url, count + 1) }, 5000));
    }
    else if (o.code == 200) {
        this._finishQuery(o.data);
    }
    else {
        var error;
        if (o.data) {
            error = Solstice.String.encodeHTML(o.data.error);
        }
        if (o.code == 414) {
            error = Solstice.Lang.getString('SQLShare', 'error_query_too_long');
        }
        if (error == "") {
            error = Solstice.Lang.getString('SQLShare', 'error_query_generic');
        }
        this._renderTo(this.id+"_results", "query/error.html", { error: error });
    }
};

QueryBase.prototype._finishQuery = function(data) {
    var header = document.getElementById('dataset_preview_header');
    if (header) {
        document.getElementById('preview_total_rows').innerHTML = data.rows_total;
        if (data.rows_total < SQLShare.Constants.MAX_PREVIEW_ROWS) {
            document.getElementById('preview_max_rows').innerHTML = data.rows_total;
        }
        else {
            document.getElementById('preview_max_rows').innerHTML = SQLShare.Constants.MAX_PREVIEW_ROWS;
            document.getElementById('preview_total_rows').innerHTML = Solstice.Lang.getString('SQLShare', 'preview_found_max_hits', { max: SQLShare.Constants.MAX_PREVIEW_ROWS });
        }
        var column_count = data.columns.length;
        document.getElementById('preview_total_cols').innerHTML = column_count;
        if (column_count < SQLShare.Constants.MAX_PREVIEW_COLS) {
            document.getElementById('preview_max_cols').innerHTML = column_count;
        }
        else {
            document.getElementById('preview_max_cols').innerHTML = SQLShare.Constants.MAX_PREVIEW_COLS;
        }

        Solstice.Element.show('dataset_preview_header');
    }

    var cols = [];
    var len = data.columns.length;
    for (var i = 0; i < len; i++) {
        cols.push(data.columns[i].name);
    }

    this._drawTable(this.id+"_results", cols, data.sample_data);
};

QueryBase.prototype._saveQueryAs = function() {
    var popin = Solstice.YahooUI.PopIn.init('save_query_as', true);
    popin.cfg.setProperty('width', '440px');

    popin.setHeader(Solstice.Lang.getString('SQLShare', 'save_query_title'));

    var description;
    var name;
    var is_public;
    if (this._model) {
        description = this._model.description;
        name = this._model.name;
        is_public = this._model.is_public;
    }
    var view = new SQLShare.View.Query.SavePanel({
        id: this.id,
        description: description,
        name: name,
        is_public: is_public
    });

    popin.setBody(view.toString());
    popin.show();
    view.postRender();
    this._save_panel_view = view;

    YAHOO.util.Event.addListener(this.id+'_save', "click", this._save, this, true);
    YAHOO.util.Event.addListener(this.id+'_cancel', "click", this._cancelSaveAs, this, true);
};

QueryBase.prototype._cancelSaveAs = function(ev) {
    if (ev) {
        YAHOO.util.Event.stopEvent(ev);
    }
    var popin = Solstice.YahooUI.PopIn.get('save_query_as');
    popin.hide();
};

QueryBase.prototype._save = function() {
    var name = document.getElementById(this.id+"_query_name").value;
    var description = document.getElementById(this.id+"_query_desc").value;

    if (name.match(/[^a-z0-9!@$%^&\*\(\)_\-={}\|;:'",\.<> ]/i)) {
        Solstice.Element.show(this.id+"_query_name_error");
        return;
    }

    var is_public = false;
    if (document.getElementById(this.id+"_is_public_check").checked) {
        is_public = true;
    }

    var query;
    if (this._editor) {
        query = this._editor.getCode();
    }
    else {
        query = this._query;
    }

    var is_snapshot = false;
    if (this._model && this._model.is_snapshot) {
        is_snapshot = true;
        query = this._model.sql_code;
    }

    this.AsyncPUT(this._getRestRoot()+"/proxy/REST.svc/v2/db/dataset/"+solstice_user.sqlshare_schema+"/"+encodeURIComponent(name),
        {
            sql_code: query,
            description: description,
            is_public: is_public,
            is_snapshot: is_snapshot
        }, this._postSave);
};

QueryBase.prototype._postSave = function(o) {
    if (o.code == 201 || o.code == 200) {
        var tags = this._save_panel_view.getTagger().getTags();
        if (tags) {
            this.AsyncPUT(this._getRestRoot()+"/proxy/REST.svc/v2/db/dataset/"+solstice_user.sqlshare_schema+"/"+o.data.name+"/tags", [{"name":solstice_user.sqlshare_schema, "tags":tags }], this._postSaveTags, o);
        }
        else {
            this._postSaveAs(o);
        }
    }
    else {
        Solstice.Message.setError(Solstice.Lang.getMessage('SQLShare', 'error_saving_query'));
    }
};

QueryBase.prototype._postSaveTags = function(o, first_response) {
    if (o.code == 201 || o.code == 200) {
        this._postSaveAs(first_response);
    }
    else {
        Solstice.Message.setError(Solstice.Lang.getMessage('SQLShare', 'error_saving_query'));
    }
};

QueryBase.prototype._getNewTagData = function() {
    var has_change = false;
    var is_dataset_owner = false;

    if (this._model.owner == solstice_user.login_name) {
        is_dataset_owner = true;
    }

    var starting_tags = this._model.tags;

    var starting_tag_hash = {};
    for (var pc = 0; pc < starting_tags.length; pc++) {
        var person_tags = starting_tags[pc].tags;
        var owner = starting_tags[pc].name;

        for (var t = 0; t < person_tags.length; t++) {
            starting_tag_hash[person_tags[t]] = true;
        }
    }

    var current_tags = this._tagger.getTags();
    var current_tag_hash = {};

    var new_tags_for_user = [];
    for (var i = 0; i < current_tags.length; i++) {
        var tag = current_tags[i];
        current_tag_hash[tag] = true;

        if (!starting_tag_hash[tag]) {
            has_change = true;
            new_tags_for_user.push(tag);
        }
    }

    var return_tags = [];

    for (var pc = 0; pc < starting_tags.length; pc++) {
        var person_tags = starting_tags[pc].tags;
        var owner = starting_tags[pc].name;

        if (owner == solstice_user.login_name) {
            for (var t = 0; t < person_tags.length; t++) {
                var tag = person_tags[t];
                if (!current_tag_hash[tag]) {
                    has_change = true;
                }
                else {
                    new_tags_for_user.push(tag);
                }
            }
        }
        else {
            if (is_dataset_owner) {
                var new_user_tags = [];
                for (var t = 0; t < person_tags.length; t++) {
                    var tag = person_tags[t];
                    if (!current_tag_hash[tag]) {
                        has_change = true;
                    }
                    else {
                        new_user_tags.push(tag);
                    }
                }
                return_tags.push({
                    name: owner,
                    tags: new_user_tags
                });
            }
            else {
                return_tags.push(starting_tags[pc]);
            }
        }
    }

    return_tags.push({
        name: solstice_user.login_name,
        tags: new_tags_for_user
    });

    return {
        is_changed: has_change,
        tags: return_tags
    };
};

QueryBase.prototype._getURIFragment = function() {
    return 'dataset/'+this.query_id;
};


text:
<?php

namespace Alvi\Bundle\ImageProcessor\ScalerBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * AlviImageProcessorScalerBundle.
 *
 * @author Alexander <iam.asm89@gmail.com>
 */
class AlviImageProcessorScalerBundle extends Bundle
{

}

redpajama_set_name: RedPajamaGithub


text:
package com.gdn.venice.facade;

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

import javax.ejb.Local;

import com.gdn.venice.persistence.VenOrderItemContactDetail;
import com.djarum.raf.utilities.JPQLAdvancedQueryCriteria;
import com.gdn.venice.facade.finder.FinderReturn;

@Local
public interface VenOrderItemContactDetailSessionEJBLocal {

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.gdn.venice.facade.VenOrderItemContactDetailSessionEJBRemote#queryByRange(java.lang
	 * .String, int, int)
	 */
	public List<VenOrderItemContactDetail> queryByRange(String jpqlStmt, int firstResult,
			int maxResults);

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.gdn.venice.facade.VenOrderItemContactDetailSessionEJBRemote#persistVenOrderItemContactDetail(com
	 * .gdn.venice.persistence.VenOrderItemContactDetail)
	 */
	public VenOrderItemContactDetail persistVenOrderItemContactDetail(VenOrderItemContactDetail venOrderItemContactDetail);

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.gdn.venice.facade.VenOrderItemContactDetailSessionEJBRemote#persistVenOrderItemContactDetailList
	 * (java.util.List)
	 */
	public ArrayList<VenOrderItemContactDetail> persistVenOrderItemContactDetailList(
			List<VenOrderItemContactDetail> venOrderItemContactDetailList);

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.gdn.venice.facade.VenOrderItemContactDetailSessionEJBRemote#mergeVenOrderItemContactDetail(com.
	 * gdn.venice.persistence.VenOrderItemContactDetail)
	 */
	public VenOrderItemContactDetail mergeVenOrderItemContactDetail(VenOrderItemContactDetail venOrderItemContactDetail);

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.gdn.venice.facade.VenOrderItemContactDetailSessionEJBRemote#mergeVenOrderItemContactDetailList(
	 * java.util.List)
	 */
	public ArrayList<VenOrderItemContactDetail> mergeVenOrderItemContactDetailList(
			List<VenOrderItemContactDetail> venOrderItemContactDetailList);

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.gdn.venice.facade.VenOrderItemContactDetailSessionEJBRemote#removeVenOrderItemContactDetail(com
	 * .gdn.venice.persistence.VenOrderItemContactDetail)
	 */
	public void removeVenOrderItemContactDetail(VenOrderItemContactDetail venOrderItemContactDetail);

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.gdn.venice.facade.VenOrderItemContactDetailSessionEJBRemote#removeVenOrderItemContactDetailList
	 * (java.util.List)
	 */
	public void removeVenOrderItemContactDetailList(List<VenOrderItemContactDetail> venOrderItemContactDetailList);

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.gdn.venice.facade.VenOrderItemContactDetailSessionEJBRemote#findByVenOrderItemContactDetailLike
	 * (com.gdn.venice.persistence.VenOrderItemContactDetail, int, int)
	 */
	public List<VenOrderItemContactDetail> findByVenOrderItemContactDetailLike(VenOrderItemContactDetail venOrderItemContactDetail,
			JPQLAdvancedQueryCriteria criteria, int firstResult, int maxResults);

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.gdn.venice.facade.VenOrderItemContactDetailSessionEJBRemote#findByVenOrderItemContactDetailLikeFR
	 * (com.gdn.venice.persistence.VenOrderItemContactDetail, int, int)
	 */
	public FinderReturn findByVenOrderItemContactDetailLikeFR(VenOrderItemContactDetail venOrderItemContactDetail,
			JPQLAdvancedQueryCriteria criteria, int firstResult, int maxResults);

}


text:
.class public Landroid/provider/BrowserContract;
.super Ljava/lang/Object;
.source "BrowserContract.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/provider/BrowserContract$Accounts;,
        Landroid/provider/BrowserContract$BaseSyncColumns;,
        Landroid/provider/BrowserContract$Bookmarks;,
        Landroid/provider/BrowserContract$ChromeSyncColumns;,
        Landroid/provider/BrowserContract$Combined;,
        Landroid/provider/BrowserContract$CommonColumns;,
        Landroid/provider/BrowserContract$History;,
        Landroid/provider/BrowserContract$HistoryColumns;,
        Landroid/provider/BrowserContract$ImageColumns;,
        Landroid/provider/BrowserContract$ImageMappingColumns;,
        Landroid/provider/BrowserContract$ImageMappings;,
        Landroid/provider/BrowserContract$Images;,
        Landroid/provider/BrowserContract$Searches;,
        Landroid/provider/BrowserContract$Settings;,
        Landroid/provider/BrowserContract$SyncColumns;,
        Landroid/provider/BrowserContract$SyncState;
    }
.end annotation

# static fields
.field public static final AUTHORITY:Ljava/lang/String; = "com.android.browser"

.field public static final AUTHORITY_URI:Landroid/net/Uri;

.field public static final CALLER_IS_SYNCADAPTER:Ljava/lang/String; = "caller_is_syncadapter"

.field public static final PARAM_LIMIT:Ljava/lang/String; = "limit"

# direct methods
.method static constructor <clinit>()V
    .locals 1

    const-string/jumbo v0, "content://com.android.browser"

    invoke-static {v0}, Landroid/net/Uri;->parse(Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    sput-object v0, Landroid/provider/BrowserContract;->AUTHORITY_URI:Landroid/net/Uri;

    return-void
.end method

.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
package org.apache.camel.component.jms;

import javax.jms.ConnectionFactory;

import org.apache.camel.CamelContext;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

import static org.apache.camel.component.jms.JmsComponent.jmsComponentAutoAcknowledge;

public class JmsConsumeTemplateTest extends CamelTestSupport {

    @Test
    public void testConsumeTemplate() throws Exception {
        // must start CamelContext because use route builder is false
        context.start();

        String url = "activemq:queue:foo";
        template.sendBody(url, "Hello World");

        Object out = consumer.receiveBody(url, 5000);
        assertEquals("Hello World", out);
    }

    protected CamelContext createCamelContext() throws Exception {
        CamelContext camelContext = super.createCamelContext();

        // must be persistent so the consumer can receive the message as we receive AFTER the message
        // has been published
        ConnectionFactory connectionFactory = CamelJmsTestHelper.createPersistentConnectionFactory();
        camelContext.addComponent("activemq", jmsComponentAutoAcknowledge(connectionFactory));

        return camelContext;
    }

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }
}


text:
./Scripts/Test.ps1 `
    -configuration $env:BUILD_CONFIGURATION


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

package org.apache.kudu.mapreduce.tools;

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

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.yetus.audience.InterfaceStability;

import org.apache.kudu.client.Bytes;

/**
 * Column-separated values parser that gives access to the different columns inside each line of
 * data.
 */
@InterfaceAudience.Public
@InterfaceStability.Unstable
public class CsvParser {

  private final byte separatorByte;

  private final int maxColumnCount;

  private final List<String> columnNames;

  /**
   * @param columnsSpecification the list of columns to parse out, comma separated.
   * @param separatorStr The 1 byte separator.
   */
  public CsvParser(String columnsSpecification, String separatorStr) {
    // Configure separator
    byte[] separator = Bytes.fromString(separatorStr);
    Preconditions.checkArgument(separator.length == 1, "CsvParser only supports single-byte " +
        "separators");
    separatorByte = separator[0];

    // Configure columns
    columnNames = Lists.newArrayList(Splitter.on(',').trimResults().split(columnsSpecification));

    maxColumnCount = columnNames.size();
  }

  /**
   * Creates a ParsedLine of a line of data.
   * @param lineBytes Whole line as a byte array.
   * @param length How long the line really is in the byte array
   * @return A parsed line of CSV.
   * @throws BadCsvLineException
   */
  public ParsedLine parse(byte[] lineBytes, int length) throws BadCsvLineException {
    // Enumerate separator offsets
    List<Integer> tabOffsets = new ArrayList<>(maxColumnCount);
    for (int i = 0; i < length; i++) {
      if (lineBytes[i] == separatorByte) {
        tabOffsets.add(i);
      }
    }
    if (tabOffsets.isEmpty()) {
      throw new BadCsvLineException("No delimiter");
    }

    // trailing separator shouldn't count as a column
    if (lineBytes[length - 1] != separatorByte) {
      tabOffsets.add(length);
    }

    if (tabOffsets.size() > maxColumnCount) {
      throw new BadCsvLineException("Excessive columns");
    }

    if (tabOffsets.size() < maxColumnCount) {
      throw new BadCsvLineException("Not enough columns");
    }

    return new ParsedLine(tabOffsets, lineBytes);
  }

  /**
   * Helper class that knows where the columns are situated in the line.
   */
  class ParsedLine {
    private final List<Integer> tabOffsets;
    private final byte[] lineBytes;

    ParsedLine(List<Integer> tabOffsets, byte[] lineBytes) {
      this.tabOffsets = tabOffsets;
      this.lineBytes = lineBytes;
    }

    /**
     * Get the position for the given column.
     * @param idx Column to lookup.
     * @return Offset in the line.
     */
    public int getColumnOffset(int idx) {
      if (idx > 0) {
        return tabOffsets.get(idx - 1) + 1;
      } else {
        return 0;
      }
    }

    /**
     * Get how many bytes the given column occupies.
     * @param idx Column to lookup.
     * @return Column's length.
     */
    public int getColumnLength(int idx) {
      return tabOffsets.get(idx) - getColumnOffset(idx);
    }

    /**
     * Get the number of columns in this file.
     * @return Number of columns.
     */
    public int getColumnCount() {
      return tabOffsets.size();
    }

    /**
     * Get the bytes originally given for this line.
     * @return Original byte array.
     */
    public byte[] getLineBytes() {
      return lineBytes;
    }

    /**
     * Get the given column's name.
     * @param idx Column to lookup.
     * @return Column's name.
     */
    public String getColumnName(int idx) {
      return columnNames.get(idx);
    }
  }

  /**
   * Exception used when the CsvParser is unable to parse a line.
   */
  @SuppressWarnings("serial")
  public static class BadCsvLineException extends Exception {
    public BadCsvLineException(String err) {
      super(err);
    }
  }
}


text:
[![Documentation Status](https://readthedocs.org/projects/amgcl/badge/?version=latest)](http://amgcl.readthedocs.io/en/latest/?badge=latest)
[![DOI](https://zenodo.org/badge/6987353.svg)](https://zenodo.org/badge/latestdoi/6987353)
[![Build Status](https://travis-ci.org/ddemidov/amgcl.svg?branch=master)](https://travis-ci.org/ddemidov/amgcl)
[![Build status](https://ci.appveyor.com/api/projects/status/r0s4lbln4qf9r8aq/branch/master?svg=true)](https://ci.appveyor.com/project/ddemidov/amgcl/branch/master)
[![codecov](https://codecov.io/gh/ddemidov/amgcl/branch/master/graph/badge.svg)](https://codecov.io/gh/ddemidov/amgcl)
[![Coverity Scan Build Status](https://scan.coverity.com/projects/5301/badge.svg)](https://scan.coverity.com/projects/5301)

AMGCL is a header-only C++ library for solving large sparse linear systems with
algebraic multigrid (AMG) method. AMG is one of the most effective iterative
methods for solution of equation systems arising, for example, from
discretizing PDEs on unstructured grids. The method can be used as a black-box
solver for various computational problems, since it does not require any
information about the underlying geometry. AMG is often used not as a
standalone solver but as a preconditioner within an iterative solver (e.g.
Conjugate Gradients, BiCGStab, or GMRES).

AMGCL builds the AMG hierarchy on a CPU and then transfers it to one of the
provided backends. This allows for transparent acceleration of the solution
phase with help of OpenCL, CUDA, or OpenMP technologies. Users may provide
their own backends which enables tight integration between AMGCL and the user
code.

See AMGCL documentation at http://amgcl.readthedocs.io/

## Referencing

Demidov, Denis. AMGCL: An efficient, flexible, and extensible algebraic multigrid
implementation. Lobachevskii Journal of Mathematics, 40(5):535–546, May 2019.
[doi](https://doi.org/10.1134/S1995080219050056) [pdf](https://rdcu.be/bHFsY)
[bib](https://raw.githubusercontent.com/ddemidov/amgcl/master/docs/demidov19.bib)

Demidov, Denis. AMGCL -- A C++ library for efficient solution of large sparse linear
systems.  Software Impacts, 6:100037, November 2020.
[doi](https://doi.org/10.1016/j.simpa.2020.100037)
[bib](https://raw.githubusercontent.com/ddemidov/amgcl/master/docs/demidov20.bib)

Demidov, Denis, Lin Mu, and Bin Wang. Accelerating linear solvers for Stokes
problems with C++ metaprogramming. Journal of Computational Science (2020):
101285.
[doi](https://doi.org/10.1016/j.jocs.2020.101285)
[arxiv](https://arxiv.org/pdf/2006.06052.pdf)
[bib](https://raw.githubusercontent.com/ddemidov/amgcl/master/docs/demidov-mu-wang-20.bib)

## Support

* GitHub issues page: https://github.com/ddemidov/amgcl/issues
* Mailing list: https://groups.google.com/forum/#!forum/amgcl


text:
export interface ILigatureOptions {
  fallbackLigatures: string[];
}


text:
name: Issue with neat_cache
about: Bug, feature request or question regarding 'package:neat_cache'
title: ''
labels: pkg:neat_cache, pending-triage
assignees:
---
 * Explain the issue,
 * Using bullet points!

```dart
// Write example code here
```


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="wave">#B71C1C</color>
    <color name="bgGradient1">#FFAB40</color>
    <color name="bgGradient2">#D84315</color>

</resources>


text:
import React from "react";
import { LoadMoreStoriesBase } from "@quintype/components";
import { FullscreenStoryList } from "../layout/fullscreen-story-list.js";

class TagPage extends React.Component {

  render() {
    const stories = this.props.data.stories;
    return <LoadMoreStories {...this.props} stories={stories} />;
  }
}

function LoadMoreStories(props) {
  const storyFields = 'headline,subheadline,summary,sections,tags,author-name,author-id,authors,updated-at,last-published-at,published-at,updated-at,first-published-at,hero-image-metadata,hero-image-s3-key,story-content-id,slug,id,seo,story-template';
  const data = Object.assign(props.data, {stories: props.stories});
  const storiesPerPage = 20;

  return <LoadMoreStoriesBase template={LoadMoreStoriesTemplate}
      fields={storyFields}
      params={{ 'tag-slugs': props.data.tagSlug }}
      data={data}
      storiesPerPage={storiesPerPage} />;

}

function LoadMoreStoriesTemplate(props) {
  const config = {
    'collection-name': `Results for ${props.tagName}`,
    'collection-color': '#e32313',
    hideLoadmore: true,
    limit: 20
  }
  return

    {
      props.stories.length ?
      <FullscreenStoryList
        stories={props.stories}
        config={config}
        onLoadMore={props.onLoadMore}
        noMoreStories={props.noMoreStories} /> :

No stories found for tag '{props.tagName}'.

    }

;
}

export { TagPage };


text:
var ROD;
(function (ROD) {
    "use strict";
    angular.module("rodApp", ["ui.bootstrap"])
        .service("Settings", [function () { return new ROD.Settings.LiveSettingsService(); }])
        .service("PlayerService", ["Settings", function (settings) { return new ROD.Services.Player.YouTubePlayer(settings.isAutoPlay); }])
        .service("RedditService", [
        "$http", "Settings", "PlayerService",
        function ($http, settings, playerService) {
            return new ROD.Services.Reddit.RedditService($http, settings, playerService);
        },
    ])
        .service("TemplateSelector", [function () { return new ROD.Features.Video.Templates.VideoTemplateSelector(); }])
        .directive("videoItem", ["$compile", "TemplateSelector",
        function ($compile, templateSelector) {
            return new ROD.Features.Video.VideoDirective($compile, templateSelector);
        },])
        .controller("VideoController", [
        "$scope", "RedditService", "PlayerService",
        function ($scope, redditService, playerService) { return new ROD.Features.Video.VideoController($scope, redditService, playerService); },
    ]);
})(ROD || (ROD = {}));


text:
from netforce.model import Model, fields
import time

class SaleOrderPromotion(Model):
    _name = "sale.order.promotion"
    _fields = {
        "sale_id": fields.Many2One("sale.order", "Sales Order", required=True, on_delete="cascade"),
        "promotion_id": fields.Many2One("sale.promotion","Promotion",required=True),
        "product_id": fields.Many2One("product","Apply To Product"),
        "percent": fields.Decimal("Promotion Percent"),
        "amount": fields.Decimal("Promotion Amount"),
    }
    _order = "id"

SaleOrderPromotion.register()


text:
description: Upgrading your stack
keywords: azure, microsoft, iaas, tutorial
title: Docker for Azure Upgrades
---

Docker for Azure supports upgrading from one version to the next. To upgrade, apply a new version of the Azure ARM template that powers Docker for Azure. An upgrade of Docker for Azure involves:

 * Upgrading the VHD backing the manager and worker nodes (the Docker engine ships in the VHD)
 * Upgrading service containers in the manager and worker nodes
 * Changing any other resources in the Azure Resource Group that hosts Docker for Azure

## Prerequisites

 * We recommend only attempting upgrades of swarms with at least 3 managers. A 1-manager swarm may not be able to maintain quorum during the upgrade
 * You can only upgrade one version at a time. Skipping a version during an upgrade is not supported. Downgrades are not tested.
 * Ensure there are no nodes in the swarm in "down" status. If there are such nodes in the swarm, please remove them from the swarm using `docker node rm node-id`

## Upgrading

New releases are announced on the [Release Notes](release-notes.md) page.

To initiate an upgrade, SSH into a manager node and issue the following command:

    upgrade.sh https://download.docker.com/azure/stable/Docker.tmpl

This will initiate a rolling upgrade of the Docker swarm and service state will be maintained during and after the upgrade. Appropriately scaled services should not experience downtime during an upgrade. Note that single containers started (for example) with `docker run -d` are **not** preserved during an upgrade. This is because they are not Docker Swarm services but are known only to the individual Docker engines.

## Monitoring

The upgrade process may take several minutes to complete. You can follow the progress of the upgrade either from the output of the upgrade command or from the Azure UI by going to the Azure UI blades corresponding to the Virtual Machine Scale Sets hosting your manager and worker nodes. The URL for the Azure UI blades corresponding to your subscription and resource group is printed in the output of upgrade command above. They follow the following format:

```none
https://portal.azure.com/#resource/subscriptions/[subscription-id]/resourceGroups/[resource-group]/providers/Microsoft.Compute/virtualMachineScaleSets/swarm-manager-vmss/instances
```

```none
https://portal.azure.com/#resource/subscriptions/[subscription-id]/resourceGroups/[resource-group]/providers/Microsoft.Compute/virtualMachineScaleSets/swarm-worker-vmss/instances
```
`[subscription-id]` and `[resource-group]` are placeholders which will be replaced by
real values.

Note that in the last stage of the upgrade, the manager node where the upgrade is initiated from needs to be shut down, upgraded and reimaged. During this time, you won't be able to access the node and if you were logged in, your SSH connection will drop.

## Post Upgrade

After the upgrade, the IP address and the port needed to SSH into the manager nodes do not change. However, the host identity of the manager nodes does change as the VMs get reimaged. So when you try to SSH in after a successful upgrade, your SSH client may suspect a Man-In-The-Middle attack. You will need to delete the old entries in your SSH client's store [typically `~/.ssh/known_hosts`] for new SSH connections to succeed to the upgraded manager nodes.

## Changing instance sizes and other template parameters

This is not supported for Azure at the moment.


text:
import sys
import os
import urllib2
import threading

def print_usg():
    print('usage:\n\t' + sys.argv[0] + ' http://URL THREAD_NUM')
    sys.exit(1)

def check_argv():
    if len(sys.argv) != 3:
        print_usg()
    elif not sys.argv[1].startswith('http://'):
        print_usg()
    try:
        num = int(sys.argv[2])
    except:
        print_usg()
    return(sys.argv[1], num)

class downloader(object):
    def __init__(self, p_url, p_num, p_fd):
        self.url, self.num, self.fd = (p_url, p_num, p_fd)

        resp = urllib2.urlopen(self.url).info()
        self.total = int( resp['Content-Length'] )
        self.offset = int( self.total / self.num ) + 1
        if self.offset > 4096:
            self.offset = (self.offset + 4096) / 4096 * 4096
        print('\ninit:\n\tfile size: %d, offset: %d') % (self.total, self.offset)

    def gen_ranges(self):
        '''gen the http header info of range for each threading'''
        ranges = []
        for i in xrange(self.num):
            j = i * self.offset
            if (j + self.offset) > self.total:
                ranges.append( (j, self.total))
            else:
                ranges.append( (j, j + self.offset))
        return(ranges)

    def thread_handler(self, p_start, p_end):
        '''gen a thread to download from p_start to p_end'''
        req = urllib2.Request(self.url)
        req.add_header('Range', 'Bytes=' + str(p_start) + '-' + str(p_end) )
        try:
            resp = urllib2.urlopen(req)
        except:
            print("error when open url: %s", self.url)
            sys.exit(2)

        # write file
        cont = resp.read()
        lock = threading.Lock()
        lock.acquire()
        self.fd.seek(p_start)
        self.fd.write(cont)
        self.fd.flush()
        lock.release()

    def run(self):
        '''main func for this class for running downloader with multi-threading'''
        thread_lists = []
        n = 0
        for item_range in self.gen_ranges():
            start, end = item_range
            print('thread %d - start: %s, end: %s') % (n, start, end)
            thread = threading.Thread(target=self.thread_handler, args=(start, end))
            thread.start()
            thread_lists.append(thread)
            n += 1

        for i in thread_lists:
            i.join()

if __name__ == '__main__':
    url, num = check_argv()
    try:
        same_name = url.split('/')[-1]
    except:
        save_name = './tmp.file'

    with open(same_name, 'w+') as fd:
        down = downloader(url, num, fd)
        down.run()
    print('file: %s download success!' % same_name )


text:
package com.biasedbit.hotpotato.client.host;

import com.biasedbit.hotpotato.client.HttpRequestContext;
import com.biasedbit.hotpotato.client.connection.HttpConnection;

/**
 * @author Bruno de Carvalho
 */
public class EagerDrainHostContext extends AbstractHostContext {

    // constructors ---------------------------------------------------------------------------------------------------

    public EagerDrainHostContext(String host, int port, int maxConnections) {
        super(host, port, maxConnections);
    }

    // DefaultHostContext ---------------------------------------------------------------------------------------------

    @Override
    public DrainQueueResult drainQueue() {
        // 1. Test if there's anything to drain
        if (this.queue.isEmpty()) {
            return DrainQueueResult.QUEUE_EMPTY;
        }

        // 2. There are contents to drain, test if there are any connections created.
        if (this.connectionPool.getConnections().isEmpty()) {
            // 2a. No connections open, test if there is still room to create a new one.
            if (this.connectionPool.getTotalConnections() < this.maxConnections) {
                return DrainQueueResult.OPEN_CONNECTION;
            } else {
                return DrainQueueResult.NOT_DRAINED;
            }
        }

        // 3. There is content to drain and there are connections, drain as much as possible in a single loop.
        boolean drained = false;
        for (HttpConnection connection : this.connectionPool.getConnections()) {
            // Drain the first element in queue.
            // There will always be an element in the queue, ensured by 1. or by the premature exit right below.
            while (connection.isAvailable()) {
                // Peek the next request and see if the connection is able to accept it.
                HttpRequestContext context = this.queue.peek();
                if (connection.execute(context)) {
                    // Request was accepted by the connection, remove it from the queue.
                    this.queue.remove();
                    if (this.queue.isEmpty()) {
                        // Prematurely exit in case there are no further requests to execute.
                        // Returning prematurely dispenses additional check before queue.remove()
                        return DrainQueueResult.DRAINED;
                    }
                    // Otherwise, result WILL be DRAINED, no matter if we manage do execute another request or not.
                    drained = true;
                }
                // Request was not accepted by this connection, keep trying other connections.
            }
        }
        if (drained) {
            return DrainQueueResult.DRAINED;
        }

        // 4. There were connections open but none of them was available; if possible, request a new one.
        if (this.connectionPool.getTotalConnections() < this.maxConnections) {
            return DrainQueueResult.OPEN_CONNECTION;
        } else {
            return DrainQueueResult.NOT_DRAINED;
        }
    }
}


text:
<?php
$connect=new PDO('mysql:host=localhost;dbname=app_stay','root','');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>


text:
* User Management.
* Employee Management.

## Technology Stack:
* Spring Framework.
* Spring Security.
* Hibernate ORM.
* MySQL Database.
* Sitemesh.
* Bootstrap.
* jQuery.

## Step to Build:
* Import as Maven Project.
* Modify and Fix Your classpath.
* Edit username and password for Your Database in hibernate.cfg.xml.
* Create "application" Schema using UTF-8 Encoding.
* Export application.sql File to Your MySQL Database Schema.
* Run as Maven Project.


text:
package org.apache.scrunch

import java.lang.{Iterable => JIterable}

import scala.collection.JavaConversions._

import org.apache.hadoop.conf.Configuration

import org.apache.crunch.{Pair => P}
import org.apache.crunch.{Source, TableSource, Target}
import org.apache.crunch.impl.mem.MemPipeline
import org.apache.scrunch.Conversions._

/**
 * Object for working with in-memory PCollection and PTable instances.
 */
object Mem extends MemEmbeddedPipeline with PipelineHelper {
  private val ptf = Avros

  /**
   * Constructs a PCollection using in memory data.
   *
   * @param collect The data to load.
   * @return A PCollection containing the specified data.
   */
  def collectionOf[T](ts: T*)(implicit pt: PTypeH[T]): PCollection[T] = {
    collectionOf(List(ts:_*))
  }

  /**
   * Constructs a PCollection using in memory data.
   *
   * @param collect The data to load.
   * @return A PCollection containing the specified data.
   */
  def collectionOf[T](collect: Iterable[T])(implicit pt: PTypeH[T]): PCollection[T] = {
    val native = MemPipeline.typedCollectionOf(pt.get(ptf), asJavaIterable(collect))
    new PCollection[T](native)
  }

  /**
   * Constructs a PTable using in memory data.
   *
   * @param pairs The data to load.
   * @return A PTable containing the specified data.
   */
  def tableOf[K, V](pairs: (K, V)*)(implicit pk: PTypeH[K], pv: PTypeH[V]): PTable[K, V] = {
    tableOf(List(pairs:_*))
  }

  /**
   * Constructs a PTable using in memory data.
   *
   * @param pairs The data to load.
   * @return A PTable containing the specified data.
   */
  def tableOf[K, V](pairs: Iterable[(K, V)])(implicit pk: PTypeH[K], pv: PTypeH[V]): PTable[K, V] = {
    val cpairs = pairs.map(kv => P.of(kv._1, kv._2))
    val ptype = ptf.tableOf(pk.get(ptf), pv.get(ptf))
    new PTable[K, V](MemPipeline.typedTableOf(ptype, asJavaIterable(cpairs)))
  }

  /** Contains factory methods used to create `Source`s. */
  val from = From

  /** Contains factory methods used to create `Target`s. */
  val to = To

  /** Contains factory methods used to create `SourceTarget`s. */
  val at = At
}


text:
<?php

namespace Google\AdsApi\AdWords\v201702\cm;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class FeedOrigin
{
    const USER = 'USER';
    const ADWORDS = 'ADWORDS';
    const UNKNOWN = 'UNKNOWN';

}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@color/colorPrimaryDark</item>
        <item name="android:windowBackground">@color/windowBackground</item>
        <item name="android:textColorPrimary">@color/textColorPrimary</item>
        <item name="android:textColor">@color/textColor</item>
        <item name="android:itemBackground">@color/itemBackground</item>
        <!-- enable window content transitions -->
        <item name="android:windowContentTransitions">true</item>
        <item name="android:textColorSecondary">@color/textColorSecondary</item>
        <item name="android:textColorHint">@color/textColorHint</item>
    </style>

    <style name="action_button">
        <item name="android:layout_width">@dimen/action_button_size</item>
        <item name="android:layout_height">@dimen/action_button_size</item>
        <item name="android:padding">4dp</item>
        <item name="android:layout_margin">6dp</item>
        <item name="android:scaleType">centerInside</item>
    </style>

    <style name="menu_button">
        <item name="android:layout_width">@dimen/action_button_size</item>
        <item name="android:layout_height">@dimen/action_button_size</item>
        <item name="android:padding">4dp</item>
        <item name="android:scaleType">centerInside</item>
        <item name="android:layout_gravity">center</item>
    </style>

    <style name="menu_button.small">
        <item name="android:layout_width">24dp</item>
        <item name="android:layout_height">24dp</item>
        <item name="android:padding">4dp</item>
        <item name="android:scaleType">centerInside</item>
        <item name="android:layout_gravity">center</item>
    </style>

    <style name="action_textbutton">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">@dimen/action_button_size</item>
        <item name="android:padding">4dp</item>
        <item name="android:layout_gravity">end|center_vertical</item>
        <item name="android:gravity">center</item>
        <item name="android:layout_marginEnd">12dp</item>
        <item name="android:layout_marginStart">12dp</item>
        <item name="android:textSize">@dimen/text_14</item>
    </style>

    <style name="keyboardPanel">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">@dimen/keyboard_panel_height</item>
        <item name="android:background">@color/divider_color</item>
    </style>

    <style name="toolbarTitle">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_gravity">center</item>
        <item name="android:gravity">center</item>
        <item name="android:textColor">@color/textColorPrimary</item>
        <item name="android:textSize">@dimen/text_14</item>
        <item name="android:textStyle">bold</item>
    </style>

    <style name="toolbarTitle.Linear">
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_weight">1</item>
    </style>

    <style name="drawer_menu_item">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:drawablePadding">@dimen/gap_16</item>
        <item name="android:gravity">center_vertical</item>
        <item name="android:paddingBottom">@dimen/gap_8</item>
        <item name="android:paddingEnd">@dimen/gap_16</item>
        <item name="android:paddingStart">@dimen/gap_16</item>
        <item name="android:paddingTop">@dimen/gap_8</item>
        <item name="android:textColor">@color/text_click_secondary_primary</item>
        <item name="android:textSize">@dimen/text_16</item>
    </style>

    <style name="text_bold_primary">
        <item name="android:textColor">@color/textColorPrimary</item>
        <item name="android:textStyle">bold</item>
    </style>

    <dimen name="keyboard_panel_height">200dp</dimen>
</resources>


text:
Tru.Repo
========

Experimental repository pattern, aiming to bundle ORM with SQL database patching, such
that creating a new repo in code will automatically patch the database if necessary. The
attempt to patch the database will only happen the first time the repo is instantiated.

To run the tests simply update the 2 connection strings in
`Tru.Repo.Test/Given_a_valid_sql_connection_string.cs` so they are pointing at an accessible
sql server instance.


text:
{% extends "page.html" %}{% load i18n l10n %}

{% block meta_tags %}{{ block.super }}
    <meta name="robots" content="noindex, nofollow">
{% endblock %}

{% block body_class %}activation-error{% endblock %}

{% block menu_signup %}

{% trans "Sign up" %}

{% endblock %}

{% block container %}

{% trans "Signup is closed" %}

                        {% blocktrans %}This site is currently in closed beta.
                            If you want to be a beta tester of this service please contact us by contact
                            form.{% endblocktrans %}

                        {% trans "Go to Contact" %}

{% endblock %}


text:
<settings>
    <proxies>
        <proxy>
            <id>httpProxy</id>
            <active>{{proxy_env.use_proxy}}</active>
            <protocol>http</protocol>
            <host>{{proxy_env.http_maven_proxy_host}}</host>
            <port>{{proxy_env.http_maven_proxy_port}}</port>
            <username></username>
            <password></password>
            <nonProxyHosts></nonProxyHosts>
        </proxy>
        <proxy>
            <id>httpsProxy</id>
            <active>{{proxy_env.use_proxy}}</active>
            <protocol>https</protocol>
            <host>{{proxy_env.http_maven_proxy_host}}</host>
            <port>{{proxy_env.http_maven_proxy_port}}</port>
            <username></username>
            <password></password>
            <nonProxyHosts></nonProxyHosts>
        </proxy>
    </proxies>
</settings>


text:
require 'net/twitter/api/request'
require 'net/twitter/errors'

module Net
  module Twitter
    module Models
      class User
        attr_reader :screen_name, :follower_count

        def initialize(attrs = {})
          attrs.each{|k, v| instance_variable_set("@#{k}", v) unless v.nil?}
          @follower_count = attrs['followers_count']
        end

        # Returns the existing Twitter user matching the provided attributes or
        # nil when the user is not found.
        #
        # @return [Net::Twitter::Models::User] when the user is found.
        # @return [nil] when the user is not found or suspended.
        # @param [Hash] params the attributes to find a user by.
        # @option params [String] :screen_name The Twitter user's screen name
        #   (case-insensitive).
        def self.find_by(params = {})
          find_by! params
        rescue Errors::UnknownUser, Errors::SuspendedUser
          nil
        end

        # Returns the existing Twitter user matching the provided attributes or
        # raises an error when the user is not found or suspended.
        #
        # @return [Net::Twitter::Models::User] the Twitter user.
        # @param [Hash] params the attributes to find a user by.
        # @option params [String] :screen_name The Twitter user's screen name
        #   (case-insensitive).
        # @raise [Net::Errors::UnknownUser] if the user cannot be found.
        # @raise [Net::Errors::SuspendedUser] if the user account is suspended.
        def self.find_by!(params = {})
          request = Api::Request.new endpoint: 'users/show', params: params
          user_data = request.run
          new user_data
        rescue Errors::ResponseError => error
          case error.response
            when Net::HTTPNotFound then raise Errors::UnknownUser
            when Net::HTTPForbidden then raise Errors::SuspendedUser
          end
        end

        # Returns up to 100 existing Twitter users matching the provided
        # attributes. Raises an error when requesting more than 100 users.
        # Does not return users in the same order that they are requested.

        # @return [Array<Net::Twitter::Models::User>] the Twitter users.
        # @param [Hash] conditions The attributes to find users by.
        # @option conditions [Array<String>] screen_name The Twitter user's
        #   screen names (case-insensitive).
        # @raise [Net::Errors::TooManyUsers] when more than 100 Twitter users
        #   match the provided attributes.
        def self.where(conditions = {})
          params = to_where_params conditions
          request = Api::Request.new endpoint: 'users/lookup', params: params
          users_data = request.run
          users_data.map{|user_data| new user_data}
        rescue Errors::ResponseError => error
          case error.response
            when Net::HTTPNotFound then []
            when Net::HTTPForbidden then raise Errors::TooManyUsers
          end
        end

      private

        def self.to_where_params(conditions = {})
          conditions.dup.tap do |params|
            params.each{|k,v| params[k] = v.join(',') if v.is_a?(Array)}
          end
        end
      end
    end
  end
end


text:
package org.openlayers.ol.extent;

import java.util.HashMap;
import java.util.Map;

/**
 * Relationship to an extent.
 *
 * @author Serge Silaev aka iSergio <s.serge.b@gmail.com>
 */
public enum Relationship {
    UNKNOWN(0),
    INTERSECTING(1),
    ABOVE(2),
    RIGHT(4),
    BELOW(8),
    LEFT(16);

    private static final Map<Integer, Relationship> ENUM_MAP = new HashMap<>();
    static {
        for (Relationship value : values()) {
            ENUM_MAP.put(value.value, value);
        }
    }

    private final Integer value;

    Relationship(Integer value) {
        this.value = value;
    }

    public static Relationship fromValue(Integer value) {
        return ENUM_MAP.get(value);
    }

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


text:
package com.alexandrofs.gfp.web.rest;

import java.io.IOException;
import java.net.URISyntaxException;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alexandrofs.gfp.domain.enumeration.FileImporterType;
import com.alexandrofs.gfp.service.FileImporterService;
import com.alexandrofs.gfp.service.FileImporterServiceFactory;
import com.alexandrofs.gfp.web.rest.util.HeaderUtil;

import io.micrometer.core.annotation.Timed;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * REST controller for managing IndiceSerieDi.
 */
@RestController
@RequestMapping("/api")
@Slf4j
@AllArgsConstructor
public class FileImporterResource {

    private FileImporterServiceFactory factory;

    @RequestMapping(value = "/importer/{fileImporterType}",
            method = RequestMethod.POST,
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Timed
    public ResponseEntity<Void> uploadFile(@RequestParam("file") MultipartFile file, @PathVariable("fileImporterType") FileImporterType fileImporterType) throws URISyntaxException, IOException {

    	log.info("REST request to import File : {}", file.getOriginalFilename());

    	FileImporterService fileImporterService = factory.factory(fileImporterType);

    	fileImporterService.importa(file.getInputStream());

        return ResponseEntity.ok()
            .headers(HeaderUtil.createAlert("Arquivo importado com sucesso", file.getOriginalFilename()))
            .build();
    }

}


text:
#include <aws/macie2/model/GetUsageStatisticsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Macie2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetUsageStatisticsRequest::GetUsageStatisticsRequest() :
    m_filterByHasBeenSet(false),
    m_maxResults(0),
    m_maxResultsHasBeenSet(false),
    m_nextTokenHasBeenSet(false),
    m_sortByHasBeenSet(false),
    m_timeRange(TimeRange::NOT_SET),
    m_timeRangeHasBeenSet(false)
{
}

Aws::String GetUsageStatisticsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_filterByHasBeenSet)
  {
   Array<JsonValue> filterByJsonList(m_filterBy.size());
   for(unsigned filterByIndex = 0; filterByIndex < filterByJsonList.GetLength(); ++filterByIndex)
   {
     filterByJsonList[filterByIndex].AsObject(m_filterBy[filterByIndex].Jsonize());
   }
   payload.WithArray("filterBy", std::move(filterByJsonList));

  }

  if(m_maxResultsHasBeenSet)
  {
   payload.WithInteger("maxResults", m_maxResults);

  }

  if(m_nextTokenHasBeenSet)
  {
   payload.WithString("nextToken", m_nextToken);

  }

  if(m_sortByHasBeenSet)
  {
   payload.WithObject("sortBy", m_sortBy.Jsonize());

  }

  if(m_timeRangeHasBeenSet)
  {
   payload.WithString("timeRange", TimeRangeMapper::GetNameForTimeRange(m_timeRange));
  }

  return payload.View().WriteReadable();
}


text:
var Player = Class.create(GameEntity,IShooter,{
	xSpeed : 5,
	ySpedd : 5,
	weaponId : Input.WEAPON_1,
	isSecondWeaponAvailable : false,
	initialize : function(x,y,collisionGroups,collisionFilters){
		GameEntity.call(this,x,y,collisionGroups,collisionFilters);
		IShooter.call(this);
		hitBox = new Rectangle(x-2,y-2,x+2,y+2);
	},
	shoot : function() {
		if( Input.isKeyDown(Input.SHOOT)) {
			if (this.weaponId == 1 ) {
				game.currentScreen.addEntity(bulletFactory.createBullet(this.weaponId));
			} else {
				for(e in bulletFactory.createBullet(this.weaponId)) {
					game.currentScreen.addEntity(e);
				}
			}
		}
	},
	update : function() {
		if( Input.isKeyDown(Input.UP)) {
			this.hitBox.moveTo(this.x,this.y-level*this.ySpeed);
			this.y-=level*this.ySpeed;
		}
		if( Input.isKeyDown(Input.LEFT)) {
			this.hitBox.moveTo(this.x-level*this.xSpeed,this.y);
			this.x-=level*this.xSpeed;
		}
		if( Input.isKeyDown(InputDOWN)) {
			this.hitBox.moveTo(this.x,this.y+level*this.ySpeed);
			this.x-=level*this.xSpeed;
		}
		if( Input.isKeyDown(Input.RIGHT)) {
			this.hitBox.moveTo(this.x+level*this.xSpeed,this.y);
			this.x+=level*this.xSpeed;
		}
		if( Input.isKeyDown(Input.WEAPON_1)) {
			weaponId = 1;
		}
		if( this.isSecondWeaponAvailable && Input.isKeyDown(Input.WEAPON_2)) {
			weaponId = 2;
		}
	},
	render : function( graphics ) {
		graphics.drawImage("player1",this.x,this.y);
	}
});


text:
from a10sdk.common.A10BaseClass import A10BaseClass

class VeStats(A10BaseClass):

    """Class Description::
    Enables/Disables vlan ve interface stats generation.

    Class ve-stats supports CRUD Operations and inherits from `common/A10BaseClass`.
    This class is the `"PARENT"` class for this module.`

    :param enable: {"default": 0, "optional": true, "type": "number", "description": "Enable vlan ve interface stats generation", "format": "flag"}
    :param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
    :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`

    URL for this object::
    `https://<Hostname|Ip address>//axapi/v3/network/ve-stats`.

    """
    def __init__(self, **kwargs):
        self.ERROR_MSG = ""
        self.required=[]
        self.b_key = "ve-stats"
        self.a10_url="/axapi/v3/network/ve-stats"
        self.DeviceProxy = ""
        self.enable = ""
        self.uuid = ""

        for keys, value in kwargs.items():
            setattr(self,keys, value)


text:
SQLAlchemy
==========

The Python SQL Toolkit and Object Relational Mapper

Introduction
-------------

SQLAlchemy is the Python SQL toolkit and Object Relational Mapper
that gives application developers the full power and
flexibility of SQL. SQLAlchemy provides a full suite
of well known enterprise-level persistence patterns,
designed for efficient and high-performing database
access, adapted into a simple and Pythonic domain
language.

Major SQLAlchemy features include:

* An industrial strength ORM, built
  from the core on the identity map, unit of work,
  and data mapper patterns.   These patterns
  allow transparent persistence of objects
  using a declarative configuration system.
  Domain models
  can be constructed and manipulated naturally,
  and changes are synchronized with the
  current transaction automatically.
* A relationally-oriented query system, exposing
  the full range of SQL's capabilities
  explicitly, including joins, subqueries,
  correlation, and most everything else,
  in terms of the object model.
  Writing queries with the ORM uses the same
  techniques of relational composition you use
  when writing SQL.  While you can drop into
  literal SQL at any time, it's virtually never
  needed.
* A comprehensive and flexible system
  of eager loading for related collections and objects.
  Collections are cached within a session,
  and can be loaded on individual access, all
  at once using joins, or by query per collection
  across the full result set.
* A Core SQL construction system and DBAPI
  interaction layer.  The SQLAlchemy Core is
  separate from the ORM and is a full database
  abstraction layer in its own right, and includes
  an extensible Python-based SQL expression
  language, schema metadata, connection pooling,
  type coercion, and custom types.
* All primary and foreign key constraints are
  assumed to be composite and natural.  Surrogate
  integer primary keys are of course still the
  norm, but SQLAlchemy never assumes or hardcodes
  to this model.
* Database introspection and generation.  Database
  schemas can be "reflected" in one step into
  Python structures representing database metadata;
  those same structures can then generate
  CREATE statements right back out - all within
  the Core, independent of the ORM.

SQLAlchemy's philosophy:

* SQL databases behave less and less like object
  collections the more size and performance start to
  matter; object collections behave less and less like
  tables and rows the more abstraction starts to matter.
  SQLAlchemy aims to accommodate both of these
  principles.
* An ORM doesn't need to hide the "R".   A relational
  database provides rich, set-based functionality
  that should be fully exposed.   SQLAlchemy's
  ORM provides an open-ended set of patterns
  that allow a developer to construct a custom
  mediation layer between a domain model and
  a relational schema, turning the so-called
  "object relational impedance" issue into
  a distant memory.
* The developer, in all cases, makes all decisions
  regarding the design, structure, and naming conventions
  of both the object model as well as the relational
  schema.   SQLAlchemy only provides the means
  to automate the execution of these decisions.
* With SQLAlchemy, there's no such thing as
  "the ORM generated a bad query" - you
  retain full control over the structure of
  queries, including how joins are organized,
  how subqueries and correlation is used, what
  columns are requested.  Everything SQLAlchemy
  does is ultimately the result of a developer-
  initiated decision.
* Don't use an ORM if the problem doesn't need one.
  SQLAlchemy consists of a Core and separate ORM
  component.   The Core offers a full SQL expression
  language that allows Pythonic construction
  of SQL constructs that render directly to SQL
  strings for a target database, returning
  result sets that are essentially enhanced DBAPI
  cursors.
* Transactions should be the norm.  With SQLAlchemy's
  ORM, nothing goes to permanent storage until
  commit() is called.  SQLAlchemy encourages applications
  to create a consistent means of delineating
  the start and end of a series of operations.
* Never render a literal value in a SQL statement.
  Bound parameters are used to the greatest degree
  possible, allowing query optimizers to cache
  query plans effectively and making SQL injection
  attacks a non-issue.

Documentation
-------------

Latest documentation is at:

http://www.sqlalchemy.org/docs/

Installation / Requirements
---------------------------

Full documentation for installation is at
`Installation <http://www.sqlalchemy.org/docs/intro.html#installation>`_.

Getting Help / Development / Bug reporting
------------------------------------------

Please refer to the `SQLAlchemy Community Guide <http://www.sqlalchemy.org/support.html>`_.

License
-------

SQLAlchemy is distributed under the `MIT license
<http://www.opensource.org/licenses/mit-license.php>`_.


text:
package io.apiman.test.integration.rest.plugins.policies.jsonpplugin;

import io.apiman.test.integration.categories.PluginTest;
import io.apiman.test.integration.categories.PolicyTest;
import io.apiman.test.integration.runner.annotations.entity.Client;
import io.apiman.test.integration.runner.annotations.entity.Plan;
import io.apiman.test.integration.runner.annotations.misc.ApiKey;
import io.apiman.test.integration.runner.annotations.misc.Contract;
import io.apiman.test.integration.runner.annotations.misc.ManagedEndpoint;
import io.apiman.test.integration.runner.annotations.misc.Policies;
import io.apiman.test.integration.runner.annotations.version.ApiVersion;
import io.apiman.test.integration.runner.annotations.version.ClientVersion;
import io.apiman.test.integration.runner.annotations.version.PlanVersion;
import io.apiman.manager.api.beans.apis.ApiVersionBean;
import io.apiman.manager.api.beans.plans.PlanBean;

import org.junit.experimental.categories.Category;

/**
 * @author jkaspar
 */
@Category({PolicyTest.class, PluginTest.class})
public class JSONPClientPolicyIT extends AbstractJSONPPolicyIT {

    @ApiVersion(api = "api", vPlans = {"plan"})
    private static ApiVersionBean apiVersion;

    @ManagedEndpoint("apiVersion")
    private static String endpoint;

    @Plan(organization = "organization")
    @PlanVersion private static PlanBean plan;

    @Client(organization = "organization")
    @ClientVersion(contracts = @Contract(vPlan = "plan", vApi = "apiVersion"),
        policies = @Policies(value = "plugins/jsonp_001", params = {"param", CALLBACK_PARAM}))
    @ApiKey(vPlan = "plan", vApi = "apiVersion")
    private static String apikey;

    @Override
    protected String getResourceURL() {
        return addApiKeyParameter(endpoint, apikey);
    }

    @Override
    protected String getApiEndpoint() {
        return apiVersion.getEndpoint();
    }
}


text:
twominds-wp-base-theme
======================

My WordPress blank slate.

This is a CONSTANT WORK IN PROGRESS and should not be used by anyone but me.


text:
from __future__ import print_function
from __future__ import unicode_literals

class ModuleImportError(Exception):
    pass

class ConnectionException(Exception):
    pass

class ReplaceConfigException(Exception):
    pass

class MergeConfigException(Exception):
    pass

class SessionLockedException(Exception):
    pass

class CommandTimeoutException(Exception):
    pass

class CommandErrorException(Exception):
    pass

class DriverTemplateNotImplemented(Exception):
    pass

class TemplateNotImplemented(Exception):
    pass

class TemplateRenderException(Exception):
    pass

class ValidationException(Exception):
    pass


text:
"""
gRPC client meant to connect to a gRPC server endpoint, and query the
end-point's schema by calling SchemaService.Schema(Empty) and all of its
semantics are derived from the recovered schema.
"""

from __future__ import absolute_import
import os
import sys
import time
from random import randint
from zlib import decompress

import functools
import grpc
from consul import Consul
from grpc._channel import _Rendezvous
from structlog import get_logger
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.internet.error import ConnectError

from .protos.schema_pb2_grpc import SchemaServiceStub
from google.protobuf.empty_pb2 import Empty

from .asleep import asleep

log = get_logger()

class GrpcClient(object):
    """
    Connect to a gRPC server, fetch its schema, and process the downloaded
    schema files to drive the customization of the north-bound interface(s)
    of Chameleon.
    """
    RETRY_BACKOFF = [0.05, 0.1, 0.2, 0.5, 1, 2, 5]

    def __init__(self, consul_endpoint, work_dir, endpoint='localhost:50055',
                 reconnect_callback=None, credentials=None, restart_on_disconnect=False):
        self.consul_endpoint = consul_endpoint
        self.endpoint = endpoint
        self.work_dir = work_dir
        self.reconnect_callback = reconnect_callback
        self.credentials = credentials
        self.restart_on_disconnect = restart_on_disconnect
        self.google_api_dir = os.path.abspath(os.path.join(
            os.path.dirname(__file__), 'protos'))
        self.plugin_dir = os.path.abspath(os.path.join(
            os.path.dirname(__file__), 'protoc_plugins'))

        self.channel = None
        self.schema = None
        self.retries = 0
        self.shutting_down = False
        self.connected = False
        self.was_connected = False

    def start(self):
        log.debug('starting')
        if not self.connected:
            reactor.callLater(0, self.connect)
        log.info('started')
        return self

    def stop(self):
        log.debug('stopping')
        if self.shutting_down:
            return
        self.shutting_down = True
        log.info('stopped')

    def set_reconnect_callback(self, reconnect_callback):
        self.reconnect_callback = reconnect_callback
        return self

    def connectivity_callback(self, client, connectivity):
        if (self.was_connected) and (connectivity in [connectivity.TRANSIENT_FAILURE, connectivity.SHUTDOWN]):
            log.info("connectivity lost -- restarting")
            os.execv(sys.executable, ['python'] + sys.argv)

        if (connectivity == connectivity.READY):
            self.was_connected = True

        # Sometimes gRPC transitions from READY to IDLE, skipping TRANSIENT_FAILURE even though a socket is
        # disconnected. So on idle, force a connectivity check.
        if (connectivity == connectivity.IDLE) and (self.was_connected):
            connectivity = client.channel._channel.check_connectivity_state(True)
            # The result will probably show IDLE, but passing in True has the side effect of reconnecting if the
            # connection has been lost, which will trigger the TRANSIENT_FALURE we were looking for.

    @inlineCallbacks
    def connect(self):
        """
        (Re-)Connect to end-point
        """

        if self.shutting_down or self.connected:
            return

        try:
            if self.endpoint.startswith('@'):
                _endpoint = yield self._get_endpoint_from_consul(
                    self.endpoint[1:])
            else:
                _endpoint = self.endpoint

            if self.credentials:
                log.info('securely connecting', endpoint=_endpoint)
                self.channel = grpc.secure_channel(_endpoint, self.credentials)
            else:
                log.info('insecurely connecting', endpoint=_endpoint)
                self.channel = grpc.insecure_channel(_endpoint)

            if self.restart_on_disconnect:
                connectivity_callback = functools.partial(self.connectivity_callback, self)
                self.channel.subscribe(connectivity_callback)

            # Delay between initiating connection and executing first gRPC. See CORD-3012.
            time.sleep(0.5)

            swagger_from = self._retrieve_schema()
            self._compile_proto_files(swagger_from)
            self._clear_backoff()

            self.connected = True
            if self.reconnect_callback is not None:
                reactor.callLater(0, self.reconnect_callback)

            return

        except _Rendezvous as e:
            if e.code() == grpc.StatusCode.UNAVAILABLE:
                log.info('grpc-endpoint-not-available')
            else:
                log.exception('rendezvous error', e=e)
            yield self._backoff('not-available')

        except Exception:
            if not self.shutting_down:
                log.exception('cannot-connect', endpoint=_endpoint)
            yield self._backoff('unknown-error')

        reactor.callLater(0, self.connect)

    def _backoff(self, msg):
        wait_time = self.RETRY_BACKOFF[min(self.retries,
                                           len(self.RETRY_BACKOFF) - 1)]
        self.retries += 1
        log.error(msg, retry_in=wait_time)
        return asleep(wait_time)

    def _clear_backoff(self):
        if self.retries:
            log.info('reconnected', after_retries=self.retries)
            self.retries = 0

    @inlineCallbacks
    def _get_endpoint_from_consul(self, service_name):
        """
        Look up an appropriate grpc endpoint (host, port) from
        consul, under the service name specified by service-name
        """
        host = self.consul_endpoint.split(':')[0].strip()
        port = int(self.consul_endpoint.split(':')[1].strip())

        while True:
            log.debug('consul-lookup', host=host, port=port)
            consul = Consul(host=host, port=port)
            _, services = consul.catalog.service(service_name)
            log.debug('consul-response', services=services)
            if services:
                break
            log.warning('no-service', consul_host=host, consul_port=port,
                        service_name=service_name)
            yield asleep(1.0)

        # pick local addresses when resolving a service via consul
        # see CORD-815 (https://jira.opencord.org/browse/CORD-815)

        service = services[randint(0, len(services) - 1)]
        endpoint = '{}:{}'.format(service['ServiceAddress'],
                                  service['ServicePort'])
        returnValue(endpoint)

    def _retrieve_schema(self):
        """
        Retrieve schema from gRPC end-point, and save all *.proto files in
        the work directory.
        """
        assert isinstance(self.channel, grpc.Channel)
        stub = SchemaServiceStub(self.channel)
        # try:
        schemas = stub.GetSchema(Empty(), timeout=120)
        # except _Rendezvous, e:
        #     if e.code == grpc.StatusCode.UNAVAILABLE:
        #
        #     else:
        #         raise e

        os.system('mkdir -p %s' % self.work_dir)
        os.system('rm -fr /tmp/%s/*' %
                  self.work_dir.replace('/tmp/', ''))  # safer

        for proto_file in schemas.protos:
            proto_fname = proto_file.file_name
            proto_content = proto_file.proto
            log.debug('saving-proto', fname=proto_fname, dir=self.work_dir,
                      length=len(proto_content))
            with open(os.path.join(self.work_dir, proto_fname), 'w') as f:
                f.write(proto_content)

            desc_content = decompress(proto_file.descriptor)
            desc_fname = proto_fname.replace('.proto', '.desc')
            log.debug('saving-descriptor', fname=desc_fname, dir=self.work_dir,
                      length=len(desc_content))
            with open(os.path.join(self.work_dir, desc_fname), 'wb') as f:
                f.write(desc_content)
        return schemas.swagger_from

    def _compile_proto_files(self, swagger_from):
        """
        For each *.proto file in the work directory, compile the proto
        file into the respective *_pb2.py file as well as generate the
        web server gateway python file *_gw.py.
        :return: None
        """

        chameleon_base_dir = os.path.abspath(os.path.join(
            os.path.dirname(__file__), '.'
        ))

        for fname in [f for f in os.listdir(self.work_dir)
                      if f.endswith('.proto')]:

            need_swagger = fname == swagger_from
            log.debug('compiling', file=fname, need_swagger=need_swagger)
            cmd = (
                'cd %s && '
                'env PATH=%s PYTHONPATH=%s '
                'python -m grpc.tools.protoc '
                '-I. -I %s '
                '--python_out=. '
                '--grpc_python_out=. '
                '--plugin=protoc-gen-gw=%s/gw_gen.py '
                '--gw_out=. '
                '%s' % (
                    self.work_dir,
                    ':'.join([os.environ['PATH'], self.plugin_dir]),
                    chameleon_base_dir,
                    self.google_api_dir,
                    self.plugin_dir,
                    fname)
            )
            log.debug('executing', cmd=cmd, file=fname)
            os.system(cmd)
            log.info('compiled', file=fname)

        # test-load each _pb2 file to see all is right
        if self.work_dir not in sys.path:
            sys.path.insert(0, self.work_dir)

        for fname in [f for f in os.listdir(self.work_dir)
                      if f.endswith('_pb2.py')]:
            modname = fname[:-len('.py')]
            log.debug('test-import', modname=modname)
            _ = __import__(modname)  # noqa: F841

    @inlineCallbacks
    def invoke(self, stub, method_name, request, metadata, retry=1):
        """
        Invoke a gRPC call to the remote server and return the response.
        :param stub: Reference to the *_pb2 service stub
        :param method_name: The method name inside the service stub
        :param request: The request protobuf message
        :param metadata: [(str, str), (str, str), ...]
        :return: The response protobuf message and returned trailing metadata
        """

        if not self.connected:
            raise ConnectError()

        try:
            method = getattr(stub(self.channel), method_name)
            response, rendezvous = method.with_call(request, metadata=metadata)
            returnValue((response, rendezvous.trailing_metadata()))

        except grpc._channel._Rendezvous as e:
            code = e.code()
            if code == grpc.StatusCode.UNAVAILABLE:
                e = ConnectError()

                if self.connected:
                    self.connected = False
                    yield self.connect()
                    if retry > 0:
                        response = yield self.invoke(stub, method_name,
                                                     request, metadata,
                                                     retry=retry - 1)
                        returnValue(response)

            elif code in (
                    grpc.StatusCode.NOT_FOUND,
                    grpc.StatusCode.INVALID_ARGUMENT,
                    grpc.StatusCode.ALREADY_EXISTS,
                    grpc.StatusCode.UNAUTHENTICATED,
                    grpc.StatusCode.PERMISSION_DENIED):

                pass  # don't log error, these occur naturally

            else:
                log.exception(e)

            raise e


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using JetBrains.Annotations;

namespace Nuke.Common.CI
{
    [PublicAPI]
    [TypeConverter(typeof(TypeConverter))]
    public class Partition
    {
        public static Partition Single { get; } = new Partition { Part = 1, Total = 1 };

        public int Part { get; set; }
        public int Total { get; set; }

        public class TypeConverter : System.ComponentModel.TypeConverter
        {
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {
                return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
            }

            public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
            {
                if (value is string stringValue)
                {
                    var values = stringValue.Split('/');
                    return new Partition
                           {
                               Part = int.Parse(values[0]),
                               Total = int.Parse(values[1])
                           };
                }

                return base.ConvertFrom(context, culture, value);
            }
        }

        public bool IsIn(int part)
        {
            return Total == 1 || part == Part;
        }

        public IEnumerable<T> GetCurrent<T>(IEnumerable<T> enumerable)
        {
            var i = 0;
            foreach (var item in enumerable)
            {
                if (i == Part - 1)
                    yield return item;
                i = (i + 1) % Total;
            }
        }

        public override string ToString()
        {
            return $"{Part}/{Total}";
        }
    }
}


text:
package org.jetbrains.plugins.scala.macroAnnotations

import org.junit.Assert

/**
 * Author: Svyatoslav Ilinskiy
 * Date: 9/17/15.
 */
class CachedTest extends CachedTestBase {
  def testNoParametersSingleThread(): Unit = {
    class Foo extends Managed {
      @Cached(ModCount.getModificationCount, this)
      def currentTime(): Long = System.currentTimeMillis()
    }

    val foo = new Foo
    val firstRes: Long = foo.currentTime()
    Thread.sleep(1)
    Assert.assertEquals(firstRes, foo.currentTime())
    Thread.sleep(1)
    val tracker = foo.getModTracker
    val oldModCount = tracker.getModificationCount
    tracker.incCounter()
    val newModCount = tracker.getModificationCount
    Assert.assertTrue(oldModCount < newModCount)
    val secondRes: Long = foo.currentTime()
    Assert.assertTrue(firstRes < secondRes)
    Thread.sleep(1)
    Assert.assertEquals(secondRes, foo.currentTime())
  }

  def testModificationTrackers(): Unit = {
    object Foo extends Managed {
      @Cached(ModCount.getModificationCount, this)
      def currentTime: Long = System.currentTimeMillis()
    }

    val firstRes = Foo.currentTime
    Thread.sleep(1)
    Assert.assertEquals(firstRes, Foo.currentTime)
    Foo.getModTracker.incOutOfCodeBlockModificationCounter()
    Assert.assertTrue(firstRes < Foo.currentTime)
  }

  def testWithParameters(): Unit = {
    object Foo extends Managed {
      @Cached(ModCount.getModificationCount, this)
      def currentTime(a: Int, b: Int): Long = System.currentTimeMillis()
    }

    val firstRes = Foo.currentTime(0, 0)
    Thread.sleep(1)
    Assert.assertEquals(firstRes, Foo.currentTime(0, 0))
    Assert.assertTrue(firstRes < Foo.currentTime(1, 0))
    Assert.assertTrue(firstRes < Foo.currentTime(0, 1))
    Foo.getModTracker.incCounter()
    val secondRes = Foo.currentTime(0, 0)
    Assert.assertTrue(firstRes < secondRes)
    Thread.sleep(1)
    Assert.assertEquals(secondRes, Foo.currentTime(0, 0))
  }
}


text:
import sys
import datetime
from os.path import isdir, isfile
from itertools import tee
from corpus import Corpus, PaperCorpus
from gensim import models

class W2VCorpus(object):

    def __init__(self, directory=None, w2v_model=None, list_files=None, max_docs=None, distributions=None, **kwargs):
        if list_files:
            with open(list_files) as f:
                docs = [line.strip() for line in f]
        elif directory and distributions:
            docs = Corpus.get_docs(directory, distributions, max_docs)

        start_time = datetime.datetime.now()
        if not w2v_model:

            self.docs = PaperCorpus(docs)
            self.model = models.Doc2Vec(self._gen_docs(self.docs), min_count=20, workers=4)
        else:
            self.model = models.Doc2Vec.load(w2v_model)
        end_time = datetime.datetime.now()

        self.train_time = end_time - start_time
        return

    def similarity(self, label, items):
        if not self.model:
            self.model = models.Doc2Vec(self._gen_docs(self.docs), min_count=20, workers=4)
        return self.model.most_similar(label, topn=items)

    def save(self, dictionary_file="w2v_corpus.dict", corpus_file="corpus.mm", sup_file="vector.w2vs"):
        if self.model:
            self.model.save(sup_file)
        if dictionary_file and type(self.docs) is PaperCorpus:
            self.docs.save(dictionary_file)

    @classmethod
    def load(cls, sup_file=None, dictionary_file=None, **kwargs):
        return cls(w2v_model=sup_file, list_files=dictionary_file)

    @staticmethod
    def _gen_docs(docs, label="DOC_"):
        docs = docs.get_texts()
        for doc_id, doc in enumerate(docs):
            yield models.doc2vec.LabeledSentence(words=doc, labels=['%s%s' % (label, doc_id)])

    def get_train_time(self):
        return self.train_time

    def run_query(self, query, best_matches):
        # Small hack to return most simlar docs. Not guaranteed to get best_matches
        sim_matches = self.similarity(query, 10000)
        return list(filter(lambda x: 'DOC_' in x[0], sim_matches))[:best_matches]

    def run_queries(self, queries, best_matches):
        matches = list()
        queries_train, queries = tee(self._gen_docs(queries))
        self.model.train(queries_train)
        for query in queries:
            matches.append(self.run_query(query.labels[0], best_matches))
        return matches

def main():
    w2v = "w2vcorpus.w2v"
    if len(sys.argv) is 4 and isdir(sys.argv[1]):
        if not isfile(w2v):
            corpus = W2VCorpus(directory=sys.argv[1])
            corpus.save(dictionary_file=sys.argv[2], corpus_file=sys.argv[3], sup_file=w2v)
        else:
            corpus = W2VCorpus.load(dictionary_file=sys.argv[2], corpus_file=sys.argv[3], sup_file=w2v)
        time = corpus.get_train_time()
        print "W2V Train Time:\t" + str(time)
    else:
        print "Corpus requires directory as an argument."

if __name__ == "__main__":
    main()


text:
'use strict'

const opentracing = require('opentracing')
const Tracer = opentracing.Tracer
const EventEmitter = require('@protobufjs/eventemitter')
const Span = require('./span')
const TextMapPropagator = require('./propagation/text_map')
const BinaryPropagator = require('./propagation/binary')
const Endpoint = require('./endpoint')

class DatadogTracer extends Tracer {
  constructor (config) {
    super()
    EventEmitter.call(this)

    const service = config.service
    const endpoint = config.endpoint
    const hostname = config.hostname || 'localhost'
    const port = config.port || 8126
    const protocol = config.protocol || 'http'

    this._service = service
    this._endpoint = new Endpoint(endpoint || `${protocol}://${hostname}:${port}`)
    this._propagators = {
      [opentracing.FORMAT_TEXT_MAP]: new TextMapPropagator(),
      [opentracing.FORMAT_HTTP_HEADERS]: new TextMapPropagator(),
      [opentracing.FORMAT_BINARY]: new BinaryPropagator()
    }
  }

  _startSpan (name, fields) {
    return new Span(this, {
      operationName: fields.operationName || name,
      parent: getParent(fields.references),
      tags: fields.tags,
      startTime: fields.startTime
    })
  }

  _inject (spanContext, format, carrier) {
    this._propagators[format].inject(spanContext, carrier)
    return this
  }

  _extract (format, carrier) {
    return this._propagators[format].extract(carrier)
  }
}

Object.assign(DatadogTracer.prototype, EventEmitter.prototype)

function getParent (references) {
  let parent = null

  if (references) {
    for (let i = 0; i < references.length; i++) {
      const ref = references[i]
      if (ref.type() === opentracing.REFERENCE_CHILD_OF) {
        parent = ref.referencedContext()
        break
      } else if (ref.type() === opentracing.REFERENCE_FOLLOWS_FROM) {
        if (!parent) {
          parent = ref.referencedContext()
        }
      }
    }
  }

  return parent
}

module.exports = DatadogTracer


text:
package org.multiverse.stms.gamma;

import org.multiverse.api.references.TxnRefFactory;
import org.multiverse.stms.gamma.transactionalobjects.*;

/**
 * A {@link org.multiverse.api.references.TxnRefFactory} tailored for the GammaStm.
 *
 * @author Peter Veentjer.
 */
public interface GammaTxnRefFactory extends TxnRefFactory {

    @Override
    <E> GammaTxnRef<E> newTxnRef(E value);

    @Override
    GammaTxnInteger newTxnInteger(int value);

    @Override
    GammaTxnBoolean newTxnBoolean(boolean value);

    @Override
    GammaTxnDouble newTxnDouble(double value);

    @Override
    GammaTxnLong newTxnLong(long value);
}