text:
open sourced digital watch.
Personal project, written to be distributed how you wish.
Will include code, relavent CAD files and bill of materials, and instructions on installation.

redpajama_set_name: RedPajamaGithub


text:
/*
 * This file is generated by jOOQ.
 */
package org.simpleflatmapper.jooq.test.books;

import org.jooq.Schema;
import org.jooq.impl.CatalogImpl;

import javax.annotation.Generated;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.12.0"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class DefaultCatalog extends CatalogImpl {

    private static final long serialVersionUID = 344550825;

    /**
     * The reference instance of
     */
    public static final DefaultCatalog DEFAULT_CATALOG = new DefaultCatalog();

    /**
     * The schema PUBLIC.
     */
    public final Public PUBLIC = Public.PUBLIC;

    /**
     * No further instances allowed
     */
    private DefaultCatalog() {
        super("");
    }

    @Override
    public final List<Schema> getSchemas() {
        List result = new ArrayList();
        result.addAll(getSchemas0());
        return result;
    }

    private final List<Schema> getSchemas0() {
        return Arrays.<Schema>asList(
            Public.PUBLIC);
    }
}


text:
/**
 * Created by meathill on 15/3/7.
 */
'use strict';
(function (ns, _, Backbone) {
  /**
   * @class
   */
  ns.Pager = Backbone.View.extend({
    events: {
      'click a': 'clickHandler'
    },
    initialize: function (options) {
      this.template = this.$('script').remove().html() || '';
      this.template = this.template ? Handlebars.compile(this.template) : false;
      this.pagesize = this.collection.pagesize;
      this.total = Math.ceil(options.length / this.pagesize);
      this.render();
      this.displayPageNum();
      this.collection.on('sync', this.collection_syncHandler, this);
    },
    remove: function () {
      this.collection.off(null, null, this);
      this.model = this.collection = null;
      Backbone.View.prototype.remove.call(this);
    },
    render: function () {
      if (!this.template) {
        return;
      }
      var page = this.model.get('page')
        , arr = []
        , start = page - 5 > 0 ? page - 5 : 0
        , end = start + 10 < this.total ? start + 10 : this.total
        , length = end - start;
      for (var i = 0; i < length; i++) {
        arr[i] = {
          index: i + start,
          label: i + start + 1
        };
      }
      this.$el.html(this.template({
        pages: arr,
        prev: page - 1,
        next: page + 1
      }));
    },
    displayPageNum: function () {
      var page = this.model.get('page') || 0
        , total = this.total;
      this.$('[href="#/to/' + page + '"]').closest('.hidden-xs').addClass('active')
        .siblings().removeClass('active');
      this.$el.each(function () {
        $(this).children().first().toggleClass('disabled', page === 0)
          .end().last().toggleClass('disabled', page >= total - 1);
      });
    },
    setTotal: function (total, pagesize) {
      this.pagesize = pagesize || this.pagesize;
      this.total = Math.ceil(total / this.pagesize);
      this.render();
      this.displayPageNum();
    },
    collection_syncHandler: function () {
      this.setTotal(this.collection.total, this.collection.pagesize);
    },
    clickHandler: function (event) {
      var target = $(event.currentTarget)
        , parent = target.parent();
      if (parent.hasClass('disabled') || parent.hasClass('active')) {
        return false;
      }
      var href = target.attr('href')
        , index = Number(href.substr(href.lastIndexOf('/') + 1));
      this.model.set('page', index);
      target.html(tp.component.spinner);
      this.$el.children().addClass('disabled');
      event.preventDefault();
    }
  });

  /**
   * @class
   */
  ns.Search = Backbone.View.extend({
    events: {
      'keydown': 'keydownHandler'
    },
    initialize: function () {
      if (this.model.get('keyword')) {
        this.$el.val(this.model.get('keyword'));
      }
      if (this.el.value) {
        this.model.set('keyword', this.el.value, {silent: true});
      }
      this.model.on('change:keyword', this.model_changeHandler, this);
      this.collection.on('sync', this.collection_syncHandler, this);
    },
    remove: function () {
      this.model.off(null, null, this);
      this.collection.off(null, null, this);
      this.collection = this.model = null;
      Backbone.View.prototype.remove.call(this);
    },
    collection_syncHandler: function () {
      this.$el.prop('readonly', false);
      this.spinner && this.spinner.remove();
    },
    model_changeHandler: function (model, keyword) {
      this.el.value = keyword || '';
      this.$el.prop('readonly', true);
      this.spinner = this.spinner || $(tp.component.spinner);
      this.spinner.insertAfter(this.$el);
    },
    keydownHandler: function (event) {
      if (event.keyCode === 13) {
        event.preventDefault();
        var no_keyword = !event.target.value;
        this.model.unset('keyword', {silent: !no_keyword}); // 这次搜索之前要先把关键字删掉,保证触发change
        if (!no_keyword) {
          this.model.set({
            keyword: event.target.value,
            page: 0
          });
        }
      }
    }
  });

  /**
   * @class
   */
  ns.Filter = Backbone.View.extend({
    events: {
      'change': 'changeHandler',
      'dp.change .filter': 'changeHandler'
    },
    initialize: function () {
      this.model.on('change', this.model_changeHandler, this);
      this.collection.on('sync', this.collection_syncHandler, this);
      this.render();
    },
    render: function () {
      var data = this.model.toJSON();
      for (var prop in data) {
        var input = this.$('[name=' + prop + ']');
        if (input.is('select')) {
          input
            .val(data[prop])
            .data('value', data[prop]);
        } else if (input.is('[type=radio], [type=checkbox]')) {
          input.filter('[value="' + data[prop] + '"]').prop('checked', true)
            .parent('label').addClass('active')
            .siblings().removeClass('active');
        } else {
          input.val(data[prop]);
        }
      }
    },
    remove: function () {
      this.collection.off(null, null, this);
      this.collection = this.model = null;
      Backbone.View.prototype.remove.call(this);
    },
    collection_syncHandler: function () {
      this.$('.fa-spin').remove();
      this.$('select').prop('disabled', false);

      // 用options里的值填充select
      var options = this.collection.real ? this.collection.real.options : this.collection.options;
      if (!options) {
        return;
      }
      this.$('select').each(function () {
        var self = $(this)
          , name = self.data('options');
        if (!(name in options) || self.hasClass('ready')) {
          return true;
        }
        var template = self.find('script').html()
          , fixed = self.find('.fixed');
        template = Handlebars.compile(template);
        self
          .addClass('ready')
          .html(template(options))
          .prepend(fixed)
          .val(self.data('value'));
      });
    },
    model_changeHandler: function () {
      this.$('select').prop('disabled', true);
    },
    changeHandler: function (event) {
      var target = event.target
        , name = target.name
        , value = target.value;
      if (!name) {
        return;
      }
      if (!value) {
        this.model.set('page', 0, {silent: true});
        this.model.unset(name, {reset: true});
      } else {
        var attr = {page: 0};
        attr[name] = value;
        this.model.set(attr, {
          reset: true
        });
      }
      $(target).after(tp.component.spinner);
    }
  });

  /**
   * @class
   */
  ns.FixedHeader = Backbone.View.extend({
    className: 'fixed-table-header',
    tagName: 'div',
    visible: false,
    events: {
      'click .filter,.order': 'button_clickHandler'
    },
    initialize: function (options) {
      this.target = options.target;
      this.target.on('table-rendered', this.render, this);
      this.top = this.target.$el.offset().top;
      this.scrollHandler = _.bind(this.scrollHandler, this);
      $(window).scroll(this.scrollHandler);
      this.$el.appendTo('body');
    },
    remove: function () {
      this.target = null;
      $(window).off('scroll', this.scrollHandler);
      Backbone.View.prototype.remove.call(this);
    },
    render: function () {
      var clone = this.target.$el.clone()
        , ths = clone.find('th');
      clone.find('tbody, tfoot').remove();
      this.target.$('th').each(function (i) {
        ths[i].width = this.offsetWidth;
      });
      this.$el.html(clone);
    },
    button_clickHandler: function (event) {
      var type = event.target.className.indexOf('filter') != -1 ? 'filter' : 'order';
      this.target.$('thead .' + type + '[href="' + event.target.hash + '"]').click();
      event.preventDefault();
    },
    scrollHandler: function () {
      var scroll = document.body.scrollTop + 70; // 50是topbar高度,20是间隙
      if (scroll > this.top) {
        if (!this.visible) {
          this.visible = true;
          this.$el.show();
        }
      } else {
        this.$el.hide();
        this.visible = false;
      }
    }
  });
}(Nervenet.createNameSpace('tp.component.table'), _, Backbone));


text:
              ${i18n.summarizeAttributes}

                ${i18n.summarizeAttributes}

              ${i18n.oneLabel}
              ${i18n.inputFeatures}

              <select class="esriLeadingMargin1 longInput esriLongLabel"  style="margin-top:1.0em;" data-dojo-type="dijit/form/Select" data-dojo-attach-point="_analysisSelect" data-dojo-attach-event="onChange:_handleAnalysisLayerChange"></select>

              ${i18n.twoLabel}
              ${i18n.fieldLabel}

              <select multiple="true"  class="esriLeadingMargin1" style="width:100%;margin-top:10px;" data-dojo-props="required:true" data-dojo-type="dojox/form/CheckedMultiSelect" data-dojo-attach-point="_fieldSelect"></select>

              ${i18n.threeLabel}
              ${i18n.addStatsLabel}

              ${i18n.fourLabel}
              ${i18n.outputLayerLabel}

              <input type="text" data-dojo-type="dijit/form/ValidationTextBox" class="esriLeadingMargin1 longInput" data-dojo-props="trim:true,required:true" data-dojo-attach-point="_outputLayerInput" value=""></input>

                 ${i18n.saveResultIn}
                 <input class="longInput esriFolderSelect" data-dojo-attach-point="_webMapFolderSelect" dojotype="dijit/form/FilteringSelect" trim="true"></input>

        ${i18n.showCredits}

         <input type="radio" data-dojo-attach-point="_useExtentCheck" data-dojo-type="dijit/form/CheckBox" data-dojo-props="checked:true" name="extent" value="true"/>
           ${i18n.useMapExtent}

      <button data-dojo-type="dijit/form/Button" type="submit" data-dojo-attach-point="_saveBtn" class="esriLeadingMargin4 esriAnalysisSubmitButton" data-dojo-attach-event="onClick:_handleSaveBtnClick">
          ${i18n.runAnalysis}
      </button>


text:
  <input type="text" class="filterInput" placeholder="Filter..." ng-model="search" focus="">

{{node}}


text:
package vexatos.cheatycomputers;

import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import li.cil.oc.api.CreativeTab;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.oredict.ShapedOreRecipe;
import org.apache.logging.log4j.Logger;
import vexatos.cheatycomputers.item.ItemPackage;
import vexatos.cheatycomputers.reference.Mods;

import java.util.ArrayList;

@Mod(modid = Mods.CC, name = Mods.CC_NAME, version = "@VERSION@", dependencies = "required-after:" + Mods.OC + "@[1.5.21,)")
public class CheatyComputers {

	@Instance
	public static CheatyComputers INSTANCE;

