text:
<?php

namespace Lokos\ShopBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use JMS\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Exclude;
use JMS\Serializer\Annotation\Expose;

/**
 * Product
 *
 * @ORM\Table(name="product", indexes={@ORM\Index(name="fk_product_category_idx", columns={"category_id"}), @ORM\Index(name="fk_product_brand1_idx", columns={"brand_id"})})
 * @ORM\Entity(repositoryClass="Lokos\ShopBundle\Repositories\ProductRepository")
 */
class Product
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     *
     * @Assert\NotBlank()
     *
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, nullable=false)
     */
    private $name;

    /**
     * @Assert\NotBlank()
     *
     * @var string
     *
     * @ORM\Column(name="description", type="text", length=16777215, nullable=false)
     */
    private $description;

    /**
     * @var float
     *
     * @ORM\Column(name="price", type="float", precision=10, scale=0, nullable=false)
     */
    private $price;

    /**
     * @var integer
     *
     * @ORM\Column(name="quantity", type="integer", nullable=true)
     */
    private $quantity;

    /**
     * @Assert\NotBlank()
     *
     * @var \Category
     *
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     * })
     */
    private $category;

    /**
     * @var \Brand
     *
     * @ORM\ManyToOne(targetEntity="Brand", inversedBy="products")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="brand_id", referencedColumnName="id")
     * })
     */
    private $brand;

    /**
     * @ORM\OneToMany(targetEntity="ProductSet", mappedBy="product", cascade={"persist"})
     */
    private $productSets;

    /**
     * @ORM\OneToMany(targetEntity="Product2Attribute", mappedBy="product", cascade={"persist"})
     */
    private $product2Attributes;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->attribute          = new ArrayCollection();
        $this->productSets        = new ArrayCollection();
        $this->product2Attributes = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Product
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Product
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set price
     *
     * @param float $price
     *
     * @return Product
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return float
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set quantity
     *
     * @param integer $quantity
     *
     * @return Product
     */
    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;

        return $this;
    }

    /**
     * Get quantity
     *
     * @return integer
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * Set category
     *
     * @param \Lokos\ShopBundle\Entity\Category $category
     *
     * @return Product
     */
    public function setCategory(Category $category = null)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * @return \Category
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * @param Brand|null $brand
     *
     * @return $this
     */
    public function setBrand(Brand $brand = null)
    {
        $this->brand = $brand;

        return $this;
    }

    /**
     * Get brand
     *
     * @return \Lokos\ShopBundle\Entity\Brand
     */
    /**
     * @return \Brand
     */
    public function getBrand()
    {
        return $this->brand;
    }

    /**
     * @return mixed
     */
    public function getProductSets()
    {
        return $this->productSets;
    }

    /**
     * @param $productSets
     *
     * @return $this
     */
    public function setProductSets($productSets)
    {
        $this->productSets = $productSets;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getProduct2Attributes()
    {
        return $this->product2Attributes;
    }

    /**
     * @param $product2Attributes
     *
     * @return $this
     */
    public function setProduct2Attributes($product2Attributes)
    {
        $this->product2Attributes = $product2Attributes;

        return $this;
    }

    /**
     * @return mixed
     */
    function __toString()
    {
        return ($this->getName())?$this->getName():'New product';
    }

}


text:
@implementation NSMutableDictionary(SafeSet)

