text:
<?php

namespace Drupal\Console\Core\Utils;

use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Finder\Finder;
use Dflydev\DotAccessConfiguration\YamlFileConfigurationBuilder;
use Dflydev\DotAccessConfiguration\ConfigurationInterface;

/**
 * Class ConfigurationManager.
 */
class ConfigurationManager
{
    /**
     * @var ConfigurationInterface
     */
    private $configuration = null;

    /**
     * @var string
     */
    private $applicationDirectory = null;

    /**
     * @var array
     */
    private $missingConfigurationFiles = [];

    /**
     * @var array
     */
    private $configurationDirectories = [];

    /**
     * @var array
     */
    private $sites = [];

    /**
     * @param $applicationDirectory
     * @return $this
     */
    public function loadConfiguration($applicationDirectory)
    {
        $homeConfig = $this->getHomeDirectory() . '/.console/';
        if (!is_dir($homeConfig)) {
            mkdir($homeConfig, 0777);
        }

        $this->applicationDirectory = $applicationDirectory;
        $input = new ArgvInput();
        $root = $input->getParameterOption(['--root'], null);

        $configurationDirectories[] = $applicationDirectory;
        $configurationDirectories[] = $applicationDirectory.DRUPAL_CONSOLE_CORE;
        $configurationDirectories[] = $applicationDirectory.DRUPAL_CONSOLE;
        $configurationDirectories[] = '/etc/console/';
        $configurationDirectories[] = $this->getHomeDirectory() . '/.console/';
        $configurationDirectories[] = $applicationDirectory .'/console/';
        if ($root) {
            $configurationDirectories[] = $root . '/console/';
        }
        $configurationDirectories = array_unique($configurationDirectories);

        $configurationFiles = [];
        foreach ($configurationDirectories as $configurationDirectory) {
            $file =  $configurationDirectory . 'config.yml';

            if (stripos($configurationDirectory, '/vendor/') <= 0
                && stripos($configurationDirectory, '/bin/') <= 0
                && stripos($configurationDirectory, 'console/') > 0
            ) {
                $this->configurationDirectories[] = str_replace('//', '/', $configurationDirectory);
            }

            if (!file_exists($file)) {
                $this->missingConfigurationFiles[] = $file;
                continue;
            }
            if (file_get_contents($file)==='') {
                $this->missingConfigurationFiles[] = $file;
                continue;
            }

            $configurationFiles[] = $file;
        }

        $this->configurationDirectories =
            array_unique($this->configurationDirectories);

        $builder = new YamlFileConfigurationBuilder($configurationFiles);
        $this->configuration = $builder->build();
        $this->appendCommandAliases();

        if ($configurationFiles) {
            $this->missingConfigurationFiles = [];
        }

        return $this;
    }

    public function loadConfigurationFromDirectory($directory)
    {
        $builder = new YamlFileConfigurationBuilder([$directory.'/console/config.yml']);

        return $builder->build();
    }

    /**
     * @return ConfigurationInterface
     */
    public function getConfiguration()
    {
        return $this->configuration;
    }

    public function readSite($siteFile)
    {
        if (!file_exists($siteFile)) {
            return [];
        }

        return Yaml::parse(file_get_contents($siteFile));
    }

    /**
     * @param $target
     *
     * @return array
     */
    public function readTarget($target)
    {
        if (!array_key_exists($target, $this->sites)) {
            return [];
        }

        $targetInformation = $this->sites[$target];

        if (array_key_exists('host', $targetInformation) && $targetInformation['host'] != 'local') {
            $targetInformation['remote'] = true;
        }

        return array_merge(
            $this->configuration->get('application.remote'),
            $targetInformation
        );
    }

    /**
     * Return the user home directory.
     *
     * @return string
     */
    public function getHomeDirectory()
    {
        if (function_exists('posix_getuid')) {
            return posix_getpwuid(posix_getuid())['dir'];
        }

        return realpath(rtrim(getenv('HOME') ?: getenv('USERPROFILE'), '/\\'));
    }

    /**
     * @return string
     */
    public function getApplicationDirectory()
    {
        return $this->applicationDirectory;
    }

    /**
     * Return the sites config directory.
     *
     * @return array
     */
    private function getSitesDirectories()
    {
        $configurationDirectories = $this->getConfigurationDirectories();
        $configurationDirectories = array_map(
            function ($directory) {
                return sprintf(
                    '%s/sites',
                    $directory
                );
            },
            $configurationDirectories
        );

        $configurationDirectories = array_filter(
            $configurationDirectories,
            function ($directory) {
                return is_dir($directory);
            }
        );

        return $configurationDirectories;
    }

    /**
     * @param string $commandName
     * @return mixed
     */
    public function readDrushEquivalents($commandName)
    {
        $equivalents = [];
        $aliasInformation = Yaml::parse(
            file_get_contents(
                $this->applicationDirectory.DRUPAL_CONSOLE_CORE.'config/drush.yml'
            )
        );

        foreach ($aliasInformation['commands'] as $key => $commands) {
            foreach ($commands as $drush => $console) {
                $equivalents[$drush] = $console;
            }
        }

        if (!$commandName) {
            $aliasInformation = [];
            foreach ($equivalents as $key => $alternative) {
                $aliasInformation[] = [$key, $alternative];
            }

            return $aliasInformation;
        }

        if (array_key_exists($commandName, $equivalents)) {
            return $equivalents[$commandName] ?: ' ';
        }

        return [];
    }

    /**
     * @return string
     */
    public function getConsoleDirectory()
    {
        return sprintf('%s/.console/', $this->getHomeDirectory());
    }

    /**
     * @return array
     */
    public function getMissingConfigurationFiles()
    {
        return $this->missingConfigurationFiles;
    }

    /**
     * @return array
     */
    public function getConfigurationDirectories()
    {
        return $this->configurationDirectories;
    }

    /**
     * @return string
     */
    public function appendCommandAliases()
    {
        $configurationDirectories = array_merge(
            [$this->applicationDirectory . DRUPAL_CONSOLE_CORE . 'config/dist/'],
            $this->configurationDirectories
        );
        $aliases = [];
        foreach ($configurationDirectories as $directory) {
            $aliasFile = $directory . 'aliases.yml';
            if (file_exists($aliasFile)) {
                $aliases = array_merge(
                    $aliases,
                    Yaml::parse(file_get_contents($aliasFile))
                );
            }
        }
        if (array_key_exists('commands', $aliases) && array_key_exists('aliases', $aliases['commands'])) {
            $this->configuration->set(
                'application.commands.aliases',
                $aliases['commands']['aliases']
            );
        }
    }

    public function loadExtendConfiguration()
    {
        $directory = $this->getHomeDirectory() . '/.console/extend/';
        if (!is_dir($directory)) {
            return null;
        }

        $autoloadFile = $directory . 'vendor/autoload.php';
        if (!is_file($autoloadFile)) {
            return null;
        }
        include_once $autoloadFile;
        $extendFile= $directory . 'extend.console.config.yml';

        $this->importConfigurationFile($extendFile);
    }

    public function importConfigurationFile($configFile)
    {
        if (is_file($configFile) && file_get_contents($configFile)!='') {
            $builder = new YamlFileConfigurationBuilder([$configFile]);
            $this->configuration->import($builder->build());
        }
    }