	@SidedProxy(modId = Mods.CC, serverSide = "vexatos.cheatycomputers.CommonProxy", clientSide = "vexatos.cheatycomputers.ClientProxy")
	public static CommonProxy proxy;

	public static CreativeTabs tab;

	public static Configuration config;
	public static Logger log;

	public static ItemPackage item;

	@EventHandler
	public void preInit(FMLPreInitializationEvent e) {
		log = e.getModLog();
		//MinecraftForge.EVENT_BUS.register(this);
		//FMLCommonHandler.instance().bus().register(this);
		config = new Configuration(e.getSuggestedConfigurationFile());
		//config.load();
		tab = CreativeTab.instance;
		item = new ItemPackage();
		GameRegistry.registerItem(item, "cheatycomputers.package");
	}

	@EventHandler
	public void init(FMLInitializationEvent e) {
		proxy.registerRenderers();
	}

	public static ArrayList<ShapedOreRecipe> recipes = new ArrayList<ShapedOreRecipe>();
	public static ArrayList<ItemStack> itemList = new ArrayList<ItemStack>();

	public static void addPackageRecipe(ItemStack result, Object other) {
		result.setItemDamage(itemList.size());
		recipes.add(new ShapedOreRecipe(result,
			"sss", "sds", "prp",
			's', other,
			'd', "gemDiamond",
			'p', Items.paper,
			'r', "dustRedstone"
		));

		itemList.add(result);
	}

	@EventHandler
	public void postInit(FMLPostInitializationEvent e) {
		ScalaProxy.createRecipes();
		for(ShapedOreRecipe recipe : recipes) {
			GameRegistry.addRecipe(recipe);
		}
		//config.save();
	}
}


text:
const app = require('express')();
// const router = require('./src/router');
const configs = require('./src/configs');
const path = require('path');

// routers
// app.use('/', router);

app.get('/', (req, res) => {
  res.sendFile(path.resolve('./src/public/index.html'));
});

// error handlers
app.use((err, req, res, next) => {
  if (err) {
    console.error(err.stack);
  }
});

app.listen(configs.server.port, configs.server.host, () => {
  console.log(`listening at port ${configs.server.port}`);
});


text:
class NavbarController {
  constructor($scope, $mdSidenav, $log) {
    'ngInject';
    this.name = "navbar";
    this.$mdSidenav = $mdSidenav;
    this.$log = $log;

    $scope.toggleLeft = this.buildToggler('left');
  }

  /**
   * Build handler to open/close a SideNav; when animation finishes
   * report completion in console
   */
  buildToggler(navID) {
    var vm = this;
    return () => {
      this.$mdSidenav(navID)
        .toggle()
        .then(function() {
          vm.$log.debug("toggle " + navID + " is done");
        });

    };
  }

  closeLeft() {
    this.$mdSidenav('left').close()
      .then(function() {
        this.$log.debug("close LEFT is done");
      });
  }

  closeRight() {
    this.$mdSidenav('right').close()
      .then(function() {
        this.$log.debug("close RIGHT is done");
      });
  }
}

export default NavbarController;


text:
using System;
using System.Runtime.Serialization;

namespace RaynMaker.Modules.Import.Spec.v1
{
    /// <summary>
    /// Base class of all formats that describe the whole table instead of a series.
    /// </summary>
    [DataContract( Namespace = "https://github.com/bg0jr/RaynMaker/Import/Spec", Name = "AbstractTableFormat" )]
    abstract class AbstractTableFormat : AbstractDimensionalFormat
    {
        protected AbstractTableFormat( string datum, params FormatColumn[] cols )
            : base( datum )
        {
            if( cols == null )
            {
                throw new ArgumentNullException( "cols" );
            }
            Columns = cols;
        }

        [DataMember]
        public FormatColumn[] Columns { get; private set; }
    }
}


text:
package com.glaf.matrix.data.query;

import java.util.Date;

import com.glaf.core.query.DataQuery;

public class TableDataItemQuery extends DataQuery {
	private static final long serialVersionUID = 1L;
	protected String titleLike;
	protected String descriptionLike;
	protected String tableName;
	protected String tableNameLike;
	protected String nameColumn;
	protected String nameColumnLike;
	protected String valueColumn;
	protected String valueColumnLike;
	protected String type;
	protected Date createTimeGreaterThanOrEqual;
	protected Date createTimeLessThanOrEqual;

	public TableDataItemQuery() {

	}

	public TableDataItemQuery createTimeGreaterThanOrEqual(Date createTimeGreaterThanOrEqual) {
		if (createTimeGreaterThanOrEqual == null) {
			throw new RuntimeException("createTime is null");
		}
		this.createTimeGreaterThanOrEqual = createTimeGreaterThanOrEqual;
		return this;
	}

	public TableDataItemQuery createTimeLessThanOrEqual(Date createTimeLessThanOrEqual) {
		if (createTimeLessThanOrEqual == null) {
			throw new RuntimeException("createTime is null");
		}
		this.createTimeLessThanOrEqual = createTimeLessThanOrEqual;
		return this;
	}

	public TableDataItemQuery descriptionLike(String descriptionLike) {
		if (descriptionLike == null) {
			throw new RuntimeException("description is null");
		}
		this.descriptionLike = descriptionLike;
		return this;
	}

	public Date getCreateTimeGreaterThanOrEqual() {
		return createTimeGreaterThanOrEqual;
	}

	public Date getCreateTimeLessThanOrEqual() {
		return createTimeLessThanOrEqual;
	}

	public String getDescriptionLike() {
		if (descriptionLike != null && descriptionLike.trim().length() > 0) {
			if (!descriptionLike.startsWith("%")) {
				descriptionLike = "%" + descriptionLike;
			}
			if (!descriptionLike.endsWith("%")) {
				descriptionLike = descriptionLike + "%";
			}
		}
		return descriptionLike;
	}

	public String getNameColumn() {
		return nameColumn;
	}

	public String getNameColumnLike() {
		if (nameColumnLike != null && nameColumnLike.trim().length() > 0) {
			if (!nameColumnLike.startsWith("%")) {
				nameColumnLike = "%" + nameColumnLike;
			}
			if (!nameColumnLike.endsWith("%")) {
				nameColumnLike = nameColumnLike + "%";
			}
		}
		return nameColumnLike;
	}

	public String getOrderBy() {
		if (sortColumn != null) {
			String a_x = " asc ";
			if (sortOrder != null) {
				a_x = sortOrder;
			}

			if ("title".equals(sortColumn)) {
				orderBy = "E.TITLE_" + a_x;
			}

			if ("description".equals(sortColumn)) {
				orderBy = "E.DESCRIPTION_" + a_x;
			}

			if ("tableName".equals(sortColumn)) {
				orderBy = "E.TABLENAME_" + a_x;
			}

			if ("nameColumn".equals(sortColumn)) {
				orderBy = "E.NAMECOLUMN_" + a_x;
			}

			if ("valueColumn".equals(sortColumn)) {
				orderBy = "E.VALUECOLUMN_" + a_x;
			}

			if ("filterFlag".equals(sortColumn)) {
				orderBy = "E.FILTERFLAG_" + a_x;
			}

			if ("type".equals(sortColumn)) {
				orderBy = "E.TYPE_" + a_x;
			}

			if ("createBy".equals(sortColumn)) {
				orderBy = "E.CREATEBY_" + a_x;
			}

			if ("createTime".equals(sortColumn)) {
				orderBy = "E.CREATETIME_" + a_x;
			}

			if ("updateBy".equals(sortColumn)) {
				orderBy = "E.UPDATEBY_" + a_x;
			}

			if ("updateTime".equals(sortColumn)) {
				orderBy = "E.UPDATETIME_" + a_x;
			}

		}
		return orderBy;
	}

	public String getTableName() {
		return tableName;
	}

	public String getTableNameLike() {
		if (tableNameLike != null && tableNameLike.trim().length() > 0) {
			if (!tableNameLike.startsWith("%")) {
				tableNameLike = "%" + tableNameLike;
			}
			if (!tableNameLike.endsWith("%")) {
				tableNameLike = tableNameLike + "%";
			}
		}
		return tableNameLike;
	}

	public String getTitleLike() {
		if (titleLike != null && titleLike.trim().length() > 0) {
			if (!titleLike.startsWith("%")) {
				titleLike = "%" + titleLike;
			}
			if (!titleLike.endsWith("%")) {
				titleLike = titleLike + "%";
			}
		}
		return titleLike;
	}

	public String getType() {
		return type;
	}

	public String getValueColumn() {
		return valueColumn;
	}

	public String getValueColumnLike() {
		if (valueColumnLike != null && valueColumnLike.trim().length() > 0) {
			if (!valueColumnLike.startsWith("%")) {
				valueColumnLike = "%" + valueColumnLike;
			}
			if (!valueColumnLike.endsWith("%")) {
				valueColumnLike = valueColumnLike + "%";
			}
		}
		return valueColumnLike;
	}

	@Override
	public void initQueryColumns() {
		super.initQueryColumns();
		addColumn("id", "ID_");
		addColumn("title", "TITLE_");
		addColumn("description", "DESCRIPTION_");
		addColumn("tableName", "TABLENAME_");
		addColumn("nameColumn", "NAMECOLUMN_");
		addColumn("valueColumn", "VALUECOLUMN_");
		addColumn("filterFlag", "FILTERFLAG_");
		addColumn("type", "TYPE_");
		addColumn("createBy", "CREATEBY_");
		addColumn("createTime", "CREATETIME_");
		addColumn("updateBy", "UPDATEBY_");
		addColumn("updateTime", "UPDATETIME_");
	}

	public TableDataItemQuery nameColumn(String nameColumn) {
		if (nameColumn == null) {
			throw new RuntimeException("nameColumn is null");
		}
		this.nameColumn = nameColumn;
		return this;
	}

	public TableDataItemQuery nameColumnLike(String nameColumnLike) {
		if (nameColumnLike == null) {
			throw new RuntimeException("nameColumn is null");
		}
		this.nameColumnLike = nameColumnLike;
		return this;
	}

	public void setCreateTimeGreaterThanOrEqual(Date createTimeGreaterThanOrEqual) {
		this.createTimeGreaterThanOrEqual = createTimeGreaterThanOrEqual;
	}

	public void setCreateTimeLessThanOrEqual(Date createTimeLessThanOrEqual) {
		this.createTimeLessThanOrEqual = createTimeLessThanOrEqual;
	}

	public void setDescriptionLike(String descriptionLike) {
		this.descriptionLike = descriptionLike;
	}

	public void setNameColumn(String nameColumn) {
		this.nameColumn = nameColumn;
	}

	public void setNameColumnLike(String nameColumnLike) {
		this.nameColumnLike = nameColumnLike;
	}

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public void setTableNameLike(String tableNameLike) {
		this.tableNameLike = tableNameLike;
	}

	public void setTitleLike(String titleLike) {
		this.titleLike = titleLike;
	}

	public void setType(String type) {
		this.type = type;
	}

	public void setValueColumn(String valueColumn) {
		this.valueColumn = valueColumn;
	}

	public void setValueColumnLike(String valueColumnLike) {
		this.valueColumnLike = valueColumnLike;
	}