- (void)safeSetObject:(id)object forKey:(NSString *)key{
    if (key.length == 0 || object == nil) {
        NSLog(@"安全问题: %@ %@", key, object);
        return;
    }else{
        [self setObject:object forKey:key];
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
package org.gessinger.gepard.xmp ;
import org.gessinger.gepard.* ;
import java.io.* ;
public class SizeTest
{
  static public void main ( String[] args )
  {
    Util.argsToProperties ( args ) ;
    try
    {
      SizeTest j = new SizeTest() ;
    }
    catch ( Exception exc )
    {
      exc.printStackTrace() ;
    }
  }
  SizeTest()
  throws Exception
  {
    Client client = Client.getInstance() ;
    String fn = Util.getProperty ( "file", "RSE_0_1-R6_Scenario5_2.xml" ) ;
    byte[] ba = Util.getBytes ( new File ( fn ) ) ;
    Event e = new Event ( "ALARM" ) ;
    e.putValue ( "DATA", ba ) ;
    client.emit ( e ) ;
    client.emit ( e, new StatusCallback()
    {
      public void status ( Event e )
      {
        System.out.println ( "status=" + e.getStatusName() ) ;
        System.out.println ( e.getStatusReason() ) ;
        e.getClient().close() ;
      }
    } ) ;
  }
}


text:
<?php
namespace qtil\Tests\Mock\ExtendedQueryChain {
    class Join extends \qtil\Tests\Mock\QueryChain\Statement {

    }
}


text:
package com.jme3.bullet.joints;

import com.jme3.bullet.objects.PhysicsRigidBody;
import com.jme3.math.Matrixable;
import com.jme3.math.Vector3f;

/**
 * From bullet manual:

 * This generic constraint can emulate a variety of standard constraints,
 * by configuring each of the 6 degrees of freedom (dof).
 * The first 3 dof axis are linear axis, which represent translation of rigidbodies,
 * and the latter 3 dof axis represent the angular motion. Each axis can be either locked,
 * free or limited. On construction of a new btGeneric6DofConstraint, all axis are locked.
 * Afterwards the axis can be reconfigured. Note that several combinations that
 * include free and/or limited angular degrees of freedom are undefined.
 * @author normenhansen
 */
public class SixDofSpringJoint extends SixDofJoint {

   final boolean       springEnabled[] = new boolean[6];
   final float equilibriumPoint[] = new float[6];
   final float springStiffness[] = new float[6];
   final float springDamping[] = new float[6]; // between 0 and 1 (1 == no damping)

    public SixDofSpringJoint() {
    }

    /**
     * @param pivotA local translation of the joint connection point in node A
     * @param pivotB local translation of the joint connection point in node B
     */
    public SixDofSpringJoint(PhysicsRigidBody nodeA, PhysicsRigidBody nodeB, Vector3f pivotA, Vector3f pivotB, Matrixable rotA, Matrixable rotB, boolean useLinearReferenceFrameA) {
        super(nodeA, nodeB, pivotA, pivotB, rotA, rotB, useLinearReferenceFrameA);
    }
    public void enableSpring(int index, boolean onOff) {
        enableSpring(objectId, index, onOff);
    }
    native void enableSpring(long objctId, int index, boolean onOff);

    public void setStiffness(int index, float stiffness) {
        setStiffness(objectId, index, stiffness);
    }
    native void setStiffness(long objctId, int index, float stiffness);

    public void setDamping(int index, float damping) {
        setDamping(objectId, index, damping);

    }
    native void setDamping(long objctId, int index, float damping);
    public void setEquilibriumPoint() { // set the current constraint position/orientation as an equilibrium point for all DOF
        setEquilibriumPoint(objectId);
    }
    native void setEquilibriumPoint(long objctId);
    public void setEquilibriumPoint(int index){ // set the current constraint position/orientation as an equilibrium point for given DOF
        setEquilibriumPoint(objectId, index);
    }
    native void setEquilibriumPoint(long objctId, int index);
    @Override
    native long createJoint(long objectIdA, long objectIdB, Vector3f pivotA, Matrixable rotA, Vector3f pivotB, Matrixable rotB, boolean useLinearReferenceFrameA);

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Glaucium haussknechtii Bornm. & Fedde

### Remarks
null


text:
package info.dgjones.st2x.transform.method.intra;

import java.util.List;

import info.dgjones.st2x.JavaMethod;
import info.dgjones.st2x.javatoken.JavaCallStart;
import info.dgjones.st2x.javatoken.JavaIdentifier;
import info.dgjones.st2x.transform.method.AbstractMethodBodyTransformation;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcher;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcherFactory;

public class TransformSelfSends extends AbstractMethodBodyTransformation {

	public TransformSelfSends() {
		super();
	}
	public TransformSelfSends(TokenMatcherFactory factory) {
		super(factory);
	}

	protected TokenMatcher matchers(TokenMatcherFactory factory) {
		return factory.seq(
				factory.token(JavaIdentifier.class, "this"),
				factory.token(JavaCallStart.class));
	}

	protected int transform(JavaMethod javaMethod, List methodBodyTokens, int i) {
		methodBodyTokens.remove(i);

		return i;
	}
}


text:
"""
Filter support
"""

from oslo_log import log as logging

from nova.i18n import _LI
from nova import loadables

LOG = logging.getLogger(__name__)

class BaseFilter(object):
    """Base class for all filter classes."""
    def _filter_one(self, obj, filter_properties):
        """Return True if it passes the filter, False otherwise.
        Override this in a subclass.
        """
        return True

    def filter_all(self, filter_obj_list, filter_properties):
        """Yield objects that pass the filter.

        Can be overridden in a subclass, if you need to base filtering
        decisions on all objects.  Otherwise, one can just override
        _filter_one() to filter a single object.
        """
        for obj in filter_obj_list:
            if self._filter_one(obj, filter_properties):
                yield obj

    # Set to true in a subclass if a filter only needs to be run once
    # for each request rather than for each instance
    run_filter_once_per_request = False

    def run_filter_for_index(self, index):
        """Return True if the filter needs to be run for the "index-th"
        instance in a request.  Only need to override this if a filter
        needs anything other than "first only" or "all" behaviour.
        """
        if self.run_filter_once_per_request and index > 0:
            return False
        else:
            return True

class BaseFilterHandler(loadables.BaseLoader):
    """Base class to handle loading filter classes.

    This class should be subclassed where one needs to use filters.
    """

    def get_filtered_objects(self, filters, objs, filter_properties, index=0):
        list_objs = list(objs)
        LOG.debug("Starting with %d host(s)", len(list_objs))
        # Track the hosts as they are removed. The 'full_filter_results' list
        # contains the host/nodename info for every host that passes each
        # filter, while the 'part_filter_results' list just tracks the number
        # removed by each filter, unless the filter returns zero hosts, in
        # which case it records the host/nodename for the last batch that was
        # removed. Since the full_filter_results can be very large, it is only
        # recorded if the LOG level is set to debug.
        part_filter_results = []
        full_filter_results = []
        log_msg = "%(cls_name)s: (start: %(start)s, end: %(end)s)"
        for filter_ in filters:
            if filter_.run_filter_for_index(index):
                cls_name = filter_.__class__.__name__
                start_count = len(list_objs)
                objs = filter_.filter_all(list_objs, filter_properties)
                if objs is None:
                    LOG.debug("Filter %s says to stop filtering", cls_name)
                    return
                list_objs = list(objs)
                end_count = len(list_objs)
                part_filter_results.append(log_msg % {"cls_name": cls_name,
                        "start": start_count, "end": end_count})
                if list_objs:
                    remaining = [(getattr(obj, "host", obj),
                                  getattr(obj, "nodename", ""))
                                 for obj in list_objs]
                    full_filter_results.append((cls_name, remaining))
                else:
                    LOG.info(_LI("Filter %s returned 0 hosts"), cls_name)
                    full_filter_results.append((cls_name, None))
                    break
                LOG.debug("Filter %(cls_name)s returned "
                          "%(obj_len)d host(s)",
                          {'cls_name': cls_name, 'obj_len': len(list_objs)})
        if not list_objs:
            # Log the filtration history
            rspec = filter_properties.get("request_spec", {})
            inst_props = rspec.get("instance_properties", {})
            msg_dict = {"res_id": inst_props.get("reservation_id", ""),
                        "inst_uuid": inst_props.get("uuid", ""),
                        "str_results": str(full_filter_results),
                       }
            full_msg = ("Filtering removed all hosts for the request with "
                        "reservation ID '%(res_id)s' and instance ID "
                        "'%(inst_uuid)s'. Filter results: %(str_results)s"
                       ) % msg_dict
            msg_dict["str_results"] = str(part_filter_results)
            part_msg = _LI("Filtering removed all hosts for the request with "
                           "reservation ID '%(res_id)s' and instance ID "
                           "'%(inst_uuid)s'. Filter results: %(str_results)s"
                           ) % msg_dict
            LOG.debug(full_msg)
            LOG.info(part_msg)
        return list_objs


text:
Symfony Contact Form

Installation

Requirements
composer

1. Clone this repo and cd into it
2. Run composer install
3. Add database_name parameter
4. Add google_app_key parameter
4. To create db run - php bin/console doctrine:database:create
5. To add db tables run - php bin/console doctrine:schema:update --force
6. Start server - php bin/console server:run
7. Browse to http://127.0.0.1:8000/contact/


text:
subdir = src/backend/access/transam
top_builddir = ../../../..
include $(top_builddir)/src/Makefile.global

OBJS = clog.o transam.o varsup.o xact.o xlog.o xlogutils.o rmgr.o slru.o subtrans.o multixact.o twophase.o twophase_rmgr.o

all: SUBSYS.o

SUBSYS.o: $(OBJS)
	$(LD) $(LDREL) $(LDOUT) SUBSYS.o $(OBJS)

clean:
	rm -f SUBSYS.o $(OBJS)

# ensure that version checks in xlog.c get recompiled when catversion.h changes
xlog.o: xlog.c $(top_srcdir)/src/include/catalog/catversion.h


text:
package org.dolphin.lib.progaurd;

/**
 * Created by hanyanan on 2015/11/4.
 */
public interface KeepAttr {
}


text:
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="robots" content="index, follow, all" />
        <title>HealthCareAbroad\InstitutionBundle\Form\InstitutionMedicalProcedureFormType | HealthCareAbroad API</title>
                    <link rel="stylesheet" type="text/css" href="../../../stylesheet.css">

Classes

Namespaces

Interfaces

Index

HealthCareAbroad API

Class

HealthCareAbroad\InstitutionBundle\Form\InstitutionMedicalProcedureFormType

class    InstitutionMedicalProcedureFormType        extends AbstractType

Methods

                    buildForm(FormBuilderInterface $builder, array $options)

                    setDefaultOptions(OptionsResolverInterface $resolver)

                    getName()

Details

at line 21

                    public
    buildForm(FormBuilderInterface $builder, array $options)

Parameters

                FormBuilderInterface
                $builder

                array
                $options

at line 43

                    public
    setDefaultOptions(OptionsResolverInterface $resolver)

Parameters

                OptionsResolverInterface
                $resolver

at line 51

                    public
    getName()

        Generated by Sami, the API Documentation Generator.


text:
<?php
/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * e.g., it puts together the home page when no home.php file exists.
 *
 * Learn more: {@link https://codex.wordpress.org/Template_Hierarchy}
 *
 * @package FoundationPress
 * @since FoundationPress 1.0.0
 */

get_header(); ?>

        <?php

        $args = array(
            'posts_per_page' => 1,
            'post__in' => get_option('sticky_posts'),
            'ignore_sticky_posts' => 1
        );
        $my_query_featured = new WP_Query($args);
        while ($my_query_featured->have_posts()) : $my_query_featured->the_post();

            $featured_image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'fp-hero');
            ?>
            <div class="hero hero-background-image" data-parallax="scroll"
                 data-image-src="<?php echo $featured_image[0]; ?>"
                 data-z-index="1"
                 data-speed="0.8"
                >

                    <?php

                    ?>

                    <?php ?>

                        <?php get_template_part('template-parts/sample-content-news_featured'); ?>

        <?php endwhile; ?>

Latest articles

                <button class="hide-for-large button medium expanded secondary dropdown blog-filter-button"
                        type="button" data-open="mobile-menu-2">Filter
                </button>

            <?php if (have_posts()) :

                $Postargs = array(
                    'post_type' => array('post'),
                    'post__not_in' => get_option('sticky_posts'),
                    'ignore_sticky_posts' => 1,
                    'post_per_page' => 5,
                    'paged' => get_query_var( 'paged' )
                );
                $my_query_posts = new WP_Query($Postargs); ?>

                <?php /* Start the Loop */ ?>
                <?php while ($my_query_posts->have_posts()) : $my_query_posts->the_post(); ?>

                <?php get_template_part('template-parts/sample-content-news_archived', get_post_format()); ?>
            <?php endwhile; ?>

            <?php else : ?>

                <?php get_template_part('template-parts/content', 'none'); ?>

            <?php endif; // End have_posts() check. ?>
            <?php /* Display navigation to next/previous pages when applicable */ ?>
            <?php if (function_exists('foundationpress_pagination')) {
                foundationpress_pagination();

            } else if (is_paged()) { ?>

<?php next_posts_link(__('← Older posts', 'foundationpress')); ?>

<?php previous_posts_link(__('Newer posts →', 'foundationpress')); ?>

            <?php } ?>

            <?php
            get_sidebar('blog');
            ?>

<?php get_footer();


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>com.pizzashack</groupId>
        <artifactId>pizzashack</artifactId>
        <version>1.0.0</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>pizzashack-api</artifactId>

    <packaging>war</packaging>
    <name>PizzaShack JAX-RS API</name>
    <description>Simple CXF JAX-RS webapp service using spring configuration</description>
    <properties>
        <jackson.version>1.8.6</jackson.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-jaxrs</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.0.6.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>tomcat-maven-plugin</artifactId>
                    <version>1.1</version>
                    <executions>
                        <execution>
                            <id>default-cli</id>
                            <goals>
                                <goal>run</goal>
                            </goals>
                            <configuration>
                                <port>13000</port>
                                <path>/jaxrs-service</path>
                                <useSeparateTomcatClassLoader>true</useSeparateTomcatClassLoader>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.5</source>
                        <target>1.5</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-eclipse-plugin</artifactId>
                    <configuration>
                        <projectNameTemplate>[artifactId]-[version]</projectNameTemplate>
                        <wtpmanifest>true</wtpmanifest>
                        <wtpapplicationxml>true</wtpapplicationxml>
                        <wtpversion>2.0</wtpversion>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <id>reserve-network-port</id>
                        <goals>
                            <goal>reserve-network-port</goal>
                        </goals>
                        <phase>process-test-resources</phase>
                        <configuration>
                            <portNames>
                                <portName>test.server.port</portName>
                            </portNames>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>tomcat-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>start-tomcat</id>
                        <goals>
                            <goal>run-war</goal>
                        </goals>
                        <phase>pre-integration-test</phase>
                        <configuration>
                            <port>${test.server.port}</port>
                            <path>/jaxrs-service</path>
                            <fork>true</fork>
                            <useSeparateTomcatClassLoader>true</useSeparateTomcatClassLoader>
                        </configuration>
                    </execution>
                    <execution>
                        <id>stop-tomcat</id>
                        <goals>
                            <goal>shutdown</goal>
                        </goals>
                        <phase>post-integration-test</phase>
                        <configuration>
                            <path>/jaxrs-service</path>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.8.1</version>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                        <configuration>
                            <systemPropertyVariables>
                                <service.url>http://localhost:${test.server.port}/jaxrs-service</service.url>
                            </systemPropertyVariables>
                        </configuration>
                    </execution>
                    <execution>
                        <id>verify</id>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
CKEDITOR.plugins.setLang( 'table', 'cs', {
	border: 'Ohraničení',
	caption: 'Popis',
	cell: {
		menu: 'Buňka',
		insertBefore: 'Vložit buňku před',
		insertAfter: 'Vložit buňku za',
		deleteCell: 'Smazat buňky',
		merge: 'Sloučit buňky',
		mergeRight: 'Sloučit doprava',
		mergeDown: 'Sloučit dolů',
		splitHorizontal: 'Rozdělit buňky vodorovně',
		splitVertical: 'Rozdělit buňky svisle',
		title: 'Vlastnosti buňky',
		cellType: 'Typ buňky',
		rowSpan: 'Spojit řádky',
		colSpan: 'Spojit sloupce',
		wordWrap: 'Zalamování',
		hAlign: 'Vodorovné zarovnání',
		vAlign: 'Svislé zarovnání',
		alignBaseline: 'Na účaří',
		bgColor: 'Barva pozadí',
		borderColor: 'Barva okraje',
		data: 'Data',
		header: 'Hlavička',
		yes: 'Ano',
		no: 'Ne',
		invalidWidth: 'Šířka buňky musí být číslo.',
		invalidHeight: 'Zadaná výška buňky musí být číslená.',
		invalidRowSpan: 'Zadaný počet sloučených řádků musí být celé číslo.',
		invalidColSpan: 'Zadaný počet sloučených sloupců musí být celé číslo.',
		chooseColor: 'Výběr'
	},
	cellPad: 'Odsazení obsahu v buňce',
	cellSpace: 'Vzdálenost buněk',
	column: {
		menu: 'Sloupec',
		insertBefore: 'Vložit sloupec před',
		insertAfter: 'Vložit sloupec za',
		deleteColumn: 'Smazat sloupec'
	},
	columns: 'Sloupce',
	deleteTable: 'Smazat tabulku',
	headers: 'Záhlaví',
	headersBoth: 'Obojí',
	headersColumn: 'První sloupec',
	headersNone: 'Žádné',
	headersRow: 'První řádek',
	invalidBorder: 'Zdaná velikost okraje musí být číselná.',
	invalidCellPadding: 'Zadané odsazení obsahu v buňce musí být číselné.',
	invalidCellSpacing: 'Zadaná vzdálenost buněk musí být číselná.',
	invalidCols: 'Počet sloupců musí být číslo větší než 0.',
	invalidHeight: 'Zadaná výška tabulky musí být číselná.',
	invalidRows: 'Počet řádků musí být číslo větší než 0.',
	invalidWidth: 'Šířka tabulky musí být číslo.',
	menu: 'Vlastnosti tabulky',
	row: {
		menu: 'Řádek',
		insertBefore: 'Vložit řádek před',
		insertAfter: 'Vložit řádek za',
		deleteRow: 'Smazat řádky'
	},
	rows: 'Řádky',
	summary: 'Souhrn',
	title: 'Vlastnosti tabulky',
	toolbar: 'Tabulka',
	widthPc: 'procent',
	widthPx: 'bodů',
	widthUnit: 'jednotka šířky'
} );


text:
using Nager.Date.Contract;
using Nager.Date.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Nager.Date.PublicHolidays
{
    /// <summary>
    /// //Åland
    /// </summary>
    public class AlandProvider : IPublicHolidayProvider
    {
        private readonly ICatholicProvider _catholicProvider;

        /// <summary>
        /// AlandProvider
        /// </summary>
        /// <param name="catholicProvider"></param>
        public AlandProvider(ICatholicProvider catholicProvider)
        {
            this._catholicProvider = catholicProvider;
        }

        ///<inheritdoc/>
        public IEnumerable<PublicHoliday> Get(int year)
        {
            var countryCode = CountryCode.AX;

            var thirdFridayInJune = DateSystem.FindDay(year, Month.June, DayOfWeek.Friday, Occurrence.Third);
            var thirdSaturdayInJune = DateSystem.FindDay(year, Month.June, DayOfWeek.Saturday, Occurrence.Third);
            var firstSaturdayInNovember = DateSystem.FindDay(year, Month.November, DayOfWeek.Saturday, Occurrence.First);

            var items = new List<PublicHoliday>();
            items.Add(new PublicHoliday(year, 1, 1, "Nyårsdagen", "New Year's Day", countryCode));
            items.Add(new PublicHoliday(year, 6, 1, "Trettondagen", "Epiphany", countryCode));
            items.Add(new PublicHoliday(year, 3, 30, "Ålands demilitariseringsdag", "Demilitarization Day", countryCode));
            items.Add(this._catholicProvider.GoodFriday("Långfredag", year, countryCode));
            items.Add(this._catholicProvider.EasterSunday("Påskdagen", year, countryCode).SetLaunchYear(1642));
            items.Add(this._catholicProvider.EasterMonday("Annandag påsk", year, countryCode).SetLaunchYear(1642));
            items.Add(new PublicHoliday(year, 4, 30, "Valborgsmässoafton", "Walpurgis Night", countryCode));
            items.Add(new PublicHoliday(year, 5, 1, "Första maj", "May Day", countryCode));
            items.Add(this._catholicProvider.AscensionDay("Kristi himmelsfärdsdagn", year, countryCode));
            items.Add(this._catholicProvider.Pentecost("Pingstdagen", year, countryCode));
            items.Add(this._catholicProvider.WhitMonday("Annandag Pingst", year, countryCode));
            items.Add(new PublicHoliday(year, 6, 9, "Självstyrelsedagen", "Autonomy Day", countryCode));
            items.Add(new PublicHoliday(thirdFridayInJune, "Midsommarafton", "Midsummer Eve", countryCode));
            items.Add(new PublicHoliday(thirdSaturdayInJune, "Midsommardagen", "Midsummer Day", countryCode));
            items.Add(new PublicHoliday(firstSaturdayInNovember, "Alla helgons dag", "All Saints Day", countryCode));
            items.Add(new PublicHoliday(year, 12, 6, "Självständighetsdagen", "Independence Day", countryCode));
            items.Add(new PublicHoliday(year, 12, 24, "Julafton", "Christmas Eve", countryCode));
            items.Add(new PublicHoliday(year, 12, 25, "Juldagen", "Christmas Day", countryCode));
            items.Add(new PublicHoliday(year, 12, 26, "Annandag jul", "St. Stephen's Day", countryCode));

            return items.OrderBy(o => o.Date);
        }

        ///<inheritdoc/>
        public IEnumerable<string> GetSources()
        {
            return new string[]
            {
                "https://en.wikipedia.org/wiki/Public_holidays_in_%C3%85land",
                "https://de.wikipedia.org/wiki/%C3%85land"
            };
        }
    }
}


text:
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()
urlpatterns = patterns('',
    url(r'^reporting-service/', include('sqlreports.urls')),
    # Django Admin URL
    url(r'^admin/', include(admin.site.urls)),
)


text:
<?php

namespace Bolt\Tests\Filesystem\Plugin;

use Bolt\Filesystem\Adapter\Local;
use Bolt\Filesystem\Filesystem;
use Bolt\Filesystem\Manager;
use Bolt\Filesystem\Plugin;
use Bolt\Tests\BoltUnitTest;

class AuthorizedTest extends BoltUnitTest
{
    public function testSetup()
    {
        $app = $this->getApp();

        $adapter = new Local(PHPUNIT_ROOT . '/resources');
        $fs1 = new Filesystem($adapter);
        $fs2 = new Filesystem($adapter);
        $fs3 = new Filesystem($adapter);

        $manager = new Manager([]);
        $manager->mountFilesystem('files', $fs1);
        $manager->mountFilesystem('cache', $fs2);
        $manager->mountFilesystem('something', $fs3);
        $manager->addPlugin(new Plugin\Authorized($app));

        $this->assertTrue($fs1->authorized(''));
        $this->assertFalse($fs2->authorized(''));
        $this->assertFalse($fs3->authorized(''));
    }
}


text:
package com.nagopy.android.mypkgs.view.preference;

public interface Selectable {

    String getName();
    int getTitleResourceId();
    int getSummaryResourceId();
}


text:
package hawkular

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/Stackdriver/heapster/metrics/core"
	"github.com/hawkular/hawkular-client-go/metrics"

	assert "github.com/stretchr/testify/require"
)

func dummySink() *hawkularSink {
	return &hawkularSink{
		expReg: make(map[string]*expiringItem),
		models: make(map[string]*metrics.MetricDefinition),
	}
}

func TestDescriptorTransform(t *testing.T) {

	hSink := dummySink()

	ld := core.LabelDescriptor{
		Key:         "k1",
		Description: "d1",
	}
	smd := core.MetricDescriptor{
		Name:      "test/metric/1",
		Units:     core.UnitsBytes,
		ValueType: core.ValueInt64,
		Type:      core.MetricGauge,
		Labels:    []core.LabelDescriptor{ld},
	}

	md := hSink.descriptorToDefinition(&smd)

	assert.Equal(t, smd.Name, md.ID)
	assert.Equal(t, 3, len(md.Tags)) // descriptorTag, unitsTag, typesTag, k1

	assert.Equal(t, smd.Units.String(), md.Tags[unitsTag])
	assert.Equal(t, "d1", md.Tags["k1_description"])

	smd.Type = core.MetricCumulative

	md = hSink.descriptorToDefinition(&smd)
	assert.EqualValues(t, md.Type, metrics.Counter)
}

func TestMetricTransform(t *testing.T) {
	hSink := dummySink()

	l := make(map[string]string)
	l["spooky"] = "notvisible"
	l[core.LabelHostname.Key] = "localhost"
	l[core.LabelHostID.Key] = "localhost"
	l[core.LabelContainerName.Key] = "docker"
	l[core.LabelPodId.Key] = "aaaa-bbbb-cccc-dddd"
	l[core.LabelNodename.Key] = "myNode"

	metricName := "test/metric/1"
	labeledMetricNameA := "test/labeledmetric/A"
	labeledMetricNameB := "test/labeledmetric/B"

	metricSet := core.MetricSet{
		Labels: l,
		MetricValues: map[string]core.MetricValue{
			metricName: {
				ValueType:  core.ValueInt64,
				MetricType: core.MetricGauge,
				IntValue:   123456,
			},
		},
		LabeledMetrics: []core.LabeledMetric{
			{
				Name: labeledMetricNameA,
				Labels: map[string]string{
					core.LabelResourceID.Key: "XYZ",
				},
				MetricValue: core.MetricValue{
					MetricType: core.MetricGauge,
					FloatValue: 124.456,
				},
			},
			{
				Name: labeledMetricNameB,
				MetricValue: core.MetricValue{
					MetricType: core.MetricGauge,
					FloatValue: 454,
				},
			},
		},
	}

	metricSet.LabeledMetrics = append(metricSet.LabeledMetrics, metricValueToLabeledMetric(metricSet.MetricValues)...)

	now := time.Now()
	//
	m, err := hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[2], now)
	assert.NoError(t, err)

	assert.Equal(t, fmt.Sprintf("%s/%s/%s", metricSet.Labels[core.LabelContainerName.Key],
		metricSet.Labels[core.LabelPodId.Key], metricName), m.ID)

	assert.Equal(t, 1, len(m.Data))
	_, ok := m.Data[0].Value.(float64)
	assert.True(t, ok, "Value should have been converted to float64")

	delete(l, core.LabelPodId.Key)

	//
	m, err = hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[2], now)
	assert.NoError(t, err)

	assert.Equal(t, fmt.Sprintf("%s/%s/%s", metricSet.Labels[core.LabelContainerName.Key], metricSet.Labels[core.LabelNodename.Key], metricName), m.ID)

	//
	m, err = hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[0], now)
	assert.NoError(t, err)

	assert.Equal(t, fmt.Sprintf("%s/%s/%s/%s", metricSet.Labels[core.LabelContainerName.Key],
		metricSet.Labels[core.LabelNodename.Key], labeledMetricNameA,
		metricSet.LabeledMetrics[0].Labels[core.LabelResourceID.Key]), m.ID)

	//
	m, err = hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[1], now)
	assert.NoError(t, err)
	assert.Equal(t, fmt.Sprintf("%s/%s/%s", metricSet.Labels[core.LabelContainerName.Key],
		metricSet.Labels[core.LabelNodename.Key], labeledMetricNameB), m.ID)
}