    /**
     * @return array
     */
    public function getSites()
    {
        if ($this->sites) {
            return $this->sites;
        }

        $sitesDirectories = $this->getSitesDirectories();
        $finder = new Finder();
        $finder->in($sitesDirectories);
        $finder->name("*.yml");

        foreach ($finder as $site) {
            $siteName = $site->getBasename('.yml');
            $environments = $this->readSite($site->getRealPath());

            if (!$environments || !is_array($environments)) {
                continue;
            }

            foreach ($environments as $environment => $config) {
                $site = $siteName . '.' . $environment;
                $this->sites[$site] = $config;
            }
        }

        return $this->sites;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.itest.greeter;

import java.util.List;
import javax.xml.ws.Endpoint;

import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.cxf.CxfConstants;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

@ContextConfiguration
public class CamelGreeterTest extends AbstractJUnit4SpringContextTests {
    private static final transient Log LOG = LogFactory.getLog(CamelGreeterTest.class);

    private static Endpoint endpoint;
    @Autowired
    protected CamelContext camelContext;

    @EndpointInject(uri = "mock:resultEndpoint")
    protected MockEndpoint resultEndpoint;

    @BeforeClass
    public static void startServer() throws Exception {
        // Start the Greeter Server
        Object implementor = new GreeterImpl();
        String address = "http://localhost:9000/SoapContext/SoapPort";
        endpoint = Endpoint.publish(address, implementor);
        LOG.info("The WS endpoint is published! ");
    }

    @AfterClass
    public static void stopServer() throws Exception {
        // Shutdown the Greeter Server
        if (endpoint != null) {
            endpoint.stop();
            endpoint = null;
        }
    }

    @Test
    public void testMocksAreValid() throws Exception {
        assertNotNull(camelContext);
        assertNotNull(resultEndpoint);

        ProducerTemplate template = camelContext.createProducerTemplate();
        template.sendBodyAndHeader("jms:requestQueue", "Willem", CxfConstants.OPERATION_NAME, "greetMe");

        // Sleep a while and wait for the message whole processing
        Thread.sleep(4000);
        template.stop();

        MockEndpoint.assertIsSatisfied(camelContext);
        List<Exchange> list = resultEndpoint.getReceivedExchanges();
        assertEquals("Should get one message", list.size(), 1);
        for (Exchange exchange : list) {
            String result = (String) exchange.getIn().getBody();
            assertEquals("Get the wrong result ", result, "Hello Willem");
        }
    }

}


text:
package io.atomix.core;

import io.atomix.cluster.ClusterConfig;
import io.atomix.core.profile.ProfileConfig;
import io.atomix.primitive.config.PrimitiveConfig;
import io.atomix.primitive.partition.PartitionGroupConfig;
import io.atomix.utils.config.Config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Atomix configuration.
 */
public class AtomixConfig implements Config {
  private static final String MANAGEMENT_GROUP_NAME = "system";

  private ClusterConfig cluster = new ClusterConfig();
  private boolean enableShutdownHook;
  private PartitionGroupConfig managementGroup;
  private Map<String, PartitionGroupConfig<?>> partitionGroups = new HashMap<>();
  private Map<String, PrimitiveConfig> primitiveDefaults = new HashMap<>();
  private Map<String, PrimitiveConfig> primitives = new HashMap<>();
  private List<ProfileConfig> profiles = new ArrayList<>();
  private boolean typeRegistrationRequired = false;
  private boolean compatibleSerialization = false;

  /**
   * Returns the cluster configuration.
   *
   * @return the cluster configuration
   */
  public ClusterConfig getClusterConfig() {
    return cluster;
  }

  /**
   * Sets the cluster configuration.
   *
   * @param cluster the cluster configuration
   * @return the Atomix configuration
   */
  public AtomixConfig setClusterConfig(ClusterConfig cluster) {
    this.cluster = cluster;
    return this;
  }

  /**
   * Returns whether to enable the shutdown hook.
   *
   * @return whether to enable the shutdown hook
   */
  public boolean isEnableShutdownHook() {
    return enableShutdownHook;
  }

  /**
   * Sets whether to enable the shutdown hook.
   *
   * @param enableShutdownHook whether to enable the shutdown hook
   * @return the Atomix configuration
   */
  public AtomixConfig setEnableShutdownHook(boolean enableShutdownHook) {
    this.enableShutdownHook = enableShutdownHook;
    return this;
  }

  /**
   * Returns the system management partition group.
   *
   * @return the system management partition group
   */
  public PartitionGroupConfig<?> getManagementGroup() {
    return managementGroup;
  }

  /**
   * Sets the system management partition group.
   *
   * @param managementGroup the system management partition group
   * @return the Atomix configuration
   */
  public AtomixConfig setManagementGroup(PartitionGroupConfig<?> managementGroup) {
    managementGroup.setName(MANAGEMENT_GROUP_NAME);
    this.managementGroup = managementGroup;
    return this;
  }

  /**
   * Returns the partition group configurations.
   *
   * @return the partition group configurations
   */
  public Map<String, PartitionGroupConfig<?>> getPartitionGroups() {
    return partitionGroups;
  }

  /**
   * Sets the partition group configurations.
   *
   * @param partitionGroups the partition group configurations
   * @return the Atomix configuration
   */
  public AtomixConfig setPartitionGroups(Map<String, PartitionGroupConfig<?>> partitionGroups) {
    partitionGroups.forEach((name, group) -> group.setName(name));
    this.partitionGroups = partitionGroups;
    return this;
  }

  /**
   * Adds a partition group configuration.
   *
   * @param partitionGroup the partition group configuration to add
   * @return the Atomix configuration
   */
  public AtomixConfig addPartitionGroup(PartitionGroupConfig partitionGroup) {
    partitionGroups.put(partitionGroup.getName(), partitionGroup);
    return this;
  }

  /**
   * Returns the primitive default configurations.
   *
   * @return the primitive default configurations
   */
  public Map<String, PrimitiveConfig> getPrimitiveDefaults() {
    return primitiveDefaults;
  }

  /**
   * Sets the primitive default configurations.
   *
   * @param primitiveDefaults the primitive default configurations
   * @return the Atomix configuration
   */
  public AtomixConfig setPrimitiveDefaults(Map<String, PrimitiveConfig> primitiveDefaults) {
    this.primitiveDefaults = primitiveDefaults;
    return this;
  }

  /**
   * Returns a default primitive configuration.
   *
   * @param name the primitive name
   * @param <C>  the configuration type
   * @return the primitive configuration
   */
  @SuppressWarnings("unchecked")
  public <C extends PrimitiveConfig<C>> C getPrimitiveDefault(String name) {
    return (C) primitiveDefaults.get(name);
  }

  /**
   * Returns the primitive configurations.
   *
   * @return the primitive configurations
   */
  public Map<String, PrimitiveConfig> getPrimitives() {
    return primitives;
  }

  /**
   * Sets the primitive configurations.
   *
   * @param primitives the primitive configurations
   * @return the primitive configuration holder
   */
  public AtomixConfig setPrimitives(Map<String, PrimitiveConfig> primitives) {
    this.primitives = checkNotNull(primitives);
    return this;
  }

  /**
   * Adds a primitive configuration.
   *
   * @param name   the primitive name
   * @param config the primitive configuration
   * @return the primitive configuration holder
   */
  public AtomixConfig addPrimitive(String name, PrimitiveConfig config) {
    primitives.put(name, config);
    return this;
  }

  /**
   * Returns a primitive configuration.
   *
   * @param name the primitive name
   * @param <C>  the configuration type
   * @return the primitive configuration
   */
  @SuppressWarnings("unchecked")
  public <C extends PrimitiveConfig<C>> C getPrimitive(String name) {
    return (C) primitives.get(name);
  }

  /**
   * Returns the Atomix profile.
   *
   * @return the Atomix profile
   */
  public List<ProfileConfig> getProfiles() {
    return profiles;
  }

  /**
   * Sets the Atomix profile.
   *
   * @param profiles the profiles
   * @return the Atomix configuration
   */
  public AtomixConfig setProfiles(List<ProfileConfig> profiles) {
    this.profiles = profiles;
    return this;
  }

  /**
   * Adds an Atomix profile.
   *
   * @param profile the profile to add
   * @return the Atomix configuration
   */
  public AtomixConfig addProfile(ProfileConfig profile) {
    profiles.add(checkNotNull(profile, "profile cannot be null"));
    return this;
  }

  /**
   * Returns whether serializable type registration is required for user types.
   *
   * @return whether serializable type registration is required for user types
   */
  public boolean isTypeRegistrationRequired() {
    return typeRegistrationRequired;
  }

  /**
   * Sets whether serializable type registration is required for user types.
   *
   * @param typeRegistrationRequired whether serializable type registration is required for user types
   * @return the Atomix configuration
   */
  public AtomixConfig setTypeRegistrationRequired(boolean typeRegistrationRequired) {
    this.typeRegistrationRequired = typeRegistrationRequired;
    return this;
  }

  /**
   * Returns whether compatible serialization is enabled for user types.
   *
   * @return whether compatible serialization is enabled for user types
   */
  public boolean isCompatibleSerialization() {
    return compatibleSerialization;
  }

  /**
   * Sets whether compatible serialization is enabled for user types.
   *
   * @param compatibleSerialization whether compatible serialization is enabled for user types
   * @return the Atomix configuration
   */
  public AtomixConfig setCompatibleSerialization(boolean compatibleSerialization) {
    this.compatibleSerialization = compatibleSerialization;
    return this;
  }
}


text:
package com.payu.sdk.exceptions;

/**
 * The PayU SDK generic exception
 *
 * @author PayU Latam
 * @since 1.0.0
 * @version 1.0.0, 06/09/2013
 */
public class SDKException extends Exception {

	/**
	 * The class serial version
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The exception error code.
	 * @see ErrorCode
	 */
	private ErrorCode errorCode;

	/**
	 * The exception constructor
	 *
	 * @param errorCode
	 *            the exception's error code
	 * @param message
	 *            the exception's message
	 * @param innerException
	 *            the exception that will be embedded
	 */
	public SDKException(ErrorCode errorCode, String message,
			Exception innerException) {

		super(message, innerException);
		this.errorCode = errorCode;
	}

	/**
	 * The exception constructor
	 *
	 * @param errorCode
	 *            the exception's error code
	 * @param message
	 *            the exception's message
	 */
	public SDKException(ErrorCode errorCode, String message) {

		super(message);
		this.errorCode = errorCode;
	}

	/**
	 * The exception constructor
	 *
	 * @param errorCode
	 *            the exception's error code
	 * @param innerException
	 *            the exception that will be embedded
	 */
	public SDKException(ErrorCode errorCode, Exception innerException) {

		super(innerException);
		this.errorCode = errorCode;
	}

	/**
	 * Returns the api error code
	 *
	 * @param errorCode
	 *            the exception's error code
	 */
	public SDKException(ErrorCode errorCode) {
		this.errorCode = errorCode;
	}

	/**
	 * Returns the error code
	 *
	 * @return the errorCode
	 */
	public ErrorCode getErrorCode() {
		return errorCode;
	}

	/**
	 * The types of Error codes to use inside a SDK Exception.
	 */
	public enum ErrorCode {

		/** Error associated to a problem serializing an object. */
		XML_SERIALIZATION_ERROR,
		/** Error associated to a problem deserializing an object. */
		XML_DESERIALIZATION_ERROR,
		/** Error associated to an invalid parameter sent. */
		INVALID_PARAMETERS,
		/** Error associated to a connection problem with the server. */
		CONNECTION_EXCEPTION,
		/** Error associated to an internal API error. */
		API_ERROR,
		/** Error associated to an no found entity. */
		NO_RESULTS_FOUND
	}
}


text:
/**
 * angular-strap
 * @version v2.0.0-rc.3 - 2014-02-10
 * @link http://mgcrea.github.io/angular-strap
 * @author Olivier Louvignes (olivier@mg-crea.com)
 * @license MIT License, http://www.opensource.org/licenses/MIT
 */
'use strict';
angular.module('mgcrea.ngStrap.affix', ['mgcrea.ngStrap.helpers.dimensions']).provider('$affix', function () {
  var defaults = this.defaults = { offsetTop: 'auto' };
  this.$get = [
    '$window',
    'dimensions',
    function ($window, dimensions) {
      var bodyEl = angular.element($window.document.body);
      function AffixFactory(element, config) {
        var $affix = {};
        var options = angular.extend({}, defaults, config);
        var targetEl = options.target;
        var reset = 'affix affix-top affix-bottom', initialAffixTop = 0, initialOffsetTop = 0, affixed = null, unpin = null;
        var parent = element.parent();
        if (options.offsetParent) {
          if (options.offsetParent.match(/^\d+$/)) {
            for (var i = 0; i < options.offsetParent * 1 - 1; i++) {
              parent = parent.parent();
            }
          } else {
            parent = angular.element(options.offsetParent);
          }
        }
        var offsetTop = 0;
        if (options.offsetTop) {
          if (options.offsetTop === 'auto') {
            options.offsetTop = '+0';
          }
          if (options.offsetTop.match(/^[-+]\d+$/)) {
            initialAffixTop -= options.offsetTop * 1;
            if (options.offsetParent) {
              offsetTop = dimensions.offset(parent[0]).top + options.offsetTop * 1;
            } else {
              offsetTop = dimensions.offset(element[0]).top - dimensions.css(element[0], 'marginTop', true) + options.offsetTop * 1;
            }
          } else {
            offsetTop = options.offsetTop * 1;
          }
        }
        var offsetBottom = 0;
        if (options.offsetBottom) {
          if (options.offsetParent && options.offsetBottom.match(/^[-+]\d+$/)) {
            offsetBottom = getScrollHeight() - (dimensions.offset(parent[0]).top + dimensions.height(parent[0])) + options.offsetBottom * 1 + 1;
          } else {
            offsetBottom = options.offsetBottom * 1;
          }
        }
        $affix.init = function () {
          initialOffsetTop = dimensions.offset(element[0]).top + initialAffixTop;
          targetEl.on('scroll', this.checkPosition);
          targetEl.on('click', this.checkPositionWithEventLoop);
          this.checkPosition();
          this.checkPositionWithEventLoop();
        };
        $affix.destroy = function () {
          targetEl.off('scroll', this.checkPosition);
          targetEl.off('click', this.checkPositionWithEventLoop);
        };
        $affix.checkPositionWithEventLoop = function () {
          setTimeout(this.checkPosition, 1);
        };
        $affix.checkPosition = function () {
          var scrollTop = getScrollTop();
          var position = dimensions.offset(element[0]);
          var elementHeight = dimensions.height(element[0]);
          var affix = getRequiredAffixClass(unpin, position, elementHeight);
          if (affixed === affix)
            return;
          affixed = affix;
          element.removeClass(reset).addClass('affix' + (affix !== 'middle' ? '-' + affix : ''));
          if (affix === 'top') {
            unpin = null;
            element.css('position', options.offsetParent ? '' : 'relative');
            element.css('top', '');
          } else if (affix === 'bottom') {
            if (options.offsetUnpin) {
              unpin = -(options.offsetUnpin * 1);
            } else {
              unpin = position.top - scrollTop;
            }
            element.css('position', options.offsetParent ? '' : 'relative');
            element.css('top', options.offsetParent ? '' : bodyEl[0].offsetHeight - offsetBottom - elementHeight - initialOffsetTop + 'px');
          } else {
            unpin = null;
            element.css('position', 'fixed');
            element.css('top', initialAffixTop + 'px');
          }
        };
        function getRequiredAffixClass(unpin, position, elementHeight) {
          var scrollTop = getScrollTop();
          var scrollHeight = getScrollHeight();
          if (scrollTop <= offsetTop) {
            return 'top';
          } else if (unpin !== null && scrollTop + unpin <= position.top) {
            return 'middle';
          } else if (offsetBottom !== null && position.top + elementHeight + initialAffixTop >= scrollHeight - offsetBottom) {
            return 'bottom';
          } else {
            return 'middle';
          }
        }
        function getScrollTop() {
          return targetEl[0] === $window ? $window.pageYOffset : targetEl[0] === $window;
        }
        function getScrollHeight() {
          return targetEl[0] === $window ? $window.document.body.scrollHeight : targetEl[0].scrollHeight;
        }
        $affix.init();
        return $affix;
      }
      return AffixFactory;
    }
  ];
}).directive('bsAffix', [
  '$affix',
  '$window',
  function ($affix, $window) {
    return {
      restrict: 'EAC',
      require: '^?bsAffixTarget',
      link: function postLink(scope, element, attr, affixTarget) {
        var options = {
            scope: scope,
            offsetTop: 'auto',
            target: affixTarget ? affixTarget.$element : angular.element($window)
          };
        angular.forEach([
          'offsetTop',
          'offsetBottom',
          'offsetParent',
          'offsetUnpin'
        ], function (key) {
          if (angular.isDefined(attr[key]))
            options[key] = attr[key];
        });
        var affix = $affix(element, options);
        scope.$on('$destroy', function () {
          options = null;
          affix = null;
        });
      }
    };
  }
]).directive('bsAffixTarget', function () {
  return {
    controller: [
      '$element',
      function ($element) {
        this.$element = $element;
      }
    ]
  };
});


text:
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<!-- Mobile friendliness -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">

<!-- Mobile IE allows us to activate ClearType technology for smoothing fonts for easy reading -->
<meta http-equiv="cleartype" content="on">


text:
package org.skyscreamer.yoga.listener;

import java.util.Map;

import junit.framework.Assert;

import org.junit.Test;
import org.skyscreamer.yoga.mapper.ResultTraverser;
import org.skyscreamer.yoga.test.model.basic.DataGenerator;
import org.skyscreamer.yoga.test.model.extended.Album;
import org.skyscreamer.yoga.test.model.extended.AlbumEntityConfiguration;
import org.skyscreamer.yoga.test.model.extended.User;
import org.skyscreamer.yoga.test.util.AbstractTraverserTest;

/**
 * User: corby Date: 5/14/12
 */
public class HrefListenerTest extends AbstractTraverserTest
{
    // Put an HrefListener in the listener chain. Traverse a user object where
    // the @URITemplate is defined as "/user/{id}". Verify that the correct URL
    // is appended to the output.
    @Test
    public void testAnnotatedModel()
    {
        User solomon = DataGenerator.solomon();
        ResultTraverser traverser = new ResultTraverser();

        Map<String, Object> objectTree = doTraverse( solomon, ":", traverser, new HrefListener() );

        Assert.assertEquals( "/user/" + solomon.getId() + ".test", objectTree.get( "href" ) );
    }

    // No @URITemplate annotation exists on the Album class, but the
    // AlbumEntityConfiguration defines a template.
    // Put an HrefListener in the listener chain, and verify that the correct
    // URL is appended to the output
    @Test
    public void testEntityConfiguration()
    {
        Album funeral = DataGenerator.funeral();
        ResultTraverser traverser = new ResultTraverser();
        getEntityConfigurationRegistry().register( new AlbumEntityConfiguration() );

        HrefListener listener = new HrefListener( new UriGenerator( getEntityConfigurationRegistry() ) );
        Map<String, Object> objectTree = doTraverse( funeral, ":", traverser, listener );

        Assert.assertEquals( "/album/" + funeral.getId() + ".test", objectTree.get( "href" ) );
    }
}


text:
import { expect } from 'chai';
import {
  loadCachedTestBed,
  takeScreenshot,
  TestBed,
} from '../../../puppeteer-tests/util';

describe('email-chooser-sk', () => {
  let testBed: TestBed;
  before(async () => {
    testBed = await loadCachedTestBed();
  });

  beforeEach(async () => {
    await testBed.page.goto(testBed.baseUrl);
    await testBed.page.setViewport({ width: 300, height: 600 });
  });

  it('should render the demo page', async () => {
    // Smoke test.
    expect(await testBed.page.$$('email-chooser-sk')).to.have.length(1);
  });

  describe('screenshots', () => {
    it('shows the default view', async () => {
      await takeScreenshot(testBed.page, 'am', 'email-chooser-sk');
    });

    it('shows that unassigned is selected', async () => {
      await testBed.page.click('email-chooser-sk option:nth-child(1)');
      await takeScreenshot(testBed.page, 'am', 'email-chooser-sk_unassigned-selected');
    });

    it('shows that a non-owner is selected', async () => {
      await testBed.page.click('email-chooser-sk option:nth-child(2)');
      await takeScreenshot(testBed.page, 'am', 'email-chooser-sk_non-owner-selected');
    });
  });
});


text:
// ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================

package org.talend.dataprep.dataset.service.analysis.synchronous;

import static org.talend.dataprep.exception.error.DataSetErrorCodes.UNABLE_TO_ANALYZE_COLUMN_TYPES;

import java.util.List;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.talend.dataprep.api.dataset.ColumnMetadata;
import org.talend.dataprep.api.dataset.DataSetMetadata;
import org.talend.dataprep.api.dataset.row.DataSetRow;
import org.talend.dataprep.dataset.StatisticsAdapter;
import org.talend.dataprep.dataset.store.content.ContentStoreRouter;
import org.talend.dataprep.dataset.store.metadata.DataSetMetadataRepository;
import org.talend.dataprep.exception.TDPException;
import org.talend.dataprep.lock.DistributedLock;
import org.talend.dataprep.quality.AnalyzerService;
import org.talend.dataquality.common.inference.Analyzer;
import org.talend.dataquality.common.inference.Analyzers;

/**
 *

 * Schema analysis use the first 20 rows of the dataset content to find out columns' :
 *

 *
data type

 *
semantic

 *
quality (valid, invalid and empty)

 *

 *

 */
@Component
public class SchemaAnalysis implements SynchronousDataSetAnalyzer {

    private static final Logger LOGGER = LoggerFactory.getLogger(SchemaAnalysis.class);

    @Autowired
    DataSetMetadataRepository repository;

    @Autowired
    ContentStoreRouter store;

    @Autowired
    StatisticsAdapter adapter;

    @Autowired
    AnalyzerService analyzerService;

    @Override
    public void analyze(String dataSetId) {
        if (StringUtils.isEmpty(dataSetId)) {
            throw new IllegalArgumentException("Data set id cannot be null or empty.");
        }
        DistributedLock datasetLock = repository.createDatasetMetadataLock(dataSetId);
        datasetLock.lock();
        try {
            DataSetMetadata metadata = repository.get(dataSetId);
            if (metadata == null) {
                LOGGER.info("Unable to analyze schema of data set #{}: seems to be removed.", dataSetId);
                return;
            }
            // Schema analysis
            try (Stream<DataSetRow> stream = store.stream(metadata)) {
                LOGGER.info("Analyzing schema in dataset #{}...", dataSetId);
                // Configure analyzers
                final List<ColumnMetadata> columns = metadata.getRowMetadata().getColumns();
                try (Analyzer<Analyzers.Result> analyzer = analyzerService.schemaAnalysis(columns)) {
                    // Determine schema for the content.
                    stream.limit(100).map(row -> row.toArray(DataSetRow.SKIP_TDP_ID)).forEach(analyzer::analyze);

                    // Find the best suitable type
                    adapter.adapt(columns, analyzer.getResult());
                    LOGGER.info("Analyzed schema in dataset #{}.", dataSetId);
                    metadata.getLifecycle().schemaAnalyzed(true);

                    DataSetMetadata savedDataSetMetadata = repository.get(dataSetId);
                    // in order to check that the dataset was not deleted during analysis
                    if (savedDataSetMetadata != null) {
                        repository.save(metadata);
                    } else {
                        LOGGER.info("Data set #{} no longer exists.", dataSetId); //$NON-NLS-1$
                    }
                }
            } catch (Exception e) {
                LOGGER.error("Unable to analyse schema for dataset " + dataSetId + ".", e);
                TDPException.rethrowOrWrap(e, UNABLE_TO_ANALYZE_COLUMN_TYPES);
            }
        } finally {
            datasetLock.unlock();
        }
    }

    @Override
    public int order() {
        return 1;
    }
}


text:
#include "screen.h"
#include "../kernel/kernel.h"

/* Print a char on the screen at col, row, or at cursor position */
void print_char(char character, int col, int row, char attribute_byte) {
  /* Create a byte (char) pointer to the start of video memory */
  unsigned char *vidmem = (unsigned char *) VIDEO_ADDRESS;

  /* If attribute byte is zero, assume the default style */
  if (!attribute_byte) {
    attribute_byte = WHITE_ON_BLACK;
  }

  /* Get the video memory offset for the screen location */
  int offset;
  /* If col and row are non-negative, use them for offset */
  if (col >=0 && row >= 0)  {
    offset = get_screen_offset(col, row);
  } else {
    offset = get_cursor();
  }

  // If we see a newline character, set offset to the end of
  // current row, so it will be advanced to the first col
  // of the next row.
  if (character == '\n') {
    int rows = offset / (2*MAX_COLS);
    offset = get_screen_offset(MAX_COLS-1, rows);
  // Otherwise, write the character and its attributes byte to
  // video memory at our calculated offset.
  } else {
    vidmem[offset] = character;
    vidmem[offset+1] = attribute_byte;
  }

  // Update the offset to the next  character cell, which is
  // two bytes ahead of the current cell.
  offset += 2;
  // Make scrolling adjustment, for when we reach the bottom
  // of the screen.
  offset = handle_scrolling(offset);
  // Update the cursor position on the screen device.
  set_cursor(offset);
}

int get_screen_offset(int col, int row) {
  return (row*MAX_COLS + col)<<1;
}

int get_cursor() {
  // The device uses its control register as an index
  // to select its internal registers, of which we are
  // interested in:
  //     reg 14: which is the high byte of the cursor's offset
  //     reg 15: which is the low  byte of the cursor's offset
  // Once the internal register has been selected, we may read or
  // write a byte on the dagta register.
  port_byte_out(REG_SCREEN_CTRL, 14);
  int offset = port_byte_in(REG_SCREEN_DATA) << 8;
  port_byte_out(REG_SCREEN_CTRL, 15);
  offset += port_byte_in(REG_SCREEN_DATA);
  // since the cursor offset reported by the VGA hardware is the
  // number of characters, we muliply by two to convert it to
  // a chracter cell offset.
  return offset*2;
}

void set_cursor(int offset) {
  offset /= 2;    // Convert from cell offset to char offset.
  // This is similar to get_cursor, only now we write
  // bytes to those internal device registers.
  port_byte_out(REG_SCREEN_CTRL, 14);
  port_byte_out(REG_SCREEN_DATA, (unsigned char) (offset >> 8));
  port_byte_out(REG_SCREEN_CTRL, 15);
  port_byte_out(REG_SCREEN_DATA, (unsigned char) (offset % 256));
}

/* Advance the text cursor, scrolling the video buffer if necessary.  */
int handle_scrolling(int cursor_offset) {
  // if the cursor is within the screen, return it unmodified.
  if (cursor_offset < MAX_ROWS*MAX_COLS*2) {
    return cursor_offset;
  }

  /* Shuffle the rows back one */
  int i;
  for (i = 1; i < MAX_ROWS; ++ i) {
    memory_copy((char*) (get_screen_offset(0, i) + VIDEO_ADDRESS),
                (char*) (get_screen_offset(0, i-1) + VIDEO_ADDRESS),
                MAX_COLS*2);
  }

  /* Blank the last line by setting all bytes to 0 */
  char *last_line = (char*)( get_screen_offset(0, MAX_ROWS-1) + VIDEO_ADDRESS );
  /* BUG: if we set the memory in attrbute byte to zero. when scrool the last line. The cursor will not visible
  for (i = 0; i < MAX_COLS*2; ++ i) {
    last_line[i] = 0;
  }
  */
  for (i = 0; i < MAX_COLS; ++ i) {
    last_line[i*2] = 0;
    last_line[i*2+1] = WHITE_ON_BLACK;
  }

  // Move the offset back one row, such that it is now on the last
  // row, rather than off the edge of the screen.
  cursor_offset -= 2*MAX_COLS;

  return cursor_offset;
}

void print_at(char *message, int col, int row) {
  // Update the cursor if col and row not negative.
  if (col >= 0 && row >= 0) {
    set_cursor(get_screen_offset (col, row) );
  }

  // Loop through each char of the message and print it.
  int i = 0;
  while (message[i]) {
    print_char(message[i++], col, row, WHITE_ON_BLACK);
  }
}

void print(char *message) {
  print_at(message, -1, -1);
}

void clear_screen() {
  int row = 0;
  int col = 0;

  /* Loop through video memory and write blak characters. */
  for (row = 0; row < MAX_ROWS; ++ row) {
    for (col = 0; col < MAX_COLS; ++ col) {
      print_char(' ', col, row, WHITE_ON_BLACK);
    }
  }

  // Move the cursor back to the top left
  set_cursor(get_screen_offset(0, 0));
}


text:
package org.apache.logging.log4j.message;

import java.io.Serializable;
import org.apache.logging.log4j.util.StringBuilderFormattable;

/**
 * An interface for various Message implementations that can be logged. Messages can act as wrappers
 * around Objects so that user can have control over converting Objects to Strings when necessary without
 * requiring complicated formatters and as a way to manipulate the message based on information available
 * at runtime such as the locale of the system.
 *

 * Custom Message implementations should consider implementing the {@link StringBuilderFormattable}
 * interface for more efficient processing. Garbage-free Layouts will call
 * {@link StringBuilderFormattable#formatTo(StringBuilder) formatTo(StringBuilder)} instead of
 * {@link Message#getFormattedMessage()} if the Message implements StringBuilderFormattable.
 *

 *

 * Note: Message objects should not be considered to be thread safe nor should they be assumed to be
 * safely reusable even on the same thread. The logging system may provide information to the Message
 * objects and the Messages might be queued for asynchronous delivery. Thus, any modifications to a
 * Message object by an application should by avoided after the Message has been passed as a parameter on
 * a Logger method.
 *

 *
 * @see StringBuilderFormattable
 */
/*
 * Implementation note: this interface extends Serializable since LogEvents must be serializable.
 */
public interface Message extends Serializable {

    /**
     * Gets the Message formatted as a String. Each Message implementation determines the
     * appropriate way to format the data encapsulated in the Message. Messages that provide
     * more than one way of formatting the Message will implement MultiformatMessage.
     *

     * When configured to log asynchronously, this method is called before the Message is queued, unless this
     * message implements {@link ReusableMessage} or is annotated with {@link AsynchronouslyFormattable}.
     * This gives the Message implementation class a chance to create a formatted message String with the current value
     * of any mutable objects.
     * The intention is that the Message implementation caches this formatted message and returns it on subsequent
     * calls. (See LOG4J2-763.)
     *

     *

     * When logging synchronously, this method will not be called for Messages that implement the
     * {@link StringBuilderFormattable} interface: instead, the
     * {@link StringBuilderFormattable#formatTo(StringBuilder) formatTo(StringBuilder)} method will be called so the
     * Message can format its contents without creating intermediate String objects.
     *

     *
     * @return The message String.
     */
    String getFormattedMessage();

    /**
     * Gets the format portion of the Message.
     *
     * @return The message format. Some implementations, such as ParameterizedMessage, will use this as
     * the message "pattern". Other Messages may simply return an empty String.
     * TODO Do all messages have a format?  What syntax?  Using a Formatter object could be cleaner.
     * (RG) In SimpleMessage the format is identical to the formatted message. In ParameterizedMessage and
     * StructuredDataMessage it is not. It is up to the Message implementer to determine what this
     * method will return. A Formatter is inappropriate as this is very specific to the Message
     * implementation so it isn't clear to me how having a Formatter separate from the Message would be cleaner.
     */
    String getFormat();

    /**
     * Gets parameter values, if any.
     *
     * @return An array of parameter values or null.
     */
    Object[] getParameters();

    /**
     * Gets the throwable, if any.
     *
     * @return the throwable or null.
     */
    Throwable getThrowable();
}


text:
{{ $artifactId := .Get "artifactId"}}{{ $version := .Get "version"}}{{ $mongoDriverVersion := .Get "mongoDriverVersion"}}{{ $reactiveStreamsVersion := .Get "reactiveStreamsVersion"}}

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>{{$artifactId}}</artifactId>
        <version>{{$version}}</version>
    </dependency>
</dependencies>

  dependencies {
      compile 'org.mongodb:{{$artifactId}}:{{$version}}'
  }

You can also download the jars
  directly
  from sonatype.

    Note: {{$artifactId}} requires the following dependencies:
    RxJava,
    bson,
    mongodb-driver-core
    and
    mongodb-driver-async.


text:
*Cucumber-style BDD in symfony.*

sfBehatPlugin is a plugin for symfony applications. It help to write Cucumber-like Behat features to test symfony applications.

## Prerequisites ##

1. Behat is written on PHP 5.3, so you need PHP 5.3.2 to run your features;
2. You need Behat itself. Installation instruction is at [http://everzet.com/Behat](http://everzet.com/Behat);
3. You need PHPUnit 3.5.0 to be available in your PATH.

## Installation ##

### Using symfony:plugin ###

Use this to install as a plugin in a symfony app:

	$ symfony plugin:install sfBehatPlugin

### Using git clone ###

Use this to install as a plugin in a symfony app:

	$ cd plugins && git clone git://github.com/everzet/sfBehatPlugin.git

### Using git submodules ###

Use this if you prefer to use git submodules for plugins:

	$ git submodule add git://github.com/everzet/sfBehatPlugin.git plugins/sfBehatPlugin

and enable plugin in your ProjectConfigurations class.

## Usage ##

### Prepare ###

After installation, you need to create features folders for your applications inside symfony's `test` folder. To do this, simply run:

	symfony behat:setup frontend

where `frontend` is your application name.

### Generate Features ###

To begin with Behat, you need to create your first feature file. Run:

	symfony behat:generate-feature frontend main

where `frontend` & `main` is your application & module names to test

### Run Features ###

You can either run all app tests with:

	behat test/features/frontend

or specific feature with:

	behat test/features/frontend/main.feature

or all frontend features with simply:

	behat

sfBehatPlugin installs `behat.yml` into your project root. This is a Behat configuration file for sf environment. So, if
you want to run your symfony features from different directory - specify configuration path manually with
(-c|--configuration option) like that:

    behat -c ../behat.yml

## Write Features ##

### Write New Steps ###

You can create new steps simply by placing definitions in any `*.php` file under `steps/` folder in your app features.

### Specify App Routes ###

sfBehatPlugin has base steps to run over your application. One of them is `/^I am on(?: the)? (.*)$/`. This step tries to load specified page as is, but you can specify path manually in `support/paths.php`:

	<?php
	$this->pathTo = function($page) use($world) {
	    switch ($page) {
	        case 'homepage':        return '/';
	        case 'articles list':   return '/articles';
	        default:                $page;
	    }
	};

## Contributors ##

* everzet (lead): [http://github.com/everzet](http://github.com/everzet)

Behat is maintained by ever.zet [http://github.com/everzet](http://github.com/everzet)


text:
describe('vizify `to exist`', function () {
    it('should be defined globally', function () {
        expect(Vizify).toBeDefined();
    });
});

describe('vizify loadExt', function () {
    it('should load an external file', function () {
        var options = {
            library: "google",
            type: "timeline",
            hook: "someClass"
        };
        spyOn(Vizify, "loadExt");
        Vizify.init(options);
        expect(Vizify.loadExt).toHaveBeenCalled();
    });
});

describe('vizify googleLoadedEvent', function () {
    it('should dispatch an event', function () {
        var options = {
            library: "google",
            type: "timeline",
            hook: "someClass"
        };
        spyOn(document, "dispatchEvent");
        Vizify.googleLoadedEvent();
        expect(document.dispatchEvent).toHaveBeenCalled();
    });
});

describe('vizify googleLoadedSubscribe', function () {
    it('should call googleLoadedSubscribe method', function () {
        var options = {
            library: "google",
            type: "timeline",
            hook: "someClass"
        };
        spyOn(Vizify, "loadVisualization");
        Vizify.googleLoadedSubscribe();
        expect(Vizify.loadVisualization).toHaveBeenCalled();

    });
});

describe('vizify loadExt', function () {
    it('should create a script element', function () {
        var options = {
            library: "google",
            type: "timeline",
            hook: "someClass"
        };
        var tmpScript = document.createElement("script");
        spyOn(document, "createElement").and.callFake(function () {
            return tmpScript;
        });
        Vizify.loadExt("", function () {
        });
        expect(document.createElement).toHaveBeenCalled();
    });
});

describe('vizify load', function () {
    it('should push to hooks and data array', function () {
        var options = {
            library: "google",
            type: "timeline"
        };
        spyOn(Vizify.data, "push");
        spyOn(Vizify.hooks, "push");
        Vizify.init(options);
        Vizify.load({data: {}, hooks: {}});
        expect(Vizify.data.push).toHaveBeenCalled();
        expect(Vizify.hooks.push).toHaveBeenCalled();
    });
});

describe('vizify loadVisualization', function () {
    it('should load google visualization', function () {
        var options = {
            library: "google",
            type: "timeline"
        };
        window.google = {};
        window.google.load = function () {
        }
        spyOn(window.google, "load");
        Vizify.init(options);
        Vizify.loadVisualization();
        expect(window.google.load).toHaveBeenCalled();
    });
});

describe('vizify loadData', function () {
    it('should call a function based on names', function () {
        var options = {
            library: "google",
            type: "timeline"
        };
        Vizify.init(options);
        Vizify.load({data: {}, hook: "#time"});
        spyOn(Vizify, "renderGoogleTimeline");
        Vizify.loadData();
        expect(Vizify.renderGoogleTimeline).toHaveBeenCalled();

    });
});

describe('vizify renderGoogleTimeline', function () {
    it('should call render a google timeline', function () {
        var options = {
            library: "google",
            type: "timeline"
        };
        Vizify.init(options);
        Vizify.load({data: {}, hook: "#time"});
        window.google = {};
        window.google.visualization = {};
        window.google.visualization.Timeline = function () {
        };
        window.google.visualization.Timeline.prototype.draw = function () {
        };
        window.google.visualization.DataTable = function () {
        };
        window.google.visualization.DataTable.prototype.addColumn = function (a) {
        };
        window.google.visualization.DataTable.prototype.addRows = function (a) {
        };
        spyOn(window.google.visualization.Timeline.prototype, "draw");
        Vizify.renderGoogleTimeline([{columnName: "test", rows: [1, 2, 3]}], ["#time"]);
        expect(window.google.visualization.Timeline.prototype.draw).toHaveBeenCalled();

    });
});


text:
'use strict';
import test from 'ava';
import '../lib/babel-register';
import DependencyGraph from '../lib/dependency-graph';

test.beforeEach(t => {
	t.context = new DependencyGraph();
	t.end();
});

test('a brand new dependency is not solvable', t => {
	const graph = t.context;

	const node = graph.node('a');

	t.notOk(node.trySolve());
	t.notOk(node.solved);

	t.end();
});

test('a dependency by itself is solved', t => {
	const graph = t.context;

	const node = graph.node('a');

	node.addDepList(['a']);

	t.ok(node.trySolve());
	t.ok(node.solved);

	t.end();
});

test('other nodes must be solved before A can be', t => {
	const graph = t.context;
	const nodeA = graph.node('a').addDepList(['a', 'b']);
	const nodeB = graph.node('b');

	t.notOk(nodeB.trySolve());
	t.notOk(nodeA.trySolve());
	t.notOk(nodeA.solved);

	nodeB.addDepList(['b']);

	t.ok(nodeB.trySolve());
	t.ok(nodeB.solved);

	t.ok(nodeA.trySolve());
	t.ok(nodeA.solved);
	t.end();
});

test('other nodes must be solved before A can be (two dependencies)', t => {
	const graph = t.context;
	const nodeA = graph.node('a').addDepList(['a', 'b', 'c']);
	const nodeB = graph.node('b');

	t.notOk(nodeB.trySolve());
	t.notOk(nodeA.trySolve());
	t.notOk(nodeA.solved);

	nodeB.addDepList(['b']);

	t.ok(nodeB.trySolve());
	t.ok(nodeB.solved);

	t.notOk(nodeA.trySolve());
	t.notOk(nodeA.solved);

	graph.node('c').addDepList(['c']).trySolve();

	t.ok(nodeA.trySolve());
	t.ok(nodeA.solved);
	t.notOk(nodeA.trySolve(), 'trySolve should only return true once');

	t.end();
});

test('finds shortest solution', t => {
	const graph = t.context;

	graph.addDependencyList(['a', 'b', 'c']);
	graph.addDependencyList(['a', 'b', 'd']);
	graph.addDependencyList(['a', 'b']);
	graph.addDependencyList(['b', 'c']);
	graph.addDependencyList(['c']);

	graph.solve();

	t.same(graph.node('a').solutions, [
		['a', 'b'], ['a', 'b', 'c']
	]);

	t.end();
});


text:
require 'set'
require 'elasticity'

# Ruby class to execute SnowPlow's Hive jobs against Amazon EMR
# using Elasticity (https://github.com/rslifka/elasticity).
module SnowPlow
  module EmrEtlRunner
    class EmrJob

      # Need to understand the status of all our jobflow steps
      @@running_states = Set.new(%w(WAITING RUNNING PENDING SHUTTING_DOWN))
      @@failed_states  = Set.new(%w(FAILED CANCELLED))

      # Initializes our wrapper for the Amazon EMR client.
      #
      # Parameters:
      # +config+:: contains all the control data for the SnowPlow Hive job
      def initialize(config)

        puts "Initializing EMR jobflow"

        # Create a job flow with your AWS credentials
        @jobflow = Elasticity::JobFlow.new(config[:aws][:access_key_id], config[:aws][:secret_access_key])

        # Configure
        @jobflow.name = config[:etl][:job_name]
        @jobflow.hadoop_version = config[:emr][:hadoop_version]
        @jobflow.ec2_key_name = config[:emr][:ec2_key_name]
        @jobflow.placement = config[:emr][:placement]
        @jobflow.ec2_subnet_id = config[:emr][:ec2_subnet_id]
        @jobflow.log_uri = config[:s3][:buckets][:log]
        @jobflow.enable_debugging = config[:debug]
        @jobflow.visible_to_all_users = true

        # Add bootstap action
        # Ideal buffer size for S3 and look in user classpath first
        if config[:etl][:collector_format] == 'thrift-raw'
            [
              Elasticity::HadoopBootstrapAction.new('-s', 'io.file.buffer.size=65536'),
              Elasticity::HadoopBootstrapAction.new('-m', 'mapreduce.user.classpath.first=true')
            ].each do |action|
              @jobflow.add_bootstrap_action(action)
            end
        end

        # Add extra configuration
        if config[:emr][:jobflow].respond_to?(:each)
          config[:emr][:jobflow].each { |key, value|
            k = key.to_s
            # Don't include the task fields
            if not k.start_with?("task_")
              @jobflow.send("#{k}=", value)
            end
          }
        end

        # Now let's add our task group if required
        tic = config[:emr][:jobflow][:task_instance_count]
        unless tic.nil? or tic == 0
          ig = Elasticity::InstanceGroup.new
          ig.count = tic
          ig.type  = config[:emr][:jobflow][:task_instance_type]
          tib = config[:emr][:jobflow][:task_instance_bid]
          if tib.nil?
            ig.set_on_demand_instances
          else
            ig.set_spot_instances(tib)
          end
          @jobflow.set_task_instance_group(ig)
        end

        # We only consolidate files on HDFS folder for CloudFront currently
        unless config[:etl][:collector_format] == "cloudfront"
          hadoop_input = config[:s3][:buckets][:processing]

        else
          hadoop_input = "hdfs:///local/snowplow-logs"

          # Create the Hadoop MR step for the file crushing
          filecrush_step = Elasticity::CustomJarStep.new(config[:s3distcp_asset])

          filecrush_step.arguments = [
            "--src"               , config[:s3][:buckets][:processing],
            "--dest"              , hadoop_input,
            "--groupBy"           , ".*\\.([0-9]+-[0-9]+-[0-9]+)-[0-9]+\\..*",
            "--targetSize"        , "128",
            "--outputCodec"       , "lzo",
            "--s3Endpoint"        , config[:s3][:endpoint],
          ]

          # Add to our jobflow
          @jobflow.add_step(filecrush_step)
        end

        # Now create the Hadoop MR step for the jobflow
        hadoop_step = Elasticity::CustomJarStep.new(config[:hadoop_asset])

        # Add extra configuration (undocumented feature)
        if config[:emr][:hadoop_step].respond_to?(:each)
          config[:emr][:hadoop_step].each { |key, value|
            hadoop_step.send("#{key}=", value)
          }
        end

        # We need to partition our output buckets by run ID
        # Note buckets already have trailing slashes
        partition = lambda { |bucket| "#{bucket}run%3D#{config[:run_id]}/" } # TODO: s/%3D/=/ when Scalding Args supports it

        hadoop_step.arguments = [
          "com.snowplowanalytics.snowplow.enrich.hadoop.EtlJob", # Job to run
          "--hdfs", # Always --hdfs mode, never --local
          "--input_folder"      , hadoop_input, # Argument names are "--arguments" too
          "--input_format"      , config[:etl][:collector_format],
          "--maxmind_file"      , config[:maxmind_asset],
          "--output_folder"     , partition.call(config[:s3][:buckets][:out]),
          "--bad_rows_folder"   , partition.call(config[:s3][:buckets][:out_bad_rows]),
          "--anon_ip_quartets"  , config[:enrichments][:anon_ip_octets]
        ]

        # Conditionally add exceptions_folder
        if config[:etl][:continue_on_unexpected_error]
          hadoop_step.arguments.concat [
            "--exceptions_folder" , partition.call(config[:s3][:buckets][:out_errors])
          ]
        end

        # Finally add to our jobflow
        @jobflow.add_step(hadoop_step)
      end

      # Run (and wait for) the daily ETL job.
      #
      # Throws a RuntimeError if the jobflow does not succeed.
      def run()

        jobflow_id = @jobflow.run
        puts "EMR jobflow #{jobflow_id} started, waiting for jobflow to complete..."
        status = wait_for(jobflow_id)

        if !status
          raise EmrExecutionError, "EMR jobflow #{jobflow_id} failed, check Amazon EMR console and Hadoop logs for details (help: https://github.com/snowplow/snowplow/wiki/Troubleshooting-jobs-on-Elastic-MapReduce). Data files not archived."
        end

        puts "EMR jobflow #{jobflow_id} completed successfully."
      end

      # Wait for a jobflow.
      # Check its status every 5 minutes till it completes.
      #
      # Parameters:
      # +jobflow_id+:: the ID of the EMR job we wait for
      #
      # Returns true if the jobflow completed without error,
      # false otherwise.
      def wait_for(jobflow_id)

        # Loop until we can quit...
        while true do
          begin
            # Count up running tasks and failures
            statuses = @jobflow.status.steps.map(&:state).inject([0, 0]) do |sum, state|
              [ sum[0] + (@@running_states.include?(state) ? 1 : 0), sum[1] + (@@failed_states.include?(state) ? 1 : 0) ]
            end

            # If no step is still running, then quit
            if statuses[0] == 0
              return statuses[1] == 0 # True if no failures
            end

            # Sleep a while before we check again
            sleep(120)

          rescue SocketError => se
            puts "Got socket error #{se}, waiting 5 minutes before checking jobflow again"
            sleep(300)
          end
        end
      end
    end

  end
end


text:
/*
 * Routes for rendering home index page
 */
var User = require('../models/user');
var Size= require('../models/size');
var Fashion= require('../models/fashion')
var Category = require('../models/category');
var Cart= require('../models/cart')
var Sesscart = require('../models/sesscart');

module.exports = {

  new : function(req, res){
    if(!req.session.cart){
      return res.render('pages/checkout', {products:null, totalPrice:'0'});
    }
    var cart = new Sesscart(req.session.cart);
    res.render('pages/checkout', {products:cart.generateArray(), totalPrice:cart.totalPrice});
  },

  addtocart: function(req, res, next){
    var size_id = req.params.size_id;
    var fashion_id = req.params.fashion_id;
    var sesscart = new Sesscart(req.session.cart? req.session.cart : {items:{}});

    Size.findById(size_id, function(err, size){
      if(err) return err;

      Fashion.findOne({_id:size.fashion}, function(err, fashion){
        if(err) return err;

        sesscart.add(size._id, size.name, fashion.price, fashion._id, fashion.name, fashion.photo);
        req.session.cart = sesscart;
        res.redirect('/fashion/item/'+fashion_id);
      });
    });
  },

  addqtytocart : function(req, res, next){
    var size_id = req.params.size_id;
    var sesscart = new Sesscart(req.session.cart);

    Size.findById(size_id, function(err, size){
      if(err) return(err);

      Fashion.findOne({_id:size.fashion}, function(err, fashion){
        if(err) return(err);

        sesscart.addqty(size._id, fashion.price);
        req.session.cart = sesscart;
        res.redirect('/fashion/checkout');
      });
    });
  },

  removeonefromcart: function(req, res, next){
    var size_id = req.params.size_id;
    var sesscart = new Sesscart(req.session.cart);
    Size.findById(size_id, function(err, size){
      if(err) return err;

      Fashion.findOne({_id:size.fashion}, function(err, fashion){
        if(err) return err;
        sesscart.remove(size._id, fashion.price);
        req.session.cart = sesscart;
        res.redirect('/fashion/checkout');
      });
    });
  },

  deletecart : function(req, res, next){
    req.session.destroy(function(err){
      if(err) return(err);

      res.redirect('/');
    });
  },

  removecartobject: function(req, res, next){
    var size_id = req.params.size_id;
    var sesscart = new Sesscart(req.session.cart);

    sesscart.removeobject(size_id);
    req.session.cart = sesscart;
    res.redirect('/fashion/checkout');
  },

  add: function(req, res){
    Fashion.findOne({_id :req.body.id}, function(err, foundFashion){
      if(err) res.send(err);

      if(foundFashion){
        cart.quantity = req.body.quantity;
        cart.size     = foundFashion._id;
        cart.fashion  = foundFashion._id;

        cart.save(function(err, cart){
          if(err) res.send(err);

          res.redirect('/pages/cart')

        });
      }
      else{
        res.send("fashion does not exist so fuck off dude");
      }

    });
  },

  //serves normal users to view various sizes of clothes in the db
  item : function(req, res){
    Fashion.findOne({_id:req.params.id}, function(err, fashion){
      if(err) res.send(err);

      if(fashion){
        Size.find({fashion:fashion._id}, function(err, sizes){
          if(err) res.send(err);
          if(sizes){
            res.render('pages/cart',{
              fashion:fashion,
              sizes:sizes
            });
          }else{
            res.send("looks like you dont have any sizes in the database");
          }
        });
      }else{
        res.send("please call system admin to confirm some petty issues");
      }
    });
  },
  pay : function(req, res){
    Fashion.findOne({_id:req.params.id}, function(err, fashion){
      if(err) res.send(err);

      if(fashion){
        Size.find({fashion:fashion._id}, function(err, sizes){
          if(err) res.send(err);
          if(sizes){
            res.render('pages/pay',{
              fashion:fashion,
              sizes:sizes
            });
          }else{
            res.send("looks like you dont have any sizes in the database");
          }
        });
      }else{
        res.send("please call system admin to confirm some petty issues");
      }
    });
  },
};


text:
<?php
/**
 * @link http://www.yee-soft.com/
 */

namespace console\controllers;

use Yii;
use yii\console\Controller;
use yii\console\Exception;
use yii\db\Connection;
use yii\base\Security;

/**
 * Inits root user.
 *
 * Below are some common usages of this command:
 *
 * ~~~
 * # init root user
 * yii init-admin
 *
 * # init root user
 * yii init-admin --username=root --password=qwerty
 * ~~~
 *
 * @author Taras Makitra <makitrataras@gmail.com>
 */
class InitAdminController extends Controller
{
    /**
     * @var string the default command action.
     */
    public $defaultAction = 'init';

    /**
     * @var boolean indicate whether is root user initialization allowed
     * more that one time.
     */
    public $allowOverwrite = false;

    /**
     * @var string username of root user.
     */
    public $username;

    /**
     * @var string password of root user.
     */
    public $password;

    /**
     * @var string email of root user.
     */
    public $email;

    /**
     * @var boolean whether to execute the migration in an interactive mode.
     */
    public $interactive = true;

    /**
     * @var Connection|string the DB connection object or the application
     * component ID of the DB connection.
     */
    public $db = 'db';

    /**
     * @inheritdoc
     */
    public function options($actionId)
    {
        return array_merge(parent::options($actionId), ['allowOverwrite', 'interactive', 'username', 'password', 'email', 'db']);
    }

    /**
     * This method is invoked right before an action is to be executed (after all possible filters.)
     *
     * @param \yii\base\Action $action the action to be executed.
     *
     * @throws Exception if db component isn't configured
     * @return boolean whether the action should continue to be executed.
     */
    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {

            if (is_string($this->db)) {
                $this->db = Yii::$app->get($this->db);
            }
            if (!$this->db instanceof Connection) {
                throw new Exception("The 'db' option must refer to the application component ID of a DB connection.");
            }

            echo "Yee CMS Root User Init Tool\n";
            if (isset($this->db->dsn)) {
                echo "Database Connection: ".$this->db->dsn."\n\n";
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * Init root user.
     * For example,
     *
     * ~~~
     * yii init-admin
     * yii init-admin --username=admin --password=admin123
     * ~~~
     *
     */
    public function actionInit()
    {
        if (!$this->canUpdateRootUser()) {
            echo "Root user has already been initialized.\n";

            return;
        }

        if (!$this->username) {
            $this->username = $this->prompt('Enter root user name: ', [
                'required' => true,
                'default' => 'admin',
            ]);
        }

        if (!$this->validateUsername($this->username)) {
            echo "Username must contains only alphabets and numbers and be at least 4 characters long.\n";

            return;
        }

        if (!$this->password) {
            $this->password = $this->prompt('Enter password for root user: ', [
                'required' => true,
            ]);
        }

        if (!$this->validatePassword($this->password)) {
            echo "Password must contains only alphabets and numbers and be at least 6 characters long.\n";

            return;
        }

        if (!$this->email) {
            $this->email = $this->prompt('Enter email of root user: ', [
                'required' => true,
            ]);
        }

        if (!$this->validateEmail($this->email)) {
            echo "Invalid email.\n";

            return;
        }

        if ( ($this->interactive==false) or ($this->confirm("Create root user '{$this->username}' with password '{$this->password}' ?")) ) {

            if (!$this->createUser($this->username, $this->password, $this->email)) {
                echo "\nCreation failed.\n";

                return;
            }

            echo "\nRoot user created successfully.\n";
        }
    }

    private function validateUsername($username)
    {
        if (strlen($username) < 4) {
            return false;
        }

        if (preg_match('/[^a-z_\-0-9]/i', $username)) {
            return false;
        }

        return true;
    }

    private function validatePassword($password)
    {
        if (strlen($password) < 6) {
            return false;
        }

        if (preg_match('/[^a-z_\-0-9]/i', $password)) {
            return false;
        }

        return true;
    }

    private function validateEmail($email)
    {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return true;
        }

        return false;
    }

    private function canUpdateRootUser()
    {
        $user = $this->db->createCommand('SELECT * FROM {{%user}} WHERE id = 1')->queryOne(\PDO::FETCH_OBJ);

        return ($user && (empty($user->password_hash) || $this->allowOverwrite));
    }

    private function createUser($username, $password, $email)
    {

        if ($this->canUpdateRootUser()) {
            $security      = new Security();
            $password_hash = $security->generatePasswordHash($password);

            $result = $this->db->createCommand()->update('{{%user}}', [
                    'username' => $username,
                    'password_hash' => $password_hash,
                    'email' => $email,
                    ], [ 'id' => '1'])->execute();

            if ($result > 0) {
                return true;
            }
        }

        return false;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>compareTo method - KId class - hetimatorrent.dht library - Dart API</title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the compareTo method from the KId class, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

hetimatorrent

hetimatorrent.dht

KId

compareTo

compareTo

hetimatorrent

hetimatorrent.dht

KId

compareTo

method
 compareTo

Source

hetimatorrent

hetimatorrent.dht

KId

Static methods

createIDAtRandom

createToken

Properties

hashCode

idAsString

iterator

length

rawvalue

value

Constructors

KId

zeroClear

Operators

operator <

operator <=

operator ==

operator >

operator >=

operator []

Methods

compareTo

getRootingTabkeIndex

toString

xor

xorToThe

            int
            compareTo(

                KId other

            )

Compares this object to another Comparable

Returns a value like a Comparator when comparing this to other.
That is, it returns a negative integer if this is ordered before other,
a positive integer if this is ordered after other,
and zero if this and other are ordered together.

The other argument must be a value that is comparable to this object.

Source

int compareTo(KId other) {
  if (this == other) {
    return 0;
  } else if (this > other) {
    return 1;
  } else {
    return -1;
  }
}

                  hetimatorrent 0.0.1 api docs

                •

                •

                  cc license


text:
//
//  SlideView.m
//  Esquire
//
//  Created by Valentina Sautto on 8/27/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "SlideView.h"

@implementation SlideView

@synthesize hide, slideTo;
@synthesize delegate = _delegate;
@synthesize customOffset;
@synthesize interval;

#define DEFAULT_INTERVAL 0.5;

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
		self.hide = FALSE;
		interval = DEFAULT_INTERVAL;
		initialPositions = frame;
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self slideOut];
    interval = DEFAULT_INTERVAL;
}
/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (void)dealloc {

}

#pragma mark -
#pragma mark methods

- (void) slide{
	if(self.hide){
		[self slideIn];
	}else {
		[self slideOut];
	}

}

- (void) slideIn {
	if (!self.hide) return;
	self.hide = NO;
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:interval];
	[UIView setAnimationDelegate:self];
	switch (slideTo) {
		case LEFT:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x - self.customOffset, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x - self.customOffset, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			break;
		case RIGHT:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x + self.customOffset, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x + self.customOffset, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			break;
		case UP:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - self.customOffset, self.frame.size.width, self.frame.size.height);
			else{
				//NSLog(@"-->%f %f %f %f",self.frame.origin.x, self.frame.origin.y - self.frame.size.height, self.frame.size.width, self.frame.size.height);
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - self.frame.size.height, self.frame.size.width, self.frame.size.height);
			}
			break;
		case DOWN:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.customOffset, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, self.frame.size.height);
			break;
		default:
			break;
	}
	[UIView setAnimationDidStopSelector:@selector(animationDidFinish)];
	[UIView commitAnimations];
}

- (void) slideOut {
	if (self.hide) return;
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:interval];
	[UIView setAnimationDelegate:self];
	switch (slideTo) {
		case LEFT:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x + self.customOffset, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x + self.frame.size.width, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			break;
		case RIGHT:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x - self.customOffset, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x - self.frame.size.width, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			break;
		case UP:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.customOffset, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, self.frame.size.height);
			break;
		case DOWN:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - self.customOffset, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - self.frame.size.height, self.frame.size.width, self.frame.size.height);
			break;
		default:
			break;
	}
	[UIView setAnimationDidStopSelector:@selector(animationDidFinish)];
	[UIView commitAnimations];
	self.hide = YES;
}

