text:
package org.apache.spark.examples.sql.hive

// $example on:spark_hive$
import java.io.File

import org.apache.spark.sql.Row
import org.apache.spark.sql.SparkSession
// $example off:spark_hive$

object SparkHiveExample {

  // $example on:spark_hive$
  case class Record(key: Int, value: String)
  // $example off:spark_hive$

  def main(args: Array[String]) {
    // When working with Hive, one must instantiate `SparkSession` with Hive support, including
    // connectivity to a persistent Hive metastore, support for Hive serdes, and Hive user-defined
    // functions. Users who do not have an existing Hive deployment can still enable Hive support.
    // When not configured by the hive-site.xml, the context automatically creates `metastore_db`
    // in the current directory and creates a directory configured by `spark.sql.warehouse.dir`,
    // which defaults to the directory `spark-warehouse` in the current directory that the spark
    // application is started.

    // $example on:spark_hive$
    // warehouseLocation points to the default location for managed databases and tables
    val warehouseLocation = new File("spark-warehouse").getAbsolutePath

    val spark = SparkSession
      .builder()
      .appName("Spark Hive Example")
      .config("spark.sql.warehouse.dir", warehouseLocation)
      .enableHiveSupport()
      .getOrCreate()

    import spark.implicits._
    import spark.sql

    sql("CREATE TABLE IF NOT EXISTS src (key INT, value STRING) USING hive")
    sql("LOAD DATA LOCAL INPATH 'examples/src/main/resources/kv1.txt' INTO TABLE src")

    // Queries are expressed in HiveQL
    sql("SELECT * FROM src").show()
    // +---+-------+
    // |key|  value|
    // +---+-------+
    // |238|val_238|
    // | 86| val_86|
    // |311|val_311|
    // ...

    // Aggregation queries are also supported.
    sql("SELECT COUNT(*) FROM src").show()
    // +--------+
    // |count(1)|
    // +--------+
    // |    500 |
    // +--------+

    // The results of SQL queries are themselves DataFrames and support all normal functions.
    val sqlDF = sql("SELECT key, value FROM src WHERE key < 10 ORDER BY key")

    // The items in DataFrames are of type Row, which allows you to access each column by ordinal.
    val stringsDS = sqlDF.map {
      case Row(key: Int, value: String) => s"Key: $key, Value: $value"
    }
    stringsDS.show()
    // +--------------------+
    // |               value|
    // +--------------------+
    // |Key: 0, Value: val_0|
    // |Key: 0, Value: val_0|
    // |Key: 0, Value: val_0|
    // ...

    // You can also use DataFrames to create temporary views within a SparkSession.
    val recordsDF = spark.createDataFrame((1 to 100).map(i => Record(i, s"val_$i")))
    recordsDF.createOrReplaceTempView("records")

    // Queries can then join DataFrame data with data stored in Hive.
    sql("SELECT * FROM records r JOIN src s ON r.key = s.key").show()
    // +---+------+---+------+
    // |key| value|key| value|
    // +---+------+---+------+
    // |  2| val_2|  2| val_2|
    // |  4| val_4|  4| val_4|
    // |  5| val_5|  5| val_5|
    // ...
    // $example off:spark_hive$

    spark.stop()
  }
}


text:
from c7n.utils import type_schema
from c7n_kube.actions import MethodAction
from c7n_kube.labels import LabelResource
from c7n_kube.query import QueryResourceManager, TypeInfo
from c7n_kube.provider import resources

from kubernetes.client import V1DeleteOptions

@resources.register('namespace')
class Namespace(QueryResourceManager):
    class resource_type(TypeInfo):
        group = 'Core'
        version = 'V1'
        enum_spec = ('list_namespace', 'items', None)

@Namespace.action_registry.register('delete')
class Delete(MethodAction):
    """
    Deletes a Namespace

    .. code-block:: yaml
      policies:
        - name: delete-namespace
          resource: kube.namespace
          filters:
            - 'metadata.name': 'test-namespace'
          actions:
            - delete
    """
    schema = type_schema('delete')
    method_spec = {'op': 'delete_namespace'}

    def process_resource_set(self, client, model, resources):
        op_name = self.method_spec['op']
        for r in resources:
            getattr(client, op_name)(r['metadata']['name'], V1DeleteOptions())

@Namespace.action_registry.register('label')
class LabelNamespace(LabelResource):
    """
    Labels a Namespace

    .. code-block:: yaml
      policies:
        - name: label-namespace
          resource: kube.namespace
          filters:
            - 'metadata.name': 'test-namespace'
          actions:
            - type: label
              labels:
                label1: value1
                label2: value2

    To remove a label from a namespace, provide the label with the value ``null``

    .. code-block:: yaml
      policies:
        - name: remove-label-from-namespace
          resource: kube.namespace
          filters:
            - 'metadata.labels.label1': present
          actions:
            - type: label
              labels:
                label1: null

    """

    permissions = ('PatchNamespace',)
    method_spec = {'op': 'patch_namespace'}

redpajama_set_name: RedPajamaGithub


text:
/*jshint node:true*/
'use strict';

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'thinkspace-peer-assessment-results',
    environment: environment
  }

  return ENV;
};


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

import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.ui.paint.PaintUtil.RoundingMode;
import com.intellij.util.ui.ImageUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.WavePainter2D;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import java.awt.*;
import java.awt.font.LineMetrics;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Sergey.Malenkov
 * @author tav
 */
public enum EffectPainter2D implements RegionPainter2D<Font> {
  /**
   * @see com.intellij.openapi.editor.markup.EffectType#LINE_UNDERSCORE
   */
  LINE_UNDERSCORE {
    /**
     * Draws a horizontal line under a text.
     *
     * @param g      the {@code Graphics2D} object to render to
     * @param x      text position
     * @param y      text baseline
     * @param width  text width
     * @param height available space under text
     * @param font   optional font to calculate line metrics
     */
    @Override
    public void paint(Graphics2D g, double x, double y, double width, double height, Font font) {
      if (!Registry.is("ide.text.effect.new")) {
        LinePainter2D.paint(g, x, y + 1, x + width, y + 1);
      }
      else {
        paintUnderline(g, x, y, width, height, font, 1, this);
      }
    }
  },
  /**
   * @see com.intellij.openapi.editor.markup.EffectType#BOLD_LINE_UNDERSCORE
   */
  BOLD_LINE_UNDERSCORE {
    /**
     * Draws a bold horizontal line under a text.
     *
     * @param g      the {@code Graphics2D} object to render to
     * @param x      text position
     * @param y      text baseline
     * @param width  text width
     * @param height available space under text
     * @param font   optional font to calculate line metrics
     */
    @Override
    public void paint(Graphics2D g, double x, double y, double width, double height, Font font) {
      if (!Registry.is("ide.text.effect.new")) {
        int h = JBUI.scale(Registry.intValue("editor.bold.underline.height", 2));
        RectanglePainter2D.FILL.paint(g, x, y, width, h);
      }
      else {
        paintUnderline(g, x, y, width, height, font, 2, this);
      }
    }
  },
  /**
   * @see com.intellij.openapi.editor.markup.EffectType#BOLD_DOTTED_LINE
   */
  BOLD_DOTTED_UNDERSCORE {
    /**
     * Draws a bold horizontal line of dots under a text.
     *
     * @param g      the {@code Graphics2D} object to render to
     * @param x      text position
     * @param y      text baseline
     * @param width  text width
     * @param height available space under text
     * @param font   optional font to calculate line metrics
     */
    @Override
    public void paint(Graphics2D g, double x, double y, double width, double height, Font font) {
      paintUnderline(g, x, y, width, height, font, 2, this);
    }
  },
  /**
   * @see com.intellij.openapi.editor.markup.EffectType#WAVE_UNDERSCORE
   */
  WAVE_UNDERSCORE {
    /**
     * Draws a horizontal wave under a text.
     *
     * @param g      the {@code Graphics2D} object to render to
     * @param x      text position
     * @param y      text baseline
     * @param width  text width
     * @param height available space under text
     * @param font   optional font to calculate line metrics
     */
    @Override
    public void paint(Graphics2D g, double x, double y, double width, double height, Font font) {
      if (!Registry.is("ide.text.effect.new")) {
        WavePainter2D.forColor(g.getColor()).paint(g, x, x + width, y + height);
      }
      else if (Registry.is("ide.text.effect.new.metrics")) {
        paintUnderline(g, x, y, width, height, font, 3, this);
      }
      else if (width > 0 && height > 0) {
        Cached.WAVE_UNDERSCORE.paint(g, x, y, width, height, null);
      }
    }
  },
  /**
   * @see com.intellij.openapi.editor.markup.EffectType#STRIKEOUT
   */
  STRIKE_THROUGH {
    /**
     * Draws a horizontal line through a text.
     *
     * @param g      the {@code Graphics2D} object to render to
     * @param x      text position
     * @param y      text baseline
     * @param width  text width
     * @param height text height
     * @param font   optional font to calculate line metrics
     */
    @Override
    public void paint(Graphics2D g, double x, double y, double width, double height, Font font) {
      if (width > 0 && height > 0) {
        if (!Registry.is("ide.text.effect.new.metrics")) {
          drawLineCentered(g, x, y - height, width, height, 1, this);
        }
        else {
          if (font == null) font = g.getFont();
          LineMetrics metrics = font.getLineMetrics("", g.getFontRenderContext());
          double offset = PaintUtil.alignToInt(-metrics.getStrikethroughOffset(), g, RoundingMode.FLOOR);
          double thickness = PaintUtil.alignToInt(maybeScaleFontMetricsThickness(metrics.getStrikethroughThickness(), font), g, RoundingMode.FLOOR);
          drawLine(g, x, y - offset, width, thickness, this);
        }
      }
    }
  };

  private static double getMaxHeight(double height) {
    return height > 7 && Registry.is("ide.text.effect.new.scale") ? height / 2 : 3;
  }

  private static void paintUnderline(Graphics2D g, double x, double y, double width, double height, Font font, double thickness, EffectPainter2D painter) {
    if (width > 0 && height > 0) {
      if (Registry.is("ide.text.effect.new.metrics")) {
        if (font == null) font = g.getFont();
        RoundingMode roundingMode = !UIUtil.isJreHiDPIEnabled() || painter != WAVE_UNDERSCORE || font.getSize2D() / UISettings.getDefFontSize() > 1 ?
                                    RoundingMode.FLOOR : RoundingMode.CEIL;
        LineMetrics metrics = font.getLineMetrics("", g.getFontRenderContext());
        double devPixel = PaintUtil.devPixel(g);
        double underlineThickness = maybeScaleFontMetricsThickness(metrics.getUnderlineThickness(), font);
        double underlineOffset = Math.max(devPixel, metrics.getUnderlineOffset());

        thickness = PaintUtil.alignToInt(thickness * underlineThickness, g, roundingMode);
        double offset = Math.min(height - thickness, underlineOffset);

        if (offset < devPixel) {
          offset = height > 3 * devPixel ? devPixel : 0;
          thickness = PaintUtil.alignToInt(Math.min(thickness, height - offset), g, roundingMode);
        }
        else {
          offset = PaintUtil.alignToInt(offset, g, roundingMode);
        }
        drawLine(g, x, y + offset, width, thickness, painter);
      }
      else {
        if (height > 3) {
          double max = getMaxHeight(height);
          y += height - max;
          height = max;
          if (thickness > 1 && height > 3) {
            thickness = JBUI.scale((float)thickness);
          }
        }
        drawLineCentered(g, x, y, width, height, thickness, painter);
      }
    }
  }