func TestMetricIds(t *testing.T) {
	hSink := dummySink()

	l := make(map[string]string)
	l["spooky"] = "notvisible"
	l[core.LabelHostname.Key] = "localhost"
	l[core.LabelHostID.Key] = "localhost"
	l[core.LabelContainerName.Key] = "docker"
	l[core.LabelPodId.Key] = "aaaa-bbbb-cccc-dddd"
	l[core.LabelNodename.Key] = "myNode"
	l[core.LabelNamespaceName.Key] = "myNamespace"

	metricName := "test/metric/nodeType"

	metricSet := core.MetricSet{
		Labels: l,
		MetricValues: map[string]core.MetricValue{
			metricName: {
				ValueType:  core.ValueInt64,
				MetricType: core.MetricGauge,
				IntValue:   123456,
			},
		},
	}
	metricSet.LabeledMetrics = metricValueToLabeledMetric(metricSet.MetricValues)

	now := time.Now()
	//
	m, err := hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[0], now)
	assert.NoError(t, err)
	assert.Equal(t, fmt.Sprintf("%s/%s/%s", metricSet.Labels[core.LabelContainerName.Key], metricSet.Labels[core.LabelPodId.Key], metricName), m.ID)

	//
	metricSet.Labels[core.LabelMetricSetType.Key] = core.MetricSetTypeNode
	m, err = hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[0], now)
	assert.NoError(t, err)
	assert.Equal(t, fmt.Sprintf("%s/%s/%s", "machine", metricSet.Labels[core.LabelNodename.Key], metricName), m.ID)

	//
	metricSet.Labels[core.LabelMetricSetType.Key] = core.MetricSetTypePod
	m, err = hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[0], now)
	assert.NoError(t, err)
	assert.Equal(t, fmt.Sprintf("%s/%s/%s", core.MetricSetTypePod, metricSet.Labels[core.LabelPodId.Key], metricName), m.ID)

	//
	metricSet.Labels[core.LabelMetricSetType.Key] = core.MetricSetTypePodContainer
	m, err = hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[0], now)
	assert.NoError(t, err)
	assert.Equal(t, fmt.Sprintf("%s/%s/%s", metricSet.Labels[core.LabelContainerName.Key], metricSet.Labels[core.LabelPodId.Key], metricName), m.ID)

	//
	metricSet.Labels[core.LabelMetricSetType.Key] = core.MetricSetTypeSystemContainer
	m, err = hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[0], now)
	assert.NoError(t, err)
	assert.Equal(t, fmt.Sprintf("%s/%s/%s/%s", core.MetricSetTypeSystemContainer, metricSet.Labels[core.LabelContainerName.Key], metricSet.Labels[core.LabelPodId.Key], metricName), m.ID)

	//
	metricSet.Labels[core.LabelMetricSetType.Key] = core.MetricSetTypeCluster
	m, err = hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[0], now)
	assert.NoError(t, err)
	assert.Equal(t, fmt.Sprintf("%s/%s", core.MetricSetTypeCluster, metricName), m.ID)

	//
	metricSet.Labels[core.LabelMetricSetType.Key] = core.MetricSetTypeNamespace
	m, err = hSink.pointToLabeledMetricHeader(&metricSet, metricSet.LabeledMetrics[0], now)
	assert.NoError(t, err)
	assert.Equal(t, fmt.Sprintf("%s/%s/%s", core.MetricSetTypeNamespace, metricSet.Labels[core.LabelNamespaceName.Key], metricName), m.ID)

}