- (void) setSlideTo:(SlideOptions)st{
	slideTo = st;
	switch (slideTo) {
		case LEFT:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x + self.customOffset, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x + self.frame.size.width, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			break;
		case RIGHT:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x - self.customOffset, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x - self.frame.size.width, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
			break;
		case UP:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.customOffset, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height, self.frame.size.width, self.frame.size.height);
			break;
		case DOWN:
			if (customOffsetAvailable)
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - self.customOffset, self.frame.size.width, self.frame.size.height);
			else
				self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - self.frame.size.height, self.frame.size.width, self.frame.size.height);
			break;
		default:
			break;
	}
	hide = YES;
}

- (void)setCustomOffset:(CGFloat)offset {
	if (offset != 0)
	{
		customOffsetAvailable = YES;
	}
	else {
		customOffsetAvailable = NO;
	}

	customOffset = offset;
}

- (void)setSlideToWithoutAnimation:(SlideOptions)st interval:(CGFloat)_interval {
	slideTo = st;
	[self setInterval:_interval];
}

- (void)animationDidFinish {
	if ([self.delegate respondsToSelector:@selector (slideViewDidFinishSliding:)]) {
		[self.delegate slideViewDidFinishSliding:self];
	}
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

	//[self slideOut];
}
@end


text:
package net.javacrumbs.shedlock.provider.dynamodb2;