  @TestOnly
  public static double maybeScaleFontMetricsThickness_TestOnly(double fontMetricsThickness, @NotNull Font font) {
    return maybeScaleFontMetricsThickness(fontMetricsThickness, font);
  }

  private static double maybeScaleFontMetricsThickness(double fontMetricsThickness, @NotNull Font font) {
    float fontScale = JBUI.getFontScale(font.getSize2D());
    float normalizedFontScale = font.getSize2D() / UISettings.getDefFontSize();
    if (normalizedFontScale > 1) {
      // k==1.0 with normalizedFontScale==1.0, k->0.5 fast enough with normalizedFontScale increasing
      double k = 1 / (Math.pow(normalizedFontScale, 2) + 1) + 0.5;
      fontScale *= k;
    }
    if (!UIUtil.isJreHiDPIEnabled()) fontScale = (int)fontScale;
    return Math.max(fontMetricsThickness, fontScale);
  }

  private static void drawLineCentered(Graphics2D g, double x, double y, double width, double height, double thickness, EffectPainter2D painter) {
    double offset = height - thickness;
    if (offset > 0) {
      y += offset - (offset / 2);
      height = thickness;
    }
    drawLine(g, x, y, width, height, painter);
  }

  private static void drawLine(Graphics2D g, double x, double y, double width, double height, EffectPainter2D painter) {
    if (painter == BOLD_DOTTED_UNDERSCORE) {
      double dx = (x % height + height) % height;
      double w = width + dx;
      double dw = (w % height + height) % height;
      Cached.BOLD_DOTTED_UNDERSCORE.paint(g, x - dx, y, dw == 0 ? w : w - dw + height, height, null);
    }
    else if (painter == WAVE_UNDERSCORE) {
      Cached.WAVE_UNDERSCORE.paint(g, x, y, width, height, null);
    }
    else {
      RectanglePainter2D.FILL.paint(g, x, y, width, height);
    }
  }

  private enum Cached implements RegionPainter2D<Paint> {
    BOLD_DOTTED_UNDERSCORE {
      @Override
      double getPeriod(double height) {
        return height;
      }

      @Override
      void paintImage(Graphics2D g, double width, double height, double period) {
        Double round = period <= 2 && !UIUtil.isJreHiDPI(g) ? null : period;
        for (int dx = 0; dx < width; dx += period + period) {
          RectanglePainter2D.FILL.paint(g, dx, 0, period, period, round, LinePainter2D.StrokeType.INSIDE, 1, RenderingHints.VALUE_ANTIALIAS_DEFAULT);
        }
      }
    },
    WAVE_UNDERSCORE {
      private final BasicStroke THIN_STROKE = new BasicStroke(.7f);

      @Override
      double getPeriod(double height) {
        return Math.max((Registry.is("ide.text.effect.new.metrics") ? height : getMaxHeight(height)) - 1, 1);
      }

      @Override
      void paintImage(Graphics2D g, double width, double height, double period) {
        double dx = 0;
        double lower = height - 1;
        double upper = lower - period;
        if (Registry.is("ide.text.effect.new.metrics")) {
          if (height > 3) {
            double fix = height / 3;
            g.setStroke(new BasicStroke((float)fix));
            if (fix > 1) {
              fix = (fix - 1) / 2;
              lower -= fix;
              upper += fix;
            }
          }
          height += 2;
          if (g.getClass().getName().equals("com.intellij.util.HiDPIScaledGraphics")) {
            lower += .5;
            upper += .5;
          }
        }
        Path2D path = new Path2D.Double();
        path.moveTo(dx, lower);
        if (height < 6) {
          g.setStroke(THIN_STROKE);
          while (dx < width) {
            path.lineTo(dx += period, upper);
            path.lineTo(dx += period, lower);
          }
        }
        else {
          double size = period / 2;
          double prev = dx - size / 2;
          double center = (upper + lower) / 2;
          while (dx < width) {
            path.quadTo(prev += size, lower, dx += size, center);
            path.quadTo(prev += size, upper, dx += size, upper);
            path.quadTo(prev += size, upper, dx += size, center);
            path.quadTo(prev += size, lower, dx += size, lower);
          }
        }
        path.lineTo(width, lower);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.draw(path);
      }
    };

    // we should not recalculate caches when IDEA is on Retina and non-Retina
    private final ConcurrentHashMap<Integer, BufferedImage> myNormalCache = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<Integer, BufferedImage> myHiDPICache = new ConcurrentHashMap<>();

    abstract double getPeriod(double height);

    abstract void paintImage(Graphics2D g, double width, double height, double period);

    void paintImage(Graphics2D g, Paint paint, double width, double height, double period) {
      try {
        g.setPaint(paint);
        paintImage(g, width, height, period);
      }
      finally {
        g.dispose();
      }
    }

    @Nullable
    BufferedImage getImage(Graphics2D g, Color color, double height) {
      ConcurrentHashMap<Integer, BufferedImage> cache = UIUtil.isJreHiDPI(g) ? myHiDPICache : myNormalCache;
      int key = Objects.hash(color.getRGB(), JBUI.sysScale(g), height);
      BufferedImage image = cache.get(key);
      if (image == null) {
        image = createImage(g, color, height);
        if (image != null) cache.putIfAbsent(key, image);
      }
      return image;
    }

    @Nullable
    BufferedImage createImage(Graphics2D g, Paint paint, double height) {
      double period = getPeriod(height);
      int width = (int)period << (paint instanceof Color ? 8 : 1);
      if (width <= 0 || height <= 0) return null;

      BufferedImage image = UIUtil.createImage(g, width, height, BufferedImage.TYPE_INT_ARGB, RoundingMode.FLOOR);
      paintImage(image.createGraphics(), paint, width, height, period);
      return image;
    }

    @Override
    public void paint(Graphics2D g, double x, double y, double width, double height, Paint paint) {
      if (paint == null) paint = g.getPaint();
      g = (Graphics2D)g.create();
      g.translate(x, y);
      g.clip(new Rectangle2D.Double(0, 0, width, height));

      g.setComposite(AlphaComposite.SrcOver);
      BufferedImage image = paint instanceof Color ? getImage(g, (Color)paint, height) : createImage(g, paint, height);
      if (image == null) return;

      double period = ImageUtil.getRealWidth(image) / ImageUtil.getImageScale(image);
      double offset = (x % period + period) % period; // normalize
      g.translate(-offset, 0);
      for (double dx = -offset; dx < width; dx += period) {
        UIUtil.drawImage(g, image, 0, 0, null);
        g.translate(period, 0);
      }
      g.dispose();
    }
  }
}


text:
using System;
using Xamarin.Forms;
using Eventarin.Core.ViewModels;
using Eventarin.Core.Pages;
using System.Reflection;
using System.Linq;
using Eventarin.Core.Services;
using System.Net.Http;
using Eventarin.Core.Data;

namespace Eventarin.Core
{
	public static class App
	{
		static readonly INavigationService navigationService;

		static App()
		{
			RegisterAllViewModels();
			RegisterAllServices();
			navigationService = SimpleIoC.Resolve<INavigationService>();
		}

		private static void RegisterAllViewModels()
		{
			Assembly currentAssembly = typeof(App).GetTypeInfo().Assembly;

			var viewModelTypes = currentAssembly.ExportedTypes.Where(t => t.Name.EndsWith("ViewModel"));
			foreach (var type in viewModelTypes)
			{
				if (!type.GetTypeInfo().IsAbstract)
				{
					SimpleIoC.RegisterSingleton(type);
				}
			}
		}

		private static void RegisterAllServices()
		{
			SimpleIoC.RegisterSingleton<IPageCachingService, PageCachingService>();
			SimpleIoC.RegisterSingleton<INavigationService, NavigationService>();
			var client = new HttpClient();
			SimpleIoC.RegisterInstance<IWebService>(new WebService(client));
		}

		public static Page GetMainPage()
		{
			return navigationService.GetMainPage();
		}

		private static volatile SimpleIoC simpleIoC;
		private static object syncRoot = new Object();

		public static SimpleIoC SimpleIoC
		{
			get
			{
				if (simpleIoC == null)
				{
					lock (syncRoot)
					{
						if (simpleIoC == null)
							simpleIoC = new SimpleIoC();
					}
				}

				return simpleIoC;
			}
		}

        #region "Database"

        static SQLite.Net.SQLiteConnection conn;
        static EventDatabase database;
        public static void SetDatabaseConnection(SQLite.Net.SQLiteConnection connection)
        {
            conn = connection;
            database = new EventDatabase(conn);
        }

        public static EventDatabase Database
        {
            get { return database; }
        }

        #endregion

    }
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { styles } from '../styles/decorators';
export var UxInputTheme = (function () {
    function UxInputTheme() {
        this.background = 'transparent';
    }
    UxInputTheme = __decorate([
        styles()
    ], UxInputTheme);
    return UxInputTheme;
}());


text:
/* Karma configuration
 * http://karma-runner.github.io/0.10/config/configuration-file.html
 */

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    // including .test files.
    // Be aware that if no tests pass then the gulp task will throw horrible
    // errors, and that missing a depenency from this file list can cause tests
    // that would otherwise pass to fail.
    files: [
      '../node_modules/jquery/dist/jquery.js',
      '../node_modules/angular/angular.js',
      '../node_modules/angular-aria/angular-aria.js',
      '../node_modules/angular-route/angular-route.js',
      '../node_modules/angular-mocks/angular-mocks.js',
      '../src/app/app.module.js',
      '../src/app/app.config.js',
      '../src/app/app.config.route.js',
      '../src/app/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [],

    // hostname
    hostname: '127.0.0.1',

    // web server port
    port: 8083,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],

    colors: true,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    // Add code coverage.

    // The files we should count in code coverage.
    // Excludes .spec.js and .test.js test files.
    preprocessors: {
      '../app/**/!(*spec|*test).js': ['coverage']
    },

    // Test results reporter to use.
    reporters: [
      'progress',
      'coverage'
    ],

    // Output code coverage destination.
    coverageReporter: {
      // specify a common output directory
      dir: 'report/coverage',
      reporters: [
        // reporters not supporting the `file` property
        { type: 'html', subdir: 'report/report-html' },
        { type: 'lcov', subdir: 'report/report-lcov' },
        { type: 'json', subdir: 'report/coverage'}]
    }

  });
};


text:
from functools import partial

try:
    from raven.utils.compat import (
        string_types,
        binary_type,
    )
except ImportError:
    from raven._compat import (
        string_types,
        binary_type,
    )
from raven.processors import SanitizePasswordsProcessor
from raven.utils import varmap