func TestRecentTest(t *testing.T) {
	hSink := dummySink()

	modelT := make(map[string]string)

	id := "test.name"
	modelT[descriptorTag] = "d"
	modelT[groupTag] = id
	modelT["hep"+descriptionTag] = "n"

	model := metrics.MetricDefinition{
		ID:   id,
		Tags: modelT,
	}

	liveT := make(map[string]string)
	for k, v := range modelT {
		liveT[k] = v
	}

	live := metrics.MetricDefinition{
		ID:   "test/" + id,
		Tags: liveT,
	}

	assert.True(t, hSink.recent(&live, &model), "Tags are equal, live is newest")

	delete(liveT, "hep"+descriptionTag)
	live.Tags = liveT

	assert.False(t, hSink.recent(&live, &model), "Tags are not equal, live isn't recent")

}

func TestParseFiltersErrors(t *testing.T) {
	_, err := parseFilters([]string{"(missingcommand)"})
	assert.Error(t, err)

	_, err = parseFilters([]string{"missingeverything"})
	assert.Error(t, err)

	_, err = parseFilters([]string{"labelstart:^missing$)"})
	assert.Error(t, err)

	_, err = parseFilters([]string{"label(endmissing"})
	assert.Error(t, err)

	_, err = parseFilters([]string{"label(wrongsyntax)"})
	assert.Error(t, err)
}

// Integration tests
func integSink(uri string) (*hawkularSink, error) {

	u, err := url.Parse(uri)
	if err != nil {
		return nil, err
	}

	sink := &hawkularSink{
		uri: u,
	}
	if err = sink.init(); err != nil {
		return nil, err
	}

	return sink, nil
}

// Test that Definitions is called for Gauges & Counters
// Test that we have single registered model
// Test that the tags for metric is updated..
func TestRegister(t *testing.T) {
	m := &sync.Mutex{}
	// definitionsCalled := make(map[string]bool)
	updateTagsCalled := false
	requests := 0

	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		m.Lock()
		defer m.Unlock()
		w.Header().Set("Content-Type", "application/json")

		if strings.Contains(r.RequestURI, "tenants") {
			fmt.Fprintln(w, `[{ "id": "test-heapster"},{"id": "fgahj-fgas-basf-gegsg" }]`)
		} else {
			tenant := r.Header.Get("Hawkular-Tenant")
			if tenant != "test-heapster" {
				requests++
				w.WriteHeader(http.StatusNoContent)
				return
			}
			if strings.Contains(r.RequestURI, "metrics?tags=descriptor_name%3A%2A") || strings.Contains(r.RequestURI, "openshift") {
				requests++
				fmt.Fprintln(w, `[{ "id": "test.create.gauge.1", "tenantId": "test-heapster", "type": "gauge", "tags": { "descriptor_name": "test/metric/1" } }]`)
			} else if strings.Contains(r.RequestURI, "/tags") && r.Method == "PUT" {
				updateTagsCalled = true
				defer r.Body.Close()
				b, err := ioutil.ReadAll(r.Body)
				assert.NoError(t, err)

				tags := make(map[string]string)
				err = json.Unmarshal(b, &tags)
				assert.NoError(t, err)

				_, kt1 := tags["k1_description"]
				_, dt := tags["descriptor_name"]

				assert.True(t, kt1, "k1_description tag is missing")
				assert.True(t, dt, "descriptor_name is missing")

				w.WriteHeader(http.StatusOK)
			}
		}
	}))
	defer s.Close()

	hSink, err := integSink(s.URL + "?tenant=test-heapster")
	assert.NoError(t, err)

	md := make([]core.MetricDescriptor, 0, 1)
	ld := core.LabelDescriptor{
		Key:         "k1",
		Description: "d1",
	}
	smd := core.MetricDescriptor{
		Name:      "test/metric/1",
		Units:     core.UnitsBytes,
		ValueType: core.ValueInt64,
		Type:      core.MetricGauge,
		Labels:    []core.LabelDescriptor{ld},
	}
	smdg := core.MetricDescriptor{
		Name:      "test/metric/2",
		Units:     core.UnitsBytes,
		ValueType: core.ValueFloat,
		Type:      core.MetricCumulative,
		Labels:    []core.LabelDescriptor{},
	}

	md = append(md, smd, smdg)

	err = hSink.Register(md)
	assert.NoError(t, err)

	assert.Equal(t, 2, len(hSink.models))
	assert.Equal(t, 1, len(hSink.expReg))

	assert.True(t, updateTagsCalled, "Updating outdated tags was not called")
	assert.Equal(t, 1, requests)

	// Try without pre caching
	updateTagsCalled = false

	hSink, err = integSink(s.URL + "?tenant=test-heapster&disablePreCache=true")
	assert.NoError(t, err)

	err = hSink.Register(md)
	assert.NoError(t, err)

	assert.Equal(t, 2, len(hSink.models))
	assert.Equal(t, 0, len(hSink.expReg))

	assert.False(t, updateTagsCalled, "Updating outdated tags was called")
}

// Store timeseries with both gauges and cumulatives
func TestStoreTimeseries(t *testing.T) {
	m := &sync.Mutex{}
	ids := make([]string, 0, 2)
	calls := make([]string, 0, 2)
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		m.Lock()
		defer m.Unlock()
		calls = append(calls, r.RequestURI)
		w.Header().Set("Content-Type", "application/json")

		typ := r.RequestURI[strings.Index(r.RequestURI, "hawkular/metrics/")+17:]
		typ = typ[:len(typ)-4]

		switch typ {
		case "counters":
			assert.Equal(t, "test-label", r.Header.Get("Hawkular-Tenant"))
			break
		case "gauges":
			assert.Equal(t, "test-heapster", r.Header.Get("Hawkular-Tenant"))
			break
		default:
			assert.FailNow(t, "Unrecognized type "+typ)
		}

		defer r.Body.Close()
		b, err := ioutil.ReadAll(r.Body)
		assert.NoError(t, err)

		mH := []metrics.MetricHeader{}
		err = json.Unmarshal(b, &mH)
		assert.NoError(t, err)

		assert.Equal(t, 1, len(mH))

		ids = append(ids, mH[0].ID)
	}))
	defer s.Close()

	hSink, err := integSink(s.URL + "?tenant=test-heapster&labelToTenant=projectId")
	assert.NoError(t, err)

	l := make(map[string]string)
	l["projectId"] = "test-label"
	l[core.LabelContainerName.Key] = "test-container"
	l[core.LabelPodId.Key] = "test-podid"

	lg := make(map[string]string)
	lg[core.LabelContainerName.Key] = "test-container"
	lg[core.LabelPodId.Key] = "test-podid"

	metricSet1 := core.MetricSet{
		Labels: l,
		MetricValues: map[string]core.MetricValue{
			"test/metric/1": {
				ValueType:  core.ValueInt64,
				MetricType: core.MetricCumulative,
				IntValue:   123456,
			},
		},
	}

	metricSet2 := core.MetricSet{
		Labels: lg,
		MetricValues: map[string]core.MetricValue{
			"test/metric/2": {
				ValueType:  core.ValueFloat,
				MetricType: core.MetricGauge,
				FloatValue: 123.456,
			},
		},
	}

	data := core.DataBatch{
		Timestamp: time.Now(),
		MetricSets: map[string]*core.MetricSet{
			"pod1": &metricSet1,
			"pod2": &metricSet2,
		},
	}

	hSink.ExportData(&data)
	assert.Equal(t, 2, len(calls))
	assert.Equal(t, 2, len(ids))

	assert.NotEqual(t, ids[0], ids[1])
}

func TestTags(t *testing.T) {
	m := &sync.Mutex{}
	calls := make([]string, 0, 2)
	serverTags := make(map[string]string)
	// how many times tags have been updated
	tagsUpdated := 0
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		m.Lock()
		defer m.Unlock()
		calls = append(calls, r.RequestURI)
		w.Header().Set("Content-Type", "application/json")

		defer r.Body.Close()
		b, err := ioutil.ReadAll(r.Body)
		assert.NoError(t, err)

		if strings.HasSuffix(r.RequestURI, "/tags") {
			err := json.Unmarshal(b, &serverTags)
			assert.NoError(t, err)
			tagsUpdated++
		}
	}))
	defer s.Close()

	hSink, err := integSink(s.URL + "?tenant=test-heapster&labelToTenant=projectId")
	assert.NoError(t, err)

	l := make(map[string]string)
	l["projectId"] = "test-label"
	l[core.LabelContainerName.Key] = "test-container"
	l[core.LabelPodId.Key] = "test-podid"
	l[core.LabelLabels.Key] = "testLabelA:testValueA,testLabelB:testValueB"

	labeledMetric := core.LabeledMetric{
		Name: "test/metric/A",
		Labels: map[string]string{
			core.LabelResourceID.Key: "XYZ",
		},
		MetricValue: core.MetricValue{
			MetricType: core.MetricGauge,
			FloatValue: 124.456,
		},
	}

	metricSet := core.MetricSet{
		Labels:         l,
		LabeledMetrics: []core.LabeledMetric{labeledMetric},
		MetricValues: map[string]core.MetricValue{
			"test/metric/A": {
				ValueType:  core.ValueInt64,
				MetricType: core.MetricCumulative,
				IntValue:   123456,
			},
		},
	}

	smd := core.MetricDescriptor{
		Name:      "test/metric/A",
		Units:     core.UnitsBytes,
		ValueType: core.ValueInt64,
		Type:      core.MetricGauge,
		Labels:    []core.LabelDescriptor{},
	}

	//register the metric definitions
	hSink.Register([]core.MetricDescriptor{smd})
	//register the metrics themselves
	wg := &sync.WaitGroup{}
	hSink.registerLabeledIfNecessaryInline(&metricSet, labeledMetric, wg)

	wg.Wait()
	assert.Equal(t, 1, tagsUpdated)

	assert.True(t, hSink.expReg["test-container/test-podid/test/metric/A/XYZ"].hash > 0)

	assert.Equal(t, 10, len(serverTags))
	assert.Equal(t, "test-label", serverTags["projectId"])
	assert.Equal(t, "test-container", serverTags[core.LabelContainerName.Key])
	assert.Equal(t, "test-podid", serverTags[core.LabelPodId.Key])
	assert.Equal(t, "test-container/test/metric/A", serverTags["group_id"])
	assert.Equal(t, "test/metric/A", serverTags["descriptor_name"])
	assert.Equal(t, "XYZ", serverTags[core.LabelResourceID.Key])
	assert.Equal(t, "bytes", serverTags["units"])

	assert.Equal(t, "testLabelA:testValueA,testLabelB:testValueB", serverTags[core.LabelLabels.Key])
	assert.Equal(t, "testValueA", serverTags["labels.testLabelA"])
	assert.Equal(t, "testValueB", serverTags["labels.testLabelB"])

	// Make modifications to the metrics and check that they're updated correctly

	// First, no changes - no update should happen
	hSink.registerLabeledIfNecessaryInline(&metricSet, labeledMetric, wg)
	wg.Wait()
	assert.Equal(t, 1, tagsUpdated)

	// Now modify the labels and expect an update
	metricSet.Labels[core.LabelLabels.Key] = "testLabelA:testValueA,testLabelB:testValueB,testLabelC:testValueC"
	hSink.registerLabeledIfNecessaryInline(&metricSet, labeledMetric, wg)
	wg.Wait()
	assert.Equal(t, 2, tagsUpdated)

	assert.Equal(t, "testLabelA:testValueA,testLabelB:testValueB,testLabelC:testValueC", serverTags[core.LabelLabels.Key])
	assert.Equal(t, "testValueA", serverTags["labels.testLabelA"])
	assert.Equal(t, "testValueB", serverTags["labels.testLabelB"])
	assert.Equal(t, "testValueC", serverTags["labels.testLabelC"])
}