import net.javacrumbs.shedlock.core.AbstractSimpleLock;
import net.javacrumbs.shedlock.core.ClockProvider;
import net.javacrumbs.shedlock.core.LockConfiguration;
import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.core.SimpleLock;
import net.javacrumbs.shedlock.support.Utils;
import net.javacrumbs.shedlock.support.annotation.NonNull;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static java.util.Collections.singletonMap;
import static java.util.Objects.requireNonNull;
import static net.javacrumbs.shedlock.support.Utils.toIsoString;

/**
 * Distributed lock using DynamoDB.
 * Depends on software.amazon.awssdk:dynamodb.
 *

 * It uses a table with the following structure:
 *

 * {
 *    "_id" : "lock name",
 *    "lockUntil" : ISODate("2017-01-07T16:52:04.071Z"),
 *    "lockedAt" : ISODate("2017-01-07T16:52:03.932Z"),
 *    "lockedBy" : "host name"
 * }
 *

 *
 * lockedAt and lockedBy are just for troubleshooting
 * and are not read by the code.
 *
 *

 *

 * Attempts to insert a new lock record.
 *

 *

 * We will try to update lock record using filter _id == :name AND lock_until <= :now.
 *

 *

 * If the update succeeded, we have the lock. If the update failed (condition check exception)
 * somebody else holds the lock.
 *

 *

 * When unlocking, lock_until is set to now or lockAtLeastUntil whichever is later.
 *

 *

 */