	public TableDataItemQuery tableName(String tableName) {
		if (tableName == null) {
			throw new RuntimeException("tableName is null");
		}
		this.tableName = tableName;
		return this;
	}

	public TableDataItemQuery tableNameLike(String tableNameLike) {
		if (tableNameLike == null) {
			throw new RuntimeException("tableName is null");
		}
		this.tableNameLike = tableNameLike;
		return this;
	}

	public TableDataItemQuery titleLike(String titleLike) {
		if (titleLike == null) {
			throw new RuntimeException("title is null");
		}
		this.titleLike = titleLike;
		return this;
	}

	public TableDataItemQuery type(String type) {
		if (type == null) {
			throw new RuntimeException("type is null");
		}
		this.type = type;
		return this;
	}

	public TableDataItemQuery valueColumn(String valueColumn) {
		if (valueColumn == null) {
			throw new RuntimeException("valueColumn is null");
		}
		this.valueColumn = valueColumn;
		return this;
	}

	public TableDataItemQuery valueColumnLike(String valueColumnLike) {
		if (valueColumnLike == null) {
			throw new RuntimeException("valueColumn is null");
		}
		this.valueColumnLike = valueColumnLike;
		return this;
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecanora rubricosa Ach.

### Remarks
null


text:
(function (angular) {
    'use strict';

    angular.module('todoApp')
        .factory('filterService', filterService);

    filterService.$inject = ['filterTypes'];

    function filterService(filterTypes) {
        var filter = {};
        var activeFilter = filterTypes.ALL_ITEMS;

        return {
            getFilter: function () {
                return filter;
            },
            getActiveFilter: function () {
                return activeFilter;
            },
            setFilter: setFilter
        };

        function setFilter(filterType) {
            switch (filterType) {
                case filterTypes.ALL_ITEMS:
                    filter = {};
                    activeFilter = filterType;
                    break;
                case filterTypes.OPEN_ITEMS:
                    filter = {completed: false};
                    activeFilter = filterType;
                    break;
                case filterTypes.COMPLETED_ITEMS:
                    filter = {completed: true};
                    activeFilter = filterType;
                    break;
                default:
                    filter = {};
                    activeFilter = filterTypes.ALL_ITEMS;
            }
        }
    }
}(angular));


text:
@import "../color/index.css";

.Button {
  background: var(--color-black);
  color: var(--color-white);
  border-radius: 0;
}


text:
package etcd

import (
	"os/exec"
	"testing"
)

func init() {
	_, err := exec.Command("etcd", "--version").Output()
	if err != nil {
		log.Fatal(err)
	}
}

func TestAcquireReleaseLock(t *testing.T) {
	startEtcd()
	defer stopEtcd()

	etcdClient := NewClient([]string{"http://localhost:4001"})

	err := AcquireLock(etcdClient, "/lock", 10)
	if err != nil {
		t.Fatalf("Unexpected error '%v'", err)
	}

	value := Get(etcdClient, "/lock")
	if value == "" {
		t.Fatalf("Expected '%v' arguments but returned '%v'", "locked", value)
	}

	if value != "locked" {
		t.Fatalf("Expected '%v' arguments but returned '%v'", "locked", value)
	}

	ReleaseLock(etcdClient)

	value = Get(etcdClient, "/lock")
	if value != "released" {
		t.Fatalf("Expected '%v' arguments but returned '%v'", "released", value)
	}

}


text:
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'

module Google
  module Apis
    module LocalservicesV1

      # An Account Report of a GLS account identified by their account id containing
      # aggregate data gathered from a particular date range.
      class GoogleAdsHomeservicesLocalservicesV1AccountReport
        include Google::Apis::Core::Hashable

        # Unique identifier of the GLS account.
        # Corresponds to the JSON property `accountId`
        # @return [Fixnum]
        attr_accessor :account_id

        # Conatiner for aggregator specific information if lead is for an aggregator GLS
        # account.
        # Corresponds to the JSON property `aggregatorInfo`
        # @return [Google::Apis::LocalservicesV1::GoogleAdsHomeservicesLocalservicesV1AggregatorInfo]
        attr_accessor :aggregator_info

        # Average review rating score from 1-5 stars.
        # Corresponds to the JSON property `averageFiveStarRating`
        # @return [Float]
        attr_accessor :average_five_star_rating

        # Average weekly budget in the currency code of the account.
        # Corresponds to the JSON property `averageWeeklyBudget`
        # @return [Float]
        attr_accessor :average_weekly_budget

        # Business name of the account.
        # Corresponds to the JSON property `businessName`
        # @return [String]
        attr_accessor :business_name

        # Currency code of the account.
        # Corresponds to the JSON property `currencyCode`
        # @return [String]
        attr_accessor :currency_code

        # Number of charged leads the account received in current specified period.
        # Corresponds to the JSON property `currentPeriodChargedLeads`
        # @return [Fixnum]
        attr_accessor :current_period_charged_leads

        # Number of connected phone calls (duration over 30s) in current specified
        # period.
        # Corresponds to the JSON property `currentPeriodConnectedPhoneCalls`
        # @return [Fixnum]
        attr_accessor :current_period_connected_phone_calls

        # Number of phone calls in current specified period, including both connected
        # and unconnected calls.
        # Corresponds to the JSON property `currentPeriodPhoneCalls`
        # @return [Fixnum]
        attr_accessor :current_period_phone_calls

        # Total cost of the account in current specified period in the account's
        # specified currency.
        # Corresponds to the JSON property `currentPeriodTotalCost`
        # @return [Float]
        attr_accessor :current_period_total_cost

        # Phone lead responsiveness of the account for the past 90 days from current
        # date. This is computed by taking the total number of connected calls from
        # charged phone leads and dividing by the total number of calls received.
        # Corresponds to the JSON property `phoneLeadResponsiveness`
        # @return [Float]
        attr_accessor :phone_lead_responsiveness

        # Number of charged leads the account received in previous specified period.
        # Corresponds to the JSON property `previousPeriodChargedLeads`
        # @return [Fixnum]
        attr_accessor :previous_period_charged_leads

        # Number of connected phone calls (duration over 30s) in previous specified
        # period.
        # Corresponds to the JSON property `previousPeriodConnectedPhoneCalls`
        # @return [Fixnum]
        attr_accessor :previous_period_connected_phone_calls

        # Number of phone calls in previous specified period, including both connected
        # and unconnected calls.
        # Corresponds to the JSON property `previousPeriodPhoneCalls`
        # @return [Fixnum]
        attr_accessor :previous_period_phone_calls

        # Total cost of the account in previous specified period in the account's
        # specified currency.
        # Corresponds to the JSON property `previousPeriodTotalCost`
        # @return [Float]
        attr_accessor :previous_period_total_cost

        # Total number of reviews the account has up to current date.
        # Corresponds to the JSON property `totalReview`
        # @return [Fixnum]
        attr_accessor :total_review

        def initialize(**args)
           update!(**args)
        end

        # Update properties of this object
        def update!(**args)
          @account_id = args[:account_id] if args.key?(:account_id)
          @aggregator_info = args[:aggregator_info] if args.key?(:aggregator_info)
          @average_five_star_rating = args[:average_five_star_rating] if args.key?(:average_five_star_rating)
          @average_weekly_budget = args[:average_weekly_budget] if args.key?(:average_weekly_budget)
          @business_name = args[:business_name] if args.key?(:business_name)
          @currency_code = args[:currency_code] if args.key?(:currency_code)
          @current_period_charged_leads = args[:current_period_charged_leads] if args.key?(:current_period_charged_leads)
          @current_period_connected_phone_calls = args[:current_period_connected_phone_calls] if args.key?(:current_period_connected_phone_calls)
          @current_period_phone_calls = args[:current_period_phone_calls] if args.key?(:current_period_phone_calls)
          @current_period_total_cost = args[:current_period_total_cost] if args.key?(:current_period_total_cost)
          @phone_lead_responsiveness = args[:phone_lead_responsiveness] if args.key?(:phone_lead_responsiveness)
          @previous_period_charged_leads = args[:previous_period_charged_leads] if args.key?(:previous_period_charged_leads)
          @previous_period_connected_phone_calls = args[:previous_period_connected_phone_calls] if args.key?(:previous_period_connected_phone_calls)
          @previous_period_phone_calls = args[:previous_period_phone_calls] if args.key?(:previous_period_phone_calls)
          @previous_period_total_cost = args[:previous_period_total_cost] if args.key?(:previous_period_total_cost)
          @total_review = args[:total_review] if args.key?(:total_review)
        end
      end

      # Conatiner for aggregator specific information if lead is for an aggregator GLS
      # account.
      class GoogleAdsHomeservicesLocalservicesV1AggregatorInfo
        include Google::Apis::Core::Hashable

        # Provider id (listed in aggregator system) which maps to a account id in GLS
        # system.
        # Corresponds to the JSON property `aggregatorProviderId`
        # @return [String]
        attr_accessor :aggregator_provider_id

        def initialize(**args)
           update!(**args)
        end

        # Update properties of this object
        def update!(**args)
          @aggregator_provider_id = args[:aggregator_provider_id] if args.key?(:aggregator_provider_id)
        end
      end

      # A Detailed Lead Report of a lead identified by their lead id and contains
      # consumer, account, monetization, and lead data.
      class GoogleAdsHomeservicesLocalservicesV1DetailedLeadReport
        include Google::Apis::Core::Hashable

        # Identifies account that received the lead.
        # Corresponds to the JSON property `accountId`
        # @return [Fixnum]
        attr_accessor :account_id

        # Conatiner for aggregator specific information if lead is for an aggregator GLS
        # account.
        # Corresponds to the JSON property `aggregatorInfo`
        # @return [Google::Apis::LocalservicesV1::GoogleAdsHomeservicesLocalservicesV1AggregatorInfo]
        attr_accessor :aggregator_info

        # Business name associated to the account.
        # Corresponds to the JSON property `businessName`
        # @return [String]
        attr_accessor :business_name

        # Whether the lead has been charged.
        # Corresponds to the JSON property `chargeStatus`
        # @return [String]
        attr_accessor :charge_status

        # Currency code.
        # Corresponds to the JSON property `currencyCode`
        # @return [String]
        attr_accessor :currency_code

        # Dispute status related to the lead.
        # Corresponds to the JSON property `disputeStatus`
        # @return [String]
        attr_accessor :dispute_status

        # Location of the associated account's home city.
        # Corresponds to the JSON property `geo`
        # @return [String]
        attr_accessor :geo

        # Lead category (e.g. hvac, plumber)
        # Corresponds to the JSON property `leadCategory`
        # @return [String]
        attr_accessor :lead_category

        # Timestamp of when the lead was created.
        # Corresponds to the JSON property `leadCreationTimestamp`
        # @return [String]
        attr_accessor :lead_creation_timestamp

        # Unique identifier of a Detailed Lead Report.
        # Corresponds to the JSON property `leadId`
        # @return [Fixnum]
        attr_accessor :lead_id

        # Price of the lead (available only after it has been charged).
        # Corresponds to the JSON property `leadPrice`
        # @return [Float]
        attr_accessor :lead_price

        # Lead type.
        # Corresponds to the JSON property `leadType`
        # @return [String]
        attr_accessor :lead_type

        # Container for message lead specific information.
        # Corresponds to the JSON property `messageLead`
        # @return [Google::Apis::LocalservicesV1::GoogleAdsHomeservicesLocalservicesV1MessageLead]
        attr_accessor :message_lead

        # Container for phone lead specific information.
        # Corresponds to the JSON property `phoneLead`
        # @return [Google::Apis::LocalservicesV1::GoogleAdsHomeservicesLocalservicesV1PhoneLead]
        attr_accessor :phone_lead

        # Represents a time zone from the [IANA Time Zone Database](https://www.iana.org/
        # time-zones).
        # Corresponds to the JSON property `timezone`
        # @return [Google::Apis::LocalservicesV1::GoogleTypeTimeZone]
        attr_accessor :timezone

        def initialize(**args)
           update!(**args)
        end

        # Update properties of this object
        def update!(**args)
          @account_id = args[:account_id] if args.key?(:account_id)
          @aggregator_info = args[:aggregator_info] if args.key?(:aggregator_info)
          @business_name = args[:business_name] if args.key?(:business_name)
          @charge_status = args[:charge_status] if args.key?(:charge_status)
          @currency_code = args[:currency_code] if args.key?(:currency_code)
          @dispute_status = args[:dispute_status] if args.key?(:dispute_status)
          @geo = args[:geo] if args.key?(:geo)
          @lead_category = args[:lead_category] if args.key?(:lead_category)
          @lead_creation_timestamp = args[:lead_creation_timestamp] if args.key?(:lead_creation_timestamp)
          @lead_id = args[:lead_id] if args.key?(:lead_id)
          @lead_price = args[:lead_price] if args.key?(:lead_price)
          @lead_type = args[:lead_type] if args.key?(:lead_type)
          @message_lead = args[:message_lead] if args.key?(:message_lead)
          @phone_lead = args[:phone_lead] if args.key?(:phone_lead)
          @timezone = args[:timezone] if args.key?(:timezone)
        end
      end

      # Container for message lead specific information.
      class GoogleAdsHomeservicesLocalservicesV1MessageLead
        include Google::Apis::Core::Hashable

        # Consumer phone number associated with the message lead.
        # Corresponds to the JSON property `consumerPhoneNumber`
        # @return [String]
        attr_accessor :consumer_phone_number

        # Name of the customer who created the lead.
        # Corresponds to the JSON property `customerName`
        # @return [String]
        attr_accessor :customer_name

        # The job type of the specified lead.
        # Corresponds to the JSON property `jobType`
        # @return [String]
        attr_accessor :job_type

        # The postal code of the customer who created the lead.
        # Corresponds to the JSON property `postalCode`
        # @return [String]
        attr_accessor :postal_code

        def initialize(**args)
           update!(**args)
        end

        # Update properties of this object
        def update!(**args)
          @consumer_phone_number = args[:consumer_phone_number] if args.key?(:consumer_phone_number)
          @customer_name = args[:customer_name] if args.key?(:customer_name)
          @job_type = args[:job_type] if args.key?(:job_type)
          @postal_code = args[:postal_code] if args.key?(:postal_code)
        end
      end

      # Container for phone lead specific information.
      class GoogleAdsHomeservicesLocalservicesV1PhoneLead
        include Google::Apis::Core::Hashable

        # Timestamp of the phone call which resulted in a charged phone lead.
        # Corresponds to the JSON property `chargedCallTimestamp`
        # @return [String]
        attr_accessor :charged_call_timestamp

        # Duration of the charged phone call in seconds.
        # Corresponds to the JSON property `chargedConnectedCallDurationSeconds`
        # @return [String]
        attr_accessor :charged_connected_call_duration_seconds

        # Consumer phone number associated with the phone lead.
        # Corresponds to the JSON property `consumerPhoneNumber`
        # @return [String]
        attr_accessor :consumer_phone_number

        def initialize(**args)
           update!(**args)
        end

        # Update properties of this object
        def update!(**args)
          @charged_call_timestamp = args[:charged_call_timestamp] if args.key?(:charged_call_timestamp)
          @charged_connected_call_duration_seconds = args[:charged_connected_call_duration_seconds] if args.key?(:charged_connected_call_duration_seconds)
          @consumer_phone_number = args[:consumer_phone_number] if args.key?(:consumer_phone_number)
        end
      end

      # A page of the response received from the SearchAccountReports method. A
      # paginated response where more pages are available has `next_page_token` set.
      # This token can be used in a subsequent request to retrieve the next request
      # page.
      class GoogleAdsHomeservicesLocalservicesV1SearchAccountReportsResponse
        include Google::Apis::Core::Hashable

        # List of account reports which maps 1:1 to a particular linked GLS account.
        # Corresponds to the JSON property `accountReports`
        # @return [Array<Google::Apis::LocalservicesV1::GoogleAdsHomeservicesLocalservicesV1AccountReport>]
        attr_accessor :account_reports

        # Pagination token to retrieve the next page of results. When `next_page_token`
        # is not filled in, there is no next page and the list returned is the last page
        # in the result set.
        # Corresponds to the JSON property `nextPageToken`
        # @return [String]
        attr_accessor :next_page_token

        def initialize(**args)
           update!(**args)
        end

        # Update properties of this object
        def update!(**args)
          @account_reports = args[:account_reports] if args.key?(:account_reports)
          @next_page_token = args[:next_page_token] if args.key?(:next_page_token)
        end
      end

      # A page of the response received from the SearchDetailedLeadReports method. A
      # paginated response where more pages are available has `next_page_token` set.
      # This token can be used in a subsequent request to retrieve the next request
      # page.
      class GoogleAdsHomeservicesLocalservicesV1SearchDetailedLeadReportsResponse
        include Google::Apis::Core::Hashable

        # List of detailed lead reports uniquely identified by external lead id.
        # Corresponds to the JSON property `detailedLeadReports`
        # @return [Array<Google::Apis::LocalservicesV1::GoogleAdsHomeservicesLocalservicesV1DetailedLeadReport>]
        attr_accessor :detailed_lead_reports

        # Pagination token to retrieve the next page of results. When `next_page_token`
        # is not filled in, there is no next page and the list returned is the last page
        # in the result set.
        # Corresponds to the JSON property `nextPageToken`
        # @return [String]
        attr_accessor :next_page_token

        def initialize(**args)
           update!(**args)
        end

        # Update properties of this object
        def update!(**args)
          @detailed_lead_reports = args[:detailed_lead_reports] if args.key?(:detailed_lead_reports)
          @next_page_token = args[:next_page_token] if args.key?(:next_page_token)
        end
      end

      # Represents a time zone from the [IANA Time Zone Database](https://www.iana.org/
      # time-zones).
      class GoogleTypeTimeZone
        include Google::Apis::Core::Hashable

        # IANA Time Zone Database time zone, e.g. "America/New_York".
        # Corresponds to the JSON property `id`
        # @return [String]
        attr_accessor :id

        # Optional. IANA Time Zone Database version number, e.g. "2019a".
        # Corresponds to the JSON property `version`
        # @return [String]
        attr_accessor :version

        def initialize(**args)
           update!(**args)
        end

        # Update properties of this object
        def update!(**args)
          @id = args[:id] if args.key?(:id)
          @version = args[:version] if args.key?(:version)
        end
      end
    end
  end
end


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import logging
import os
import random
import time

import numpy as np

import ray
from ray.experimental.sgd.sgd_worker import SGDWorker
from ray.experimental.sgd.param_server import ParameterServer

logger = logging.getLogger(__name__)

class DistributedSGD(object):
    """Experimental distributed SGD implementation in Ray.

    This supports two modes:
        'simple': centralized gradient aggregation
        'ps': sharded parameter-server implementation

    To use this class, you'll have to implement model.py:Model.

    Arguments:
        model_creator (func): Function that returns a model given worker and
            device indexes as arguments. Each model replica will be created
            within its own variable scope.
        num_workers (int): Number of Ray actors to use for SGD.
        devices_per_worker (int): Number of GPU or CPU devices to use per
            worker. One model replica will be created per device.
        gpu (bool): Whether to use GPU devices.
        strategy (str): Strategy to use for distributed gradient aggregation.
            This only applies if num_workers > 1.
        grad_shard_bytes (int): Fuse gradient tensors into chunks of at most
            this size (if applicable).
        all_reduce_alg (str): TensorFlow strategy to use for gradient
            synchronization within the same worker (if applicable).
            See modified_allreduce.py for options.

    Examples:
        >>> # Setup distributed SGD
        >>> model_creator = (
        ...   lambda worker_idx, device_idx: YourModelClass(...))
        >>> sgd = DistributedSGD(
        ...   model_creator, num_workers=2,
        ...   devices_per_worker=4, gpu=True, strategy="ps")

        >>> # To train
        >>> for i in range(100):
        ...   stats = sgd.step(fetch_stats=i % 10 == 0)

        >>> # To access or update model state
        >>> sgd.foreach_model(lambda model: ...)

        >>> # To access or update worker state
        >>> sgd.foreach_worker(lambda worker: ...)
    """

    def __init__(self,
                 model_creator,
                 num_workers,
                 devices_per_worker,
                 gpu=True,
                 strategy="ps",
                 grad_shard_bytes=10000000,
                 all_reduce_alg="simple"):

        if num_workers == 1 and strategy == "ps":
            logger.warning(
                "The parameter server strategy does not make sense for single "
                "worker operation, falling back to simple mode.")
            strategy = "simple"

        if strategy == "ps":
            use_plasma_op = True
        elif strategy == "simple":
            use_plasma_op = False
            grad_shard_bytes = 0  # tensor fusion doesn't make sense
        else:
            raise ValueError("strategy must be one of 'ps', 'simple'")
        self.strategy = strategy

        self.model_creator = model_creator
        if gpu:
            requests = {"num_gpus": devices_per_worker}
        else:
            requests = {"num_cpus": devices_per_worker}

        RemoteSGDWorker = ray.remote(**requests)(SGDWorker)
        self.workers = []
        logger.info(
            "Creating SGD workers ({} total, {} devices per worker)".format(
                num_workers, devices_per_worker))
        for worker_index in range(num_workers):
            self.workers.append(
                RemoteSGDWorker.remote(
                    worker_index,
                    model_creator,
                    num_devices=devices_per_worker,
                    plasma_op=use_plasma_op,
                    gpu=gpu,
                    max_bytes=grad_shard_bytes,
                    all_reduce_alg=all_reduce_alg))

        logger.info("Waiting for gradient configuration")
        shard_shapes = ray.get(self.workers[0].shard_shapes.remote())

        logger.info("Waiting for actors to start")
        ray.get([w.shard_shapes.remote() for w in self.workers])

        if strategy == "ps":
            logger.info("Starting parameter servers ({} shards)".format(
                len(shard_shapes)))
            self.ps_list = [
                ParameterServer.remote(len(self.workers), i)
                for i, s in enumerate(shard_shapes)
            ]
            ray.get([
                ps.initialize.remote(s)
                for ps, s in zip(self.ps_list, shard_shapes)
            ])
            logger.info("Parameter servers started")
        else:
            self.ps_list = []

    def foreach_worker(self, fn):
        """Apply the given function to each remote worker.

        Returns:
            List of results from applying the function.
        """
        results = ray.get([w.foreach_worker.remote(fn) for w in self.workers])
        return results

    def foreach_model(self, fn):
        """Apply the given function to each model replica in each worker.

        Returns:
            List of results from applying the function.
        """

        results = ray.get([w.foreach_model.remote(fn) for w in self.workers])
        out = []
        for r in results:
            out.extend(r)
        return out

    def for_model(self, fn):
        """Apply the given function to a single model replica.

        Returns:
            Result from applying the function.
        """
        return ray.get(self.workers[0].for_model.remote(fn))

    def step(self, fetch_stats=False):
        """Run a single SGD step.

        Arguments:
            fetch_stats (bool): Whether to return stats from the step. This can
                slow down the computation by acting as a global barrier.
        """
        if self.strategy == "ps":
            return _distributed_sgd_step(
                self.workers,
                self.ps_list,
                write_timeline=False,
                fetch_stats=fetch_stats)
        else:
            return _simple_sgd_step(self.workers)

    def warmup(self):
        logger.info("Warming up object store of worker actors")
        ray.get([w.warmup.remote() for w in self.workers])
        logger.info("Warmup complete")

    def save_checkpoint(self, path):
        w0 = self.for_model(lambda m: m.get_weights())
        filename = os.path.join(path, "model.npy")
        np.save(filename, w0)

    def restore_checkpoint(self, path):
        filename = os.path.join(path, "model.npy")
        w0 = np.load(filename)
        self.foreach_model(lambda m: m.set_weights(w0))

def _average_gradients(grads):
    out = []
    for grad_list in zip(*grads):
        out.append(np.mean(grad_list, axis=0))
    return out

def _simple_sgd_step(actors):
    if len(actors) == 1:
        return {"loss": ray.get(actors[0].compute_apply.remote())}

    start = time.time()
    fetches = ray.get([a.compute_gradients.remote() for a in actors])
    losses = [f[0] for f in fetches]
    grads = [f[1] for f in fetches]
    logger.debug("compute all grads time {}".format(time.time() - start))
    start = time.time()
    if len(actors) == 1:
        assert len(grads) == 1
        avg_grad = grads[0]
    else:
        avg_grad = _average_gradients(grads)
        logger.debug("grad reduce time {}".format(time.time() - start))
    start = time.time()
    ray.get([a.apply_gradients.remote(avg_grad) for a in actors])
    logger.debug("apply all grads time {}".format(time.time() - start))
    return {"loss": np.mean(losses)}

def _distributed_sgd_step(actors, ps_list, fetch_stats, write_timeline):
    # Preallocate object ids that actors will write gradient shards to
    grad_shard_oids_list = [[np.random.bytes(20) for _ in ps_list]
                            for _ in actors]
    logger.debug("Generated grad oids")

    # Preallocate object ids that param servers will write new weights to
    accum_shard_ids = [np.random.bytes(20) for _ in ps_list]
    logger.debug("Generated accum oids")

    # Kick off the fused compute grad / update weights tf run for each actor
    losses = []
    for actor, grad_shard_oids in zip(actors, grad_shard_oids_list):
        losses.append(
            actor.ps_compute_apply.remote(
                grad_shard_oids,
                accum_shard_ids,
                write_timeline=write_timeline))
    logger.debug("Launched all ps_compute_applys on all actors")

    # Issue prefetch ops
    for j, (ps, weight_shard_oid) in list(
            enumerate(zip(ps_list, accum_shard_ids)))[::-1]:
        to_fetch = []
        for grad_shard_oids in grad_shard_oids_list:
            to_fetch.append(grad_shard_oids[j])
        random.shuffle(to_fetch)
        ps.prefetch.remote(to_fetch)
    logger.debug("Launched all prefetch ops")

    # Aggregate the gradients produced by the actors. These operations
    # run concurrently with the actor methods above.
    ps_gets = []
    for j, (ps, weight_shard_oid) in list(
            enumerate(zip(ps_list, accum_shard_ids)))[::-1]:
        ps.add_spinwait.remote([gs[j] for gs in grad_shard_oids_list])
        ps_gets.append(ps.get.remote(weight_shard_oid))
    logger.debug("Launched all aggregate ops")

    if write_timeline:
        timelines = [ps.get_timeline.remote() for ps in ps_list]
        logger.debug("Launched timeline gets")
        timelines = ray.get(timelines)
        t0 = timelines[0]
        for t in timelines[1:]:
            t0.merge(t)
        t0.chrome_trace_format("ps_timeline.json")
    else:
        # Wait for at least the ps gets to finish
        ray.get(ps_gets)
    if fetch_stats:
        return {"loss": np.mean(ray.get(losses))}
    else:
        return None


text:
echo "exclude=servercentral.net, .gov, facebook" >> /etc/yum/pluginconf.d/fastestmirror.conf
yum clean all

cat > /etc/yum.repos.d/epel.repo << EOM
[epel]
name=epel
mirrorlist=http://mirrors.fedoraproject.org/mirrorlist?repo=epel-7&arch=\$basearch
enabled=1
gpgcheck=0
EOM


text:
require 'spec_helper'

describe 'apt_has_dist_updates fact' do
  subject { Facter.fact(:apt_has_dist_updates).value }

  after(:each) { Facter.clear }

  describe 'on non-Debian distro' do
    before(:each) do
      Facter.fact(:osfamily).expects(:value).at_least(1).returns 'RedHat'
    end
    it { is_expected.to be_nil }
  end

  describe 'on Debian based distro missing apt-get' do
    before(:each) do
      Facter.fact(:osfamily).expects(:value).at_least(1).returns 'Debian'
      File.stubs(:executable?) # Stub all other calls
      File.expects(:executable?).with('/usr/bin/apt-get').returns false
    end
    it { is_expected.to be_nil }
  end

  describe 'on Debian based distro' do
    before(:each) do
      Facter.fact(:osfamily).expects(:value).at_least(1).returns 'Debian'
      File.stubs(:executable?) # Stub all other calls
      Facter::Util::Resolution.stubs(:exec) # Catch all other calls
      File.expects(:executable?).with('/usr/bin/apt-get').returns true
      Facter::Util::Resolution.expects(:exec).with('/usr/bin/apt-get -s -o Debug::NoLocking=true upgrade 2>&1').returns 'test'
      File.expects(:executable?).with('/usr/bin/apt-get').returns true
      apt_output = "Inst extremetuxracer [2015f-0+deb8u1] (2015g-0+deb8u1 Debian:stable-updates [all])\n" \
                   "Conf extremetuxracer (2015g-0+deb8u1 Debian:stable-updates [all])\n" \
                   "Inst planet.rb [13-1.1] (22-2~bpo8+1 Debian Backports:jessie-backports [all])\n" \
                   "Conf planet.rb (22-2~bpo8+1 Debian Backports:jessie-backports [all])\n"
      Facter::Util::Resolution.expects(:exec).with('/usr/bin/apt-get -s -o Debug::NoLocking=true dist-upgrade 2>&1').returns apt_output
    end
    it { is_expected.to be true }
  end
end


text:
import pandas as pd

def _terms_agg_to_df(aggs_json):
    """
    Given the JSON returned by an Elasticsearch aggs "terms" query,
    parse that JSON into a Pandas DataFrame. Currently only has
    support for a one-field aggs.

    The "terms" query is analogous to a COUNT() and GROUPBY in SQL world.
    It returns counts of unique values for a given attribute. For more, see
    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html

    Args:
        **aggs_json (dict)**: A dictionary representation of an aggs query
            result. If a str is passed, it will be converted to a dictionary.

    Returns:
        A pandas DataFrame representation of the aggs query.
    """

    if not isinstance(aggs_json, str):
        raise TypeError("aggs_json must be a dictionary, you gave {}".format(type(aggs_json)))

    # Parse the result into a DF
    key_name = list(aggs_json.keys())[0]

    parsed_obs = [[obs['key'], obs['doc_count']] for obs in aggs_json[key_name]['buckets']]
    out_df = pd.DataFrame(parsed_obs, columns=[key_name, 'doc_count'])

    return(out_df)

def _extended_stats_agg_to_df(aggs_json):
    """
    Given the JSON returned by an Elasticsearch "extended_stats" aggregation,
    parse that JSON into a Pandas DataFrame. Currently only has
    support for a one-field aggs.

    The "extended_stats" aggregation computes the following summary statistics
    on a given numerical field: count, min, max, mean, sum, sum of squares,
    variance, and standard deviation. For more, see
    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-extendedstats-aggregation.html

    Args:
        **aggs_json (dict)**: A dictionary representation of an aggs query
            result. If a str is passed, it will be converted to a dictionary.

    Returns:
        A pandas DataFrame representation of the aggs query.
    """

    if not isinstance(aggs_json, str):
        raise TypeError("aggs_json must be a dictionary, you gave {}".format(type(aggs_json)))

    # Parse the result into a DF
    key_name = list(aggs_json.keys())[0]

    out_df = pd.DataFrame({'agg_field': key_name,
                           'count': aggs_json[key_name]['count'],
                           'min': aggs_json[key_name]['min'],
                           'max': aggs_json[key_name]['max'],
                           'avg': aggs_json[key_name]['avg'],
                           'sum': aggs_json[key_name]['sum'],
                           'sum_of_squares': aggs_json[key_name]['sum_of_squares'],
                           'variance': aggs_json[key_name]['variance'],
                           'std_deviation': aggs_json[key_name]['std_deviation']
                           }, index=[0])

    return(out_df)

def _stats_agg_to_df(aggs_json):
    """
    Given the JSON returned by an Elasticsearch "stats" aggregation,
    parse that JSON into a Pandas DataFrame. Currently only has
    support for a one-field aggs.

    The "stats" aggregation computes the following summary statistics
    on a given numerical field: count, min, max, mean, sum. For more, see
    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-stats-aggregation.html

    Args:
        **aggs_json (dict)**: A dictionary representation of an aggs query
            result. If a str is passed, it will be converted to a dictionary.

    Returns:
        A pandas DataFrame representation of the aggs query.
    """

    if not isinstance(aggs_json, str):
        raise TypeError("aggs_json must be a dictionary, you gave {}".format(type(aggs_json)))

    # Parse the result into a DF
    key_name = list(aggs_json.keys())[0]

    out_df = pd.DataFrame({'agg_field': key_name,
                           'count': aggs_json[key_name]['count'],
                           'min': aggs_json[key_name]['min'],
                           'max': aggs_json[key_name]['max'],
                           'avg': aggs_json[key_name]['avg'],
                           'sum': aggs_json[key_name]['sum']
                           }, index=[0])

    return(out_df)

def _date_histogram_agg_to_df(aggs_json):
    """
    Given the JSON returned by an Elasticsearch aggs "date_histogram" query,
    parse that JSON into a Pandas DataFrame. Currently only has
    support for a one-field aggs.

    The "date_histogram" aggregation is used to bucket records into discrete,
    equal-sized time windows. The plain-vanilla date_histogram aggregation
    returns counts of documents within each window, but the most common use
    case involves nested other aggregations within a date_histogram to
    create time-series features. For more, see:
    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-datehistogram-aggregation.html

    Args:
        **aggs_json (dict)**: A dictionary representation of an aggs query
            result. If a str is passed, it will be converted to a dictionary.

    Returns:
        A pandas DataFrame representation of the aggs query.
    """

    if not isinstance(aggs_json, str):
        raise TypeError("aggs_json must be a dictionary, you gave {}".format(type(aggs_json)))

    # Parse the result into a DF
    key_name = list(aggs_json.keys())[0]

    parsed_obs = [[obs['key_as_string'], obs['doc_count']] for obs in aggs_json[key_name]['buckets']]
    out_df = pd.DataFrame(parsed_obs, columns=[key_name, 'doc_count'])

    return(out_df)

def _percentiles_agg_to_df(aggs_json):
    """
    Given the JSON returned by an Elasticsearch aggs "percentiles" query,
    parse that JSON into a Pandas DataFrame. Currently only has
    support for a one-field aggs.

    The "percentiles" aggregation takes in a vector of desired percentiles
    and returns the corresponding percentiles from the distribution of a
    numeric field. For more, see
    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-percentile-aggregation.html

    Args:
        **aggs_json (dict)**: A dictionary representation of an aggs query
            result. If a str is passed, it will be converted to a dictionary.

    Returns:
        A pandas DataFrame representation of the aggs query.
    """

    if not isinstance(aggs_json, str):
        raise TypeError("aggs_json must be a dictionary, you gave {}".format(type(aggs_json)))

    # Parse the result into a DF
    key_name = list(aggs_json.keys())[0]

    out_dict = {'agg_field': key_name}
    out_dict.update(aggs_json[key_name]['values'])
    out_df = pd.DataFrame(out_dict, index=[0])

    return(out_df)


text:
from pathlib import Path
from unittest import mock

from django.template import autoreload
from django.test import SimpleTestCase, override_settings
from django.test.utils import require_jinja2

ROOT = Path(__file__).parent.absolute()
EXTRA_TEMPLATES_DIR = ROOT / "templates_extra"

@override_settings(
    INSTALLED_APPS=['template_tests'],
    TEMPLATES=[{
        'BACKEND': 'django.template.backends.dummy.TemplateStrings',
        'APP_DIRS': True,
    }, {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [EXTRA_TEMPLATES_DIR],
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
            ],
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ]
        },
    }])