class PyramidSanitizePasswordsProcessor(SanitizePasswordsProcessor):
    """Do some extra sanitization to pick up places where pyramid tends to
    leak passwords through"""

    def sensitive_repr_filter(self, key, value):
        for field in self.FIELDS:
            if isinstance(value, string_types) and field + '=' in value:
                return '[Filtered]'

        return value

    def filter_stacktrace(self, data):
        """Filter out any local variables that contain sensitive-looking
        patterns in their repr()s"""
        super(PyramidSanitizePasswordsProcessor, self).filter_stacktrace(data)
        for frame in data.get('frames', []):
            if 'vars' not in frame:
                continue

            frame['vars'] = varmap(self.sensitive_repr_filter, frame['vars'])

    def filter_http(self, data):
        """Also descend into env, headers looking for keyval-ish strings"""
        super(PyramidSanitizePasswordsProcessor, self).filter_http(data)
        for n in ('headers', 'env', 'data'):
            if isinstance(data.get(n), dict):
                data[n] = varmap(
                    partial(self.vm_sanitize_keyval, delimiter='&'),
                    data[n],
                )
            elif isinstance(data.get(n), binary_type):
                data[n] = self.sensitive_repr_filter(
                    n, data.get(n).decode('utf8')
                ).encode('utf8')

    def vm_sanitize_keyval(self, key, keyval, delimiter):
        """varmap-friendly way to call _sanitize_keyvals

        Also handles mixed types in env"""
        if isinstance(keyval, string_types):
            return self._sanitize_keyvals(keyval, delimiter)
        else:
            return keyval


text:
package org.estatio.dom.lease.invoicing;

import java.util.List;
import org.joda.time.LocalDate;
import org.junit.Before;
import org.apache.isis.applib.query.Query;
import org.estatio.dom.FinderInteraction;
import org.estatio.dom.FinderInteraction.FinderMethod;

public class InvoiceItemsForLeaseTest {

    FinderInteraction finderInteraction;

    InvoiceItemsForLease invoiceItems;

    LocalDate startDate;
    LocalDate dueDate;

    @Before
    public void setup() {

        startDate = new LocalDate(2013, 4, 1);
        dueDate = new LocalDate(2013, 5, 2);

        invoiceItems = new InvoiceItemsForLease() {

            @Override
            protected <T> T firstMatch(Query<T> query) {
                finderInteraction = new FinderInteraction(query, FinderMethod.FIRST_MATCH);
                return null;
            }

            @Override
            protected List<InvoiceItemForLease> allInstances() {
                finderInteraction = new FinderInteraction(null, FinderMethod.ALL_INSTANCES);
                return null;
            }

            @Override
            protected <T> List<T> allMatches(Query<T> query) {
                finderInteraction = new FinderInteraction(query, FinderMethod.ALL_MATCHES);
                return null;
            }
        };
    }

}


text:
@implementation NSDate (Formatter)

- (NSString *)whi_dateWithFormat:(NSString *)format {
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = format;
    return [formatter stringFromDate:self];
}

- (NSString *)whi_xAxisString {
    if (self.minute == 0) {
        return [NSString stringWithFormat:@"%ld", (long)self.hour];
    } else {
        return [self whi_dateWithFormat:@"HH:mm"];
    }
}

@end


text:
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.gui.main.chatroomslist;

import java.util.*;

import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.main.chat.conference.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;

import org.jitsi.service.configuration.*;
import org.osgi.framework.*;

/**
 * The <tt>AdHocChatRoomsList</tt> is the list containing all ad-hoc chat rooms.
 *
 * @author Valentin Martinet
 */
public class AdHocChatRoomList
{
    /**
     * The list containing all chat servers and ad-hoc rooms.
     */
    private final List<AdHocChatRoomProviderWrapper> providersList
        = new Vector<AdHocChatRoomProviderWrapper>();

    /**
     * Initializes the list of ad-hoc chat rooms.
     */
    public void loadList()
    {
        Collection<ServiceReference<ProtocolProviderService>> serRefs
            = ServiceUtils.getServiceReferences(
                    GuiActivator.bundleContext,
                    ProtocolProviderService.class);

        if ((serRefs != null) && !serRefs.isEmpty())
        {
            for (ServiceReference<ProtocolProviderService> serRef : serRefs)
            {
                ProtocolProviderService protocolProvider
                    = GuiActivator.bundleContext.getService(serRef);
                Object adHocMultiUserChatOpSet
                    = protocolProvider.getOperationSet(
                            OperationSetAdHocMultiUserChat.class);

                if (adHocMultiUserChatOpSet != null)
                    addChatProvider(protocolProvider);
            }
        }
    }

    /**
     * Adds a chat server and all its existing ad-hoc chat rooms.
     *
     * @param pps the <tt>ProtocolProviderService</tt> corresponding to the chat
     * server
     */
    public void addChatProvider(ProtocolProviderService pps)
    {
        AdHocChatRoomProviderWrapper chatRoomProvider
            = new AdHocChatRoomProviderWrapper(pps);

        providersList.add(chatRoomProvider);

        ConfigurationService configService
            = GuiActivator.getConfigurationService();

        String prefix = "net.java.sip.communicator.impl.gui.accounts";

        List<String> accounts =
            configService.getPropertyNamesByPrefix(prefix, true);

        for (String accountRootPropName : accounts) {
            String accountUID
                = configService.getString(accountRootPropName);

            if(accountUID.equals(pps
                    .getAccountID().getAccountUniqueID()))
            {
                List<String> chatRooms = configService
                    .getPropertyNamesByPrefix(
                        accountRootPropName + ".chatRooms", true);

                for (String chatRoomPropName : chatRooms)
                {
                    String chatRoomID
                        = configService.getString(chatRoomPropName);

                    String chatRoomName = configService.getString(
                        chatRoomPropName + ".chatRoomName");

                    AdHocChatRoomWrapper chatRoomWrapper
                        = new AdHocChatRoomWrapper( chatRoomProvider,
                                                    chatRoomID,
                                                    chatRoomName);

                    chatRoomProvider.addAdHocChatRoom(chatRoomWrapper);
                }
            }
        }
    }

    /**
     * Removes the corresponding server and all related ad-hoc chat rooms from
     * this list.
     *
     * @param pps the <tt>ProtocolProviderService</tt> corresponding to the
     *            server to remove
     */
    public void removeChatProvider(ProtocolProviderService pps)
    {
        AdHocChatRoomProviderWrapper wrapper =
            findServerWrapperFromProvider(pps);

        if (wrapper != null)
            removeChatProvider(wrapper);
    }

    /**
     * Removes the corresponding server and all related ad-hoc chat rooms from
     * this list.
     *
     * @param adHocChatRoomProvider the <tt>AdHocChatRoomProviderWrapper</tt>
     *            corresponding to the server to remove
     */
    private void removeChatProvider(
            AdHocChatRoomProviderWrapper adHocChatRoomProvider)
    {
        providersList.remove(adHocChatRoomProvider);

        ConfigurationService configService
            = GuiActivator.getConfigurationService();
        String prefix = "net.java.sip.communicator.impl.gui.accounts";
        String providerAccountUID
            = adHocChatRoomProvider
                    .getProtocolProvider().getAccountID().getAccountUniqueID();

        for (String accountRootPropName
                : configService.getPropertyNamesByPrefix(prefix, true))
        {
            String accountUID
                = configService.getString(accountRootPropName);

            if(accountUID.equals(providerAccountUID))
            {
                List<String> chatRooms
                    = configService.getPropertyNamesByPrefix(
                            accountRootPropName + ".chatRooms",
                            true);

                for (String chatRoomPropName : chatRooms)
                {
                    configService.setProperty(
                        chatRoomPropName + ".chatRoomName",
                        null);
                }

                configService.setProperty(accountRootPropName, null);
            }
        }
    }

    /**
     * Adds a chat room to this list.
     *
     * @param adHocChatRoomWrapper the <tt>AdHocChatRoom</tt> to add
     */
    public void addAdHocChatRoom(AdHocChatRoomWrapper adHocChatRoomWrapper)
    {
        AdHocChatRoomProviderWrapper adHocChatRoomProvider
            = adHocChatRoomWrapper.getParentProvider();

        if (!adHocChatRoomProvider.containsAdHocChatRoom(adHocChatRoomWrapper))
            adHocChatRoomProvider.addAdHocChatRoom(adHocChatRoomWrapper);
    }

    /**
     * Removes the given <tt>AdHocChatRoom</tt> from the list of all ad-hoc
     * chat rooms.
     *
     * @param adHocChatRoomWrapper the <tt>AdHocChatRoomWrapper</tt> to remove
     */
    public void removeChatRoom(AdHocChatRoomWrapper adHocChatRoomWrapper)
    {
        AdHocChatRoomProviderWrapper adHocChatRoomProvider
            = adHocChatRoomWrapper.getParentProvider();

        if (providersList.contains(adHocChatRoomProvider))
        {
            adHocChatRoomProvider.removeChatRoom(adHocChatRoomWrapper);
        }
    }

    /**
     * Returns the <tt>AdHocChatRoomWrapper</tt> that correspond to the given
     * <tt>AdHocChatRoom</tt>. If the list of ad-hoc chat rooms doesn't contain
     * a corresponding wrapper - returns null.
     *
     * @param adHocChatRoom the <tt>ChatRoom</tt> that we're looking for
     * @return the <tt>ChatRoomWrapper</tt> object corresponding to the given
     * <tt>ChatRoom</tt>
     */
    public AdHocChatRoomWrapper findChatRoomWrapperFromAdHocChatRoom(
            AdHocChatRoom adHocChatRoom)
    {
        for (AdHocChatRoomProviderWrapper provider : providersList)
        {
            AdHocChatRoomWrapper chatRoomWrapper
                = provider.findChatRoomWrapperForAdHocChatRoom(
                        adHocChatRoom);

            if (chatRoomWrapper != null)
            {
                // stored chatrooms has no chatroom, but their
                // id is the same as the chatroom we are searching wrapper
                // for
                if(chatRoomWrapper.getAdHocChatRoom() == null)
                {
                    chatRoomWrapper.setAdHocChatRoom(adHocChatRoom);
                }

                return chatRoomWrapper;
            }
        }
        return null;
    }

    /**
     * Returns the <tt>AdHocChatRoomProviderWrapper</tt> that correspond to the
     * given <tt>ProtocolProviderService</tt>. If the list doesn't contain a
     * corresponding wrapper - returns null.
     *
     * @param protocolProvider the protocol provider that we're looking for
     * @return the <tt>AdHocChatRoomProvider</tt> object corresponding to
     * the given <tt>ProtocolProviderService</tt>
     */
    public AdHocChatRoomProviderWrapper findServerWrapperFromProvider(
        ProtocolProviderService protocolProvider)
    {
        for(AdHocChatRoomProviderWrapper chatRoomProvider : providersList)
        {
            if(chatRoomProvider.getProtocolProvider().equals(protocolProvider))
            {
                return chatRoomProvider;
            }
        }

        return null;
    }
}


text:
'use strict';

$(document).foundation();

// Chart section
var experience = {
    html: 36,
    css: 36,
    javascript: 36,
    java: 60,
    ruby: 2,
    php: 36,
    python: 1,
    jquery: 24,
    angular: 6
};

var data = [
    {
        value: 60,
        color:'#FF6B63',
        highlight: '#FF5A5E',
        label: 'Active'
    },
    {
        value: 40,
        color: '#CACACA',
        highlight: '#B3B3B3',
        label: 'Inactive'
    }
];

var ctx      = $('#myChart').get(0).getContext('2d');
var expChart = new Chart(ctx).Doughnut(data, {percentageInnerCutout: 75});