public class DynamoDBLockProvider implements LockProvider {
    static final String LOCK_UNTIL = "lockUntil";
    static final String LOCKED_AT = "lockedAt";
    static final String LOCKED_BY = "lockedBy";
    static final String ID = "_id";

    private static final String OBTAIN_LOCK_QUERY =
            "set " + LOCK_UNTIL + " = :lockUntil, " + LOCKED_AT + " = :lockedAt, " + LOCKED_BY + " = :lockedBy";
    private static final String OBTAIN_LOCK_CONDITION =
            LOCK_UNTIL + " <= :lockedAt or attribute_not_exists(" + LOCK_UNTIL + ")";
    private static final String RELEASE_LOCK_QUERY =
            "set " + LOCK_UNTIL + " = :lockUntil";

    private final String hostname;
    private final DynamoDbClient dynamoDbClient;
    private final String tableName;

    /**
     * Uses DynamoDB to coordinate locks
     *
     * @param dynamoDbClient v2 of DynamoDB client
     * @param tableName the lock table name
     */
    public DynamoDBLockProvider(@NonNull DynamoDbClient dynamoDbClient, @NonNull String tableName) {
        this.dynamoDbClient = requireNonNull(dynamoDbClient, "dynamoDbClient can not be null");
        this.tableName = requireNonNull(tableName, "tableName can not be null");
        this.hostname = Utils.getHostname();
    }