class TemplateReloadTests(SimpleTestCase):
    @mock.patch('django.template.autoreload.reset_loaders')
    def test_template_changed(self, mock_reset):
        template_path = Path(__file__).parent / 'templates' / 'index.html'
        self.assertTrue(autoreload.template_changed(None, template_path))
        mock_reset.assert_called_once()

    @mock.patch('django.template.autoreload.reset_loaders')
    def test_non_template_changed(self, mock_reset):
        self.assertIsNone(autoreload.template_changed(None, Path(__file__)))
        mock_reset.assert_not_called()

    def test_watch_for_template_changes(self):
        mock_reloader = mock.MagicMock()
        autoreload.watch_for_template_changes(mock_reloader)
        self.assertSequenceEqual(
            sorted(mock_reloader.watch_dir.call_args_list),
            [
                mock.call(ROOT / 'templates', '**/*'),
                mock.call(ROOT / 'templates_extra', '**/*')
            ]
        )

    def test_get_template_directories(self):
        self.assertSetEqual(
            autoreload.get_template_directories(),
            {
                ROOT / 'templates_extra',
                ROOT / 'templates',
            }
        )

    @mock.patch('django.template.loaders.base.Loader.reset')
    def test_reset_all_loaders(self, mock_reset):
        autoreload.reset_loaders()
        self.assertEqual(mock_reset.call_count, 2)

    @override_settings(
        TEMPLATES=[
            {
                "DIRS": [""],
                "BACKEND": "django.template.backends.django.DjangoTemplates",
            }
        ]
    )
    def test_template_dirs_ignore_empty_path(self):
        self.assertEqual(autoreload.get_template_directories(), set())

    @override_settings(
        TEMPLATES=[{
            'DIRS': [
                str(ROOT) + '/absolute_str',
                'template_tests/relative_str',
                Path('template_tests/relative_path'),
            ],
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
        }]
    )
    def test_template_dirs_normalized_to_paths(self):
        self.assertSetEqual(
            autoreload.get_template_directories(),
            {
                ROOT / 'absolute_str',
                Path.cwd() / 'template_tests/relative_str',
                Path.cwd() / 'template_tests/relative_path',
            }
        )