var chartExp = function(obj){
    var lang    = $(obj).data('lang');
    var key     = lang.toLowerCase();
    var percent = (experience[key] / (5 * 12)) * 100;
    var years   = (experience[key] / 12);

    expChart.segments[0].value = percent;
    expChart.segments[1].value = 100 - percent;
    expChart.update();

    if (years < 1) {
        if (experience[key] === 1) {
            $('#chart_txt_cntr h1 strong').text(experience[key] + ' month');
        } else {
            $('#chart_txt_cntr h1 strong').text(experience[key] + ' months');
        }
    } else if (years === 1) {
        $('#chart_txt_cntr h1 strong').text(years + ' year');
    } else {
        $('#chart_txt_cntr h1 strong').text(years + ' years');
    }

    $('#chart_txt_cntr h2').text(lang);

    return false;
};

// Page helpers
var scrollToTop = function() {
    $('html, body').animate({scrollTop: 0}, 'slow');
    return false;
};

var scrollToBottom = function() {
    $('html, body').animate({scrollTop: $(document).height()}, 'slow');
    return false;
};

// Navigation behavior
var navigation = $('header > div.fixed');
var scrollBtn  = $('#back_to_top');

var expandContractHeader = function(distanceY, shrinkOn){
    shrinkOn = 190;

    if (distanceY > shrinkOn && navigation.has('large')) {
        navigation.removeClass('large');
    } else {
        navigation.addClass('large');
    }
};

var hideOrShowButton = function(distanceY){
    var showDistance = 1000,
        hideDistance = 300;

    if (distanceY > showDistance) {
        scrollBtn.show().removeClass('fadeOutDown').addClass('animated fadeInUp');
    } else if (distanceY < hideDistance) {
        scrollBtn.removeClass('fadeInUp').addClass('animated fadeOutDown');
    }
};

$(window).on('scroll', function(){
    var distanceY = window.pageYOffset || document.documentElement.scrollTop;

    expandContractHeader(distanceY);
    hideOrShowButton(distanceY);
});

// Form submission
$('#message-submit').on('click', function(e){
    e.preventDefault();

    var url  = 'backend/processor.php';

    var data = {
        name: $('#message-name').val(),
        email: $('#message-email').val(),
        message: $('#message-body').val()
    };

    $.post(url, data)
        .success(function(){
            swal("Thanks!", "Your message has been received.", "success")
        })
        .fail(function(){
            swal("Oh no...", "Something went wrong!", "error");
        });
});


text:
import logging
import os
import sys
from yaml import YAMLError
from collections import UserDict
from contextlib import contextmanager

from mkdocs import exceptions
from mkdocs import utils

log = logging.getLogger('mkdocs.config')

class ValidationError(Exception):
    """Raised during the validation process of the config on errors."""

class Config(UserDict):
    """
    MkDocs Configuration dict

    This is a fairly simple extension of a standard dictionary. It adds methods
    for running validation on the structure and contents.
    """

    def __init__(self, schema, config_file_path=None):
        """
        The schema is a Python dict which maps the config name to a validator.
        """

        self._schema = schema
        self._schema_keys = set(dict(schema).keys())
        # Ensure config_file_path is a Unicode string
        if config_file_path is not None and not isinstance(config_file_path, str):
            try:
                # Assume config_file_path is encoded with the file system encoding.
                config_file_path = config_file_path.decode(encoding=sys.getfilesystemencoding())
            except UnicodeDecodeError:
                raise ValidationError("config_file_path is not a Unicode string.")
        self.config_file_path = config_file_path
        self.data = {}

        self.user_configs = []
        self.set_defaults()

    def set_defaults(self):
        """
        Set the base config by going through each validator and getting the
        default if it has one.
        """

        for key, config_option in self._schema:
            self[key] = config_option.default

    def _validate(self):

        failed, warnings = [], []

        for key, config_option in self._schema:
            try:
                value = self.get(key)
                self[key] = config_option.validate(value)
                warnings.extend([(key, w) for w in config_option.warnings])
                config_option.reset_warnings()
            except ValidationError as e:
                failed.append((key, e))

        for key in (set(self.keys()) - self._schema_keys):
            warnings.append((
                key, f"Unrecognised configuration name: {key}"
            ))

        return failed, warnings

    def _pre_validate(self):

        failed, warnings = [], []

        for key, config_option in self._schema:
            try:
                config_option.pre_validation(self, key_name=key)
                warnings.extend([(key, w) for w in config_option.warnings])
                config_option.reset_warnings()
            except ValidationError as e:
                failed.append((key, e))

        return failed, warnings

    def _post_validate(self):

        failed, warnings = [], []

        for key, config_option in self._schema:
            try:
                config_option.post_validation(self, key_name=key)
                warnings.extend([(key, w) for w in config_option.warnings])
                config_option.reset_warnings()
            except ValidationError as e:
                failed.append((key, e))

        return failed, warnings

    def validate(self):

        failed, warnings = self._pre_validate()

        run_failed, run_warnings = self._validate()

        failed.extend(run_failed)
        warnings.extend(run_warnings)

        # Only run the post validation steps if there are no failures, warnings
        # are okay.
        if len(failed) == 0:
            post_failed, post_warnings = self._post_validate()
            failed.extend(post_failed)
            warnings.extend(post_warnings)

        return failed, warnings

    def load_dict(self, patch):
        """ Load config options from a dictionary. """

        if not isinstance(patch, dict):
            raise exceptions.ConfigurationError(
                "The configuration is invalid. The expected type was a key "
                "value mapping (a python dict) but we got an object of type: "
                "{}".format(type(patch)))

        self.user_configs.append(patch)
        self.data.update(patch)

    def load_file(self, config_file):
        """ Load config options from the open file descriptor of a YAML file. """
        try:
            return self.load_dict(utils.yaml_load(config_file))
        except YAMLError as e:
            # MkDocs knows and understands ConfigurationErrors
            raise exceptions.ConfigurationError(
                f"MkDocs encountered an error parsing the configuration file: {e}"
            )

@contextmanager
def _open_config_file(config_file):
    """
    A context manager which yields an open file descriptor ready to be read.

    Accepts a filename as a string, an open or closed file descriptor, or None.
    When None, it defaults to `mkdocs.yml` in the CWD. If a closed file descriptor
    is received, a new file descriptor is opened for the same file.

    The file descriptor is automaticaly closed when the context manager block is existed.
    """

    # Default to the standard config filename.
    if config_file is None:
        config_file = os.path.abspath('mkdocs.yml')

    # If closed file descriptor, get file path to reopen later.
    if hasattr(config_file, 'closed') and config_file.closed:
        config_file = config_file.name

    log.debug(f"Loading configuration file: {config_file}")

    # If it is a string, we can assume it is a path and attempt to open it.
    if isinstance(config_file, str):
        if os.path.exists(config_file):
            config_file = open(config_file, 'rb')
        else:
            raise exceptions.ConfigurationError(
                f"Config file '{config_file}' does not exist.")

    # Ensure file descriptor is at begining
    config_file.seek(0)
    try:
        yield config_file
    finally:
        if hasattr(config_file, 'close'):
            config_file.close()

def load_config(config_file=None, **kwargs):
    """
    Load the configuration for a given file object or name

    The config_file can either be a file object, string or None. If it is None
    the default `mkdocs.yml` filename will loaded.

    Extra kwargs are passed to the configuration to replace any default values
    unless they themselves are None.
    """
    options = kwargs.copy()

    # Filter None values from the options. This usually happens with optional
    # parameters from Click.
    for key, value in options.copy().items():
        if value is None:
            options.pop(key)

    with _open_config_file(config_file) as fd:
        options['config_file_path'] = getattr(fd, 'name', '')

        # Initialise the config with the default schema.
        from mkdocs.config.defaults import get_schema
        cfg = Config(schema=get_schema(), config_file_path=options['config_file_path'])
        # load the config file
        cfg.load_file(fd)

    # Then load the options to overwrite anything in the config.
    cfg.load_dict(options)

    errors, warnings = cfg.validate()

    for config_name, warning in warnings:
        log.warning(f"Config value: '{config_name}'. Warning: {warning}")

    for config_name, error in errors:
        log.error(f"Config value: '{config_name}'. Error: {error}")

    for key, value in cfg.items():
        log.debug(f"Config value: '{key}' = {value!r}")

    if len(errors) > 0:
        raise exceptions.Abort(
            "Aborted with {} Configuration Errors!".format(len(errors))
        )
    elif cfg['strict'] and len(warnings) > 0:
        raise exceptions.Abort(
            "Aborted with {} Configuration Warnings in 'strict' mode!".format(len(warnings))
        )

    return cfg


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class edu.nps.moves.RprFomFederate</title>
<meta name="date" content="2015-10-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
edu.nps.moves.RprFomFederate

Uses of RprFomFederate in edu.nps.moves

Constructors in edu.nps.moves with parameters of type RprFomFederate

Constructor and Description

RprFomFederateAmbassador(RprFomFederate federateAmbassador)

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="250dp"
    android:minHeight="40dp"
    android:minResizeWidth="110dp"
    android:minResizeHeight="40dp"
    android:initialLayout="@layout/one_row_widget"
    android:resizeMode="horizontal"
    android:updatePeriodMillis="1800000">

</appwidget-provider>


text:
namespace foundation
{

//
// MitsHairFileReader class implementation.
//

MitsHairFileReader::MitsHairFileReader(const std::string& filename, const float radius, const size_t degree)
  : m_filename(filename)
  , m_radius(radius)
  , m_degree(degree)
{
}

void MitsHairFileReader::read(ICurveBuilder& builder)
{
    BufferedFile file(
        m_filename.c_str(),
        BufferedFile::BinaryType,
        BufferedFile::ReadMode);

    if (!file.is_open())
        throw ExceptionIOError();

    read_and_check_signature(file);

    std::unique_ptr<ReaderAdapter> reader;
    reader.reset(new PassthroughReaderAdapter(file));
    read_curves(*reader.get(), builder);
}

void MitsHairFileReader::read_and_check_signature(BufferedFile& file)
{
    static const char ExpectedSig[11] = { 'B', 'I', 'N', 'A', 'R', 'Y', '_', 'H', 'A', 'I', 'R' };

    char signature[sizeof(ExpectedSig)];
    checked_read(file, signature, sizeof(signature));

    if (memcmp(signature, ExpectedSig, sizeof(ExpectedSig)) != 0)
        throw ExceptionIOError("invalid mitshair format signature");
}

void MitsHairFileReader::read_curves(ReaderAdapter& reader, ICurveBuilder& builder)
{
    try
    {
        // Read the basis and curve count
        std::uint32_t vertex_count;
        try
        {
            checked_read(reader, vertex_count);
        }
        catch (const ExceptionEOF&)
        {
            // Expected EOF
        }

        builder.begin_curve_object(static_cast<CurveBasis>(m_degree));
        builder.begin_curve();

        std::vector<Vector3f> vertices, new_vertices;

        for (std::uint32_t c = 0; c < vertex_count; ++c)
        {
            float x;
            checked_read(reader, x);

            if (FP<float>::is_inf(x))
            {
                switch (m_degree)
                {
                  case 1:
                    if (vertices.size() >= 2)
                    {
                        for (size_t i = 0; i < vertices.size(); ++i)
                            push_vertex_properties(vertices[i], builder);
                        builder.end_curve();
                        builder.begin_curve();
                    }
                    break;

                  case 2:
                  case 3:
                  case 4:
                    if (vertices.size() >= 4)
                    {
                        assert(new_vertices.empty());
                        for (size_t i = 0; i < vertices.size(); ++i)
                        {
                            new_vertices.push_back(vertices[i]);

                            if (i > 0 && i % 2 == 0 && i + 1 < vertices.size())
                            {
                                // Add a midpoint.
                                new_vertices.push_back(0.5f * (vertices[i] + vertices[i + 1]));
                            }
                        }

                        for (size_t i = 0, e = new_vertices.size(); i + 3 < e; i += 3)
                            push_vertex_properties(new_vertices[i], builder);
                        builder.end_curve();
                        builder.begin_curve();
                    }
                    break;

                  assert_otherwise;
                }

                clear_keep_memory(vertices);
                clear_keep_memory(new_vertices);

                continue;
            }

            Vector2f yz;
            checked_read(reader, yz);
            vertices.emplace_back(x, yz[0], yz[1]);
        }

        builder.end_curve_object();
    }
    catch (const ExceptionEOF&)
    {
        // Unexpected EOF.
        throw ExceptionIOError();
    }
}

void MitsHairFileReader::push_vertex_properties(const Vector3f& v, ICurveBuilder& builder)
{
    builder.push_vertex(v);
    builder.push_vertex_width(m_radius);
    builder.push_vertex_opacity(1.0f);                      // default opacity
    builder.push_vertex_color(Color3f(0.2f, 0.0f, 0.7f));   // default color
}

}   // namespace foundation


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto

package com.google.cloud.compute.v1;

public interface FirewallPolicyRuleSecureTagOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.FirewallPolicyRuleSecureTag)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Name of the secure tag, created with TagManager's TagValue API.
   *

   *
   * optional string name = 3373707;
   *
   * @return Whether the name field is set.
   */
  boolean hasName();
  /**
   *
   *
   *

   * Name of the secure tag, created with TagManager's TagValue API.
   *

   *
   * optional string name = 3373707;
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Name of the secure tag, created with TagManager's TagValue API.
   *

   *
   * optional string name = 3373707;
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();

  /**
   *
   *
   *

   * [Output Only] State of the secure tag, either `EFFECTIVE` or `INEFFECTIVE`. A secure tag is `INEFFECTIVE` when it is deleted or its network is deleted.
   * Check the State enum for the list of possible values.
   *

   *
   * optional string state = 109757585;
   *
   * @return Whether the state field is set.
   */
  boolean hasState();
  /**
   *
   *
   *

   * [Output Only] State of the secure tag, either `EFFECTIVE` or `INEFFECTIVE`. A secure tag is `INEFFECTIVE` when it is deleted or its network is deleted.
   * Check the State enum for the list of possible values.
   *

   *
   * optional string state = 109757585;
   *
   * @return The state.
   */
  java.lang.String getState();
  /**
   *
   *
   *

   * [Output Only] State of the secure tag, either `EFFECTIVE` or `INEFFECTIVE`. A secure tag is `INEFFECTIVE` when it is deleted or its network is deleted.
   * Check the State enum for the list of possible values.
   *

   *
   * optional string state = 109757585;
   *
   * @return The bytes for state.
   */
  com.google.protobuf.ByteString getStateBytes();
}


text:
+++
Description = ""
date = "2018-08-20T13:26:41+01:00"
title = "Releases"

+++

* [lowRISC with run/step debugging via JTAG and GDB]({{< ref "docs/refresh-v0.6/_index.md" >}})

*Release version 0.6, released October 2018*

This release updates the Rocket IP to March 2018 and includes compressed instructions and JTAG debugging conforming to the RISCV Debug Specification with custom JTAG DTM (see [JTAG internals]({{< ref "docs/jtag.md" >}}) for details). The root filing system is updated to use the mostly upstreamed Debian repository and the peripheral data path widths are increased to 64-bits for better performance.

* [lowRISC with 100MHz Ethernet and Network filing system access]({{< ref "docs/ethernet-v0.5/_index.md" >}})

*Release version 0.5, 01-2018*

This preview release provides a complete Ethernet reference design, tools, and NFS root capability.
This includes the ability to arp, ping, ssh client and server, mount remote NFS disks, and run a full multi-user system (within the available RAM and FPGA CPU performance limitations)
The SD-card interface is promoted to a Rocket peripheral to boost performance.
The human interface (keyboard and VGA compatible text display) are integrated as the default Rocket console.
We continue to support the Nexys4 DDR FPGA platform, only the Minion is omitted.
The [tutorial]({{< ref "docs/ethernet-v0.5/_index.md" >}})
outlines the build procedure and forthcoming releases that we are
planning.

* [lowRISC with tagged memory and minion core]({{< ref "docs/minion-v0.4/_index.md" >}})

*Release version 0.4, 06-2017*

This release provides a more complete prototype of tagged memory implementation.
This includes the ability to define tag propagation rules and policies that control when encountering unexpected tags should raise exceptions.
These features have been incorporated into the Rocket core.
An optimised tag cache has also been developed in order to minimise any additional main memory traffic from the use of tags.
A simple "minion" core is added to provide an SD-card interface.
This system also supports a keyboard and provides a VGA compatible text display.
We continue to support the Nexys4 DDR FPGA platform.
The [tutorial]({{< ref "docs/minion-v0.4/_index.md" >}})
outlines the build procedure and forthcoming releases that we are
planning.

* [lowRISC with a trace debugger]({{< ref "docs/debug-v0.3/_index.md" >}})

*Release version 0.3, 07-2016*

In this code release we present a first prototype of the lowRISC debug
infrastructure. It extends the `untethered` lowRISC system with the
means to control the system, load programs and trace the software
execution. The [tutorial]({{< ref "docs/debug-v0.3/_index.md" >}})
outlines the debug system and the future directions we are
planning. It demonstrates debugging with the RTL simulation and on
the Nexys4 DDR FPGA board.

* [Untethered lowRISC]({{< ref "docs/untether-v0.2/_index.md" >}})

*Release version 0.2, 12-2015*

A code release providing a standalone lowRISC by `untethering` the Rocket chip.
Cores in the original Rocket chip relies on a  companion processor to access I/O devices.
This release repalce this companion core with actual FPGA peripherals.
A [tutorial]({{< ref "docs/untether-v0.2/_index.md" >}}) explains how to use this code release and explains the underlying structural changes.

* [lowRISC with tagged memory]({{< ref "docs/tagged-memory-v0.1/_index.md" >}})

 *Release version 0.1, 04-2015*

A code release builds on the Rocket RISC-V implementation to offer
support for tagged memory (see the [release blog post](
{{< ref "blog/lowrisc-tagged-memory-preview-release.md" >}})). We've put together an
[extensive tutorial]({{< ref "docs/tagged-memory-v0.1/_index.md" >}}) on how to use this
code release as well as documenting many of the changes made.

## Memos

Our [first memo](
{{< ref "docs/memo-2014-001-tagged-memory-and-minion-cores.md" >}}) describes our
plans for tagged memory and minion cores in lowRISC.

## Other