    @Override
    @NonNull
    public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {
        String nowIso = toIsoString(now());
        String lockUntilIso = toIsoString(lockConfiguration.getLockAtMostUntil());

        Map<String, AttributeValue> key = singletonMap(ID, attr(lockConfiguration.getName()));

        Map<String, AttributeValue> attributeUpdates = new HashMap<>(3);
        attributeUpdates.put(":lockUntil", attr(lockUntilIso));
        attributeUpdates.put(":lockedAt", attr(nowIso));
        attributeUpdates.put(":lockedBy", attr(hostname));

        UpdateItemRequest request = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression(OBTAIN_LOCK_QUERY)
                .conditionExpression(OBTAIN_LOCK_CONDITION)
                .expressionAttributeValues(attributeUpdates)
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

        try {
            // There are three possible situations:
            // 1. The lock document does not exist yet - it is inserted - we have the lock
            // 2. The lock document exists and lockUtil <= now - it is updated - we have the lock
            // 3. The lock document exists and lockUtil > now - ConditionalCheckFailedException is thrown
            dynamoDbClient.updateItem(request);
            return Optional.of(new DynamoDBLock(dynamoDbClient, tableName, lockConfiguration));
        } catch (ConditionalCheckFailedException e) {
            // Condition failed. This means there was a lock with lockUntil > now.
            return Optional.empty();
        }
    }