func TestExpiringCache(t *testing.T) {
	total := 10
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer s.Close()

	hSink, err := integSink(s.URL + "?tenant=test-heapster&labelToTenant=projectId&batchSize=20&concurrencyLimit=5")
	assert.NoError(t, err)

	l := make(map[string]string)
	l["projectId"] = "test-label"
	l[core.LabelContainerName.Key] = "test-container"
	l[core.LabelPodId.Key] = "test-podid"

	metrics := make(map[string]core.MetricValue, total)
	descriptors := make([]core.MetricDescriptor, total)
	for i := 0; i < total; i++ {
		id := fmt.Sprintf("test/metric/%d", i)
		metrics[id] = core.MetricValue{
			ValueType:  core.ValueInt64,
			MetricType: core.MetricCumulative,
			IntValue:   123 * int64(i),
		}
		descriptors = append(descriptors, core.MetricDescriptor{
			Name:      id,
			Units:     core.UnitsBytes,
			ValueType: core.ValueInt64,
			Type:      core.MetricGauge,
		})
	}

	err = hSink.Register(descriptors)
	assert.NoError(t, err)

	metricSet := core.MetricSet{
		Labels:       l,
		MetricValues: metrics,
	}

	data := core.DataBatch{
		Timestamp: time.Now(),
		MetricSets: map[string]*core.MetricSet{
			"pod1": &metricSet,
		},
	}

	hSink.ExportData(&data)
	hSink.regLock.RLock()
	assert.Equal(t, total, len(hSink.expReg))
	assert.Equal(t, uint64(1), hSink.expReg["test-container/test-podid/test/metric/9"].ttl)
	hSink.regLock.RUnlock()

	// Now delete part of the metrics and then check that they're expired
	delete(metrics, "test/metric/1")
	delete(metrics, "test/metric/6")

	data.Timestamp = time.Now()
	hSink.ExportData(&data)
	hSink.regLock.RLock()
	assert.Equal(t, total, len(hSink.expReg))
	assert.Equal(t, uint64(2), hSink.expReg["test-container/test-podid/test/metric/9"].ttl)
	hSink.regLock.RUnlock()

	data.Timestamp = time.Now()
	hSink.ExportData(&data)
	hSink.regLock.RLock()
	assert.Equal(t, total-2, len(hSink.expReg))
	hSink.regLock.RUnlock()
}

func TestUserPass(t *testing.T) {
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-Authorization", r.Header.Get("Authorization"))
		auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
		if len(auth) != 2 || auth[0] != "Basic" {
			assert.FailNow(t, "Could not find Basic authentication")
		}
		assert.True(t, len(auth[1]) > 0)
		w.WriteHeader(http.StatusNoContent)
	}))
	defer s.Close()

	hSink, err := integSink(s.URL + "?user=tester&pass=hidden")
	assert.NoError(t, err)
	assert.Equal(t, 1, len(hSink.modifiers))

	// md := make([]core.MetricDescriptor, 0, 1)
	ld := core.LabelDescriptor{
		Key:         "k1",
		Description: "d1",
	}
	smd := core.MetricDescriptor{
		Name:      "test/metric/1",
		Units:     core.UnitsBytes,
		ValueType: core.ValueInt64,
		Type:      core.MetricGauge,
		Labels:    []core.LabelDescriptor{ld},
	}
	err = hSink.Register([]core.MetricDescriptor{smd})
	assert.NoError(t, err)
}

func TestFiltering(t *testing.T) {
	m := &sync.Mutex{}
	mH := []metrics.MetricHeader{}
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		m.Lock()
		defer m.Unlock()
		if strings.Contains(r.RequestURI, "raw") {
			defer r.Body.Close()
			b, err := ioutil.ReadAll(r.Body)
			assert.NoError(t, err)

			err = json.Unmarshal(b, &mH)
			assert.NoError(t, err)
		}
	}))
	defer s.Close()

	hSink, err := integSink(s.URL + "?filter=label(namespace_id:^$)&filter=label(container_name:^[/system.slice/|/user.slice].*)&filter=name(remove*)")
	assert.NoError(t, err)

	l := make(map[string]string)
	l["namespace_id"] = "123"
	l["container_name"] = "/system.slice/-.mount"
	l[core.LabelPodId.Key] = "aaaa-bbbb-cccc-dddd"

	l2 := make(map[string]string)
	l2["namespace_id"] = "123"
	l2["container_name"] = "/system.slice/dbus.service"
	l2[core.LabelPodId.Key] = "aaaa-bbbb-cccc-dddd"

	l3 := make(map[string]string)
	l3["namespace_id"] = "123"
	l3[core.LabelPodId.Key] = "aaaa-bbbb-cccc-dddd"

	l4 := make(map[string]string)
	l4["namespace_id"] = ""
	l4[core.LabelPodId.Key] = "aaaa-bbbb-cccc-dddd"

	l5 := make(map[string]string)
	l5["namespace_id"] = "123"
	l5[core.LabelPodId.Key] = "aaaa-bbbb-cccc-dddd"

	metricSet1 := core.MetricSet{
		Labels: l,
		MetricValues: map[string]core.MetricValue{
			"/system.slice/-.mount//cpu/limit": {
				ValueType:  core.ValueInt64,
				MetricType: core.MetricCumulative,
				IntValue:   123456,
			},
		},
	}

	metricSet2 := core.MetricSet{
		Labels: l2,
		MetricValues: map[string]core.MetricValue{
			"/system.slice/dbus.service//cpu/usage": {
				ValueType:  core.ValueInt64,
				MetricType: core.MetricCumulative,
				IntValue:   123456,
			},
		},
	}

	metricSet3 := core.MetricSet{
		Labels: l3,
		MetricValues: map[string]core.MetricValue{
			"test/metric/1": {
				ValueType:  core.ValueInt64,
				MetricType: core.MetricCumulative,
				IntValue:   123456,
			},
		},
	}

	metricSet4 := core.MetricSet{
		Labels: l4,
		MetricValues: map[string]core.MetricValue{
			"test/metric/1": {
				ValueType:  core.ValueInt64,
				MetricType: core.MetricCumulative,
				IntValue:   123456,
			},
		},
	}

	metricSet5 := core.MetricSet{
		Labels: l5,
		MetricValues: map[string]core.MetricValue{
			"removeme": {
				ValueType:  core.ValueInt64,
				MetricType: core.MetricCumulative,
				IntValue:   123456,
			},
		},
	}

	data := core.DataBatch{
		Timestamp: time.Now(),
		MetricSets: map[string]*core.MetricSet{
			"pod1": &metricSet1,
			"pod2": &metricSet2,
			"pod3": &metricSet3,
			"pod4": &metricSet4,
			"pod5": &metricSet5,
		},
	}
	hSink.ExportData(&data)

	assert.Equal(t, 1, len(mH))
}
func TestBatchingTimeseries(t *testing.T) {
	total := 1000
	m := &sync.Mutex{}
	ids := make([]string, 0, total)
	calls := 0

	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		m.Lock()
		defer m.Unlock()

		w.Header().Set("Content-Type", "application/json")

		defer r.Body.Close()
		b, err := ioutil.ReadAll(r.Body)
		assert.NoError(t, err)

		mH := []metrics.MetricHeader{}
		err = json.Unmarshal(b, &mH)
		assert.NoError(t, err)

		for _, v := range mH {
			ids = append(ids, v.ID)
		}

		calls++
	}))
	defer s.Close()

	hSink, err := integSink(s.URL + "?tenant=test-heapster&labelToTenant=projectId&batchSize=20&concurrencyLimit=5")
	assert.NoError(t, err)

	l := make(map[string]string)
	l["projectId"] = "test-label"
	l[core.LabelContainerName.Key] = "test-container"
	l[core.LabelPodId.Key] = "test-podid"

	metrics := make(map[string]core.MetricValue)
	for i := 0; i < total; i++ {
		id := fmt.Sprintf("test/metric/%d", i)
		metrics[id] = core.MetricValue{
			ValueType:  core.ValueInt64,
			MetricType: core.MetricCumulative,
			IntValue:   123 * int64(i),
		}
	}

	metricSet := core.MetricSet{
		Labels:       l,
		MetricValues: metrics,
	}

	data := core.DataBatch{
		Timestamp: time.Now(),
		MetricSets: map[string]*core.MetricSet{
			"pod1": &metricSet,
		},
	}

	hSink.ExportData(&data)
	assert.Equal(t, total, len(ids))
	assert.Equal(t, calls, 50)

	// Verify that all ids are unique
	newIds := make(map[string]bool)
	for _, v := range ids {
		if newIds[v] {
			t.Errorf("Key %s was duplicate", v)
		}
		newIds[v] = true
	}
}

func BenchmarkTagsUpdates(b *testing.B) {
	http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost = 100
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer s.Close()
	hSink, err := integSink(s.URL + "?tenant=test-heapster&labelToTenant=projectId&batchSize=1000&concurrencyLimit=16")
	if err != nil {
		b.FailNow()
	}

	smd := core.MetricDescriptor{
		Name:      "test/metric/A",
		Units:     core.UnitsBytes,
		ValueType: core.ValueInt64,
		Type:      core.MetricGauge,
		Labels:    []core.LabelDescriptor{},
	}

	//register the metric definitions
	hSink.Register([]core.MetricDescriptor{smd})
	total := 10000

	mset := make(map[string]*core.MetricSet)
	for i := 0; i < total; i++ {
		id := fmt.Sprintf("pod-%d", i)

		l := make(map[string]string)
		l["projectId"] = strconv.Itoa(i)
		for i := 0; i < 32; i++ {
			tagName := fmt.Sprintf("tag_name_%d", i)
			tagValue := fmt.Sprintf("tag_value_%d", i)
			l[tagName] = tagValue
			l[core.LabelPodId.Key] = id
		}

		metrics := make(map[string]core.MetricValue)
		metrics["test/metric/A"] = core.MetricValue{
			ValueType:  core.ValueInt64,
			MetricType: core.MetricCumulative,
			IntValue:   123,
		}

		metricSet := core.MetricSet{
			Labels:       l,
			MetricValues: metrics,
		}
		mset[id] = &metricSet
	}

	data := core.DataBatch{
		Timestamp:  time.Now(),
		MetricSets: mset,
	}

	fmt.Printf("Generated data with %d metricSets\n", len(data.MetricSets))
	hSink.init()
	hSink.Register([]core.MetricDescriptor{smd})
	b.ResetTimer()
	for j := 0; j < b.N; j++ {
		for a := 0; a < 10; a++ {
			data.Timestamp = time.Now()
			hSink.ExportData(&data)
		}
	}

	fmt.Printf("Amount of unique definitions: %d\n", len(hSink.expReg))
}