@require_jinja2
@override_settings(INSTALLED_APPS=['template_tests'])
class Jinja2TemplateReloadTests(SimpleTestCase):
    def test_watch_for_template_changes(self):
        mock_reloader = mock.MagicMock()
        autoreload.watch_for_template_changes(mock_reloader)
        self.assertSequenceEqual(
            sorted(mock_reloader.watch_dir.call_args_list),
            [
                mock.call(ROOT / 'templates', '**/*'),
            ]
        )

    def test_get_template_directories(self):
        self.assertSetEqual(
            autoreload.get_template_directories(),
            {
                ROOT / 'templates',
            }
        )

    @mock.patch('django.template.loaders.base.Loader.reset')
    def test_reset_all_loaders(self, mock_reset):
        autoreload.reset_loaders()
        self.assertEqual(mock_reset.call_count, 0)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketBase;

namespace SuperSocket.Test.Udp
{
    class MyUdpProtocol : ICustomProtocol<MyUdpCommandInfo>
    {
        public ICommandReader<MyUdpCommandInfo> CreateCommandReader(IAppServer appServer)
        {
            return new MyCommandReader(appServer);
        }
    }
}


text:
0.8.2: 2014-02-11
-----------------

- Fix bug in ``GitHub#search_users`` (and ``github3.search_users``). Thanks
  @abesto