    private static AttributeValue attr(String lockUntilIso) {
        return AttributeValue.builder()
            .s(lockUntilIso)
            .build();
    }

    private Instant now() {
        return ClockProvider.now();
    }

    private static final class DynamoDBLock extends AbstractSimpleLock {
        private final DynamoDbClient dynamoDbClient;
        private final String tableName;

        private DynamoDBLock(
            DynamoDbClient dynamoDbClient,
            String tableName,
            LockConfiguration lockConfiguration
        ) {
            super(lockConfiguration);
            this.dynamoDbClient = dynamoDbClient;
            this.tableName = tableName;
        }

        @Override
        public void doUnlock() {
            // Set lockUntil to now or lockAtLeastUntil whichever is later
            String unlockTimeIso = toIsoString(lockConfiguration.getUnlockTime());

            Map<String, AttributeValue> key = singletonMap(ID, attr(lockConfiguration.getName()));

            Map<String, AttributeValue> attributeUpdates = singletonMap(":lockUntil", attr(unlockTimeIso));

            UpdateItemRequest request = UpdateItemRequest.builder()
                    .tableName(tableName)
                    .key(key)
                    .updateExpression(RELEASE_LOCK_QUERY)
                    .expressionAttributeValues(attributeUpdates)
                    .returnValues(ReturnValue.UPDATED_NEW)
                    .build();

            dynamoDbClient.updateItem(request);
        }
    }
}


text: to include another file from a near directory you can use `require_relative 'relative/path/to.file`


text:
next_version :=  $(shell cat build_version.txt)
tag := $(shell git describe --exact-match --tags 2>git_describe_error.tmp; rm -f git_describe_error.tmp)
branch := $(shell git rev-parse --abbrev-ref HEAD)
commit := $(shell git rev-parse --short=8 HEAD)
glibc_version := 2.17

ifdef NIGHTLY
	version := $(next_version)
	rpm_version := nightly
	rpm_iteration := 0
	deb_version := nightly
	deb_iteration := 0
	tar_version := nightly
else ifeq ($(tag),)
	version := $(next_version)
	rpm_version := $(version)~$(commit)-0
	rpm_iteration := 0
	deb_version := $(version)~$(commit)-0
	deb_iteration := 0
	tar_version := $(version)~$(commit)
else ifneq ($(findstring -rc,$(tag)),)
	version := $(word 1,$(subst -, ,$(tag)))
	version := $(version:v%=%)
	rc := $(word 2,$(subst -, ,$(tag)))
	rpm_version := $(version)-0.$(rc)
	rpm_iteration := 0.$(subst rc,,$(rc))
	deb_version := $(version)~$(rc)-1
	deb_iteration := 0
	tar_version := $(version)~$(rc)
else
	version := $(tag:v%=%)
	rpm_version := $(version)-1
	rpm_iteration := 1
	deb_version := $(version)-1
	deb_iteration := 1
	tar_version := $(version)
endif

MAKEFLAGS += --no-print-directory
GOOS ?= $(shell go env GOOS)
GOARCH ?= $(shell go env GOARCH)
HOSTGO := env -u GOOS -u GOARCH -u GOARM -- go

LDFLAGS := $(LDFLAGS) -X main.commit=$(commit) -X main.branch=$(branch) -X main.goos=$(GOOS) -X main.goarch=$(GOARCH)
ifneq ($(tag),)
	LDFLAGS += -X main.version=$(version)
endif

# Go built-in race detector works only for 64 bits architectures.
ifneq ($(GOARCH), 386)
	race_detector := -race
endif

GOFILES ?= $(shell git ls-files '*.go')
GOFMT ?= $(shell gofmt -l -s $(filter-out plugins/parsers/influx/machine.go, $(GOFILES)))

prefix ?= /usr/local
bindir ?= $(prefix)/bin
sysconfdir ?= $(prefix)/etc
localstatedir ?= $(prefix)/var
pkgdir ?= build/dist

.PHONY: all
all:
	@$(MAKE) deps
	@$(MAKE) telegraf

.PHONY: help
help:
	@echo 'Targets:'
	@echo '  all          - download dependencies and compile telegraf binary'
	@echo '  deps         - download dependencies'
	@echo '  telegraf     - compile telegraf binary'
	@echo '  test         - run short unit tests'
	@echo '  fmt          - format source files'
	@echo '  tidy         - tidy go modules'
	@echo '  lint         - run linter'
	@echo '  lint-branch  - run linter on changes in current branch since master'
	@echo '  lint-install - install linter'
	@echo '  check-deps   - check docs/LICENSE_OF_DEPENDENCIES.md'
	@echo '  clean        - delete build artifacts'
	@echo ''
	@echo 'Package Targets:'
	@$(foreach dist,$(dists),echo "  $(dist)";)

.PHONY: deps
deps:
	go mod download -x

.PHONY: telegraf
telegraf:
	go build -ldflags "$(LDFLAGS)" ./cmd/telegraf

# Used by dockerfile builds
.PHONY: go-install
go-install:
	go install -mod=mod -ldflags "-w -s $(LDFLAGS)" ./cmd/telegraf

.PHONY: test
test:
	go test -short $(race_detector) ./...

.PHONY: test-integration
test-integration:
	go test -run Integration $(race_detector) ./...

.PHONY: fmt
fmt:
	@gofmt -s -w $(filter-out plugins/parsers/influx/machine.go, $(GOFILES))

.PHONY: fmtcheck
fmtcheck:
	@if [ ! -z "$(GOFMT)" ]; then \
		echo "[ERROR] gofmt has found errors in the following files:"  ; \
		echo "$(GOFMT)" ; \
		echo "" ;\
		echo "Run make fmt to fix them." ; \
		exit 1 ;\
	fi

.PHONY: test-windows
test-windows:
	go test -short ./...

.PHONY: vet
vet:
	@echo 'go vet $$(go list ./... | grep -v ./plugins/parsers/influx)'
	@go vet $$(go list ./... | grep -v ./plugins/parsers/influx) ; if [ $$? -ne 0 ]; then \
		echo ""; \
		echo "go vet has found suspicious constructs. Please remediate any reported errors"; \
		echo "to fix them before submitting code for review."; \
		exit 1; \
	fi

.PHONY: lint-install
lint-install:

	go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.38.0