text:
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices

' Le informazioni generali relative a un assembly sono controllate dal seguente
' insieme di attributi. Per modificare le informazioni associate a un assembly
' è necessario modificare i valori di questi attributi.

' Controllare i valori degli attributi dell'assembly

<Assembly: AssemblyTitle("DataExporter")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("DataExporter")>
<Assembly: AssemblyCopyright("Copyright ©  2015")>
<Assembly: AssemblyTrademark("")>

<Assembly: ComVisible(False)>

'Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
<Assembly: Guid("eb3d39ba-d0d5-489b-bcd3-b3c2cb0e5dd7")>

' Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
'
'      Numero di versione principale
'      Numero di versione secondario
'      Numero build
'      Revisione
'
' È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
' utilizzando l'asterisco (*) come descritto di seguito:
' <Assembly: AssemblyVersion("1.0.*")>

<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_InterconnectAttachments_Get_sync_flattened]
    using Google.Cloud.Compute.V1;

    public sealed partial class GeneratedInterconnectAttachmentsClientSnippets
    {
        /// <summary>Snippet for Get</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void Get()
        {
            // Create client
            InterconnectAttachmentsClient interconnectAttachmentsClient = InterconnectAttachmentsClient.Create();
            // Initialize request argument(s)
            string project = "";
            string region = "";
            string interconnectAttachment = "";
            // Make the request
            InterconnectAttachment response = interconnectAttachmentsClient.Get(project, region, interconnectAttachment);
        }
    }
    // [END compute_v1_generated_InterconnectAttachments_Get_sync_flattened]
}


text:
package org.apache.hadoop.hive.serde2.avro;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.Schema.Type;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericData.Fixed;
import org.apache.avro.generic.GenericEnumSymbol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hive.common.type.HiveChar;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.common.type.HiveVarchar;
import org.apache.hadoop.hive.serde2.io.DateWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.UnionObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.DateObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.UnionTypeInfo;
import org.apache.hadoop.io.Writable;

class AvroSerializer {
  /**
   * The Schema to use when serializing Map keys.
   * Since we're sharing this across Serializer instances, it must be immutable;
   * any properties need to be added in a static initializer.
   */
  private static final Schema STRING_SCHEMA = Schema.create(Schema.Type.STRING);
  AvroGenericRecordWritable cache = new AvroGenericRecordWritable();

  // Hive is pretty simple (read: stupid) in writing out values via the serializer.
  // We're just going to go through, matching indices.  Hive formats normally
  // handle mismatches with null.  We don't have that option, so instead we'll
  // end up throwing an exception for invalid records.
  public Writable serialize(Object o, ObjectInspector objectInspector, List<String> columnNames, List<TypeInfo> columnTypes, Schema schema) throws AvroSerdeException {
    StructObjectInspector soi = (StructObjectInspector) objectInspector;
    GenericData.Record record = new GenericData.Record(schema);

    List<? extends StructField> outputFieldRefs = soi.getAllStructFieldRefs();
    if(outputFieldRefs.size() != columnNames.size()) {
      throw new AvroSerdeException("Number of input columns was different than output columns (in = " + columnNames.size() + " vs out = " + outputFieldRefs.size());
    }

    int size = schema.getFields().size();
    if(outputFieldRefs.size() != size) {
      throw new AvroSerdeException("Hive passed in a different number of fields than the schema expected: (Hive wanted " + outputFieldRefs.size() +", Avro expected " + schema.getFields().size());
    }

    List<? extends StructField> allStructFieldRefs = soi.getAllStructFieldRefs();
    List<Object> structFieldsDataAsList = soi.getStructFieldsDataAsList(o);

    for(int i  = 0; i < size; i++) {
      Field field = schema.getFields().get(i);
      TypeInfo typeInfo = columnTypes.get(i);
      StructField structFieldRef = allStructFieldRefs.get(i);
      Object structFieldData = structFieldsDataAsList.get(i);
      ObjectInspector fieldOI = structFieldRef.getFieldObjectInspector();

      Object val = serialize(typeInfo, fieldOI, structFieldData, field.schema());
      record.put(field.name(), val);
    }

    if(!GenericData.get().validate(schema, record)) {
      throw new SerializeToAvroException(schema, record);
    }

    cache.setRecord(record);

    return cache;
  }

  private Object serialize(TypeInfo typeInfo, ObjectInspector fieldOI, Object structFieldData, Schema schema) throws AvroSerdeException {
    if(null == structFieldData) {
      return null;
    }

    if(AvroSerdeUtils.isNullableType(schema)) {
      schema = AvroSerdeUtils.getOtherTypeFromNullableType(schema);
    }
    /* Because we use Hive's 'string' type when Avro calls for enum, we have to expressly check for enum-ness */
    if(Schema.Type.ENUM.equals(schema.getType())) {
      assert fieldOI instanceof PrimitiveObjectInspector;
      return serializeEnum(typeInfo, (PrimitiveObjectInspector) fieldOI, structFieldData, schema);
    }
    switch(typeInfo.getCategory()) {
      case PRIMITIVE:
        assert fieldOI instanceof PrimitiveObjectInspector;
        return serializePrimitive(typeInfo, (PrimitiveObjectInspector) fieldOI, structFieldData, schema);
      case MAP:
        assert fieldOI instanceof MapObjectInspector;
        assert typeInfo instanceof MapTypeInfo;
        return serializeMap((MapTypeInfo) typeInfo, (MapObjectInspector) fieldOI, structFieldData, schema);
      case LIST:
        assert fieldOI instanceof ListObjectInspector;
        assert typeInfo instanceof ListTypeInfo;
        return serializeList((ListTypeInfo) typeInfo, (ListObjectInspector) fieldOI, structFieldData, schema);
      case UNION:
        assert fieldOI instanceof UnionObjectInspector;
        assert typeInfo instanceof UnionTypeInfo;
        return serializeUnion((UnionTypeInfo) typeInfo, (UnionObjectInspector) fieldOI, structFieldData, schema);
      case STRUCT:
        assert fieldOI instanceof StructObjectInspector;
        assert typeInfo instanceof StructTypeInfo;
        return serializeStruct((StructTypeInfo) typeInfo, (StructObjectInspector) fieldOI, structFieldData, schema);
      default:
        throw new AvroSerdeException("Ran out of TypeInfo Categories: " + typeInfo.getCategory());
    }
  }

  /** private cache to avoid lots of EnumSymbol creation while serializing.
   *  Two levels because the enum symbol is specific to a schema.
   *  Object because we want to avoid the overhead of repeated toString calls while maintaining compatability.
   *  Provided there are few enum types per record, and few symbols per enum, memory use should be moderate.
   *  eg 20 types with 50 symbols each as length-10 Strings should be on the order of 100KB per AvroSerializer.
   */
  final InstanceCache<Schema, InstanceCache<Object, GenericEnumSymbol>> enums
      = new InstanceCache<Schema, InstanceCache<Object, GenericEnumSymbol>>() {
          @Override
          protected InstanceCache<Object, GenericEnumSymbol> makeInstance(final Schema schema,
                     Set<Schema> seenSchemas) {
            return new InstanceCache<Object, GenericEnumSymbol>() {
              @Override
              protected GenericEnumSymbol makeInstance(Object seed,
                             Set<Object> seenSchemas) {
                return new GenericData.EnumSymbol(schema, seed.toString());
              }
            };
          }
        };

  private Object serializeEnum(TypeInfo typeInfo, PrimitiveObjectInspector fieldOI, Object structFieldData, Schema schema) throws AvroSerdeException {
    return enums.retrieve(schema).retrieve(serializePrimitive(typeInfo, fieldOI, structFieldData, schema));
  }

  private Object serializeStruct(StructTypeInfo typeInfo, StructObjectInspector ssoi, Object o, Schema schema) throws AvroSerdeException {
    int size = schema.getFields().size();
    List<? extends StructField> allStructFieldRefs = ssoi.getAllStructFieldRefs();
    List<Object> structFieldsDataAsList = ssoi.getStructFieldsDataAsList(o);
    GenericData.Record record = new GenericData.Record(schema);
    ArrayList<TypeInfo> allStructFieldTypeInfos = typeInfo.getAllStructFieldTypeInfos();

    for(int i  = 0; i < size; i++) {
      Field field = schema.getFields().get(i);
      TypeInfo colTypeInfo = allStructFieldTypeInfos.get(i);
      StructField structFieldRef = allStructFieldRefs.get(i);
      Object structFieldData = structFieldsDataAsList.get(i);
      ObjectInspector fieldOI = structFieldRef.getFieldObjectInspector();

      Object val = serialize(colTypeInfo, fieldOI, structFieldData, field.schema());
      record.put(field.name(), val);
    }
    return record;
  }

  private Object serializePrimitive(TypeInfo typeInfo, PrimitiveObjectInspector fieldOI, Object structFieldData, Schema schema) throws AvroSerdeException {
    switch(fieldOI.getPrimitiveCategory()) {
    case BINARY:
      if (schema.getType() == Type.BYTES){
        return AvroSerdeUtils.getBufferFromBytes((byte[])fieldOI.getPrimitiveJavaObject(structFieldData));
      } else if (schema.getType() == Type.FIXED){
        Fixed fixed = new GenericData.Fixed(schema, (byte[])fieldOI.getPrimitiveJavaObject(structFieldData));
        return fixed;
      } else {
        throw new AvroSerdeException("Unexpected Avro schema for Binary TypeInfo: " + schema.getType());
      }
    case DECIMAL:
      HiveDecimal dec = (HiveDecimal)fieldOI.getPrimitiveJavaObject(structFieldData);
      return AvroSerdeUtils.getBufferFromDecimal(dec, ((DecimalTypeInfo)typeInfo).scale());
    case CHAR:
      HiveChar ch = (HiveChar)fieldOI.getPrimitiveJavaObject(structFieldData);
      return ch.getStrippedValue();
    case VARCHAR:
      HiveVarchar vc = (HiveVarchar)fieldOI.getPrimitiveJavaObject(structFieldData);
      return vc.getValue();
    case DATE:
      Date date = ((DateObjectInspector)fieldOI).getPrimitiveJavaObject(structFieldData);
      return DateWritable.dateToDays(date);
    case TIMESTAMP:
      Timestamp timestamp =
        ((TimestampObjectInspector) fieldOI).getPrimitiveJavaObject(structFieldData);
      return timestamp.getTime();
    case UNKNOWN:
      throw new AvroSerdeException("Received UNKNOWN primitive category.");
    case VOID:
      return null;
    default: // All other primitive types are simple
      return fieldOI.getPrimitiveJavaObject(structFieldData);
    }
  }