Over the summer of 2016 we hosted a group of interns, kindly sponsored by [IMC
Financial Markets](http://www.imc.nl) who worked on adding custom acceleraors
for video decoding to the lowRISC platform. This work resulted in the creation
of several documents:

* A detailed [report]({{< ref "docs/internship-2016/report.md" >}}) on what
was produced over the summer, what went well and what didn't, as well as a
description of the accelerators.
* A tutorial on [adding new stream processors]({{< ref
"docs/internship-2016/accelerator-tutorial.md" >}}) to the video accelerator
infrastructure developed over the summer.
* A tutorial on [extending lowRISC with new devices]({{< ref
"docs/internship-2016/device-tutorial.md" >}}).
* A guide describing how to [recreate the video decode demo]({{< ref
"docs/internship-2016/video-tutorial.md"
>}}).

Although now over, you may be interested in our [project
idea list for Google Summer of Code 2015]({{< ref "docs/gsoc-2015-ideas.md"
>}}) and for [GSoC 2016]({{< ref "docs/gsoc-2016-ideas.md" >}}).


text:
---
title: Crea tu propio plugin de Gradle
author: markitox
date: 2015-11-15
url: /2015/11/15/crea-tu-propio-plugin-de-gradle/
featured_image: /2015/11/15/AzadiSquare-Tehran-124306.jpg
featured_text: Construye tu camino
featured_image_origin: http://alpha.wallhaven.cc/wallpaper/124306
categories:
  - Guide
tags:
  - Comunidad
  - Gradle
  - Plugins
  - Groovy
  - Build Tools
---

## Motivación
Últimamente he estado trabajando con _SpringBoot_, _Gradle_ y _Java_ básicamente con la arquitectura de microservicios, por lo tanto tenemos varios proyectos (inclusive en .NET) y cada uno de ellos con la misma (o casi) configuración en nuestros **build.gradle**; Entonces me di a la tarea de crear un plugin gradle para nuestros proyectos con el fin de abstraer y limpiar estos archivos **build.gradle**.

---
### Primeros pasos
Empecemos este microproyecto (ahora que esta de moda lo micro =P), aquí encontraras mas documentación acerca de como crear tu [plugin en _Gradle_][1].

Lo primero crea tu directorio, para este ejercicio lo llamaremos _myPlugin_:

```shell
mkdir -p myPlugin/src/main/{groovy,resources/META-INF/gradle-plugins} myPlugin/gradle
```

Revisemos la estructura generada con el siguiente comando ([tree][2] es una herramienta para mostrar el árbol de directorios):
```
tree myPlugin

myPlugin
├── gradle
└── src
    └── main
        ├── groovy
        └── resources
            └── META-INF
                └── gradle-plugins

7 directories, 0 files
```

---
### Archivos necesarios para nuestro plugin

Los siguientes archivos son requeridos por nuestro plugin, por favor crearlos en el directorio como se especifica tomando como base la raíz de nuestro proyecto:

**build.gradle**: Por supuesto necesitamos un archivo build para nuestro plugin, al final incluimos un script el cual tiene la configuración para simular el upload de nuestro plugin ha algún repositorio.
```groovy
apply plugin: 'groovy'

dependencies {
    compile gradleApi()
    compile localGroovy()
}

apply plugin: 'maven'

repositories {
    mavenCentral()
}

group = myGroup
version = myVersion

apply from: "$rootDir/gradle/publish-config.gradle"
```

---
**gradle/publish-config.gradle**: Aqui solo tenemos configuración para subir nuestro plugin al repositorio de la empresa o alguno publico, para este ejercicio sera en un folder de nuestra computadora, esto es solo para abstraer un poco mas de configuración.
```groovy
uploadArchives {
  repositories {
    mavenDeployer {
      repository(url: uri('../repo'))
    }
  }
}
```
---
**gradle.properties**: Aquí mantenemos configuración centralizada para nuestros _Groovy_ scripts
```properties
myGroup=org.groovy.ando
myVersion=0.1-SNAPSHOT
```

---
**settings.gradle**: Configuración acerca de nuestro proyecto, con lo siguiente determinamos el nombre de nuestro _JAR_ y por lo tanto el nombre de la dependencia para los proyectos que quieran usar nuestro plugin.
```groovy
rootProject.name='myPlugin'
```

---
**src/main/groovy/org/groovy/ando/plugin/MyPlugin.groovy**: Esta es nuestra clase principal donde aplicaremos varias cosas a los **build.gradle** de cada proyecto que use nuestro plugin, por ahora no agregamos algo mas que algunos println para mostrar en consola _group_, _name_ y _version_ del proyecto que use nuestro plugin.
```groovy
package org.groovy.ando.plugin

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.Copy

class MyPlugin implements Plugin<Project> {

  @Override
  public void apply(Project project) {
    println '==================================='
    println "Group: ${project.group}"
    println "ArtifactId: ${project.name}"
    println "Version: ${project.version}"
  }

}
```

---
**src/main/resources/META-INF/gradle-plugins/org.groovy.ando.properties**: Este archivo es muy importante, ya que el nombre del archivo define el Id de nuestro plugin y su contenido la clase principal de nuestro plugin.
```
implementation-class=org.groovy.ando.plugin.MyPlugin
```

---
Para 'desplegar' nuestro plugin a nuestro repositorio (en este caso es una carpeta llamada _repo_ en la carpeta padre de nuestro proyecto) ejecutamos la siguiente _task_ de _Gradle_
```shell
gradle uploadArchives
```

Veamos que genero:
```
tree repo

repo
└── org
    └── groovy
        └── ando
            └── myPlugin
                ├── 0.1-SNAPSHOT
                │   ├── maven-metadata.xml
                │   ├── maven-metadata.xml.md5
                │   ├── maven-metadata.xml.sha1
                │   ├── myPlugin-0.1-20151115.131137-1.jar
                │   ├── myPlugin-0.1-20151115.131137-1.jar.md5
                │   ├── myPlugin-0.1-20151115.131137-1.jar.sha1
                │   ├── myPlugin-0.1-20151115.131137-1.pom
                │   ├── myPlugin-0.1-20151115.131137-1.pom.md5
                │   └── myPlugin-0.1-20151115.131137-1.pom.sha1
                ├── maven-metadata.xml
                ├── maven-metadata.xml.md5
                └── maven-metadata.xml.sha1

5 directories, 12 files
```

---
### Probemos nuestro plugin
Pues bien ya tenemos nuestro plugin que mostrara cosas basicas en consola, ahora veamos si es real todo esto.
Para creamos un proyecto con un simple archivo _build.gradle_ que haga uso de nuestro impresionante plugin.

```
tree testMyPlugin

testMyPlugin
└── build.gradle
```

En nuestro _build.gradle_ agregamos esto:
```groovy
buildscript {
  repositories {
    maven {
      url uri('../repo') // nuestro repositorio local
    }
  }
  dependencies {
    classpath 'org.groovy.ando:myPlugin:0.1-SNAPSHOT' // nuestra dependencia al JAR que contiene nuestro plugin
  }
}

group = 'org.teste.ando'  // configuración de nuestro proyecto
version = 0.1

apply plugin: 'org.groovy.ando' // Recuerdan el ID de nuestro plugin??
```

Y eso es todo, para ver en acción nuestro flamante plugin ejecutemos simplemente _gradle_ y veremos en consola algo similar a esto:
```
gradle
===================================
Group: org.teste.ando
ArtifactId: testMyPlugin
Version: 0.1
:help

Welcome to Gradle 2.8.

To run a build, run gradle <task> ...

To see a list of available tasks, run gradle tasks

To see a list of command-line options, run gradle --help

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL

Total time: 1.841 secs
```

---
### Agregamos cosas mas divertidas
Hasta ahora hemos logrado ejecutar cosas basicas en nuestro proyecto usando nuestro plugin ahora necesitamos algo mas avanzado, entonces vamos agregar mas cosas a nuestro plugin, regregamos al archivo **MyPlugin.groovy** dentro nuestro plugin y agregamos como se nuestra abajo:
```groovy
package org.groovy.ando.plugin

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.Copy

class MyPlugin implements Plugin<Project> {

  @Override
	public void apply(Project project) {
    println '==================================='
    println "Group: ${project.group}"
    println "ArtifactId: ${project.name}"
    println "Version: ${project.version}"

    project.allprojects extraConfig << checkRequiredPlugins << addCustomRepositories

	}

  /*
    Disponemos repositorios a los proyectos de esta forma:
      javaNet()
      nexus()
  */
  Closure addCustomRepositories = {
    def javaNetUrl = 'https://maven.java.net/content/repositories/public/'
    def nexusRepositoryUrl = "${project.nexusURL}/nexus/content/groups/public"

    // javaNetUrl
    repositories.ext.javaNet = {
      repositories.maven { url javaNetUrl }
    }

    // Nexus
    repositories.ext.nexus = {
      repositories.maven { url nexusRepositoryUrl }
    }

  }

  Closure checkRequiredPlugins = {
    def checkPlugin = checkPluginName.curry(plugins)
    println '\n==> checking required plugins'
    checkPlugin('java')
    checkPlugin('groovy')
    checkPlugin('eclipse')
    checkPlugin('idea')
    checkPlugin('jacoco')
  }

  Closure checkPluginName = {plugins, pluginName ->
    if (!plugins.hasPlugin(pluginName)) {
      println "Adding plugin: $pluginName"
      plugins.apply(pluginName)
    }
  }

  /*
    Aplicamos algunas configuraciones extras, agregamos tareas
    y configuramos que depedencias entre tareas
  */
  Closure extraConfig = {
    configurations.all {
      exclude module: 'slf4j-log4j12'
    }

    task(type: Copy, "copyDeploy", copyDeployTaks)

    build.dependsOn(copyDeploy, jacocoTestReport)

    loadCredentialsFile(project)
  }

  /*
    Cargamos configuración extra al properties del proyecto que use nuestro
    plugin, en este caso cargamos las credenciales de nuestro usuario de Nexus
  */
	void loadCredentialsFile(Project project) {
		def homeDir = System.properties['user.home']
		Properties props = new Properties()
		props.load(new FileInputStream("$homeDir/credentials.properties"))
		props.each { project.ext[it.key] = it.value }
	}

  /*
    Definimos una tarea para inyectarla a los build.gradle de los proyectos
    que usen nuestro plugin.
  */
	Closure copyDeployTaks = {
		into 'deployment'
		from ("${project.buildDir}/libs") {
			include '*.jar'
		}
	}

}
```

Como ven hemos agregado varias cosas como:

- Repositorios
- Plugins
- Excluimos algunas dependencias transitorias
- Tasks, configuramos Tasks para depender de otras
- Cargamos properties al proyecto

Listo creo que por ahora es suficiente, solo nos resta 'desplegar' nuestro plugin, recuerdan como hacerlo?? ```gradle uploadArchives```

---
## Veamos los resultados
El ultimo paso es agregar la configuración necesaria que requiere nuestro plugin (entre ellas la URL del repositorio Nexus, la version del plugin de Jococo) desde nuestro proyecto de prueba, crea el siguiente archivo _gradle.properties_ y agregamos la siguiente línea
```
nexusURL=http://100.200.300.400:9876
```

---
Y modifica el archivo _build.gradle_ como se muestra:
```groovy
buildscript {
  repositories {
    maven {
      url uri('../repo')
    }
    jcenter()
  }
  dependencies {
    classpath 'org.groovy.ando:myPlugin:0.1-SNAPSHOT'
  }
}

group = 'org.teste.ando'
version = 0.1

apply plugin: 'org.groovy.ando'

// Jacoco es injectado desde nuestro plugin
jacoco {
  toolVersion = '0.7.1.201405082137'
}

repositories {
  javaNet() // Este metodo agrega este repositorio: maven.java.net
  nexus()   // Este es nuetro repositorio privado
}
```

---
Para ver el resultado de esto ejecuten `gradle tasks` y veran algo similiar a esto:
```shell
gradle tasks
===================================
Group: org.teste.ando
ArtifactId: testMyPlugin
Version: 0.1

==> checking required plugins
Adding plugin: java
Adding plugin: groovy
Adding plugin: eclipse
Adding plugin: idea
Adding plugin: jacoco
:tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Documentation tasks
-------------------
groovydoc - Generates Groovydoc API documentation for the main source code.
javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
components - Displays the components produced by root project 'testMyPlugin'. [incubating]
dependencies - Displays all dependencies declared in root project 'testMyPlugin'.
dependencyInsight - Displays the insight into a specific dependency in root project 'testMyPlugin'.
help - Displays a help message.
model - Displays the configuration model of root project 'testMyPlugin'. [incubating]
projects - Displays the sub-projects of root project 'testMyPlugin'.
properties - Displays the properties of root project 'testMyPlugin'.
tasks - Displays the tasks runnable from root project 'testMyPlugin'.

IDE tasks
---------
cleanEclipse - Cleans all Eclipse files.
cleanIdea - Cleans IDEA project files (IML, IPR)
eclipse - Generates all Eclipse files.
idea - Generates IDEA project files (IML, IPR, IWS)

Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.

Other tasks
-----------
cleanIdeaWorkspace
```

---
Ahí veran los tasks de los plugins que agregamos desde nuestro plugin (suena como a Inception) y al inicio la validación de estos si es que ya fueron agregados desde el proyecto.

Bueno eso ha sido todo, espero les sea de utilidad y sea entendible totalmente.

[1]: https://docs.gradle.org/current/userguide/custom_plugins.html
[2]: http://mama.indstate.edu/users/ice/tree/


text:
require 'rails_helper'

module Hatchy
  RSpec.describe Users::ContributionsController, type: :controller do

  end
end


text:
export const UPGRADE_MODULE_NAME = '$$UpgradeModule';
export const INJECTOR_KEY = '$$angularInjector';

export const $INJECTOR = '$injector';
export const $PARSE = '$parse';
export const $ROOT_SCOPE = '$rootScope';
export const $SCOPE = '$scope';
export const $PROVIDE = '$provide';
export const $DELEGATE = '$delegate';
export const $$TESTABILITY = '$$testability';

export const $COMPILE = '$compile';
export const $TEMPLATE_CACHE = '$templateCache';
export const $HTTP_BACKEND = '$httpBackend';
export const $CONTROLLER = '$controller';


text:
namespace Envoy {
namespace Server {
namespace Configuration {
MockFilterChainFactoryContext::MockFilterChainFactoryContext() = default;

MockFilterChainFactoryContext::~MockFilterChainFactoryContext() = default;

} // namespace Configuration
} // namespace Server
} // namespace Envoy


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--

    Copyright 2007-2016, Kaazing Corporation. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<gateway-config xmlns="http://xmlns.kaazing.org/2015/11/gateway">

  <!--
  #############################################################################
  #############################################################################

                Kaazing WebSocket Gateway Configuration File

    See Kaazing Documentation for details: http://kaazing.com/documentation

  #############################################################################
  #############################################################################
  -->

  <properties>

    <property>
      <name>gateway.hostname</name>
      <value>localhost</value>
    </property>

    <property>
      <name>gateway.port</name>
      <value>8000</value>
    </property>

  </properties>

  <service>
    <name>welcome-directory</name>
    <description>Directory service for welcome page</description>
    <accept>http://${gateway.hostname}:${gateway.port}/</accept>

    <type>directory</type>

    <properties>
      <directory>/welcome</directory>
      <welcome-file>index.html</welcome-file>
      <error-pages-directory>/error-pages</error-pages-directory>
      <options>indexes</options>
      <location>
        <patterns>**/*</patterns>
        <cache-control>max-age=0</cache-control>
      </location>
    </properties>
  </service>

  <service>
    <name>echo</name>
    <description>Simple echo service</description>
    <accept>ws://${gateway.hostname}:${gateway.port}/echo</accept>

    <type>echo</type>

    <!-- Restrict cross site constraints before running in production -->
    <cross-site-constraint>
      <allow-origin>*</allow-origin>
    </cross-site-constraint>
  </service>

  <service>
    <name>AMQP Service</name>
    <accept>ws://${gateway.hostname}:${gateway.port}/amqp</accept>
    <connect>tcp://${gateway.hostname}:5672</connect>

    <type>amqp.proxy</type>

    <properties>
      <service.domain>${gateway.hostname}</service.domain>
      <encryption.key.alias>session</encryption.key.alias>
    </properties>

    <realm-name>demo</realm-name>

    <!-- Restrict cross site constraints before running in production -->
    <cross-site-constraint>
      <allow-origin>*</allow-origin>
    </cross-site-constraint>
  </service>

  <security>

    <keystore>
      <type>JCEKS</type>
      <file>keystore.db</file>
      <password-file>keystore.pw</password-file>
    </keystore>

    <truststore>
      <file>truststore.db</file>
    </truststore>

    <realm>
      <name>demo</name>
      <description>Sample realm for file-based authentication</description>

      <authentication>
        <http-challenge-scheme>Application Basic</http-challenge-scheme>
        <login-modules>
          <login-module>
            <type>file</type>
            <success>required</success>
            <options>
              <file>jaas-config.xml</file>
            </options>
          </login-module>
        </login-modules>
      </authentication>
    </realm>

  </security>

</gateway-config>


text:
function init() {
	var inst;

	tinyMCEPopup.resizeToInnerSize();
	inst = tinyMCE.selectedInstance;

	// Give FF some time
	window.setTimeout('insertHelpIFrame();', 10);

	var tcont = document.getElementById('plugintablecontainer');
	var plugins = tinyMCE.getParam('plugins', '', true, ',');
	if (plugins.length == 0)
		document.getElementById('plugins_tab').style.display = 'none';

	var html = "";
	html += '
';
	html += '
';
	html += '
';
	html += '' + tinyMCE.getLang('lang_plugin') + '	';
	html += '' + tinyMCE.getLang('lang_author') + '	';
	html += '' + tinyMCE.getLang('lang_version') + '	';
	html += '
';
	html += '
';
	html += '
';

	for (var i=0; i<inst.plugins.length; i++) {
		var info = getPluginInfo(inst.plugins[i]);

		html += '
';

		if (info.infourl != null && info.infourl != '')
			html += '' + info.longname + '	';
		else
			html += '' + info.longname + '	';

		if (info.authorurl != null && info.authorurl != '')
			html += '' + info.author + '	';
		else
			html += '' + info.author + '	';

		html += '' + info.version + '	';
		html += '
';
	}

	html += '
';
	html += '
';

	tcont.innerHTML = html;
}

function getPluginInfo(name) {
	if (tinyMCE.plugins[name].getInfo)
		return tinyMCE.plugins[name].getInfo();

	return {
		longname : name,
		authorurl : '',
		infourl : '',
		author : '--',
		version : '--'
	};
}

function insertHelpIFrame() {
	var html = '';

	document.getElementById('iframecontainer').innerHTML = html;

	html = '';
	html += ' ';
	html += ' ';
	html += ' ';

	document.getElementById('buttoncontainer').innerHTML = html;
}


text:
/**
 * 1.1更新
 *  - 添加对查询排序字段的支持
 *      - option.order = {
 *          name:"orderby" //排序字段参数
 *          order:"order"        //识别码参数名
 *          keys:{
 *              "desc":1, //配置倒序识别码
 *              "asc":-1  //配置顺序识别码
 *          }
 *      }
 * 2.0 更新
 *  - 简化编写form时候的html结构,使复杂重复部分可以自动填充
 * 2.1 更新
 *  - 增加afterValidation配置
 *  - 修改onSubmit事件为延迟事件,需要被resolve
 */

require("bootstrap");
let validate = require('../validate/validate')
let page = require('../page/page');
var styleMap = {
    "success": "has-success"
    , "error": "has-error"
};

//校验
var check = function ($form, $field, validations) {

    var rs = false;
    var checkResult = validate.check($field.val(), validations);

    var fieldname = $field.attr("name");
    //获取对应的error_box以及给input 添加相应样式
    var $style_set = $form.find("[comp-form-styleset=" + fieldname + "]").removeClass(styleMap.success).removeClass(styleMap.error)
    var $error_box = $form.find("[comp-form-errorbox=" + fieldname + "]").empty();

    var $feed_back;
    if ($style_set.hasClass("has-feedback")) {
        $feed_back = $style_set.find(".form-control-feedback");
    }

    if (checkResult.result) {
        $style_set.addClass(styleMap.success);
        if ($feed_back) {
            $feed_back.removeClass("glyphicon-remove").addClass("glyphicon-ok").show();
        }
        rs = true;
    } else {
        $style_set.addClass(styleMap.error);
        if ($feed_back) {
            $feed_back.removeClass("glyphicon-ok").addClass("glyphicon-remove").show();
        }
        $error_box.html(checkResult.message);
        rs = false;
    }

    return rs;
}
module.exports = {
    /**
     * 创建组件
     * $form:传进来的经jQuery封装的form对象
     * options:部分配置参数
     * promiseFunction:ajax延迟对象
     */
    "create": function ($form, options, promisedFunction) {
        //检查是否已经被初始化,如果是,则不创建新对象
        var compObject = $form.data("comp-object");
        if (compObject) {
            return compObject;
        }
        var obj = Object.create(this);
        obj.form = $form;
        obj.options = {
            "page": undefined,//分页组件
            "onSubmit": function () {
                return true;
            }
            , "order": undefined
            , "autoCheck": false
            , "submitType": "form"//提交类型:ajax,form
            , "dataType": undefined
            , "type": $form.attr("method") || "post"//提交方式:post,get
            , "url": $form.attr("action")
            , "validate": {}
        };

        $.extend(true, obj.options, options);

        var config = obj.options;

        if (config.page) {
            config.page.page.data("form", obj);

        }

        //2.0新增:遍历validate将需要校验的表单项,添加校验提示组件

        (function () {
            try {
                for (var v in config.validate) {
                    var $item = $form.find("[name=" + v + "]");
                    var $parent = $item.parent();
                    if ($parent.is(".input-group")) {
                        $parent = $parent.parent();
                    }
                    $parent.parent().addClass("has-feedback").attr("comp-form-styleset", v);
                    var $help_block = $parent.parent().find("[comp-form-errorbox=" + v + "]");
                    var $feed_back = $parent.find(".form-control-feedback");

                    $feed_back = $feed_back.size() === 0 ? $('')
                        .appendTo($parent) : $feed_back;

                    $help_block = $help_block.size() === 0 ? $('')
                        .appendTo($parent) : $help_block;

                }
            } catch (e) {
            }
        })();

        //是否有排序字段
        var $input_order = undefined;
        var $input_orderby = undefined;
        if (config.order) {
            //排序方式
            $input_order = $('<input type="hidden">').attr("name", config.order.order).appendTo($form);
            //排序字段
            $input_orderby = $('<input type="hidden">').attr("name", config.order.name).appendTo($form);
        }
        if (config.autoCheck) {
            $form.find(":input").map(function () {
                var $i = $(this),
                    _name = $i.attr("name");
                var validates = config.validate[_name];
                if (_name && validates) {
                    var t;
//						$i.on("keyup blur",function(){
                    $i.on("input blur select change", function () {
                        clearTimeout(t);
                        t = setTimeout(function () {
                            check($form, $i, validates);
                        }, 200);
                    });
                }
            })
        }

        $form.on("submit", function () {
            if (arguments[1] && arguments[1].skip === true) {
                return true;
            }
            //修正排序字段识别码
            if ($input_order) {
                var order_keys = config.order.keys || {};
                $input_order.val(order_keys[$input_orderby.data("order")] || $input_orderby.data("order"))
            }
            //封锁按钮

            //console.log($form.serialize());
            //校验
            if (!config.onSubmit())return false;
            var validates = config.validate;//已注册的所有校验规则
            try {
                for (var fieldname in validates) {
                    var $field = $form.find("[name=" + fieldname + "]");
                    var validations = validates[fieldname];
                    var checkResult = check($form, $field, validations);
                    if (!checkResult)return false;
                }
            } catch (ex) {
                return false;
            }

            //新增-提交延迟事件
            var deferred_submit = $.Deferred();

            deferred_submit.done(function () {
                if (config.submitType === "ajax") {
                    var $btn = $form.find(':submit').button('loading');
                    var ajaxOption = {
                        "url": config.url
                        , "type": config.type
                        , "data": $form.serialize()
                    };

                    if (config.dataType) {
                        ajaxOption['dataType'] = config.dataType;
                    }
                    var promise = $.ajax(ajaxOption);
                    if (!!promisedFunction) {
                        promisedFunction(promise);
                    }
                    promise.then(function (data) {
                        //response
                        var response = config.response;
                        if (response && response instanceof Function) {
                            var responseFormat = response(data);

                            var dataCallback = responseFormat.data;
                            //数据更新回调
                            dataCallback();
                            //更新分页
                            var _comp_page = config.page;
                            if (_comp_page) {
                                var pageData = responseFormat.pageData;
                                _comp_page.page.data("curpage", pageData["curpage"]);
                                _comp_page.page.data("total", pageData["total"]);
                                _comp_page.page.data("pagesize", pageData["pagesize"]);
                                config.page.createHtml();
                            }
                        }
                    }, function () {
                    }).always(function () {
                        setTimeout(function () {
                            $btn.button("reset")
                        }, 200)
                    });
                } else {
                    //直接提交form,跳过所有验证
                    obj.submit({"skip": true});
                }
            });
            //判断afterValidation
            if ($.isFunction(config.afterValidation)) {
                //option.afterValidation:function(obj,next,back){
                //  next();//通过
                //  back();//不通过
                //}
                config.afterValidation(obj, function () {
                    deferred_submit.resolve();
                }, function () {
                    deferred_submit.reject();
                });
            } else {
                deferred_submit.resolve();
            }
            //始终会return false
            return false;
        });
        $form.data("comp-object", obj);
        return obj;
    },
    "submit": function (submitData) {
        this.form.trigger('submit', submitData);
    },
    "get": function (field_name) {
        return this.form.find("[name=" + field_name + "]");
    }
}


text:
<!DOCTYPE html>

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

<title>Performs k-means clustering on an H2O dataset — h2o.kmeans • h2o</title>

<link href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/cosmo/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous">

<link href="../pkgdown.css" rel="stylesheet">

  <link href="../extra.css" rel="stylesheet">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">

      </button>
      H2O.ai

  The H2O-R Package

  Getting Started

  R Reference Guide

Performs k-means clustering on an H2O dataset

Performs k-means clustering on an H2O dataset

h2o.kmeans(training_frame, x, model_id = NULL, validation_frame = NULL,
  nfolds = 0, keep_cross_validation_predictions = FALSE,
  keep_cross_validation_fold_assignment = FALSE, fold_assignment = c("AUTO",
  "Random", "Modulo", "Stratified"), fold_column = NULL,
  ignore_const_cols = TRUE, score_each_iteration = FALSE, k = 1,
  estimate_k = FALSE, user_points = NULL, max_iterations = 10,
  standardize = TRUE, seed = -1, init = c("Random", "PlusPlus",
  "Furthest", "User"), max_runtime_secs = 0,
  categorical_encoding = c("AUTO", "Enum", "OneHotInternal", "OneHotExplicit",
  "Binary", "Eigen", "LabelEncoder", "SortByResponse", "EnumLimited"))

 Arguments

    <colgroup><col class="name" /><col class="desc" /></colgroup>

      training_frame

Id of the training data frame.

      x

A vector containing the character names of the predictors in the model.

      model_id

Destination id for this model; auto-generated if not specified.

      validation_frame

Id of the validation data frame.

      nfolds

Number of folds for K-fold cross-validation (0 to disable or >= 2). Defaults to 0.

      keep_cross_validation_predictions

Logical. Whether to keep the predictions of the cross-validation models. Defaults to FALSE.

      keep_cross_validation_fold_assignment

Logical. Whether to keep the cross-validation fold assignment. Defaults to FALSE.

      fold_assignment

Cross-validation fold assignment scheme, if fold_column is not specified. The 'Stratified' option will
stratify the folds based on the response variable, for classification problems. Must be one of: "AUTO",
"Random", "Modulo", "Stratified". Defaults to AUTO.

      fold_column

Column with cross-validation fold index assignment per observation.

      ignore_const_cols

Logical. Ignore constant columns. Defaults to TRUE.

      score_each_iteration

Logical. Whether to score during each iteration of model training. Defaults to FALSE.

      k

The max. number of clusters. If estimate_k is disabled, the model will find k centroids, otherwise it will
find up to k centroids. Defaults to 1.

      estimate_k

Logical. Whether to estimate the number of clusters (<=k) iteratively and deterministically. Defaults
to FALSE.

      user_points

This option allows you to specify a dataframe, where each row represents an initial cluster center. The user-
specified points must have the same number of columns as the training observations. The number of rows must
equal the number of clusters

      max_iterations

Maximum training iterations (if estimate_k is enabled, then this is for each inner Lloyds iteration) Defaults
to 10.

      standardize

Logical. Standardize columns before computing distances Defaults to TRUE.

      seed

Seed for random numbers (affects certain parts of the algo that are stochastic and those might or might not be enabled by default)
Defaults to -1 (time-based random number).

      init

Initialization mode Must be one of: "Random", "PlusPlus", "Furthest", "User". Defaults to Furthest.

      max_runtime_secs

Maximum allowed runtime in seconds for model training. Use 0 to disable. Defaults to 0.

      categorical_encoding

Encoding scheme for categorical features Must be one of: "AUTO", "Enum", "OneHotInternal", "OneHotExplicit",
"Binary", "Eigen", "LabelEncoder", "SortByResponse", "EnumLimited". Defaults to AUTO.

Value

Returns an object of class H2OClusteringModel.

See also

h2o.cluster_sizes, h2o.totss, h2o.num_iterations,
         h2o.betweenss, h2o.tot_withinss, h2o.withinss,
         h2o.centersSTD, h2o.centers

Examples

# NOT RUN {
library(h2o)
h2o.init()
prosPath <- system.file("extdata", "prostate.csv", package="h2o")
prostate.hex <- h2o.uploadFile(path = prosPath)
h2o.kmeans(training_frame = prostate.hex, k = 10, x = c("AGE", "RACE", "VOL", "GLEASON"))
# }

Contents

Arguments

Value

See also

Examples

Developed by The H2O.ai team.

Site built with pkgdown.


text:
/**
 * Doubled sub-class, form #1.
 */
public class DoubledExtend extends Base {
    public DoubledExtend() {
        //System.out.println("Ctor: doubled extend, type 1");
    }

    @Override
    public DoubledExtend getExtended() {
        System.out.println("getExtended 1");
        return new DoubledExtend();
    }

    public String getStr() {
        return "DoubledExtend 1";
    }
}


text:
export default {
    entry: 'dist/index.js',
    dest: 'dist/bundles/index.js',
    sourceMap: false,
    format: 'umd',
    moduleName: 'ng.tsObjectHash',
    globals: {
        '@angular/core': 'ng.core',
        'rxjs/Observable': 'Rx',
        'rxjs/ReplaySubject': 'Rx',
        'rxjs/add/operator/map': 'Rx.Observable.prototype',
        'rxjs/add/operator/mergeMap': 'Rx.Observable.prototype',
        'rxjs/add/observable/fromEvent': 'Rx.Observable',
        'rxjs/add/observable/of': 'Rx.Observable'
    }
}


text:
package gochat

import (
	"strings"
	"fmt"
	"time"
	"regexp"
	"encoding/json"
	"gochat/utils"
	"errors"
)

type syncMessageRequest struct {
	SyncKey     syncKey
	RR          int64 `json:"rr"`
	BaseRequest baseRequest
}

type syncMessageResponse struct {
	Response
	SyncKey      			syncKey
	SyncCheckKey 			syncKey
	SKey         			string
	ContinueFlag 			int
	AddMsgCount            	int
	AddMsgList             	[]map[string]interface{}
	ModContactCount        	int
	ModContactList         	[]map[string]interface{}
	DelContactCount        	int
	DelContactList         	[]map[string]interface{}
	ModChatRoomMemberCount 	int
	ModChatRoomMemberList  	[]map[string]interface{}
}

type syncKey struct {
	Count 	int
	List 	[]map[string]int64
}

var hosts = []string{
	"webpush.wx2.qq.com",
	"wx2.qq.com",
	"wx.qq.com",
	"webpush.wx.qq.com",
	"wx8.qq.com",
	"webpush.wx8.qq.com",
	"qq.com",
	"web2.wechat.com",
	"webpush.web2.wechat.com",
	"wechat.com",
	"webpush.web.wechat.com",
	"webpush.weixin.qq.com",
	"webpush.wechat.com",
	"webpush1.wechat.com",
	"webpush2.wechat.com",
	"webpush2.wx.qq.com",
}

// 开始长轮询
func (weChat *WeChat) beginListen() error {

	// 待优化
	if "wx.qq.com" == weChat.host {
		hosts[0] = "wx.qq.com"
		hosts[1] = "webpush.wx.qq.com"
		hosts[2] = "webpush.wx2.qq.com"
		hosts[3] = "wx2.qq.com"
	}

	weChat.logger.Println("[Info] Being Listen ... ")

	listenFailedCount := 0
	for {
		_, selector, err := weChat.listen()
		if err != nil {
			listenFailedCount++
			weChat.logger.Println("[Error] Listen Failed. Msg:" + err.Error() + fmt.Sprintf(", ListenFailedCount=%d.", listenFailedCount))
			weChat.triggerListenFailedEvent(listenFailedCount, weChat.host)
		} else {
			listenFailedCount = 0
		}

		// 接收到了消息
		if selector != "0" {
			continueFlag := -1
			// 持续接收消息直到continueFlag为0
			for continueFlag != 0 {
				resp, err := weChat.sync()
				if err != nil {
					weChat.logger.Println("[Error] Sync Failed. Msg:" + err.Error())
					continue
				}
				continueFlag = resp.ContinueFlag

				// 联系人有修改
				if resp.ModContactCount > 0 {
					weChat.contactsModify(resp.ModContactList)
				}

				// 联系人删除
				if resp.DelContactCount > 0 {
					weChat.contactsDelete(resp.DelContactList)
				}

				go weChat.handleSyncResponse(resp)
			}
		}
	}
}

// 监听服务器
func (weChat *WeChat) listen() (string, string, error) {

	syncCheckApi := strings.Replace(weChatApi["syncCheckApi"], "{r}", utils.GetUnixMsTime(), 1)
	syncCheckApi = strings.Replace(syncCheckApi, "{skey}", weChat.baseRequest.Skey, 1)
	syncCheckApi = strings.Replace(syncCheckApi, "{sid}", weChat.baseRequest.Sid, 1)
	syncCheckApi = strings.Replace(syncCheckApi, "{uin}", weChat.baseRequest.Uin, 1)
	syncCheckApi = strings.Replace(syncCheckApi, "{deviceid}", weChat.baseRequest.DeviceID, 1)
	syncCheckApi = strings.Replace(syncCheckApi, "{synckey}", weChat.formattedSyncCheckKey(), 1)
	syncCheckApi = strings.Replace(syncCheckApi, "{_}", utils.GetUnixTime(), 1)

	for i, host := range hosts {
		syncCheckApiDo := strings.Replace(syncCheckApi, "{host}", host, 1)
		syncCheckResContent, err := weChat.httpClient.get(syncCheckApiDo, time.Second * 26, &httpHeader{
			Accept:				"*/*",
			AcceptEncoding:		"gzip, deflate, sdch, br",
			AcceptLanguage:		"zh-CN,zh;q=0.8",
			Connection: 		"keep-alive",
			Host: 				host,
			Referer: 			"https://"+ weChat.host +"/?&lang=zh_CN",
		})
		if err != err {
			return "", "0", err
		}

		code, selector, err := weChat.analysisSelector(syncCheckResContent)
		if err != nil {
			return "", "0", err
		}

		if code == "0" {
			hosts[i] = hosts[0]
			hosts[0] = host
			return code, selector, nil
		}
	}

	return "", "0", errors.New("Code != 0")
}

// 监听到服务器通知后拉取数据
func (weChat *WeChat) sync() (*syncMessageResponse, error) {
	syncApi := strings.Replace(weChatApi["syncApi"], "{sid}", weChat.baseRequest.Sid, 1)
	syncApi = strings.Replace(syncApi, "{skey}", weChat.baseRequest.Skey, 1)
	syncApi = strings.Replace(syncApi, "{host}", weChat.host, 1)

	data, err := json.Marshal(syncMessageRequest {
		SyncKey:     weChat.syncKey,
		RR:          ^time.Now().Unix(),
		BaseRequest: weChat.baseRequest,
	})

	if err != nil {
		return nil, err
	}

	content, err := weChat.httpClient.post(syncApi, data, time.Second * 5, &httpHeader{
		ContentType:		"application/json;charset=utf-8",
		Host: 				weChat.host,
		Referer: 			"https://"+ weChat.host +"/?&lang=zh_CN",
	})
	if err != nil {
		return nil, err
	}

	var smr syncMessageResponse
	err = json.Unmarshal([]byte(content), &smr)
	if err != nil {
		return nil, err
	}

	if smr.SyncCheckKey.Count > 0 {
		weChat.syncKey = smr.SyncCheckKey
	} else {
		weChat.syncKey = smr.SyncKey
	}

	return &smr, err
}

// 解析从微信服务器返回的信息
func (weChat *WeChat) analysisSelector(syncCheckRes string) (string, string, error) {

	reg, err := regexp.Compile(`window.synccheck=\{retcode:"(.+)",selector:"(.+)"\}`)
	if err != nil {
		return "", "", err
	}
	selectorArr := reg.FindSubmatch([]byte(syncCheckRes))
	if len(selectorArr) != 3 {
		return "", "", nil
	}

	return string(selectorArr[1]), string(selectorArr[2]), nil
}

// 格式化syncKey为请求参数
func (weChat *WeChat) formattedSyncCheckKey() string {

	syncKeys := []string{}

	for _, k2v := range weChat.syncKey.List {
		syncKeys = append(syncKeys, fmt.Sprintf("%v_%v", k2v["Key"], k2v["Val"]))
	}

	return strings.Join(syncKeys, "|")
}