- Expose the stargazers count for repositories. Thanks @seveas


text:
package org.sklsft.generator.model.exception;

public class ProjectNotFoundException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public ProjectNotFoundException (String message) {
		super(message);
	}

	public ProjectNotFoundException (String message, Throwable t) {
		super(message, t);
	}
}


text:
@interface CoreDataManager ()

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

@end

@implementation CoreDataManager

#pragma mark - Singleton
// Singleton instance
+ (CoreDataManager *)sharedInstance
{
    static CoreDataManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[CoreDataManager alloc] init];
    });

    return sharedInstance;
}

#pragma mark - Static methods
// Set the coredata managed object context in order to share the same context in the application.
+ (void)setCoreDataManagedObjectContext:(NSManagedObjectContext *)context
{
    [[CoreDataManager sharedInstance] setManagedObjectContext:context];
}

// Remove all rows of the entityForName entity table.
+ (void)removeCoreDataEntityRows:(NSString*)entityForName
{
    if ([CoreDataManager sharedInstance].managedObjectContext != nil) {
        // Retrieve the rows to remove.
        NSArray *items  = [CoreDataManager getAllEntityRecords:entityForName];

        for (NSManagedObject *managedObject in items) {
            [[CoreDataManager sharedInstance].managedObjectContext deleteObject:managedObject];
        }

        items = nil;
    } else {
        // Catch an exception when the coredata context is not set.
        @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"ManagedObjectContext must be set from the app delegate"] userInfo:nil];
    }
}

// Get all the rows of the entityForName entity table.
+ (NSArray*)getAllEntityRecords:(NSString*)entityForName
{
    if ([CoreDataManager sharedInstance].managedObjectContext != nil) {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:entityForName
                                                  inManagedObjectContext:[CoreDataManager sharedInstance].managedObjectContext];
        [fetchRequest setEntity:entity];

        NSError* error;
        NSArray *fetchedRecords = [[CoreDataManager sharedInstance].managedObjectContext executeFetchRequest:fetchRequest
                                                                                error:&error];
        return fetchedRecords;
    } else {
        @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"ManagedObjectContext must be set from the app delegate"] userInfo:nil];
    }
}

@end


text:
Collection of classes and peices of code neatly organized for easy reuse:

* MABSupportFolder - class for managing + creating your app's support folder `~/Library/Application Support/YourAppName`
* NSTableView+MABTableViewSizing - class for easily resizing a table's columns to fit available width
* ThreadWorker - class for easily managing threads
* MABMacros - some helpful macros for managing preferences, checking for empty values, and other misc tasks
* NSString+Levenshtein - implementation of the Levenshtein string distance algorithm in objc
* NSString+SearchAdditions - simple contains (case and non-case sensitive) boolean functions
* MABSplitView - NSSplitView with divider image
* MABSystemInformation - A combination of the old CPSystemInformation class and Sparkle's system profiler. Self-contained and allows for the retrieval of some additional information that Sparkle does not allow for.

#Authors
Most of the code in this bundle is not my own. Most of the original concepts were developed by others and I modified them a bit or brought them up to compatability with the latest OS. Proper attribution is given when I was able to find the original authors information.


text:
<?php

/**
 * Refund  Sample
 */

require_once realpath(dirname(__FILE__)) . '/.config.inc.php';

/**
 * Throw an error if the refund is not in the
 * completed status
 *
 * @param OffAmazonPaymentsService_Model_RefundDetails $response service response
 * @throws ErrorException
 */
function validateThatRefundIsCompleted($refundDetails)
{
    if (strcasecmp($refundDetails->getRefundStatus()->getState(),"Completed") != 0) {
        throw new ErrorException(
            "Error with refund " .
            $refundDetails->getRefundReferenceId() . " - state is " .
            $refundDetails->getRefundStatus()->getState() . PHP_EOL
        );
    }
}

/**
  * Refund Action Sample

  * @param OffAmazonPaymentsService_Interface $service instance of OffAmazonPaymentsService_Interface
  * @param mixed $request OffAmazonPaymentsService_Model_Refund or array of parameters
  */