  private Object serializeUnion(UnionTypeInfo typeInfo, UnionObjectInspector fieldOI, Object structFieldData, Schema schema) throws AvroSerdeException {
    byte tag = fieldOI.getTag(structFieldData);

    // Invariant that Avro's tag ordering must match Hive's.
    return serialize(typeInfo.getAllUnionObjectTypeInfos().get(tag),
                     fieldOI.getObjectInspectors().get(tag),
                     fieldOI.getField(structFieldData),
                     schema.getTypes().get(tag));
  }

  private Object serializeList(ListTypeInfo typeInfo, ListObjectInspector fieldOI, Object structFieldData, Schema schema) throws AvroSerdeException {
    List<?> list = fieldOI.getList(structFieldData);
    List<Object> deserialized = new GenericData.Array<Object>(list.size(), schema);

    TypeInfo listElementTypeInfo = typeInfo.getListElementTypeInfo();
    ObjectInspector listElementObjectInspector = fieldOI.getListElementObjectInspector();
    Schema elementType = schema.getElementType();

    for(int i = 0; i < list.size(); i++) {
      deserialized.add(i, serialize(listElementTypeInfo, listElementObjectInspector, list.get(i), elementType));
    }

    return deserialized;
  }

  private Object serializeMap(MapTypeInfo typeInfo, MapObjectInspector fieldOI, Object structFieldData, Schema schema) throws AvroSerdeException {
    // Avro only allows maps with string keys
    if(!mapHasStringKey(fieldOI.getMapKeyObjectInspector())) {
      throw new AvroSerdeException("Avro only supports maps with keys as Strings.  Current Map is: " + typeInfo.toString());
    }

    ObjectInspector mapKeyObjectInspector = fieldOI.getMapKeyObjectInspector();
    ObjectInspector mapValueObjectInspector = fieldOI.getMapValueObjectInspector();
    TypeInfo mapKeyTypeInfo = typeInfo.getMapKeyTypeInfo();
    TypeInfo mapValueTypeInfo = typeInfo.getMapValueTypeInfo();
    Map<?,?> map = fieldOI.getMap(structFieldData);
    Schema valueType = schema.getValueType();

    Map<Object, Object> deserialized = new HashMap<Object, Object>(fieldOI.getMapSize(structFieldData));

    for (Map.Entry<?, ?> entry : map.entrySet()) {
      deserialized.put(serialize(mapKeyTypeInfo, mapKeyObjectInspector, entry.getKey(), STRING_SCHEMA),
                       serialize(mapValueTypeInfo, mapValueObjectInspector, entry.getValue(), valueType));
    }

    return deserialized;
  }

  private boolean mapHasStringKey(ObjectInspector mapKeyObjectInspector) {
    return mapKeyObjectInspector instanceof PrimitiveObjectInspector &&
        ((PrimitiveObjectInspector) mapKeyObjectInspector)
            .getPrimitiveCategory()
            .equals(PrimitiveObjectInspector.PrimitiveCategory.STRING);
  }

  /**
   * Thrown when, during serialization of a Hive row to an Avro record, Avro
   * cannot verify the converted row to the record's schema.
   */
  public static class SerializeToAvroException extends AvroSerdeException {
    final private Schema schema;
    final private GenericData.Record record;

    public SerializeToAvroException(Schema schema, GenericData.Record record) {
      this.schema = schema;
      this.record = record;
    }

    @Override
    public String toString() {
      return "Avro could not validate record against schema (record = " + record
          + ") (schema = "+schema.toString(false) + ")";
    }
  }
}


text:
package com.orientechnologies.orient.core.index;

import java.util.List;

import com.orientechnologies.orient.core.collate.OCollate;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;

/**
 * Presentation of index that is used information and contained in document
 * {@link com.orientechnologies.orient.core.metadata.schema.OClass} .
 *
 * This object cannot be created directly, use {@link com.orientechnologies.orient.core.metadata.schema.OClass} manipulation method
 * instead.
 *
 * @author Andrey Lomakin, Artem Orobets
 */
public interface OIndexDefinition extends OIndexCallback {
  /**
   * @return Names of fields which given index is used to calculate key value. Order of fields is important.
   */
  List<String> getFields();

  /**
   * @return Names of fields and their index modifiers (like "by value" for fields that hold Map values) which given
   *         index is used to calculate key value. Order of fields is important.
   */
  List<String> getFieldsToIndex();

  /**
   * @return Name of the class which this index belongs to.
   */
  String getClassName();

  /**
   * {@inheritDoc}
   */
  boolean equals(Object index);

  /**
   * {@inheritDoc}
   */
  int hashCode();

  /**
   * {@inheritDoc}
   */
  String toString();

  /**
   * Calculates key value by passed in parameters.
   *
   * If it is impossible to calculate key value by given parameters null will be returned.
   *
   * @param params
   *          Parameters from which index key will be calculated.
   *
   * @return Key value or null if calculation is impossible.
   */
  Object createValue(List<?> params);

  /**
   * Calculates key value by passed in parameters.
   *
   * If it is impossible to calculate key value by given parameters null will be returned.
   *
   *
   * @param params
   *          Parameters from which index key will be calculated.
   *
   * @return Key value or null if calculation is impossible.
   */
  Object createValue(Object... params);

  /**
   * Returns amount of parameters that are used to calculate key value. It does not mean that all parameters should be supplied. It
   * only means that if you provide more parameters they will be ignored and will not participate in index key calculation.
   *
   * @return Amount of that are used to calculate key value. Call result should be equals to {@code getTypes().length}.
   */
  int getParamCount();

  /**
   * Return types of values from which index key consist. In case of index that is built on single document property value single
   * array that contains property type will be returned. In case of composite indexes result will contain several key types.
   *
   * @return Types of values from which index key consist.
   */
  OType[] getTypes();

  /**
   * Serializes internal index state to document.
   *
   * @return Document that contains internal index state.
   */
  ODocument toStream();

  /**
   * Deserialize internal index state from document.
   *
   * @param document
   *          Serialized index presentation.
   */
  void fromStream(ODocument document);

  String toCreateIndexDDL(String indexName, String indexType);

  boolean isAutomatic();

  OCollate getCollate();

  void setCollate(OCollate collate);

  boolean isNullValuesIgnored();

  void setNullValuesIgnored(boolean value);
}


text:
<?php

namespace Symfony\Bridge\Propel1\Tests;

abstract class Propel1TestCase extends \PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass()
    {
        if (!class_exists('\Propel')) {
            self::markTestSkipped('Propel is not available.');
        }
    }
}


text:
require 'test_helper'

class TestIdentifier < MiniTest::Unit::TestCase
  def setup
    @id = Identifier.new('123')
  end

  def test_data_digits
    assert_equal %w(1 2), @id.data_digits
  end

  def test_checksum_digit
    assert_equal '3', @id.checksum_digit
  end

  def test_to_string
    assert_equal '123', @id.to_s
  end

  def test_comparison
    assert_equal Identifier.new('1'), Identifier.new('1')
    refute_equal Identifier.new('1'), Identifier.new('2')
  end

  def test_validation_not_implemented
    assert_raises(NotImplementedError) { Identifier.valid?('123') }
    assert_raises(NotImplementedError) { @id.valid? }
  end

  def test_validator_casts_input_to_string
    assert_raises(NotImplementedError) { Identifier.valid?(nil) }
  end
end


text:
package com.bluesnap.android.demoapp;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

/**
 * A utility class to save android SharedPrefs.
 * Should be used only in demo app.
 */
public class PrefsStorage {

    private static final String BLUESNAP_SHAREDPREFS_NAME = "BSNPSHAREDPREFS";
    private static SharedPreferences preferences;

    public PrefsStorage(Context context) {
        preferences = context.getSharedPreferences(BLUESNAP_SHAREDPREFS_NAME, Context.MODE_PRIVATE);
    }