.PHONY: lint
lint:
ifeq (, $(shell which golangci-lint))
	$(info golangci-lint can't be found, please run: make lint-install)
	exit 1
endif

	golangci-lint run

.PHONY: lint-branch
lint-branch:
ifeq (, $(shell which golangci-lint))
	$(info golangci-lint can't be found, please run: make lint-install)
	exit 1
endif

	golangci-lint run --new-from-rev master

.PHONY: tidy
tidy:
	go mod verify
	go mod tidy
	@if ! git diff --quiet go.mod go.sum; then \
		echo "please run go mod tidy and check in changes, you might have to use the same version of Go as the CI"; \
		exit 1; \
	fi

.PHONY: check
check: fmtcheck vet

.PHONY: test-all
test-all: fmtcheck vet
	go test $(race_detector) ./...

.PHONY: check-deps
check-deps:
	./scripts/check-deps.sh

.PHONY: clean
clean:
	rm -f telegraf
	rm -f telegraf.exe
	rm -rf build

.PHONY: docker-image
docker-image:
	docker build -f scripts/buster.docker -t "telegraf:$(commit)" .

plugins/parsers/influx/machine.go: plugins/parsers/influx/machine.go.rl
	ragel -Z -G2 $^ -o $@

.PHONY: plugin-%
plugin-%:
	@echo "Starting dev environment for $${$(@)} input plugin..."
	@docker-compose -f plugins/inputs/$${$(@)}/dev/docker-compose.yml up

.PHONY: ci-1.15
ci-1.15:
	docker build -t quay.io/influxdb/telegraf-ci:1.15.8 - < scripts/ci-1.15.docker
	docker push quay.io/influxdb/telegraf-ci:1.15.8

.PHONY: ci-1.16
ci-1.16:
	docker build -t quay.io/influxdb/telegraf-ci:1.16.6 - < scripts/ci-1.16.docker
	docker push quay.io/influxdb/telegraf-ci:1.16.6

.PHONY: install
install: $(buildbin)
	@mkdir -pv $(DESTDIR)$(bindir)
	@mkdir -pv $(DESTDIR)$(sysconfdir)
	@mkdir -pv $(DESTDIR)$(localstatedir)
	@if [ $(GOOS) != "windows" ]; then mkdir -pv $(DESTDIR)$(sysconfdir)/logrotate.d; fi
	@if [ $(GOOS) != "windows" ]; then mkdir -pv $(DESTDIR)$(localstatedir)/log/telegraf; fi
	@if [ $(GOOS) != "windows" ]; then mkdir -pv $(DESTDIR)$(sysconfdir)/telegraf/telegraf.d; fi
	@cp -fv $(buildbin) $(DESTDIR)$(bindir)
	@if [ $(GOOS) != "windows" ]; then cp -fv etc/telegraf.conf $(DESTDIR)$(sysconfdir)/telegraf/telegraf.conf$(conf_suffix); fi
	@if [ $(GOOS) != "windows" ]; then cp -fv etc/logrotate.d/telegraf $(DESTDIR)$(sysconfdir)/logrotate.d; fi
	@if [ $(GOOS) = "windows" ]; then cp -fv etc/telegraf_windows.conf $(DESTDIR)/telegraf.conf; fi
	@if [ $(GOOS) = "linux" ]; then scripts/check-dynamic-glibc-versions.sh $(buildbin) $(glibc_version); fi
	@if [ $(GOOS) = "linux" ]; then mkdir -pv $(DESTDIR)$(prefix)/lib/telegraf/scripts; fi
	@if [ $(GOOS) = "linux" ]; then cp -fv scripts/telegraf.service $(DESTDIR)$(prefix)/lib/telegraf/scripts; fi
	@if [ $(GOOS) = "linux" ]; then cp -fv scripts/init.sh $(DESTDIR)$(prefix)/lib/telegraf/scripts; fi

# Telegraf build per platform.  This improves package performance by sharing
# the bin between deb/rpm/tar packages over building directly into the package
# directory.
$(buildbin):
	@mkdir -pv $(dir $@)
	go build -o $(dir $@) -ldflags "$(LDFLAGS)" ./cmd/telegraf

ifdef mips
debs += telegraf_$(deb_version)_mips.deb
tars += telegraf-$(tar_version)_linux_mips.tar.gz
endif

ifdef mipsel
debs += telegraf_$(deb_version)_mipsel.deb
tars += telegraf-$(tar_version)_linux_mipsel.tar.gz
endif

ifdef arm64
tars += telegraf-$(tar_version)_linux_arm64.tar.gz
debs += telegraf_$(deb_version)_arm64.deb
rpms += telegraf-$(rpm_version).aarch64.rpm
endif

ifdef amd64
tars += telegraf-$(tar_version)_freebsd_amd64.tar.gz
tars += telegraf-$(tar_version)_linux_amd64.tar.gz
debs += telegraf_$(deb_version)_amd64.deb
rpms += telegraf-$(rpm_version).x86_64.rpm
endif

ifdef static
tars += telegraf-$(tar_version)_static_linux_amd64.tar.gz
endif

ifdef armel
tars += telegraf-$(tar_version)_linux_armel.tar.gz
rpms += telegraf-$(rpm_version).armel.rpm
debs += telegraf_$(deb_version)_armel.deb
endif

ifdef armhf
tars += telegraf-$(tar_version)_linux_armhf.tar.gz
tars += telegraf-$(tar_version)_freebsd_armv7.tar.gz
debs += telegraf_$(deb_version)_armhf.deb
rpms += telegraf-$(rpm_version).armv6hl.rpm
endif

ifdef s390x
tars += telegraf-$(tar_version)_linux_s390x.tar.gz
debs += telegraf_$(deb_version)_s390x.deb
rpms += telegraf-$(rpm_version).s390x.rpm
endif

ifdef ppc641e
tars += telegraf-$(tar_version)_linux_ppc64le.tar.gz
rpms += telegraf-$(rpm_version).ppc64le.rpm
debs += telegraf_$(deb_version)_ppc64el.deb
endif

ifdef i386
tars += telegraf-$(tar_version)_freebsd_i386.tar.gz
debs += telegraf_$(deb_version)_i386.deb
tars += telegraf-$(tar_version)_linux_i386.tar.gz
rpms += telegraf-$(rpm_version).i386.rpm
endif

ifdef windows
zips += telegraf-$(tar_version)_windows_i386.zip
zips += telegraf-$(tar_version)_windows_amd64.zip
endif

ifdef darwin
tars += telegraf-$(tar_version)_darwin_amd64.tar.gz
endif

dists := $(debs) $(rpms) $(tars) $(zips)

.PHONY: package
package: $(dists)

rpm_amd64 := amd64
rpm_386 := i386
rpm_s390x := s390x
rpm_ppc64le := ppc64le
rpm_arm5 := armel
rpm_arm6 := armv6hl
rpm_arm647 := aarch64
rpm_arch = $(rpm_$(GOARCH)$(GOARM))

.PHONY: $(rpms)
$(rpms):
	@$(MAKE) install
	@mkdir -p $(pkgdir)
	fpm --force \
		--log info \
		--architecture $(rpm_arch) \
		--input-type dir \
		--output-type rpm \
		--vendor InfluxData \
		--url https://github.com/influxdata/telegraf \
		--license MIT \
		--maintainer support@influxdb.com \
		--config-files /etc/telegraf/telegraf.conf \
		--config-files /etc/logrotate.d/telegraf \
		--after-install scripts/rpm/post-install.sh \
		--before-install scripts/rpm/pre-install.sh \
		--after-remove scripts/rpm/post-remove.sh \
		--description "Plugin-driven server agent for reporting metrics into InfluxDB." \
		--depends coreutils \
		--depends shadow-utils \
		--rpm-posttrans scripts/rpm/post-install.sh \
		--name telegraf \
		--version $(version) \
		--iteration $(rpm_iteration) \
        --chdir $(DESTDIR) \
		--package $(pkgdir)/$@

deb_amd64 := amd64
deb_386 := i386
deb_s390x := s390x
deb_ppc64le := ppc64el
deb_arm5 := armel
deb_arm6 := armhf
deb_arm647 := arm64
deb_mips := mips
deb_mipsle := mipsel
deb_arch = $(deb_$(GOARCH)$(GOARM))

.PHONY: $(debs)
$(debs):
	@$(MAKE) install
	@mkdir -pv $(pkgdir)
	fpm --force \
		--log info \
		--architecture $(deb_arch) \
		--input-type dir \
		--output-type deb \
		--vendor InfluxData \
		--url https://github.com/influxdata/telegraf \
		--license MIT \
		--maintainer support@influxdb.com \
		--config-files /etc/telegraf/telegraf.conf.sample \
		--config-files /etc/logrotate.d/telegraf \
		--after-install scripts/deb/post-install.sh \
		--before-install scripts/deb/pre-install.sh \
		--after-remove scripts/deb/post-remove.sh \
		--before-remove scripts/deb/pre-remove.sh \
		--description "Plugin-driven server agent for reporting metrics into InfluxDB." \
		--name telegraf \
		--version $(version) \
		--iteration $(deb_iteration) \
		--chdir $(DESTDIR) \
		--package $(pkgdir)/$@

.PHONY: $(zips)
$(zips):
	@$(MAKE) install
	@mkdir -p $(pkgdir)
	(cd $(dir $(DESTDIR)) && zip -r - ./*) > $(pkgdir)/$@

.PHONY: $(tars)
$(tars):
	@$(MAKE) install
	@mkdir -p $(pkgdir)
	tar --owner 0 --group 0 -czvf $(pkgdir)/$@ -C $(dir $(DESTDIR)) .

.PHONY: upload-nightly
upload-nightly:
	aws s3 sync $(pkgdir) s3://dl.influxdata.com/telegraf/nightlies/ \
		--exclude "*" \
		--include "*.tar.gz" \
		--include "*.deb" \
		--include "*.rpm" \
		--include "*.zip" \
		--acl public-read

%amd64.deb %x86_64.rpm %linux_amd64.tar.gz: export GOOS := linux
%amd64.deb %x86_64.rpm %linux_amd64.tar.gz: export GOARCH := amd64

%static_linux_amd64.tar.gz: export cgo := -nocgo
%static_linux_amd64.tar.gz: export CGO_ENABLED := 0

%i386.deb %i386.rpm %linux_i386.tar.gz: export GOOS := linux
%i386.deb %i386.rpm %linux_i386.tar.gz: export GOARCH := 386

%armel.deb %armel.rpm %linux_armel.tar.gz: export GOOS := linux
%armel.deb %armel.rpm %linux_armel.tar.gz: export GOARCH := arm
%armel.deb %armel.rpm %linux_armel.tar.gz: export GOARM := 5

%armhf.deb %armv6hl.rpm %linux_armhf.tar.gz: export GOOS := linux
%armhf.deb %armv6hl.rpm %linux_armhf.tar.gz: export GOARCH := arm
%armhf.deb %armv6hl.rpm %linux_armhf.tar.gz: export GOARM := 6

%arm64.deb %aarch64.rpm %linux_arm64.tar.gz: export GOOS := linux
%arm64.deb %aarch64.rpm %linux_arm64.tar.gz: export GOARCH := arm64
%arm64.deb %aarch64.rpm %linux_arm64.tar.gz: export GOARM := 7

%mips.deb %linux_mips.tar.gz: export GOOS := linux
%mips.deb %linux_mips.tar.gz: export GOARCH := mips

%mipsel.deb %linux_mipsel.tar.gz: export GOOS := linux
%mipsel.deb %linux_mipsel.tar.gz: export GOARCH := mipsle

%s390x.deb %s390x.rpm %linux_s390x.tar.gz: export GOOS := linux
%s390x.deb %s390x.rpm %linux_s390x.tar.gz: export GOARCH := s390x

%ppc64el.deb %ppc64le.rpm %linux_ppc64le.tar.gz: export GOOS := linux
%ppc64el.deb %ppc64le.rpm %linux_ppc64le.tar.gz: export GOARCH := ppc64le

%freebsd_amd64.tar.gz: export GOOS := freebsd
%freebsd_amd64.tar.gz: export GOARCH := amd64

%freebsd_i386.tar.gz: export GOOS := freebsd
%freebsd_i386.tar.gz: export GOARCH := 386

%freebsd_armv7.tar.gz: export GOOS := freebsd
%freebsd_armv7.tar.gz: export GOARCH := arm
%freebsd_armv7.tar.gz: export GOARM := 7

%windows_amd64.zip: export GOOS := windows
%windows_amd64.zip: export GOARCH := amd64

%darwin_amd64.tar.gz: export GOOS := darwin
%darwin_amd64.tar.gz: export GOARCH := amd64

%windows_i386.zip: export GOOS := windows
%windows_i386.zip: export GOARCH := 386

%windows_i386.zip %windows_amd64.zip: export prefix =
%windows_i386.zip %windows_amd64.zip: export bindir = $(prefix)
%windows_i386.zip %windows_amd64.zip: export sysconfdir = $(prefix)
%windows_i386.zip %windows_amd64.zip: export localstatedir = $(prefix)
%windows_i386.zip %windows_amd64.zip: export EXEEXT := .exe

%.deb: export pkg := deb
%.deb: export prefix := /usr
%.deb: export conf_suffix := .sample
%.deb: export sysconfdir := /etc
%.deb: export localstatedir := /var
%.rpm: export pkg := rpm
%.rpm: export prefix := /usr
%.rpm: export sysconfdir := /etc
%.rpm: export localstatedir := /var
%.tar.gz: export pkg := tar
%.tar.gz: export prefix := /usr
%.tar.gz: export sysconfdir := /etc
%.tar.gz: export localstatedir := /var
%.zip: export pkg := zip
%.zip: export prefix := /

%.deb %.rpm %.tar.gz %.zip: export DESTDIR = build/$(GOOS)-$(GOARCH)$(GOARM)$(cgo)-$(pkg)/telegraf-$(version)
%.deb %.rpm %.tar.gz %.zip: export buildbin = build/$(GOOS)-$(GOARCH)$(GOARM)$(cgo)/telegraf$(EXEEXT)
%.deb %.rpm %.tar.gz %.zip: export LDFLAGS = -w -s