function printRefundResponse($response)
{

                print "Service Response" . PHP_EOL;
                print "=============================================================================" . PHP_EOL;

                print "        RefundResponse" . PHP_EOL;
                if ($response->isSetRefundResult()) {
                    print "            RefundResult" . PHP_EOL;
                    $refundResult = $response->getRefundResult();
                    if ($refundResult->isSetRefundDetails()) {
                        print "                RefundDetails" . PHP_EOL;
                        $refundDetails = $refundResult->getRefundDetails();
                        if ($refundDetails->isSetAmazonRefundId())
                        {
                            print "                    AmazonRefundId" . PHP_EOL;
                            print "                        " . $refundDetails->getAmazonRefundId() . PHP_EOL;
                        }
                        if ($refundDetails->isSetRefundReferenceId())
                        {
                            print "                    RefundReferenceId" . PHP_EOL;
                            print "                        " . $refundDetails->getRefundReferenceId() . PHP_EOL;
                        }
                        if ($refundDetails->isSetSellerRefundNote())
                        {
                            print "                    SellerRefundNote" . PHP_EOL;
                            print "                        " . $refundDetails->getSellerRefundNote() . PHP_EOL;
                        }
                        if ($refundDetails->isSetRefundType())
                        {
                            print "                    RefundType" . PHP_EOL;
                            print "                        " . $refundDetails->getRefundType() . PHP_EOL;
                        }
                        if ($refundDetails->isSetRefundAmount()) {
                            print "                    RefundAmount" . PHP_EOL;
                            $refundAmount = $refundDetails->getRefundAmount();
                            if ($refundAmount->isSetAmount())
                            {
                                print "                        Amount" . PHP_EOL;
                                print "                            " . $refundAmount->getAmount() . PHP_EOL;
                            }
                            if ($refundAmount->isSetCurrencyCode())
                            {
                                print "                        CurrencyCode" . PHP_EOL;
                                print "                            " . $refundAmount->getCurrencyCode() . PHP_EOL;
                            }
                        }
                        if ($refundDetails->isSetFeeRefunded()) {
                            print "                    FeeRefunded" . PHP_EOL;
                            $feeRefunded = $refundDetails->getFeeRefunded();
                            if ($feeRefunded->isSetAmount())
                            {
                                print "                        Amount" . PHP_EOL;
                                print "                            " . $feeRefunded->getAmount() . PHP_EOL;
                            }
                            if ($feeRefunded->isSetCurrencyCode())
                            {
                                print "                        CurrencyCode" . PHP_EOL;
                                print "                            " . $feeRefunded->getCurrencyCode() . PHP_EOL;
                            }
                        }
                        if ($refundDetails->isSetCreationTimestamp())
                        {
                            print "                    CreationTimestamp" . PHP_EOL;
                            print "                        " . $refundDetails->getCreationTimestamp() . PHP_EOL;
                        }
                        if ($refundDetails->isSetRefundStatus()) {
                            print "                    RefundStatus" . PHP_EOL;
                            $refundStatus = $refundDetails->getRefundStatus();
                            if ($refundStatus->isSetState())
                            {
                                print "                        State" . PHP_EOL;
                                print "                            " . $refundStatus->getState() . PHP_EOL;
                            }
                            if ($refundStatus->isSetLastUpdateTimestamp())
                            {
                                print "                        LastUpdateTimestamp" . PHP_EOL;
                                print "                            " . $refundStatus->getLastUpdateTimestamp() . PHP_EOL;
                            }
                            if ($refundStatus->isSetReasonCode())
                            {
                                print "                        ReasonCode" . PHP_EOL;
                                print "                            " . $refundStatus->getReasonCode() . PHP_EOL;
                            }
                            if ($refundStatus->isSetReasonDescription())
                            {
                                print "                        ReasonDescription" . PHP_EOL;
                                print "                            " . $refundStatus->getReasonDescription() . PHP_EOL;
                            }
                        }
                        if ($refundDetails->isSetSoftDescriptor())
                        {
                            print "        SoftDescriptor" . PHP_EOL;
                            print "            " . $refundDetails->getSoftDescriptor() . PHP_EOL;
                        }
                        if($refundDetails->isSetProviderCreditReversalSummaryList()){
                        	print "                    ProviderCreditReversalSummaryList" . PHP_EOL;
                        	$providerCreditReversalSummaryList = $refundDetails->getProviderCreditReversalSummaryList();
                        	if($providerCreditReversalSummaryList->isSetProviderCreditReversalSummary()){
                        		$values = $providerCreditReversalSummaryList->getProviderCreditReversalSummary();
                        		foreach($values as $value){
                        			print "                        ProviderCreditReversalSummary" . PHP_EOL;
                        			if($value->isSetProviderId()){
                        				print "                            ProviderId" . PHP_EOL;
                        				print "                                ".$value->getProviderId() . PHP_EOL;
                        			}
                        			if($value->isSetProviderCreditReversalId()){
                        				print "                            ProviderCreditReversalId" . PHP_EOL;
                        				print "                                ".$value->getProviderCreditReversalId() . PHP_EOL;
                        			}
                        		}
                        	}
                        }
                    }
                }
                if ($response->isSetResponseMetadata()) {
                    print "            ResponseMetadata" . PHP_EOL;
                    $responseMetadata = $response->getResponseMetadata();
                    if ($responseMetadata->isSetRequestId())
                    {
                        print "                RequestId" . PHP_EOL;
                        print "                    " . $responseMetadata->getRequestId() . PHP_EOL;
                    }
                }

   	print "            ResponseHeaderMetadata: " .
    $response->getResponseHeaderMetadata() . PHP_EOL;

   	return $response;
}

?>


text:
package techreborn.init.recipes;

import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import reborncore.common.util.RebornCraftingHelper;
import techreborn.blocks.BlockOre;
import techreborn.blocks.BlockOre2;
import techreborn.init.IC2Duplicates;

/**
 * Created by Prospector
 */
public class SmeltingRecipes extends RecipeMethods {
	public static void init() {

		register(getMaterial("sap", Type.PART), getMaterial("rubber", Type.PART));
		if (!IC2Duplicates.deduplicate()) {
			register(getStack(Items.IRON_INGOT), getMaterial("refined_iron", Type.INGOT));
		}
		register(BlockOre2.getOreByName("copper"), getMaterial("copper", Type.INGOT));
		register(BlockOre2.getOreByName("tin"), getMaterial("tin", Type.INGOT));
		register(BlockOre.getOreByName("silver"), getMaterial("silver", Type.INGOT));
		register(BlockOre.getOreByName("lead"), getMaterial("lead", Type.INGOT));
		register(BlockOre.getOreByName("sheldonite"), getMaterial("platinum", Type.INGOT));
		register(IC2Duplicates.MIXED_METAL.getStackBasedOnConfig(), getMaterial("advanced_alloy", Type.INGOT));

		// Dust smelting
		register(getMaterial("iron", Type.DUST), getStack(Items.IRON_INGOT));
		register(getMaterial("gold", Type.DUST), getStack(Items.GOLD_INGOT));
		register(getMaterial("copper", Type.DUST), getMaterial("copper", Type.INGOT));
		register(getMaterial("tin", Type.DUST), getMaterial("tin", Type.INGOT));
		register(getMaterial("bronze", Type.DUST), getMaterial("bronze", Type.INGOT));
		register(getMaterial("lead", Type.DUST), getMaterial("lead", Type.INGOT));
		register(getMaterial("silver", Type.DUST), getMaterial("silver", Type.INGOT));
		register(getMaterial("nickel", Type.DUST), getMaterial("nickel", Type.INGOT));
		register(getMaterial("platinum", Type.DUST), getMaterial("platinum", Type.INGOT));
		register(getMaterial("zinc", Type.DUST), getMaterial("zinc", Type.INGOT));
		register(getMaterial("brass", Type.DUST), getMaterial("brass", Type.INGOT));
		register(getMaterial("electrum", Type.DUST), getMaterial("electrum", Type.INGOT));
		register(getMaterial("invar", Type.DUST), getMaterial("invar", Type.INGOT));

	}

	static void register(ItemStack input, ItemStack output) {
		RebornCraftingHelper.addSmelting(input, output);
	}
}


text:
name: "🚀 Feature request"
about: "If you have a feature request ... 💡"
---

**Context**

What are you trying to do and how would you want to do it differently? Is it something you currently you cannot do? Is this related to an issue/problem?

**Alternatives**

Can you achieve the same result doing it in an alternative way? Is the alternative considerable?

**Has the feature been requested before?**

Please provide a link to the issue.

**If the feature request is approved, would you be willing to submit a PR?**

Yes / No _(Help can be provided if you need assistance submitting a PR)_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 22: 175 (1883)

#### Original name
Cercosporella rhaetica Sacc. & G. Winter

### Remarks
null


text:
class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :name
      t.string :location
      t.date :date
      t.string :starts_at
      t.integer :fee
      t.string :host_org

      t.timestamps
    end
  end
end


text:
import {getGlslDifferences} from './glsl_version';
import {GPGPUProgram, useShapeUniforms} from './gpgpu_math';
import * as shader_util from './shader_compiler_util';
import {PackingScheme} from './tex_util';

export class DecodeMatrixPackedProgram implements GPGPUProgram {
  variableNames = ['A'];
  userCode: string;
  packedInputs = true;
  packedOutput = true;
  outputShape: [number, number, number];
  outPackingScheme = PackingScheme.DENSE;
  enableShapeUniforms: boolean;
  customUniforms = [{name: 'texShape', type: 'ivec2' as const }];

  constructor(outputShape: [number, number, number]) {
    const glsl = getGlslDifferences();
    this.outputShape = outputShape;
    this.enableShapeUniforms = useShapeUniforms(this.outputShape.length);

    this.userCode = `
      ivec3 outCoordsFromFlatIndex(int index) {
        ${
        this.enableShapeUniforms ?
            shader_util.getOutputLogicalCoordinatesFromFlatIndexByUniform(
                ['r', 'c', 'd'], outputShape) :
            shader_util.getLogicalCoordinatesFromFlatIndex(
                ['r', 'c', 'd'], outputShape)}
        return ivec3(r, c, d);
      }

      void main() {
        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);

        vec4 result = vec4(0.);

        for (int i=0; i<4; i++) {
          int flatIndex = index + i;
          ivec3 rc = outCoordsFromFlatIndex(flatIndex);
          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
        }

        ${glsl.output} = result;
      }
    `;
  }
}


text:
namespace Grabacr07.KanColleViewer.Views.Contents
{
	public partial class Homeport
	{
		public Homeport()
		{
			InitializeComponent();
		}
	}
}


text:
(function () {
    angular.module("MenuApp", ['data', 'ui.router']);
})();


text:
package org.liveontologies.proofs;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.liveontologies.puli.InferenceJustifier;
import org.semanticweb.elk.owl.interfaces.ElkAxiom;
import org.semanticweb.elk.owl.visitors.DummyElkAxiomVisitor;
import org.semanticweb.elk.reasoner.tracing.Conclusion;
import org.semanticweb.elk.reasoner.tracing.ConclusionBaseFactory;
import org.semanticweb.elk.reasoner.tracing.DummyConclusionVisitor;
import org.semanticweb.elk.reasoner.tracing.TracingInference;
import org.semanticweb.elk.reasoner.tracing.TracingInferencePremiseVisitor;