    /**
     * Check if external storage is writable or not
     *
     * @return true if writable, false otherwise
     */
    public static boolean isExternalStorageWritable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * Check if external storage is readable or not
     *
     * @return true if readable, false otherwise
     */
    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();

        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }

    public int getInt(String key) {
        return preferences.getInt(key, 0);
    }

    public ArrayList<Integer> getListInt(String key) {
        String[] myList = TextUtils.split(preferences.getString(key, ""), "'‗'");
        ArrayList<String> arrayToList = new ArrayList<>(Arrays.asList(myList));
        ArrayList<Integer> newList = new ArrayList<>();

        for (String item : arrayToList)
            newList.add(Integer.parseInt(item));

        return newList;
    }

    public long getLong(String key, long defaultValue) {
        return preferences.getLong(key, defaultValue);
    }

    public float getFloat(String key) {
        return preferences.getFloat(key, 0);
    }

    /**
     * Get double value from SharedPreferences at 'key'. If exception thrown, return 'defaultValue'
     *
     * @param key          SharedPreferences key
     * @param defaultValue double value returned if exception is thrown
     * @return double value at 'key' or 'defaultValue' if exception is thrown
     */
    public double getDouble(String key, double defaultValue) {
        String number = getString(key);

        try {
            return Double.parseDouble(number);

        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * Get parsed ArrayList of Double from SharedPreferences at 'key'
     *
     * @param key SharedPreferences key
     * @return ArrayList of Double
     */
    public ArrayList<Double> getListDouble(String key) {
        String[] myList = TextUtils.split(preferences.getString(key, ""), "'‗'");
        ArrayList<String> arrayToList = new ArrayList<>(Arrays.asList(myList));
        ArrayList<Double> newList = new ArrayList<>();

        for (String item : arrayToList)
            newList.add(Double.parseDouble(item));

        return newList;
    }

    /**
     * Get String value from SharedPreferences at 'key'. If key not found, return ""
     *
     * @param key SharedPreferences key
     * @return String value at 'key' or "" (empty String) if key not found
     */
    public String getString(String key) {
        return preferences.getString(key, "");
    }

    public String getString(String key, String defaultValue) {
        return preferences.getString(key, defaultValue);
    }

    /**
     * Get parsed ArrayList of String from SharedPreferences at 'key'
     *
     * @param key SharedPreferences key
     * @return ArrayList of String
     */
    public ArrayList<String> getListString(String key) {
        return new ArrayList<>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "'‗'")));
    }

    public boolean getBoolean(String key) {
        return preferences.getBoolean(key, false);
    }

    /**
     * Get parsed ArrayList of Boolean from SharedPreferences at 'key'
     *
     * @param key SharedPreferences key
     * @return ArrayList of Boolean
     */
    public ArrayList<Boolean> getListBoolean(String key) {
        ArrayList<String> myList = getListString(key);
        ArrayList<Boolean> newList = new ArrayList<>();

        for (String item : myList) {
            if (item.equals("true")) {
                newList.add(true);
            } else {
                newList.add(false);
            }
        }

        return newList;
    }

    /**
     * Put int value into SharedPreferences with 'key' and save
     *
     * @param key   SharedPreferences key
     * @param value int value to be added
     */
    public void putInt(String key, int value) {
        checkForNullKey(key);
        preferences.edit().putInt(key, value).apply();
    }

    /**
     * Put ArrayList of Integer into SharedPreferences with 'key' and save
     *
     * @param key     SharedPreferences key
     * @param intList ArrayList of Integer to be added
     */
    public void putListInt(String key, ArrayList<Integer> intList) {
        checkForNullKey(key);
        Integer[] myIntList = intList.toArray(new Integer[intList.size()]);
        preferences.edit().putString(key, TextUtils.join("'‗'", myIntList)).apply();
    }

    /**
     * Put long value into SharedPreferences with 'key' and save
     *
     * @param key   SharedPreferences key
     * @param value long value to be added
     */
    public void putLong(String key, long value) {
        checkForNullKey(key);
        preferences.edit().putLong(key, value).apply();
    }

    /**
     * Put float value into SharedPreferences with 'key' and save
     *
     * @param key   SharedPreferences key
     * @param value float value to be added
     */
    public void putFloat(String key, float value) {
        checkForNullKey(key);
        preferences.edit().putFloat(key, value).apply();
    }

    /**
     * Put double value into SharedPreferences with 'key' and save
     *
     * @param key   SharedPreferences key
     * @param value double value to be added
     */
    public void putDouble(String key, double value) {
        checkForNullKey(key);
        putString(key, String.valueOf(value));
    }

    /**
     * Put ArrayList of Double into SharedPreferences with 'key' and save
     *
     * @param key        SharedPreferences key
     * @param doubleList ArrayList of Double to be added
     */
    public void putListDouble(String key, ArrayList<Double> doubleList) {
        checkForNullKey(key);
        Double[] myDoubleList = doubleList.toArray(new Double[doubleList.size()]);
        preferences.edit().putString(key, TextUtils.join("'‗'", myDoubleList)).apply();
    }

    /**
     * Put String value into SharedPreferences with 'key' and save
     *
     * @param key   SharedPreferences key
     * @param value String value to be added
     */
    public void putString(String key, String value) {
        checkForNullKey(key);
        checkForNullValue(value);
        preferences.edit().putString(key, value).apply();
    }

    /**
     * Put ArrayList of String into SharedPreferences with 'key' and save
     *
     * @param key        SharedPreferences key
     * @param stringList ArrayList of String to be added
     */
    public void putListString(String key, ArrayList<String> stringList) {
        checkForNullKey(key);
        String[] myStringList = stringList.toArray(new String[stringList.size()]);
        preferences.edit().putString(key, TextUtils.join("'‗'", myStringList)).apply();
    }

    /**
     * Put boolean value into SharedPreferences with 'key' and save
     *
     * @param key   SharedPreferences key
     * @param value boolean value to be added
     */
    public void putBoolean(String key, boolean value) {
        checkForNullKey(key);
        preferences.edit().putBoolean(key, value).apply();
    }

    /**
     * Put ArrayList of Boolean into SharedPreferences with 'key' and save
     *
     * @param key      SharedPreferences key
     * @param boolList ArrayList of Boolean to be added
     */
    public void putListBoolean(String key, ArrayList<Boolean> boolList) {
        checkForNullKey(key);
        ArrayList<String> newList = new ArrayList<>();

        for (Boolean item : boolList) {
            if (item) {
                newList.add("true");
            } else {
                newList.add("false");
            }
        }

        putListString(key, newList);
    }

    /**
     * Remove SharedPreferences item with 'key'
     *
     * @param key SharedPreferences key
     */
    public void remove(String key) {
        preferences.edit().remove(key).apply();
    }

    /**
     * Delete image file at 'path'
     *
     * @param path path of image file
     * @return true if it successfully deleted, false otherwise
     */
    public boolean deleteImage(String path) {
        return new File(path).delete();
    }

    /**
     * Clear SharedPreferences (remove everything)
     */
    public void clear() {
        preferences.edit().clear().apply();
    }

    /**
     * Retrieve all values from SharedPreferences. Do not modify collection return by method
     *
     * @return a Map representing a list of key/value pairs from SharedPreferences
     */
    public Map<String, ?> getAll() {
        return preferences.getAll();
    }

    /**
     * Register SharedPreferences change listener
     *
     * @param listener listener object of OnSharedPreferenceChangeListener
     */
    public void registerOnSharedPreferenceChangeListener(
            SharedPreferences.OnSharedPreferenceChangeListener listener) {

        preferences.registerOnSharedPreferenceChangeListener(listener);
    }

    /**
     * Unregister SharedPreferences change listener
     *
     * @param listener listener object of OnSharedPreferenceChangeListener to be unregistered
     */
    public void unregisterOnSharedPreferenceChangeListener(
            SharedPreferences.OnSharedPreferenceChangeListener listener) {

        preferences.unregisterOnSharedPreferenceChangeListener(listener);
    }

    public void checkForNullKey(String key) {
        if (key == null) {
            throw new NullPointerException();
        }
    }

    /**
     * null keys would corrupt the shared pref file and make them unreadable this is a preventive measure
     *
     * @param the pref key
     */
    public void checkForNullValue(String value) {
        if (value == null) {
            throw new NullPointerException();
        }
    }
}


text:
package com.sc2geeks.replay.parser;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DecompressingHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * This is the replay parser that relies on sc2gears parsing service. https://sites.google.com/site/sc2gears/parsing-service
 * User: robert
 * Date: 12/10/12
 * Time: 1:27 PM
 * To change this template use File | Settings | File Templates.
 */
public class SC2GearsParsingService
{
	private static Logger logger = Logger.getLogger(SC2GearsParsingService.class);
	private static SC2GearsAPIConfig apiConfig = SC2GearsAPIConfig.getInstance();

	public static String parseReplayFile(String replayFileName)
	{
		try
		{
			logger.info("Calling sc2gears api for replay: " + replayFileName);
			HttpClient httpclient = new DecompressingHttpClient(new DefaultHttpClient());

			HttpPost httpPost = new HttpPost(apiConfig.getUrl());
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("protVer", apiConfig.getProtVer()));
			nvps.add(new BasicNameValuePair("apiKey", apiConfig.getApiKey()));
			nvps.add(new BasicNameValuePair("op", "parseRep"));
			File file = new File(replayFileName);
			nvps.add(new BasicNameValuePair("fileLength", Long.toString(file.length())));
			nvps.add(new BasicNameValuePair("fileContent", Base64FileEncoder.Base64Encode(replayFileName)));

			// options
			nvps.add(new BasicNameValuePair("parseMessages", "true"));
			nvps.add(new BasicNameValuePair("parseActions", "true"));
			nvps.add(new BasicNameValuePair("sendActionsSelect", "false"));
			nvps.add(new BasicNameValuePair("sendActionsBuild", "true"));
			nvps.add(new BasicNameValuePair("sendActionsTrain", "true"));
			nvps.add(new BasicNameValuePair("sendActionsResearch", "true"));
			nvps.add(new BasicNameValuePair("sendActionsUpgrade", "true"));
			nvps.add(new BasicNameValuePair("sendActionsOther", "true"));
			nvps.add(new BasicNameValuePair("sendActionsInaction", "false"));

			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			HttpResponse response = httpclient.execute(httpPost);

			try {
				if (response.getStatusLine().getStatusCode() != 200)
				{
					logger.warn("Failed to get replay result with status code:" + response.getStatusLine().getStatusCode() + ". Replay file: " + replayFileName);
					return null;
				}
				HttpEntity entity2 = response.getEntity();
				String resultXml = EntityUtils.toString(entity2, "UTF-8");

				logger.info("Done!");
				return resultXml;
			} finally {
				httpPost.releaseConnection();
			}

		}
		catch(Exception e)
		{
			logger.warn("Failed to parseReplayFile replay: " + replayFileName, e);
		}
		return null;
	}

	public static String parseMap(String mapUrl)
	{
		try
		{
			logger.info("Calling sc2gears api for map: " + mapUrl);
			HttpClient httpclient = new DecompressingHttpClient(new DefaultHttpClient());

			HttpPost httpPost = new HttpPost(apiConfig.getUrl());
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("protVer", apiConfig.getProtVer()));
			nvps.add(new BasicNameValuePair("apiKey", apiConfig.getApiKey()));
			nvps.add(new BasicNameValuePair("op", "mapInfo"));
			nvps.add(new BasicNameValuePair("mapFileName", mapUrl));

			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			HttpResponse response = httpclient.execute(httpPost);

			try {
				if (response.getStatusLine().getStatusCode() != 200)
				{
					logger.warn("Failed with status code:" + response.getStatusLine().getStatusCode());
					return null;
				}
				HttpEntity entity2 = response.getEntity();
				String resultXml = EntityUtils.toString(entity2, "UTF-8");

				logger.info("Done!");
				return resultXml;
			} finally {
				httpPost.releaseConnection();
			}

		}
		catch(Exception e)
		{
			logger.warn("Failed.", e);
		}
		return null;
	}
}


text:
package libretasks.app.controller.external.actions;

import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import libretasks.app.R;
import libretasks.app.controller.ResultProcessor;
import libretasks.app.controller.actions.ShowWebsiteAction;
import libretasks.app.controller.external.attributes.NetworkStateMonitor;
import libretasks.app.controller.util.Logger;

/**
 * Display a website for a given url
 */
public class ShowWebsiteService extends Service {

  private static final String TAG = ShowWebsiteService.class.getSimpleName();

  @Override
  public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    String url = null;
    try {
      url = intent.getStringExtra(ShowWebsiteAction.PARAM_WEB_URL);
    } catch (Exception e) {
      url = "";
      Logger.w(TAG, "no web url provided by user");
      ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_IRRECOVERABLE,
          getString(R.string.website_action_failed_no_url));
    }
    Uri uri = Uri.parse(url);
    Intent newIntent = new Intent(Intent.ACTION_VIEW, uri);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
      if (NetworkStateMonitor.isConnected()) {
        startActivity(newIntent);
      } else {
        ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_INTERNET,
            getString(R.string.website_action_failed_no_service));
      }
    } catch (ActivityNotFoundException e) {
      Logger.w(TAG, e.getClass().getSimpleName(), e );
      ResultProcessor.process(this, intent, ResultProcessor.RESULT_FAILURE_IRRECOVERABLE,
          getString(R.string.website_action_failed_bad_url));
      return;
    }
    ResultProcessor.process(this, intent, ResultProcessor.RESULT_SUCCESS, null);
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }
}


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import json
import os

from pants.util.contextutil import temporary_dir
from pants_test.pants_run_integration_test import PantsRunIntegrationTest

class TestJvmDependencyUsageIntegration(PantsRunIntegrationTest):

  def _run_dep_usage(self, workdir, target, clean_all=False, extra_args=None):
    with temporary_dir() as outdir:
      outfile = os.path.join(outdir, 'out.json')
      args = [
          'dep-usage',
          target,
          '--dep-usage-jvm-output-file={}'.format(outfile),
          ] + (extra_args if extra_args else [])
      if clean_all:
        args.insert(0, 'clean-all')

      # Run, and then parse the report from json.
      self.assert_success(self.run_pants_with_workdir(args, workdir))
      with open(outfile) as f:
        return json.load(f)

  def _assert_non_zero_usage(self, dep_usage_json):
    for entry in dep_usage_json:
      self.assertGreater(entry['max_usage'], 0.0, 'Usage was 0.0 in: `{}`'.format(entry))

  def test_dep_usage(self):
    target = 'testprojects/src/java/org/pantsbuild/testproject/unicode/main'
    with self.temporary_workdir() as workdir:
      # Run twice.
      run_one = self._run_dep_usage(workdir, target, clean_all=True)
      run_two = self._run_dep_usage(workdir, target, clean_all=False)

      # Confirm that usage is non-zero, and that the reports match.
      self._assert_non_zero_usage(run_two)
      self.assertEquals(run_one, run_two)