public class TracingInferenceJustifier implements
		InferenceJustifier<TracingInference, Set<? extends ElkAxiom>> {

	public static final TracingInferenceJustifier INSTANCE = new TracingInferenceJustifier();

	private static final Conclusion.Factory CONCLUSION_FACTORY_ = new ConclusionBaseFactory();

	private static final Conclusion.Visitor<Void> DUMMY_CONCLUSION_VISITOR_ = new DummyConclusionVisitor<Void>();

	private TracingInferenceJustifier() {
		// Forbid instantiation.
	}

	@Override
	public Set<? extends ElkAxiom> getJustification(
			final TracingInference inference) {
		// else
		final Set<ElkAxiom> result = new HashSet<ElkAxiom>();
		inference.accept(new TracingInferencePremiseVisitor<>(
				CONCLUSION_FACTORY_, DUMMY_CONCLUSION_VISITOR_,
				new ElkAxiomCollector(result)));
		return result;
	}

	private static class ElkAxiomCollector extends DummyElkAxiomVisitor<Void> {

		private final Collection<ElkAxiom> axioms_;

		public ElkAxiomCollector(final Collection<ElkAxiom> axioms) {
			this.axioms_ = axioms;
		}

		@Override
		protected Void defaultLogicalVisit(ElkAxiom axiom) {
			axioms_.add(axiom);
			return null;
		}

	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<comment>
		<sentence>
				<text>odlične pizza verona i pizza piša ... </text>
				<pairs>
						<pair aspect="pizza" anchor="odlične" link="+" sent="" />
						<pair aspect="pizza" anchor="odlične" link="+" sent="" />
				</pairs>
		</sentence>
		<sentence>
				<text>a dobra je i hladna salata s piletinom ! </text>
				<pairs>
						<pair aspect="salata" anchor="dobra" link="+" sent="" />
						<pair aspect="piletinom" anchor="dobra" link="+" sent="" />
						<pair aspect="salata" anchor="hladna" link="+" sent="" />
						<pair aspect="piletinom" anchor="hladna" link="+" sent="" />
				</pairs>
		</sentence>
		<sentence>
				<text>često naručujemo iz dvojke , moja preporuka </text>
				<pairs />
		</sentence>
</comment>


text:
For instructions on how to get started, please visit our GitHub project:
https://github.com/googleads/googleads-php-lib

For API and client library updates and news, please follow our
[Google+ Ads Developers page](https://plus.google.com/+GoogleAdsDevelopers/posts)
and our [Google Ads Developers blog](http://googleadsdeveloper.blogspot.com/).

For any issues relating to the API in general (not this library), please see the
[AdWords API forum](https://groups.google.com/forum/#!forum/adwords-api)


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// eslint-disable-next-line no-unused-vars
import {Flag} from '../flag.js';
// eslint-disable-next-line no-unused-vars
import {I18nString} from '../i18n_string.js';

/**
 * Returns the device board name.
 * @return {string}
 */
export function getBoard() {
  return window.loadTimeData.getString('board_name');
}

/**
 * Returns the device type.
 * @return {string}
 */
export function getDeviceType() {
  return window.loadTimeData.getString('device_type');
}

/**
 * Returns the I18N message generated by given |name| and |substitutions|.
 * @param {!I18nString} name
 * @param {...(string|number)} substitutions
 * @return {string}
 */
export function getI18nMessage(name, ...substitutions) {
  return window.loadTimeData.getStringF(name, ...substitutions);
}

/**
 * @return {string} Returns 'ltr'/'rtl' for left-to-right/right-to-left system
 *     UI language.
 */
export function getTextDirection() {
  return window.loadTimeData.getString('textdirection');
}

/**
 * Returns the boolean value of the chrome flag.
 * @param {Flag} flag
 * @return {boolean}
 */
export function getChromeFlag(flag) {
  return window.loadTimeData.getBoolean(flag);
}


text:
<?php

namespace Zoop\Shard\User\DataModel;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Zoop\Shard\Annotation\Annotations as Shard;

trait UserTrait
{
    /**
     * @ODM\Id(strategy="none")
     * @ODM\Index(unique = true, order = "asc")
     * @Shard\Validator\Chain({
     *     @Shard\Validator\Required,
     *     @Shard\Validator\Slug
     * })
     */
    protected $username;

    public function getUsername()
    {
        return $this->username;
    }

    public function setUsername($username)
    {
        $this->username = (string) $username;
    }
}


text:
from model.contact import Contact
import  re

class ContactsHelper:

    def __init__(self,app):
         self.app = app

    def add_new_contact(self, contact):
        wd = self.app.wd
        # add new contact
        wd.find_element_by_link_text("add new").click()
        # fill fields of new contact
        self.fill_contact_form(contact)
        # enter new contact
        wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click()
        self.contacts_cache = None

    def fill_contact_form(self, contact):
        wd = self.app.wd
        self.change_field_value("firstname",contact.firstname)
        self.change_field_value("middlename",contact.middlename)
        self.change_field_value("lastname",contact.lastname)
        self.change_field_value("nickname",contact.nickname)
        self.change_field_value("title",contact.title)
        self.change_field_value("company",contact.company)
        self.change_field_value("home",contact.home_phone)
        self.change_field_value("mobile",contact.mobile_phone)
        self.change_field_value("work",contact.work_phone)
        self.change_field_value("fax",contact.fax)
        self.change_field_value("byear",contact.byear)
        self.change_field_value("address2",contact.address1)
        self.change_field_value("phone2",contact.phone2)
        self.change_field_value("notes",contact.notes)
        self.change_field_value("address",contact.address)
        self.change_field_value("email",contact.email)
        self.change_field_value("email2",contact.email2)
        self.change_field_value("email3",contact.email3)

    def change_field_value(self,field_name,text):
        wd = self.app.wd
        if text is not None:
            wd.find_element_by_name(field_name).click()
            wd.find_element_by_name(field_name).clear()
            wd.find_element_by_name(field_name).send_keys(text)

    def edit_first_contact(self):
        wd = self.app.wd
        self.edit_contact_by_index(0)

    def edit_contact_by_index(self, index, new_group_data):
        wd = self.app.wd
        #self.select_contact_by_index(index)
        # init contacts edit
        rows = wd.find_elements_by_css_selector("tr[name='entry']")
        row = rows[index]
        editelement = row.find_element_by_css_selector("img[alt='Edit']")
        editelement.click()
        # edit contact
        self.fill_contact_form(new_group_data)
        wd.find_element_by_name("update").click()
        wd.find_element_by_link_text("home page").click()
        self.contacts_cache = None

    def delete_first_contact(self):
        self.delete_contact_by_index(0)

    def delete_contact_by_index(self,index):
        wd = self.app.wd
        self.select_contact_by_index(index)
        #submit deletion
        wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click()
        alert = wd.switch_to.alert
        alert.accept()
        wd.find_element_by_link_text("home").click()
        self.contacts_cache = None

    def delete_contact_by_id(self,id):
        wd = self.app.wd
        self.select_contact_by_index(id)
        #submit deletion
        wd.find_element_by_xpath("//div[@id='content']/form[2]/div[2]/input").click()
        alert = wd.switch_to.alert
        alert.accept()
        wd.find_element_by_link_text("home").click()
        self.contacts_cache = None

    def select_first_contact(self):
        wd = self.app.wd
        wd.find_element_by_name("selected[]").click()

    def select_contact_by_index(self,index):
        wd = self.app.wd
        wd.find_elements_by_name("selected[]")[index].click()

    def select_contact_by_id(self,id):
        wd = self.app.wd
        wd.find_element_by_css_selector("input[value='%s']" % id)[id].click()

    def count(self):
         wd = self.app.wd
         wd.find_element_by_link_text("home").click()
         return len(wd.find_elements_by_name("selected[]"))

    contacts_cache = None

    def get_contacts_list(self):
        if self.contacts_cache is None:
            wd = self.app.wd
            wd.find_element_by_link_text("home").click()
            self.contacts_cache = []
            rows = wd.find_elements_by_xpath("//div[1]/div[4]/form[2]/table/tbody/tr[@name='entry']")
            cells = wd.find_elements_by_tag_name("td")

            for element in wd.find_elements_by_xpath("//div[1]/div[4]/form[2]/table/tbody/tr[@name='entry']"):
                cells = element.find_elements_by_tag_name("td")
                firstname = cells[2].text
                lastname = cells[1].text
                id = cells[0].find_element_by_tag_name("input").get_attribute("value")
                all_phones = cells[5].text
                all_emails_from_home_page = cells[4].text
                all_addresses_from_home_page = cells[3].text
                self.contacts_cache.append(Contact(firstname=firstname,lastname = lastname, id = id,
                                                   all_phones_from_home_page = all_phones,all_emails_from_home_page = all_emails_from_home_page,
                                                   all_addresses_from_home_page = all_addresses_from_home_page))
        return list(self.contacts_cache)

    def open_contact_view_by_index(self, index):
        wd = self.app.wd
        wd.find_element_by_link_text("home").click()
        row = wd.find_elements_by_name('entry')[index]
        cell = row.find_elements_by_tag_name("td")[6]
        cell.find_element_by_tag_name("a").click()

    def open_contact_to_edit_by_index(self,index):
        wd = self.app.wd
        wd.find_element_by_link_text("home").click()
        row = wd.find_elements_by_name('entry')[index]
        cell = row.find_elements_by_tag_name("td")[7]
        cell.find_element_by_tag_name("a").click()

    def get_contact_info_from_edit_page(self,index):
        wd = self.app.wd
        self.open_contact_to_edit_by_index(index)
        firstname = wd.find_element_by_name("firstname").get_attribute("value")
        lastname  = wd.find_element_by_name("lastname").get_attribute("value")
        id = wd.find_element_by_name("id").get_attribute("value")
        home_phone = wd.find_element_by_name("home").get_attribute("value")
        work_phone = wd.find_element_by_name("work").get_attribute("value")
        mobile_phone = wd.find_element_by_name("mobile").get_attribute("value")
        phone2 = wd.find_element_by_name("phone2").get_attribute("value")
        email = wd.find_element_by_name("email").get_attribute("value")
        email2 = wd.find_element_by_name("email2").get_attribute("value")
        email3 = wd.find_element_by_name("email3").get_attribute("value")
        address =  wd.find_element_by_name("address").get_attribute("value")
        address1 = wd.find_element_by_name("address2").get_attribute("value")
        return Contact(firstname= firstname, lastname = lastname , id= id, home_phone = home_phone, mobile_phone = mobile_phone,
                       work_phone = work_phone,phone2 = phone2,email = email,email2 = email2, email3 = email3, address = address,address1 = address1)

    def get_contacts_from_view_page(self, index):
        self.open_contact_view_by_index(index)
        wd = self.app.wd
        text = wd.find_element_by_id("content").text
        home_phone = re.search("H: (.*)", text).group(1)
        work_phone = re.search("W: (.*)", text).group(1)
        mobile_phone = re.search("M: (.*)", text).group(1)
        phone2 = re.search("P: (.*)", text).group(1)
        return Contact(home_phone = home_phone, mobile_phone = mobile_phone,
                       work_phone = work_phone,phone2 = phone2)


text:
module RubyJmeter
  class DSL
    def tcp_sampler_config(params={}, &block)
      node = RubyJmeter::TcpSamplerConfig.new(params)
      attach_node(node, &block)
    end
  end

  class TcpSamplerConfig
    attr_accessor :doc
    include Helper

    def initialize(params={})
      testname = params.kind_of?(Array) ? 'TcpSamplerConfig' : (params[:name] || 'TcpSamplerConfig')
      @doc = Nokogiri::XML(<<-EOS.strip_heredoc)
<ConfigTestElement guiclass="TCPConfigGui" testclass="ConfigTestElement" testname="#{testname}" enabled="true">
  <stringProp name="TCPSampler.server"/>
  <boolProp name="TCPSampler.reUseConnection">true</boolProp>
  <stringProp name="TCPSampler.port"/>
  <boolProp name="TCPSampler.nodelay">false</boolProp>
  <stringProp name="TCPSampler.timeout"/>
  <stringProp name="TCPSampler.request"/>
  <boolProp name="TCPSampler.closeConnection">false</boolProp>
</ConfigTestElement>)
      EOS
      update params
      update_at_xpath params if params.is_a?(Hash) && params[:update_at_xpath]
    end
  end

end


text:
declare function BlobStream(): BlobStream.IBlobStream;

declare namespace BlobStream {

    interface IBlobStream extends NodeJS.WritableStream{
        toBlob(type?: string): Blob;
        toBlobURL(type?: string): string;
    }
}

export = BlobStream;