text:
package com.parse.AndroidProject;

/**
 * Created by Dr.Dias on 10/12/2015.
 *
 * Affichage profil
 * Selection conversation
 * ajout photo
 *
 */
public class Const {
    /** The Constant EXTRA_DATA. */
    public static final String EXTRA_DATA = "extraData";
    public static final String USER_DATA = "USER_DATA";
    public static final String USER_ID = "USER_ID";
}

redpajama_set_name: RedPajamaGithub


text:
=head1 NAME

Net::DNS::FAQ - Frequently Asked Net::DNS Questions

=head1 SYNOPSIS

 perldoc Net::DNS::FAQ

=head1 DESCRIPTION

This document serves to answer the most frequently asked questions on both the
Net::DNS Mailing List and those sent to the author.

The latest version of this FAQ can be found at
	http://www.net-dns.org/docs/FAQ.html

=head1 GENERAL

=head2 What is Net::DNS?

Net::DNS is a perl implementation of a DNS resolver.

=head1 INSTALLATION

=head2 Where can I find Test::More?

Test::More is part of the Test-Simple package, by Michael G Schwern.
You should be able to find the distrubution here:

	http://search.cpan.org/dist/Test-Simple/

=head1 USAGE

=head2 Why does Net::DNS::Resolver::query() return undef when the ANSWER section is empty?

The short answer is, don't use query().  Net::DNS::Resolver::send()
will always return the answer packet, as long as an answer was received.

The longer answer is that query() is modeled after the res_query() function
from the libresolv C library, which has similar behaviors.

=head1 VERSION

 $Id: FAQ.pod 872 2011-01-10 15:45:59Z willem $


text:
package be.trojkasoftware.android.typeconverter;

import android.os.Bundle;

public class IntTypeConverter implements TypeConverter {

	@Override
	public boolean CanConvertFrom(Class<?> from) {
		if((from == Bundle.class)
			|| (from == String.class))
			return true;
		return false;
	}

	@Override
	public boolean CanConvertTo(Class<?> to) {
		if((to == Bundle.class)
			|| (to == String.class))
			return true;
		return false;
	}

	@Override
	public Object ConvertFrom(Object object) {
		Object returnValue = null;
		if(object.getClass() == Bundle.class)
		{
			Bundle data = (Bundle)object;
			returnValue = data.getInt(BUNDLE_KEY);
		}
		if(object.getClass() == String.class)
		{
			returnValue = Integer.parseInt((String)object);
		}
		if(object.getClass() == int.class || object.getClass() == Integer.class)
		{
			returnValue = object;
		}
		return returnValue;
	}

	@Override
	public Object ConvertTo(Object object, Class<?> type) {
		Object returnValue = null;
		if(type == Bundle.class)
		{
			Bundle data = new Bundle();
			int objectAsInt = (Integer)object;
			data.putInt(BUNDLE_KEY, objectAsInt);
			returnValue = (Object)data;
		}
		if(type == String.class)
		{
			returnValue = object.toString();
		}
		if(type == int.class || type == Integer.class)
		{
			returnValue = object;
		}
		return returnValue;
	}

	final String BUNDLE_KEY = "INTEGER_VALUE";

}


text:
package chat

import "regexp"

var reStripName = regexp.MustCompile("[^\\w.-]")

// SanitizeName returns a name with only allowed characters.
func SanitizeName(s string) string {
	return reStripName.ReplaceAllString(s, "")
}

var reStripData = regexp.MustCompile("[^[:ascii:]]")

// SanitizeData returns a string with only allowed characters for client-provided metadata inputs.
func SanitizeData(s string) string {
	return reStripData.ReplaceAllString(s, "")
}


text:
<?php
/**
 * User: matt
 * Date: 21/06/14
 * Time: 10:32
 */

require_once __DIR__ . '/../Server.php';
require_once __DIR__ . '/../EHServer.php';
require_once __DIR__ . '/../EHServerBuilder.php';
require_once __DIR__ . '/../Drive.php';
require_once __DIR__ . '/../EHDrive.php';
require_once __DIR__ . '/../EHDriveBuilder.php';
require_once __DIR__ . '/../EHLogger.php';
require_once __DIR__ . '/../EHBuilder.php';
require_once __DIR__ . '/../EHVlanBuilder.php';
require_once __DIR__ . '/../Runner.php';
require_once __DIR__ . '/../ServerGroup.php';
require_once __DIR__ . '/../EHServerGroup.php';
require_once __DIR__ . '/mocks/MockRunner.php';
require_once __DIR__ . '/mocks/MockLogger.php';


text:
package hn.join.fieldwork.utils;

import java.io.File;

import org.apache.commons.io.FileUtils;
/**
 * 多媒体文件操作工具类
 * @author chenjinlong
 *
 */
public class AudioUtil extends FileUtil{
	/**
	 * 获取工单音频文件位置
	 * @param fieldworkerId
	 * @param workOrderNo
	 * @return
	 */
	public static File getWorkOrderAudioDir(String fieldworkerId, String workOrderNo) {
//		File fieldworkerDir = new File(SystemConstants.getUploadRepository(),
//				fieldworkerId);
//		if (!fieldworkerDir.exists())
//			fieldworkerDir.mkdir();
		File orderDir = new File(SystemConstants.getUploadRepository(), workOrderNo);
		if (!orderDir.exists()) {
			orderDir.mkdir();
		}
		File imageDir = new File(orderDir, "audio");
		if (!imageDir.exists()) {
			imageDir.mkdir();
		}
		return imageDir;
	}
	/**
	 * 删除文件
	 * @param fieldworkderId
	 * @param workOrderNo
	 * @param filename
	 * @return
	 */
	public static boolean removeAudioFile(String fieldworkderId,String workOrderNo,String filename){
		File audioDir=getWorkOrderAudioDir(fieldworkderId,workOrderNo);
		File audioFile=new File(audioDir,filename);
		return FileUtils.deleteQuietly(audioFile);
	}

//	public static List

}


text:
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
PipedriveRapletRails::Application.initialize!


text:
//
//  ViewController.m
//  SHIIndicatorView
//
//  Created by tomyAmi on 2015/01/25.
//  Copyright (c) 2015年 tomyAmi. All rights reserved.
//

#import "ViewController.h"
#import "SHIIndicator.h"

int cou = 0;
@interface ViewController ()
@end

@implementation ViewController

-(instancetype)init{

    self =[super init];

    if(self){

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.hidden=YES;

    /******************************************************************************
     * 使い方!
     * 第一引数にインジケーターのタイトルをセットしてください。
     * 色を16進数でグラデーション colorGradiator → 配列で指定してください NSArray
     * How to use it!
     * set the title of the indicator in the first argument.
     * Gradient color in hexadecimal colorGradiator → Please specify it as an array NSArray
     *
     ******************************************************************************/
    [SHIIndicator showStatus:@"読み込んでいます" animationType:SHIAnimationGraviator];
    [SHIIndicator showStatus:@"読み込んでいます" indicator:SHIwhiteLargeType colorGradiator:@[@"#EF4DB6",@"#C643FC"]];
    [self performSelector:@selector(dis:) withObject:nil afterDelay:2.0];
}

-(void)aliveIndicartor{
    switch (cou) {
        case 0:
            [SHIIndicator showStatus:@"読み込んでいます" indicator:SHIwhiteLargeType colorGradiator:@[@"#EF4DB6",@"#C643FC"]];
            cou++;
            break;
        case 1:
            [SHIIndicator showStatus:@"読み込んでいます" indicator:SHIwhiteLargeType colorGradiator:@[@"#EF4DB6",@"#C643FC"]];
            cou++;
            break;

        case 2:
            [SHIIndicator showStatus:@"読み込んでいます" indicator:SHIwhiteLargeType colorGradiator:@[@"#EF4DB6",@"#C643FC"]];
            cou++;
            break;
        default:
            break;
    }
    if(cou>=3){
        cou=0;
    }
    [self performSelector:@selector(gig) withObject:self afterDelay:2.0];
}

- (IBAction)alive:(id)sender {
    [self aliveIndicartor];
}
- (IBAction)dis:(id)sender {
    [[SHIIndicator sharedInstance]dissmis:SHIAnimationGraviator];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)gig{
    switch (cou) {
        case 0:
            [[SHIIndicator sharedInstance]dissmis:SHIAnimationFadeAnimation];

            break;
        case 1:
            [[SHIIndicator sharedInstance]dissmis:SHIAnimationMimunFade];
            break;

        case 2:
            [[SHIIndicator sharedInstance]dissmis:SHIAnimationDefaultDismiss];
            break;
        default:
            break;
    }
    if(cou>=3){
        cou=0;
    }

}
@end


text:
from django.contrib import admin

from models import FacebookApp, FacebookAccount

class FacebookAccountAdmin(admin.ModelAdmin):
    raw_id_fields = ('user',)

admin.site.register(FacebookApp)
admin.site.register(FacebookAccount, FacebookAccountAdmin)


text:
using System.Runtime.CompilerServices;
using System.Web;

[assembly: InternalsVisibleTo("NeuroLinker.Tests")]

namespace NeuroLinker.Extensions
{
    /// <summary>
    /// Extension methods for <see cref="string"/>
    /// </summary>
    public static class StringExtensions
    {
        #region Private Methods

        /// <summary>
        /// HtmlDecode a string
        /// </summary>
        /// <param name="self">The string to decode</param>
        /// <returns>Decoded html string</returns>
        internal static string HtmlDecode(this string self)
        {
            var decodedText = HttpUtility.HtmlDecode(self);
            return decodedText?.Replace("'", "'")
                ?? string.Empty;
        }

        #endregion
    }
}


text:
package org.apache.spark.util.collection

import scala.reflect.ClassTag

/**
 * An append-only buffer similar to ArrayBuffer, but more memory-efficient for small buffers.
 * ArrayBuffer always allocates an Object array to store the data, with 16 entries by default,
 * so it has about 80-100 bytes of overhead. In contrast, CompactBuffer can keep up to two
 * elements in fields of the main object, and only allocates an Array[AnyRef] if there are more
 * entries than that. This makes it more efficient for operations like groupBy where we expect
 * some keys to have very few elements.
 */
private[spark] class CompactBuffer[T: ClassTag] extends Seq[T] with Serializable {
  // First two elements
  private var element0: T = _
  private var element1: T = _

  // Number of elements, including our two in the main object
  private var curSize = 0

  // Array for extra elements
  private var otherElements: Array[T] = null

  def apply(position: Int): T = {
    if (position < 0 || position >= curSize) {
      throw new IndexOutOfBoundsException
    }
    if (position == 0) {
      element0
    } else if (position == 1) {
      element1
    } else {
      otherElements(position - 2)
    }
  }

  private def update(position: Int, value: T): Unit = {
    if (position < 0 || position >= curSize) {
      throw new IndexOutOfBoundsException
    }
    if (position == 0) {
      element0 = value
    } else if (position == 1) {
      element1 = value
    } else {
      otherElements(position - 2) = value
    }
  }

  def += (value: T): CompactBuffer[T] = {
    val newIndex = curSize
    if (newIndex == 0) {
      element0 = value
      curSize = 1
    } else if (newIndex == 1) {
      element1 = value
      curSize = 2
    } else {
      growToSize(curSize + 1)
      otherElements(newIndex - 2) = value
    }
    this
  }

  def ++= (values: TraversableOnce[T]): CompactBuffer[T] = {
    values match {
      // Optimize merging of CompactBuffers, used in cogroup and groupByKey
      case compactBuf: CompactBuffer[T] =>
        val oldSize = curSize
        // Copy the other buffer's size and elements to local variables in case it is equal to us
        val itsSize = compactBuf.curSize
        val itsElements = compactBuf.otherElements
        growToSize(curSize + itsSize)
        if (itsSize == 1) {
          this(oldSize) = compactBuf.element0
        } else if (itsSize == 2) {
          this(oldSize) = compactBuf.element0
          this(oldSize + 1) = compactBuf.element1
        } else if (itsSize > 2) {
          this(oldSize) = compactBuf.element0
          this(oldSize + 1) = compactBuf.element1
          // At this point our size is also above 2, so just copy its array directly into ours.
          // Note that since we added two elements above, the index in this.otherElements that we
          // should copy to is oldSize.
          System.arraycopy(itsElements, 0, otherElements, oldSize, itsSize - 2)
        }

      case _ =>
        values.foreach(e => this += e)
    }
    this
  }

  override def length: Int = curSize

  override def size: Int = curSize

  override def iterator: Iterator[T] = new Iterator[T] {
    private var pos = 0
    override def hasNext: Boolean = pos < curSize
    override def next(): T = {
      if (!hasNext) {
        throw new NoSuchElementException
      }
      pos += 1
      apply(pos - 1)
    }
  }

  /** Increase our size to newSize and grow the backing array if needed. */
  private def growToSize(newSize: Int): Unit = {
    // Some JVMs can't allocate arrays of length Integer.MAX_VALUE; actual max is somewhat
    // smaller. Be conservative and lower the cap a little.
    val arrayMax = Int.MaxValue - 8
    if (newSize < 0 || newSize - 2 > arrayMax) {
      throw new UnsupportedOperationException(s"Can't grow buffer past $arrayMax elements")
    }
    val capacity = if (otherElements != null) otherElements.length + 2 else 2
    if (newSize > capacity) {
      var newArrayLen = 8L
      while (newSize - 2 > newArrayLen) {
        newArrayLen *= 2
      }
      if (newArrayLen > arrayMax) {
        newArrayLen = arrayMax
      }
      val newArray = new Array[T](newArrayLen.toInt)
      if (otherElements != null) {
        System.arraycopy(otherElements, 0, newArray, 0, otherElements.length)
      }
      otherElements = newArray
    }
    curSize = newSize
  }
}

private[spark] object CompactBuffer {
  def apply[T: ClassTag](): CompactBuffer[T] = new CompactBuffer[T]

  def apply[T: ClassTag](value: T): CompactBuffer[T] = {
    val buf = new CompactBuffer[T]
    buf += value
  }
}


text:
* Update to webpack 3

## 0.11.3

* avoid promisifying fs ops (fixes #81) (#82)

## 0.11.2

* Update uglify-js usage to v3 api

## 0.11.1

* :arrow_up: Update dependencies
* Update example in readme
* Remove unused Template var from tests
* Fix errors for MultiCompilers build (#78)
* Add strip prefix multi windows support (#76)

## 0.11.0

* Added [chunkhash]/[hash]/[id]/[name] support for importScripts (#70)

## 0.10.1

* Update npmignore files

## 0.10.0

* Update unit tests
* Modularize and refactor
* Remove forceDelete
* Add debug option
* Add final webpack-dev-server notes to readme
* Remove unaffected sw-precache options from readme

## 0.9.1

* Lower node engine requirement to 4.0.0
* Remove unused packages from example
* :arrow_up: Update dependencies

## 0.9.0

* Remove deprecated eslint-plugin-babel options, and drop the whole plugin now that it's no longer used.
* Refactor merge behavior
* Add support for staticFileGlobs option and stripPrefix(Multi) by merging them with the webpack values.

## 0.8.0

* Add minify to docs
* update sw-precache version
* Add option to minify ServiceWorker file (#25)

## 0.7.2

* Add warning when using filepath option
* Fix failing tests from pr #38
* pass force option to `del` (#38)

## 0.7.1

* Update webpack peer dependency
* Add error handling for promise
* Hook plugin to 'after-emit' to ensure async execution
* Correct typos

## 0.7.0

* Refactor importScripts default behavior
* Fix preserving the [hash], so it will update the new hash when running in watch mode

## 0.6.3

* Use publicPath for importScripts

## 0.6.2

* Array.from returning empty array
* Use async/await for writeServiceWorker test

## 0.6.1

* Update dependencies
* Add unit tests for writeServiceWorker and apply methods
* Remove useless getAssetGlobs function

## 0.6.0

* Add spec tests and basic test [WIP]
* Update dependencies
* Allow to use [hash] on importScripts
* Fix typo
* Add circleci config
* Add node engine

## 0.5.1

* Add webpack 2 beta peer dependency
* Remove some of example

## 0.5.0

* Add test
* Add `staticFileGlobsIgnorePatterns` option

## 0.4.0

* Add link to official register example
* Update dependencies

## 0.3.1

* Update example to use filename and isolate service-worker script
* Fix filename option

## 0.3.0

* Drop support for options.options
* Add trailing / to output.path for stripPrefix

## 0.2.4

* fixed missing dependency
* Update readmes with better examples, explanations and badges
* Fix example link
* Fix example errors

## 0.2.3

* Add example project
* Use compilation assets instead of chunk.files

## 0.2.1

* Add eslint babel
* Update readme with options instructions and example
* Make options object passable as single argument

## 0.2.0

* Add changelog
* Fix package comma
* Add makefile
* Add eslint dependencies
* Fix babel-es2015 reference
* Allow options parameter to override config
* Add babel
* Move source into src dir

## 0.1.0

* Initial release

# Change Log
All enhancements and patches to sw-precache-webpack-plugin will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).


text:
package matrix;

public class IslandPerimeter {

    //TAG: Google
    //TAG: matrix
    //Difficulty: Easy

    /**
     *  463. Island Perimeter
     *  You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.

     Example:

     [[0,1,0,0],
     [1,1,1,0],
     [0,1,0,0],
     [1,1,0,0]]

     Answer: 16
     Explanation: The perimeter is the 16 yellow stripes in the image below:

     */

    /**
     * Solution:
     * for for loop the matrix, when find 1, check left, right, up, down, if at the bound or the adjacent is 0,
     * perimeter++
     *
     * Time: O(mn)
     * Space: O(1)
     */

    public int islandPerimeter(int[][] grid) {
        if (grid == null || grid.length == 0) return 0;
        int perimeter = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    perimeter += i == 0 || grid[i - 1][j] == 0 ? 1 : 0;
                    perimeter += i == grid.length - 1 || grid[i + 1][j] == 0 ? 1 : 0;
                    perimeter += j == 0 || grid[i][j - 1] == 0 ? 1 : 0;
                    perimeter += j == grid[0].length - 1 || grid[i][j + 1] == 0 ? 1 : 0;
                }
            }
        }
        return perimeter;
    }

}


text:
export class Venta {
  cliente: { id: number };
  vuelo: { id: number };
  asiento: string
}


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

<TITLE>
PasswordCreationPolicyValidator
</TITLE>

<META NAME="keywords" CONTENT="gov.nih.nci.cabig.caaers.service.security.passwordpolicy.validators.PasswordCreationPolicyValidator class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nih.nci.cabig.caaers.service.security.passwordpolicy.validators

Class PasswordCreationPolicyValidator

java.lang.Object
  gov.nih.nci.cabig.caaers.service.security.passwordpolicy.validators.PasswordCreationPolicyValidator

All Implemented Interfaces:
PasswordPolicyValidator

public class PasswordCreationPolicyValidator
extends java.lang.Object
implements PasswordPolicyValidator

Author:

Ram Seethiraju

Constructor Summary

PasswordCreationPolicyValidator()

Method Summary

 User
getUser()

 void
setUser(User user)

 boolean
validate(PasswordPolicy policy,
         Credential credential,
         ValidationErrors validationErrors)

          This method calls all the password creation policy validating methods

 boolean
validateMinPasswordAge(PasswordCreationPolicy policy,
                       Credential credential,
                       ValidationErrors validationErrors)

          Validates the minimum password age

 boolean
validateMinPasswordLength(PasswordCreationPolicy policy,
                          Credential credential,
                          ValidationErrors validationErrors)

          validates minimum password length
 note: default value is 7

 boolean
validatePasswordHistory(PasswordCreationPolicy policy,
                        Credential credential,
                        ValidationErrors validationErrors)

          Validates password history
 note: default value is 3

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PasswordCreationPolicyValidator

public PasswordCreationPolicyValidator()

Method Detail

validate

public boolean validate(PasswordPolicy policy,
                        Credential credential,
                        ValidationErrors validationErrors)
                 throws ValidationException

This method calls all the password creation policy validating methods

Specified by:
validate in interface PasswordPolicyValidator

Throws:

ValidationException

validateMinPasswordAge

public boolean validateMinPasswordAge(PasswordCreationPolicy policy,
                                      Credential credential,
                                      ValidationErrors validationErrors)

Validates the minimum password age

Parameters:
policy -
credential -

Returns:

Throws:

ValidationException - - if the user password age is less than one set in passwords creation policy

validatePasswordHistory

public boolean validatePasswordHistory(PasswordCreationPolicy policy,
                                       Credential credential,
                                       ValidationErrors validationErrors)

Validates password history
 note: default value is 3

Parameters:
policy -
credential -

Returns:

Throws:

ValidationException - - when user tries to set password which is same as the one which is already used before or currently using.

validateMinPasswordLength

public boolean validateMinPasswordLength(PasswordCreationPolicy policy,
                                         Credential credential,
                                         ValidationErrors validationErrors)

validates minimum password length
 note: default value is 7

Parameters:
policy -
credential -

Returns:

Throws:

ValidationException - - when user password length is greater than or equal to the one set in password creation policy.

getUser

public User getUser()

setUser

public void setUser(User user)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-expense-report',
  templateUrl: './expense-report.component.html',
  styleUrls: ['./expense-report.component.css']
})
export class ExpenseReportComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
<?php

namespace Symfony\Component\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ExpressionLanguage;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\ExpressionLanguage\Expression;

/**
 * @author Nicolas Grekas <p@tchwork.com>
 */
abstract class AbstractRecursivePass implements CompilerPassInterface
{
    /**
     * @var ContainerBuilder
     */
    protected $container;
    protected $currentId;

    private $processExpressions = false;
    private $expressionLanguage;
    private $inExpression = false;

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $this->container = $container;

        try {
            $this->processValue($container->getDefinitions(), true);
        } finally {
            $this->container = null;
        }
    }

    protected function enableExpressionProcessing()
    {
        $this->processExpressions = true;
    }

    protected function inExpression(bool $reset = true): bool
    {
        $inExpression = $this->inExpression;
        if ($reset) {
            $this->inExpression = false;
        }

        return $inExpression;
    }

    /**
     * Processes a value found in a definition tree.
     *
     * @param mixed $value
     *
     * @return mixed The processed value
     */
    protected function processValue($value, bool $isRoot = false)
    {
        if (\is_array($value)) {
            foreach ($value as $k => $v) {
                if ($isRoot) {
                    $this->currentId = $k;
                }
                if ($v !== $processedValue = $this->processValue($v, $isRoot)) {
                    $value[$k] = $processedValue;
                }
            }
        } elseif ($value instanceof ArgumentInterface) {
            $value->setValues($this->processValue($value->getValues()));
        } elseif ($value instanceof Expression && $this->processExpressions) {
            $this->getExpressionLanguage()->compile((string) $value, ['this' => 'container']);
        } elseif ($value instanceof Definition) {
            $value->setArguments($this->processValue($value->getArguments()));
            $value->setProperties($this->processValue($value->getProperties()));
            $value->setMethodCalls($this->processValue($value->getMethodCalls()));

            $changes = $value->getChanges();
            if (isset($changes['factory'])) {
                $value->setFactory($this->processValue($value->getFactory()));
            }
            if (isset($changes['configurator'])) {
                $value->setConfigurator($this->processValue($value->getConfigurator()));
            }
        }

        return $value;
    }

    /**
     * @return \ReflectionFunctionAbstract|null
     *
     * @throws RuntimeException
     */
    protected function getConstructor(Definition $definition, bool $required)
    {
        if (\is_string($factory = $definition->getFactory())) {
            if (!\function_exists($factory)) {
                throw new RuntimeException(sprintf('Invalid service "%s": function "%s" does not exist.', $this->currentId, $factory));
            }
            $r = new \ReflectionFunction($factory);
            if (false !== $r->getFileName() && file_exists($r->getFileName())) {
                $this->container->fileExists($r->getFileName());
            }

            return $r;
        }

        if ($factory) {
            list($class, $method) = $factory;
            if ($class instanceof Reference) {
                $class = $this->container->findDefinition((string) $class)->getClass();
            } elseif (null === $class) {
                $class = $definition->getClass();
            }
            if ('__construct' === $method) {
                throw new RuntimeException(sprintf('Invalid service "%s": "__construct()" cannot be used as a factory method.', $this->currentId));
            }

            return $this->getReflectionMethod(new Definition($class), $method);
        }

        $class = $definition->getClass();

        try {
            if (!$r = $this->container->getReflectionClass($class)) {
                throw new RuntimeException(sprintf('Invalid service "%s": class "%s" does not exist.', $this->currentId, $class));
            }
        } catch (\ReflectionException $e) {
            throw new RuntimeException(sprintf('Invalid service "%s": %s.', $this->currentId, lcfirst(rtrim($e->getMessage(), '.'))));
        }
        if (!$r = $r->getConstructor()) {
            if ($required) {
                throw new RuntimeException(sprintf('Invalid service "%s": class%s has no constructor.', $this->currentId, sprintf($class !== $this->currentId ? ' "%s"' : '', $class)));
            }
        } elseif (!$r->isPublic()) {
            throw new RuntimeException(sprintf('Invalid service "%s": %s must be public.', $this->currentId, sprintf($class !== $this->currentId ? 'constructor of class "%s"' : 'its constructor', $class)));
        }

        return $r;
    }

    /**
     * @throws RuntimeException
     *
     * @return \ReflectionFunctionAbstract
     */
    protected function getReflectionMethod(Definition $definition, string $method)
    {
        if ('__construct' === $method) {
            return $this->getConstructor($definition, true);
        }

        if (!$class = $definition->getClass()) {
            throw new RuntimeException(sprintf('Invalid service "%s": the class is not set.', $this->currentId));
        }

        if (!$r = $this->container->getReflectionClass($class)) {
            throw new RuntimeException(sprintf('Invalid service "%s": class "%s" does not exist.', $this->currentId, $class));
        }

        if (!$r->hasMethod($method)) {
            throw new RuntimeException(sprintf('Invalid service "%s": method "%s()" does not exist.', $this->currentId, $class !== $this->currentId ? $class.'::'.$method : $method));
        }

        $r = $r->getMethod($method);
        if (!$r->isPublic()) {
            throw new RuntimeException(sprintf('Invalid service "%s": method "%s()" must be public.', $this->currentId, $class !== $this->currentId ? $class.'::'.$method : $method));
        }

        return $r;
    }

    private function getExpressionLanguage(): ExpressionLanguage
    {
        if (null === $this->expressionLanguage) {
            if (!class_exists(ExpressionLanguage::class)) {
                throw new LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
            }

            $providers = $this->container->getExpressionLanguageProviders();
            $this->expressionLanguage = new ExpressionLanguage(null, $providers, function (string $arg): string {
                if ('""' === substr_replace($arg, '', 1, -1)) {
                    $id = stripcslashes(substr($arg, 1, -1));
                    $this->inExpression = true;
                    $arg = $this->processValue(new Reference($id));
                    $this->inExpression = false;
                    if (!$arg instanceof Reference) {
                        throw new RuntimeException(sprintf('"%s::processValue()" must return a Reference when processing an expression, %s returned for service("%s").', \get_class($this), \is_object($arg) ? \get_class($arg) : \gettype($arg), $id));
                    }
                    $arg = sprintf('"%s"', $arg);
                }

                return sprintf('$this->get(%s)', $arg);
            });
        }

        return $this->expressionLanguage;
    }
}


text:
<?php

namespace Suite900\Menu\Controller\Adminhtml\Team;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Dev extends Action
{
	protected $context;
	protected $pageFactory;

	public function __construct(Context $context, PageFactory $pageFactory)
	{
		$this->context = $context;
		$this->pageFactory = $pageFactory;

		parent::__construct($context);
	}

	public function execute()
	{

		$resultPage = $this->pageFactory->create();
		$resultPage->setActiveMenu('Suite900_Menu::team_dev');
		$resultPage->getConfig()->getTitle()->prepend(__('Dev Team'));
		return $resultPage;
	}
}


text:
<?php

declare(strict_types=1);

namespace Billogram\Tests\Api;

use Billogram\BillogramClient;
use Billogram\HttpClientConfigurator;
use Billogram\Model\Setting\BookkeepingSetting;
use Billogram\Model\Setting\BusinessAddress;
use Billogram\Model\Setting\Contact;
use Billogram\Model\Setting\InvoiceAddress;
use Billogram\Model\Setting\InvoiceDefaults;
use Billogram\Model\Setting\PaymentSetting;
use Billogram\Model\Setting\Setting;
use Billogram\Model\Setting\TaxSetting;
use Billogram\Model\Setting\VisitingAddress;
use Billogram\Tests\BaseTestCase;

/**
 * @author Ibrahim Hizeoui <ibrahimhizeoui@gmail.com>
 */
class SettingTest extends BaseTestCase
{
    public function testFetch()
    {
        $cacheClient = $this->getHttpClient();
        $httpClientConfigurator = new HttpClientConfigurator($cacheClient);
        $httpClientConfigurator->setAuth('20561-3vhGtAxH', '4eddc2ab063bdd53dc64836ff3a0c7bc');
        $apiClient = BillogramClient::configure($httpClientConfigurator);
        $settingFinal = $apiClient->settings()->fetch();
        $this->assertInstanceOf(Setting::class, $settingFinal);
    }

    public function testUpdate()
    {
        $setting = new Setting();
        $contact = Contact::createFromArray(['name' => 'Ib92', 'phone' => '0712345678', 'email' => 'tarafder.saptad@pig.pp.ua', 'www' => 'https://www.youtube.com/']);
        $address = BusinessAddress::createFromArray(['street_address' => 'Finlandsgatan 36', 'careof' => 'Microsoft', 'zipcode' => '164 74', 'city' => 'Kista', 'country' => 'Sweden']);
        $invoiceAddress = InvoiceAddress::createFromArray(['street_address' => 'Finlandsgatan 36', 'careof' => 'Microsoft', 'zipcode' => '164 74', 'city' => 'Kista', 'country' => 'Sweden', 'email' => 'tarafder.saptad@pig.pp.ua']);
        $visitingAddress = VisitingAddress::createFromArray(['street_address' => 'Finlandsgatan 36', 'careof' => 'Microsoft', 'zipcode' => '164 74', 'city' => 'Kista', 'country' => 'Sweden']);
        $payment = PaymentSetting::createFromArray(['bankgiro' => '', 'plusgiro' => '', 'domestic_bank_account' => ['account_no' => '', 'clearing_no' => ''], 'international_bank_account' => ['bank' => '', 'iban' => '', 'bic' => '', 'swift' => '']]);
        $tax = TaxSetting::createFromArray(['is_vat_registered' => '', 'has_fskatt' => '', 'vat_no' => '']);
        $bookkeeping = BookkeepingSetting::createFromArray(['income_account_for_vat_25' => '', 'income_account_for_vat_12' => '', 'income_account_for_vat_6' => '', 'income_account_for_vat_0' => '', 'reversed_vat_account' => '', 'vat_account_for_vat_25' => '',
                                                            'vat_account_for_vat_12' => '', 'vat_account_for_vat_6' => '', 'account_receivable_account' => '', 'client_funds_account' => '', 'banking_account' => '', 'interest_fee_account' => '', 'reminder_fee_account' => '',
                                                            'rounding_account' => '', 'factoring_receivable_account' => '', 'non_allocated_account' => '', 'income_payout_account' => '', 'written_down_receivables_account' => '', 'expected_loss_account' => '',
                                                            'regional_sweden' => ['rotavdrag_account' => ''], ]);
        $invoices = InvoiceDefaults::createFromArray(['default_message' => 'hey hey', 'default_messagedefault_message' => 8.5, 'default_reminder_fee' => 10, 'default_invoice_fee' => 30,
                                                            'automatic_reminders' => ['delay_days' => 5, 'message' => 'HEY'],
                                                            'automatic_writeoff' => ['settings' => 'all_fees', 'amount' => 100],
                                                            'automatic_collection' => ['delay_days' => 5, 'amount' => 100], ]);
        $setting = $setting->withName('debg');
        $setting = $setting->withOrgNo('556667-0591');
        $setting = $setting->withContact($contact);
        $setting = $setting->withBusinessAddress($address);
        $setting = $setting->withVisitingAddress($visitingAddress);
        $setting = $setting->withInvoiceAddress($invoiceAddress);
        $setting = $setting->withPayment($payment);
        $setting = $setting->withTax($tax);
        $setting = $setting->withBookkeeping($bookkeeping);
        $setting = $setting->withInvoices($invoices);
        $cacheClient = $this->getHttpClient();
        $httpClientConfigurator = new HttpClientConfigurator($cacheClient);
        $httpClientConfigurator->setAuth('20561-3vhGtAxH', '4eddc2ab063bdd53dc64836ff3a0c7bc');
        $apiClient = BillogramClient::configure($httpClientConfigurator);
        $settingFinal = $apiClient->settings()->update($setting);
        $this->assertInstanceOf(Setting::class, $settingFinal);
    }

    /**
     * @return string|null the directory where cached responses are stored
     */
    protected function getCacheDir()
    {
        return dirname(__DIR__).'/.cache';
    }
}


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('groceryLister', [
  'ngRoute',
  'groceryLister.products',
  'groceryLister.groceryLists',
  'groceryLister.groceryList'
])
.config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/groceryList'});
}]);


text:
\section{controller/config.c File Reference}
\label{controller_2config_8c}\index{controller/config.c@{controller/config.c}}
{\ttfamily \#include $<$upkeeper.h$>$}\par
{\ttfamily \#include $<$json/json.h$>$}\par
Include dependency graph for config.c:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=400pt]{controller_2config_8c__incl}
\end{center}
\end{figure}


text:
<?php

namespace Draw\Swagger\Schema;

use JMS\Serializer\Annotation as JMS;

/**
 * @author Martin Poirier Theoret <mpoiriert@gmail.com>
 */
class PathParameter extends BaseParameter
{
    /**
     * The extending format for the previously mentioned type. See Data Type Formats for further details.
     *
     * @var string
     * @JMS\Type("boolean")
     */
    public $required = true;
}


text:
package sobjGbApp.domain.models.view;

import java.math.BigDecimal;

public class JobDeatilaViewModel {

    private String sector;
    private String profession;
    private BigDecimal salary;
    private String description;

    public JobDeatilaViewModel() {
    }

    public String getSector() {
        return this.sector;
    }

    public void setSector(String sector) {
        this.sector = sector;
    }

    public String getProfession() {
        return this.profession;
    }

    public void setProfession(String profession) {
        this.profession = profession;
    }

    public BigDecimal getSalary() {
        return this.salary;
    }

    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}


text:
<http://berlinonline.github.io/converjon>

An advanced image conversion server and command line tool.

* [Features](#features)
* [Dependencies](#dependencies)
* [Installation](#installation)
* [Running](#running)
* [Usage](#usage)
    * [Changing Size](#changing-size)
    * [Area of Interest](#area-of-interest)
    * [Cropping Mode](#cropping-mode)
    * [Padding Color](#padding-color)
    * [Cropping Mode](#cropping-mode)
    * [Image format](#image-format)
    * [Quality](#quality)
    * [Color Palette](#color-palette)
    * [Interlaced Images](#interlaced-images)
    * [Presets](#presets)
    * [Status Page](#status-page)
* [Configuration](#configuration)
    * [Server](#server)
    * [Aliases](#aliases)
    * [Downloads](#downloads)
    * [Authentication](#authentication)
    * [Cache](#cache)
    * [Garbage Collector](#garbage-collector)
    * [Processes](#processes)
    * [Converter](#converter)
    * [Cropping](#cropping)
    * [Constraints](#constraints)
    * [Logging](#logging)
* [Testing](#testing)
* [Contributing](#contributing)
* [Changelog](#changelog)
* [Copyright Notes](#copyright-notes)

## Features

* thumbnail generation
* [responsive images](http://dev.opera.com/articles/responsive-images/)
* intelligent cropping
* [art direction use cases](http://usecases.responsiveimages.org/#art-direction)
* adaptive image quality
* no need to pre-generate different image sizes or versions

## Dependencies

* [ImageMagick](http://www.imagemagick.org/script/binary-releases.php)
* [ExifTool](http://www.sno.phy.queensu.ca/%7Ephil/exiftool/install.html) (at least version 9)
* [node.js and NPM](http://nodejs.org/download/)
    * The [crypto module](https://nodejs.org/api/crypto.html) must be supported/included in the nodejs build

## Installation

Use NPM: ``npm install [-g] converjon``

If you want to prevent the fixed dependency versions of the ``npm-shrinkwrap.json`` file to be used on install use ``--no-shrinkwrap`` as a command line argument. See [shrinkwrap docs](https://docs.npmjs.com/cli/shrinkwrap) and [install docs](https://docs.npmjs.com/cli/install) for more information on this.

Converjon follows [Semantic Versioning](http://semver.org/).

## Running

Manually on commandline, as a system service or via docker.

### Manually

Start the server with `converjon [--config your_config_file]` or use the command line utility `converjon-cli` to work on local files.

### Docker

```sh
docker run -t -p 8000:8000 -v $(pwd)/config/default.yml:/etc/converjon/config.yml berlinonline/converjon:latest
```

or

```sh
docker run -e USE_CONFIG_DIR=true -t -p 8000:8000 -v $(pwd)/config/:/etc/converjon/config berlinonline/converjon:latest
```

## Usage

Let's say you have an image at `http://example.org/image.jpg`. To get the image through Converjon, put the original URL into the request as a URL encoded parameter:

    http://localhost/?url=%20http%3A%2F%2Fexample.org%2Fimage.jpg

Another alternative is to specify a file from the server's file system as the source. Instead of `url`, you can add the
`file` parameter for this:

    http://localhost/?file=foobar%3Asome%2Fdirectory%2Fimage.jpg

The `file` parameter is URL-encoded. In plain text it is `foobar:some/directory/image.jpg`.

Here, `foobar` is the name of a filesystem alias followed by a colon and a relative path. See [Configuration: Aliases](#aliases) for more details.

More options are available as GET parameters. All parameters need to be URL encoded.

Several examples are available on the `/demo` page which is enabled when starting Converjon with the [development config file](https://github.com/berlinonline/converjon/blob/master/config/development.yml) via ``converjon --dev``.

It's recommended to set the server port to `80` in [configuration](#server) and to run Converjon on a separate subdomain of your site or behind a reverse proxy like Nginx or Varnish.

For information on how to use the command line tool, run `conversion-cli --help`.

### Changing size

You can either supply a `width`, `height` or both. If you only specify one dimension, the other one will be derived from the original image's aspect ratio.

If you set both values, the image may be cropped to the new aspect ratio and then resized to the requested pixel dimensions.

### Area of Interest

[Wiki: Area of Interest](https://github.com/berlinonline/converjon/wiki/Area-of-Interest)

By default images are cropped from the center of the original. You can specify an "area of interest" with the `aoi` parameter. The AOI is a rectangle in the following format:

    offsetX,offsetY,width,height

The AOI can also be embedded in the original image's metadata via EXIF or IPTC. The name of this metadata field can be configured and defaults to `aoi`. The request parameter overrides the AOI value from the image's metadata.

By default, the AOI in the URL parameters has precedence over the one from the image's metadata. To prefer the embedded AOI from the metadata, set the `prefer_embedded_aoi` parameter to any non-empty value.

### Cropping mode

The `crop` parameter sets the cropping mode. Available modes are:

* `centered`
* `aoi_coverage`
* `aoi_emphasis`
* `aoi_auto`

Details about the cropping modes can be found [here in the wiki](https://github.com/berlinonline/converjon/wiki/Cropping-Modes). For examples, see the [demo page](http://berlinonline.github.io/converjon/demo/demo.html).

If an AOI is set, cropping will ensure, that the area is always preserved.

### Padding Color

The `padding_color` parameter sets the background color of the padding.

The color should be specified in an HTML URL Encoded format.

If none specified, the default color set in the configuration will be used.
[see also Converter config](#converter)

### Image Format

With the `format` parameter you can change the format of the image. Supported formats are:

* `jpg` or `jpeg`
* `png`
* `gif`

If no specific format is requested, the format of the source image will be used.

### Quality

The `quality` parameter sets the JPEG quality value. It ranges from `1` to `100`.

This parameter is ignored, if the requested format is not JPEG.

### Color Palette

The `colors` parameter sets the number of colors for GIF compression. It ranges from 2 to 256 (integer).

### Interlaced Images

The `interlace` parameter allows the creation of [interlaced images](http://en.wikipedia.org/wiki/Interlacing_(bitmaps)). Supported types of interlacing scheme are:

* `plane`(try this for JPEGs)
* `line`
* `none`

A well-known example of interlaced images are progressive JPEGs. You can use this option with PNGs and GIFs as well.

### Presets

The `preset` parameter allows the automatic usage of a preset of parameters.

New presets may be added in the configuration files as follows:

```YAML
presets:
  thumbnail:
      format: "jpg"
      quality: 50
      width: 100
      hight: 100
```

So instead of specifying all the parameters in the URL:

``?url=...&width=100&height=100&format=jpg&quality=50``

you can use the preset:

``?url=...&preset=thumbnail``

### Removing Metadata

The `strip_metadata` option removes all metadata (e.g. EXIF, IPTC) from the converted images. This option has no value, it just needs to be present in the URL query parameters.

### Status Page

The URL `/status` leads to a summary of Converjon's current state and some statistics.

The status page is available as content type `application/json` via `/status.json`.

## Configuration

When launching converjon, you can specify one or more configuration files with the `--config` option which can be set multiple times to load multiple config files:

```sh
converjon --config conf_file1.yml --config conf_file2.json
```

To load a directory containing one or more config file, use the `--config-dir` option. Config files will be added in the order they appear in that directory.

```sh
converjon --config-dir /etc/converjon
```

You can use the [default.yml](https://github.com/berlinonline/converjon/blob/master/config/default.yml) or [development.yml](https://github.com/berlinonline/converjon/blob/master/config/development.yml) file as an example for writing your own.

The default configuration format is YAML but you can also use JSON files.

Every configuration file matches certain image source URLs. If a config file contains a `urls` setting, that configuration will only apply to URLs that match at least one of the patterns from that list. Config files without the `url` setting apply to all images.

Some configuration are automatically converted:

* "true" (string) is treated as `true`(bool)
* "false" (string) is treated as `false`(bool)

```yaml
# this config will only apply to source URLs from localhost or flickr
urls:
  - "http://localhost*" #this will match URLs on localhost, this is the dev/testing default
  - "http://www.flickr.com*"
```

Converjon uses [calmcard](https://github.com/lnwdr/calmcard) for string pattern matching. Documentation on how these patterns work can be found there.

This way you can define different settings depending on the source of the requested images.

### Server

```yaml
server:
  port: 8000
  instance_name: null
  timeout: 20000
  send_timeout: 2000 #time that sending the repsonse data may take.
  access_log_format: "combined"
  base_url_path: "/"
  enable_load_test: false
```

* `server.port`: port for the server to listen on
* `server.instance_name`: the name of this server that will be displayed on the status page

If not set, a random name will be generated.

* `server.timout`: global timeout for incoming requests
* `server.send_timeout`: the time streaming a finished image file into the HTTP response may take. This usually shouldn't need to be changed, except when the servers file system is expected to be exceptionally slow.
* `server.base_url_path`: Normally, Converjon's image URL paths just start with `/`, like in `http://www.example.org/?url=...`

You can set a base path to have better control over the URLs that Converjon uses. If you want the image URLs too like `http://www.example.org/photos/?url=...` set the `base_url_path` to "photos/".

* `server.access_log_format`: the formatting of access logs:
    * `combined`: Apache Combined Log Format (the default)
    * `short`: leaves out the date/time information. Use this, if you use other software for log handling that adds timestamps.

### Downloads

**URL whitelists**
`download.url_whitelist` sets list of URL patterns that are allowed to be requested as image sources.

For example, if you host your source images on `http://myimages.com/images/...` you should set the whitelist pattern to `http://myimages.com/images/` to make sure other sources are not allowed.

```yaml
# this will only allow requests for images from URLs that match these patterns
download:
  url_whitelist:
    - "http://localhost*"
    - "http://example.org/*
```

[Calmcard](https://github.com/lnwdr/calmcard) patterns are used for matching by default.

You can also prefix the pattern with ``~`` (like ``~ ^http://(foo|bar)\.example.org\/.*``) to use regular expressions. For most cases, this should not be necessary and is discouraged.

**Timeout**
`download.timeout` sets a timeout after which requests are cancelled, if the source server doesn't respond in time.

**Reject Invalid SSL Certificates**
Setting `download.rejectInvalidSSL` to `true` (default) will cause sources to be rejected, if their SSL certificates cannot be validated.

### Aliases

To access the server's local filesystem for source images, you can specify "aliases":

```yaml
#example from the development configuration files:
alias: dev

base_file_path: "test/resources/images"

fallback_base_file_paths:
  - "test/resources/photos"
  - "test/resources/misc"

headers:
  Cache-Control: "max-age=5"
```

When an image is requested with a `file` parameter (`<alias>:<path>`) instead of `url`, the `alias` part of that parameter is matched against the configuration files, just like with URLs but only the configs that have that **exact** alias will be used for that request.

There can only be one alias per config file. If you need multiple aliases, you need to have one config file for each of them. See [here](#configuration) on how to load multiple config files.

In a config file with an alias you can set a `base_file_path`. This is the directory where your source images are located. It is concatenated with the `path` part of the `file` parameter to point to the actual file. The `base_file_path` can be an absolute path or relative to the working directory of the server.

Additionally there can be multiple `fallback_base_file_paths`. If the requested file can't be found in the
`base_file_path`, Converjon will try to find it in the first fallback path, then the second, and so on.

In addition, you can set HTTP headers that will be sent along with the converted image as if they had come from a source server.

### Authentication

Converjon supports HTTP basic authentication for image sources. If you include authentication credentials in a URL specific configuration file, they will be sent along with every request to URLs that match the URL pattern of that configuration file.

```YAML
authentication:
  username: "testuser"
  password: "testpass"
```

### Cache

`cache.basepath` sets the base directory for the local file cache.

```YAML
cache:
  base_path: "/tmp/converjon/cache"
```

`cache.copy_source_file` determines, if a source file should be copied, when you're using a local file as source. By
default, files are copied into Converjon's cache directory. Set this to `false` to use the original file's location.
*You will have to make sure that these files are not changed while Converjon is using them. This could result in corrupted images or failing requests.*

The cache directory is not automatically cleaned up and may grow over time.

### Garbage Collector

Converjon can clean up the cache directory automatically. By default this is disabled. It can be enabled with the
`garbage_collector` config directives:

```YAML
garbage_collector:
  enabled: true
  source: "cache"
  target: "immediate"
  interval: 5000
```

* `enabled`: turns the garbage collector on or off
* `source`: determines when source files should be cleaned up. Possible values are:
    * `cache`: The file will be removed when it's cache lifetime has expired
    * `immediate`: The file will be removed as soon as it's no longer in use by any pending request.
    * any other value will disable the cleanup for source files
* `target`: same as `source` but for the converted target image files
* `interval`: time between garbage collector runs, in milliseconds.

Local source files that were not copied into the cache directory will not be removed by the garbage collector.

### Processes

`process.limit` sets the maximum number of child processes that converjon will spawn for converting and analyzing images.

Increasing this will likely increase memory consumption while providing better usage of multiple CPU cores.

### Converter

* `converter.padding_color` sets the background color that is used, if an image needs padding to fit the requested aspect ratio.
* `converter.filter` sets the filter, e.g. "Sinc"
* `converter.quality` sets the quality of the resulting resized image (number, e.g. 85)

### Cropping

`cropping.default_mode` sets the default mode for cropping images. Possible options are: `centered`, `aoi_coverage`, `aoi_emphasis` and `aoi_auto`.

[Wiki: Cropping Modes](https://github.com/berlinonline/converjon/wiki/Cropping-Modes)

### Constraints

Constraints can be used to limit the possible request parameters, like width and height of images. Every constraint has a `min` and a `max` value:

```YAML
constraints:
  quality:
    min: 1
    max: 100
  colors:
    min: 1
    max: 256
  width:
    min: 1
    max: 10000
  height:
    min: 1
    max: 10000
```

### Logging

There are three logging levels: `access`, `error` and `debug`. Each of them can be directed to either STDOUT, STDERR or into a log file.

```YAML
logging:
  error: "stderr" # will log errors to STDERR
  debug: "stdout" # will log debug logs to STDOUT
  access: "/var/log/access.log" # will log requests into a log file
```

To disable a log level, set it to `false`:

```YAML
logging:
  error: "stderr"
  debug: false # "false" as a string will also work
  access: "/var/log/access.log"
```

Logs are not automatically rotated. Use of a tool like `logrotate` is recommended.

## Testing

Execute tests with `npm test`. Please note, that you need to have all [dependencies](#dependencies) installed.

## Contributing

Please contribute by [forking](http://help.github.com/forking/) and sending a [pull request](http://help.github.com/pull-requests/). More information can be found in the [`CONTRIBUTING.md`](CONTRIBUTING.md) file.

## Changelog

See [`CHANGELOG.md`](CHANGELOG.md) for more information about changes.

## Copyright Notes

Converjon is [licensed under the MIT license](LICENSE).

The "sparrow" testing image is © Leon Weidauer, permission to use it for testing is granted.


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/project_file_action_create_folder_disable" android:state_enabled="false" />
    <item android:drawable="@drawable/project_file_action_create_folder_normal" />
</selector>


text:
package authentification

import (
	"errors"
	"io/ioutil"

	"github.com/GluigiPP/noteapp-middleware/core"
	"github.com/GluigiPP/noteapp-middleware/model"
	"github.com/dgrijalva/jwt-go"
)

var (
	privateKey []byte
	publicKey  []byte
)

func init() {
	privateKey, _ = ioutil.ReadFile("../config/keys/private_key.rsa")
	publicKey, _ = ioutil.ReadFile("../config/keys/public_key.rsa.pub")
}

//Authentificator have the functions to log in a user in the app
type Authentificator struct {
	userGetter func(userName string) (model.User, error)
}

//NewAuthentificator make a Authentificator
func NewAuthentificator() Authentificator {
	return Authentificator{core.NewUserClient().GetUser}
}

//LogIn return a valid JWT to use the rest of the API
func (a Authentificator) LogIn(userName string, password string) (tokenString string, err error) {

	user, getError := a.userGetter(userName)
	if getError != nil || user.Password != password {
		err = errors.New("The user and password are incorrect")
		return
	}
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["user"] = user.UserName
	tokenString, _ = token.SignedString(privateKey)
	return
}


text:
int main( int argc, char **argv ) {
  Py_Initialize();
  // Necessary because of usage of the ReleaseGil class
  PyEval_InitThreads();

  testing::InitGoogleMock( &argc, argv );
  return RUN_ALL_TESTS();
}


text:
package org.elasticsearch.bootstrap;

import org.apache.lucene.util.Constants;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.StringHelper;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.common.PidFile;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.inject.CreationException;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.LogConfigurator;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.BoundTransportAddress;
import org.elasticsearch.env.Environment;
import org.elasticsearch.monitor.jvm.JvmInfo;
import org.elasticsearch.monitor.os.OsProbe;
import org.elasticsearch.monitor.process.ProcessProbe;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.internal.InternalSettingsPreparer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Path;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * Internal startup code.
 */
final class Bootstrap {

    private static volatile Bootstrap INSTANCE;
    private volatile Node node;
    private final CountDownLatch keepAliveLatch = new CountDownLatch(1);
    private final Thread keepAliveThread;

    /** creates a new instance */
    Bootstrap() {
        keepAliveThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    keepAliveLatch.await();
                } catch (InterruptedException e) {
                    // bail out
                }
            }
        }, "elasticsearch[keepAlive/" + Version.CURRENT + "]");
        keepAliveThread.setDaemon(false);
        // keep this thread alive (non daemon thread) until we shutdown
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                keepAliveLatch.countDown();
            }
        });
    }

    /** initialize native resources */
    public static void initializeNatives(Path tmpFile, boolean mlockAll, boolean seccomp, boolean ctrlHandler) {
        final ESLogger logger = Loggers.getLogger(Bootstrap.class);

        // check if the user is running as root, and bail
        if (Natives.definitelyRunningAsRoot()) {
            throw new RuntimeException("can not run elasticsearch as root");
        }

        // enable secure computing mode
        if (seccomp) {
            Natives.trySeccomp(tmpFile);
        }

        // mlockall if requested
        if (mlockAll) {
            if (Constants.WINDOWS) {
               Natives.tryVirtualLock();
            } else {
               Natives.tryMlockall();
            }
        }

        // listener for windows close event
        if (ctrlHandler) {
            Natives.addConsoleCtrlHandler(new ConsoleCtrlHandler() {
                @Override
                public boolean handle(int code) {
                    if (CTRL_CLOSE_EVENT == code) {
                        logger.info("running graceful exit on windows");
                        try {
                            Bootstrap.stop();
                        } catch (IOException e) {
                            throw new ElasticsearchException("failed to stop node", e);
                        }
                        return true;
                    }
                    return false;
                }
            });
        }

        // force remainder of JNA to be loaded (if available).
        try {
            JNAKernel32Library.getInstance();
        } catch (Exception ignored) {
            // we've already logged this.
        }

        Natives.trySetMaxNumberOfThreads();
        Natives.trySetMaxSizeVirtualMemory();

        // init lucene random seed. it will use /dev/urandom where available:
        StringHelper.randomId();
    }

    static void initializeProbes() {
        // Force probes to be loaded
        ProcessProbe.getInstance();
        OsProbe.getInstance();
        JvmInfo.jvmInfo();
    }

    private void setup(boolean addShutdownHook, Settings settings, Environment environment) throws Exception {
        initializeNatives(
                environment.tmpFile(),
                BootstrapSettings.MEMORY_LOCK_SETTING.get(settings),
                BootstrapSettings.SECCOMP_SETTING.get(settings),
                BootstrapSettings.CTRLHANDLER_SETTING.get(settings));

        // initialize probes before the security manager is installed
        initializeProbes();

        if (addShutdownHook) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    try {
                        IOUtils.close(node);
                    } catch (IOException ex) {
                        throw new ElasticsearchException("failed to stop node", ex);
                    }
                }
            });
        }

        // look for jar hell
        JarHell.checkJarHell();

        // install SM after natives, shutdown hooks, etc.
        Security.configure(environment, BootstrapSettings.SECURITY_FILTER_BAD_DEFAULTS_SETTING.get(settings));

        node = new Node(settings) {
            @Override
            protected void validateNodeBeforeAcceptingRequests(Settings settings, BoundTransportAddress boundTransportAddress) {
                BootstrapCheck.check(settings, boundTransportAddress);
            }
        };
    }

    private static Environment initialSettings(boolean foreground, Path pidFile, Map<String, String> esSettings) {
        Terminal terminal = foreground ? Terminal.DEFAULT : null;
        Settings.Builder builder = Settings.builder();
        if (pidFile != null) {
            builder.put(Environment.PIDFILE_SETTING.getKey(), pidFile);
        }
        return InternalSettingsPreparer.prepareEnvironment(builder.build(), terminal, esSettings);
    }

    private void start() {
        node.start();
        keepAliveThread.start();
    }

    static void stop() throws IOException {
        try {
            IOUtils.close(INSTANCE.node);
        } finally {
            INSTANCE.keepAliveLatch.countDown();
        }
    }

    /** Set the system property before anything has a chance to trigger its use */
    // TODO: why? is it just a bad default somewhere? or is it some BS around 'but the client' garbage <-- my guess
    @SuppressForbidden(reason = "sets logger prefix on initialization")
    static void initLoggerPrefix() {
        System.setProperty("es.logger.prefix", "");
    }

    /**
     * This method is invoked by {@link Elasticsearch#main(String[])}
     * to startup elasticsearch.
     */
    static void init(
            final boolean foreground,
            final Path pidFile,
            final Map<String, String> esSettings) throws Exception {
        // Set the system property before anything has a chance to trigger its use
        initLoggerPrefix();

        // force the class initializer for BootstrapInfo to run before
        // the security manager is installed
        BootstrapInfo.init();

        INSTANCE = new Bootstrap();

        Environment environment = initialSettings(foreground, pidFile, esSettings);
        Settings settings = environment.settings();
        LogConfigurator.configure(settings, true);
        checkForCustomConfFile();

        if (environment.pidFile() != null) {
            PidFile.create(environment.pidFile(), true);
        }

        try {
            if (!foreground) {
                Loggers.disableConsoleLogging();
                closeSystOut();
            }

            // fail if using broken version
            JVMCheck.check();

            // fail if somebody replaced the lucene jars
            checkLucene();

            // install the default uncaught exception handler; must be done before security is
            // initialized as we do not want to grant the runtime permission
            // setDefaultUncaughtExceptionHandler
            Thread.setDefaultUncaughtExceptionHandler(
                new ElasticsearchUncaughtExceptionHandler(() -> Node.NODE_NAME_SETTING.get(settings)));

            INSTANCE.setup(true, settings, environment);

            INSTANCE.start();

            if (!foreground) {
                closeSysError();
            }
        } catch (Exception e) {
            // disable console logging, so user does not see the exception twice (jvm will show it already)
            if (foreground) {
                Loggers.disableConsoleLogging();
            }
            ESLogger logger = Loggers.getLogger(Bootstrap.class);
            if (INSTANCE.node != null) {
                logger = Loggers.getLogger(Bootstrap.class, INSTANCE.node.settings().get("node.name"));
            }
            // HACK, it sucks to do this, but we will run users out of disk space otherwise
            if (e instanceof CreationException) {
                // guice: log the shortened exc to the log file
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(os, false, "UTF-8");
                new StartupError(e).printStackTrace(ps);
                ps.flush();
                logger.error("Guice Exception: {}", os.toString("UTF-8"));
            } else {
                // full exception
                logger.error("Exception", e);
            }
            // re-enable it if appropriate, so they can see any logging during the shutdown process
            if (foreground) {
                Loggers.enableConsoleLogging();
            }

            throw e;
        }
    }

    @SuppressForbidden(reason = "System#out")
    private static void closeSystOut() {
        System.out.close();
    }

    @SuppressForbidden(reason = "System#err")
    private static void closeSysError() {
        System.err.close();
    }

    private static void checkForCustomConfFile() {
        String confFileSetting = System.getProperty("es.default.config");
        checkUnsetAndMaybeExit(confFileSetting, "es.default.config");
        confFileSetting = System.getProperty("es.config");
        checkUnsetAndMaybeExit(confFileSetting, "es.config");
        confFileSetting = System.getProperty("elasticsearch.config");
        checkUnsetAndMaybeExit(confFileSetting, "elasticsearch.config");
    }

    private static void checkUnsetAndMaybeExit(String confFileSetting, String settingName) {
        if (confFileSetting != null && confFileSetting.isEmpty() == false) {
            ESLogger logger = Loggers.getLogger(Bootstrap.class);
            logger.info("{} is no longer supported. elasticsearch.yml must be placed in the config directory and cannot be renamed.", settingName);
            exit(1);
        }
    }

    @SuppressForbidden(reason = "Allowed to exit explicitly in bootstrap phase")
    private static void exit(int status) {
        System.exit(status);
    }

    private static void checkLucene() {
        if (Version.CURRENT.luceneVersion.equals(org.apache.lucene.util.Version.LATEST) == false) {
            throw new AssertionError("Lucene version mismatch this version of Elasticsearch requires lucene version ["
                + Version.CURRENT.luceneVersion + "]  but the current lucene version is [" + org.apache.lucene.util.Version.LATEST + "]");
        }
    }

}


text:
require_relative '../../spec_helper'

describe LeanpubAPI::SalesSummary do
  describe "GET sales summary info" do
    let(:summary) { LeanpubAPI::SalesSummary.new(book_slug, api_key) }

    before :each do
      VCR.insert_cassette 'sales_summary', record: :new_episodes
    end

    after :each do
      VCR.eject_cassette
    end

    it "has data" do
      summary.must_respond_to :info
    end

    it "parses the JSON response to a hash" do
      summary.info.must_be_instance_of Hash
    end

    it "performs the request and gets the data" do
      summary.info["book"].must_equal "everydayrailsrspec"
      summary.info["url"].must_equal "https://leanpub.com/everydayrailsrspec"
      summary.info["total_author_royalties"].must_equal "23456.78"
      summary.info["total_book_royalties"].must_equal "3456.78"
      summary.info["num_happy_readers"].must_equal 3534
      summary.info["num_happy_paid_purchases"].must_equal 3522
      summary.info["num_refunded_purchases"].must_equal 12
      summary.info["unpaid_royalties"].must_equal "1208.75"
      summary.info["royalties_currently_due"].must_equal "0.0"
      summary.info["royalties_due_on_first_of_next_month"].must_equal "1208.75"
      summary.info["paid_royalties"].must_equal "12345.67"
    end

    describe "dynamic attributes" do
      before do
        summary.info
      end

      it "returns an attribute if present in the info" do
        summary.num_happy_readers.must_equal 3534
      end

      it "raises method missing if an attribute is not present in the info" do
        lambda { summary.bad_attribute }.must_raise NoMethodError
      end
    end

    describe "caching" do
      before do
        summary.info
        stub_request(:any, /leanpub.com/).to_timeout
      end

      it "caches the info" do
        summary.info.must_be_instance_of Hash
      end

      it "refreshes the info if forced" do
        lambda { summary.info(true) }.must_raise Timeout::Error
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;

namespace CommandLineParser.Arguments;

/// <summary>
/// Interface for non-generic access to <see cref="ValueArgument{TValue}"/> fields.
/// </summary>
public interface IValueArgument
{
    /// <summary>
    /// String read from command line as arguments <see cref="Value"/>.
    /// Available after <see cref="ValueArgument{TValue}"/>.<see cref="ValueArgument{TValue}.Parse"/> is called.
    /// </summary>
    /// <exception cref="InvalidOperationException">String value was read before ParseCommandLine was called or when</exception>
    string StringValue { get; }

    /// <summary>
    /// Specifies whether argument can appear multiple times on the command line.
    /// Default is false;
    /// </summary>
    bool AllowMultiple { get; set; }

    /// <summary>
    /// Mark argument optional.
    /// <see cref="CommandLineParser.CheckMandatoryArguments"/>
    /// <remarks>Default is true</remarks>
    /// </summary>
    bool Optional { get; set; }

    /// <summary>
    /// Value of the ValueArgument, for arguments with single value.
    /// Can be used only if <see cref="AllowMultiple"/> is set to false.
    /// </summary>
    object Value { get; set; }

    /// <summary>
    /// Values of the ValueArgument - for arguments with multiple values allowed.
    /// Can be used only if <see cref="Argument.AllowMultiple"/> is set to true.
    /// </summary>
    IList<object> Values { get; }

    /// <summary>
    /// Adds an item to underlying <see cref="Values"/> collection.
    /// </summary>
    void AddToValues(object value);

    /// <summary>
    /// Non-generic access to <see cref="ValueArgument{TValue}.Convert"/>
    /// </summary>
    /// <param name="stringValue">string representing the value</param>
    /// <returns>parsed value</returns>
    object Convert_obj(string stringValue);
}


text:
package com.ibm.bpm.sce.imagebuilder;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;
import com.ibm.ram.common.data.UserInformation;
import com.ibm.sce.deck.exceptions.ManagedImageException;
import com.ibm.sce.deck.exceptions.SCEClientException;
import com.ibm.sce.deck.resources.ManagedImage;
import com.ibm.sce.deck.tools.ManagedLogger;

/**
 * @author Hai Liang BJ Wang/China/IBM Aug 8, 2013
 */
public class BPMImageHandler {

	private static ManagedImage mgrImg;
	private static UserInformation[] owners;
	private static String ownerConfigFile;
	private static String assetFolder;
	private final static String className = BPMImageHandler.class.getName();
	private static ManagedLogger mgrLogger = ManagedLogger.getInstance();

	private BPMImageHandler() {

	}

	/**
	 *

	 * Title: Customize the BPM Image
	 *

	 *

	 * Description:upload the asset from RTC, change the image's visibility,add
	 * owners
	 *

	 *
	 * @param img
	 */
	public BPMImageHandler(ManagedImage mgrImg, String ownerConfigFile,
			String assetFolder) {
		this.mgrImg = mgrImg;
		this.ownerConfigFile = ownerConfigFile;
		this.assetFolder = assetFolder;
	}

	/**
	 *

	 * Title: process
	 *

	 *

	 * Description: process the bpm image - upload assets ,share ,add owners
	 *

	 *
	 * @throws ManagedImageException
	 * @throws SCEClientException
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public void process() throws ManagedImageException, SCEClientException,
			FileNotFoundException, IOException {

		mgrLogger.info(className, "prcess image id - "
				+ mgrImg.getImage().getID());

		mgrLogger.info(className, "upload asset - "
				+ mgrImg.getImage().getName() + " " + assetFolder);
		mgrImg.uploadAsset(assetFolder);

		mgrLogger.info(className, "share image");
		mgrImg.share();

		mgrLogger.info(className, "add owners");
		addOwners();

	}

	/**
	 *

	 * Title: addOwners
	 *

	 *

	 * Description: add image owners
	 *

	 *
	 * @throws SCEClientException
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	protected void addOwners() throws SCEClientException,
			FileNotFoundException, IOException {
		setOwners();
		for (int i = 0; i < owners.length; i++) {
			mgrLogger.info(className, "add owner - " + owners[i].getEmail());
			mgrImg.addOwner(owners[i]);
		}
	}

	/**
	 *

	 * Title: setOwners
	 *

	 *

	 * Description:set the owners list , the user in the list will be added as
	 * owner of the image
	 *

	 *
	 * @param ownersConfigFilePath
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	protected void setOwners() throws FileNotFoundException, IOException {
		InputStream is = new FileInputStream(ownerConfigFile);
		new JSONArray();
		JSONArray bpmOwners = JSONArray.parse(is);
		owners = new UserInformation[bpmOwners.size()];
		for (int i = 0; i < bpmOwners.size(); i++) {
			JSONObject user = (JSONObject) bpmOwners.get(i);
			owners[i] = getUserInformation((String) user.get("name"),
					(String) user.get("uid"));
		}
	}

	/**
	 *

	 * Title: getUserInformation
	 *

	 *

	 * Description:
	 *

	 *
	 * @param name
	 * @param uid
	 * @return
	 */
	protected UserInformation getUserInformation(String name, String uid) {
		UserInformation usr = new UserInformation();
		usr.setEmail(uid);
		usr.setName(name);
		usr.setUid(uid);
		usr.setImageURL("/theme/images/dummyImage.jpg");
		return usr;
	}

	/**
	 *

	 * Title: main
	 *

	 *

	 * Description:
	 *

	 *
	 * @param args
	 */
	public static void main(String[] args) {
		ManagedImage img;
		try {
			img = new ManagedImage(20107321);
			String asserFolder = new String("bpm_windows_image/asset");
			String bpmOwner = new String(
					"src/main/resources/sce_developers.json");
			BPMImageHandler bpmImgHandler = new BPMImageHandler(img, bpmOwner,
					asserFolder);
			bpmImgHandler.process();
		} catch (ManagedImageException e1) {
			e1.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SCEClientException e) {
			e.printStackTrace();
		}

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>4963 Sankt Peter am Hart, Austria</formatted_address>
  <address_component>
   <long_name>Sankt Peter am Hart</long_name>
   <short_name>Sankt Peter am Hart</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Sankt Peter am Hart</long_name>
   <short_name>Gemeinde St. Peter am Hart</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Braunau am Inn District</long_name>
   <short_name>Braunau am Inn District</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Upper Austria</long_name>
   <short_name>Upper Austria</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>4963</long_name>
   <short_name>4963</short_name>
   <type>postal_code</type>
  </address_component>
  <geometry>
   <location>
    <lat>48.2526060</lat>
    <lng>13.0967840</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>48.2451759</lat>
     <lng>13.0807766</lng>
    </southwest>
    <northeast>
     <lat>48.2600350</lat>
     <lng>13.1127914</lng>
    </northeast>
   </viewport>
  </geometry>
  <place_id>ChIJnxDKidQ1dEcRx_rTnKpfU6s</place_id>
 </result>
</GeocodeResponse>


text:
var showDownloadLinks = (function($) {
  return function(options) {
    var typeOfInstallersToShow = options.typeOfInstallersToShow;

    var settingsForAllTypes = {
      stable: {
        download_info_url : 'https://download.gocd.org/releases.json',
        download_prefix   : 'https://download.gocd.org/binaries/',
        version_to_show   : function(release) { return release['go_version']; }
      },
      experimental: {
        download_info_url : 'https://download.gocd.org/experimental/releases.json',
        download_prefix   : 'https://download.gocd.org/experimental/binaries/',
        version_to_show   : function(release) { return release['go_full_version']; }
      }
    };

    var settings = settingsForAllTypes[typeOfInstallersToShow];
    var showArchives = R.any(R.equals('archive=true'), window.location.search.substr(1).split('&'));

    var dateFilter = R.curry(function(timeInSecondsSinceEpoch) {
      if (showArchives) {
        return true;
      }
      return (new Date() - new Date(timeInSecondsSinceEpoch * 1000)) < 3600 * 24 * 366 * 1000;
    });

    var releasesLessThanAYearOld = R.filter(R.where({release_time: dateFilter}));

    var addURLToFiles = function(release) {
      var addDetailsFrom = R.curry(function(release, analyticsIDPrefix, o) {
        var afterAddingURL = R.assoc('url', settings.download_prefix + release['go_full_version'] + '/' + o["file"], o);
        var afterAddingFilename = R.assoc('filename', R.last(o["file"].split("/")), afterAddingURL, o);
        var afterAddingAnalyticsID = R.assoc('analytics_id', analyticsIDPrefix + "_" + release['go_full_version'], afterAddingFilename, o);
        return afterAddingAnalyticsID;
      });

      return R.evolve({
        win:     {server: addDetailsFrom(release, 'Windows-Server'), agent: addDetailsFrom(release, 'Windows-Agent'),  server32bit: addDetailsFrom(release, 'Windows-Server-32bit'), agent32bit: addDetailsFrom(release, 'Windows-Agent-32bit')},
        osx:     {server: addDetailsFrom(release, 'Mac-Server'),      agent: addDetailsFrom(release, 'Mac-Agent')},
        deb:     {server: addDetailsFrom(release, 'LinuxDeb-Server'), agent: addDetailsFrom(release, 'LinuxDeb-Agent')},
        rpm:     {server: addDetailsFrom(release, 'LinuxRpm-Server'), agent: addDetailsFrom(release, 'LinuxRpm-Agent')},
        generic: {server: addDetailsFrom(release, 'Package-Server'),  agent: addDetailsFrom(release, 'Package-Agent')}
      }, release);
    };

    var addDisplayVersion = R.curry(function(release) {
      return R.assoc('display_version', settings.version_to_show(release), release);
    });

    function compareVersions (a, b) {
      var i, diff;

      var segmentsA = a.go_full_version.replace('-', '.').split('.');
      var segmentsB = b.go_full_version.replace('-', '.').split('.');

      var l = Math.min(segmentsA.length, segmentsB.length);

      for (i = 0; i < l; i++) {
        diff = parseInt(segmentsB[i], 10) - parseInt(segmentsA[i], 10);
        if (diff) {
          return diff;
        }
      }
      return segmentsA.length - segmentsB.length;
    }

    var showReleases = function(data) {
      var releases = R.compose(releasesLessThanAYearOld, R.sort(compareVersions), R.map(addURLToFiles), R.map(addDisplayVersion))(data);

      var template = Handlebars.compile($("#download-revisions-template").html());
      $("#downloads").html(template({
        latest_release     : R.head(releases),
        all_other_releases : R.tail(releases),
        latest_version     : releases[0].go_version
      }));
    };

    var showFailureMessage = function(error) {
      $("#downloads").html('
Sorry. Something went wrong and we could not list the download links. \
        Please report this issue.
')
      console.log("Error: " + error);
    };

    return $.getJSON(settings.download_info_url)
      .done(showReleases)
      .fail(showFailureMessage);
  };
})(jQuery);

var setupShowVerifyChecksumMessage = (function($) {
  return function() {
    $("#downloads").on('click', '.verify-checksum', function(evt) {
      var checksumElement = $(evt.currentTarget);
      var template = Handlebars.compile($("#verify-checksum-message-template").html());
      $("#verify-checksum-message").html(template({
        filename  : checksumElement.data("filename"),
        md5sum    : checksumElement.data("md5sum"),
        sha1sum   : checksumElement.data("sha1sum"),
        sha256sum : checksumElement.data("sha256sum")
      }));
       $('body').addClass("o-h");
    });
  };
})(jQuery);


text:
using System;
using System.Windows.Forms;
using Microsoft.Deployment.WindowsInstaller;
using WixSharp;

class Script
{
    static public void Main(string[] args)
    {
        var project = new Project()
        {
            UI = WUI.WixUI_ProgressOnly,
            Name = "CustomActionTest",

            Actions = new[]
            {
                new ManagedAction("MyAction", "%this%")
            }
        };

        Compiler.BuildMsi(project);
    }
}

public class CustomActions
{
    [CustomAction]
    public static ActionResult MyAction(Session session)
    {
#if DEBUG
        System.Diagnostics.Debugger.Launch();
#endif
        session.Log("Begin CustomAction2 Hello World");

        return ActionResult.Success;
    }
}


text:
package org.apache.maven.plugin.eclipse.writers.workspace;

import java.io.File;

import junit.framework.TestCase;

public class EclipseCodeFormatterTest
    extends TestCase
{
    private static File basedir = new File( System.getProperty( "basedir", "." ) );

    public void testLoadFormatter()
        throws Exception
    {
        File testStyleFile = new File( basedir, "src/test/resources/projects/workspace-02/code-styles.xml" );

        EclipseCodeFormatterProfile formatter = new EclipseCodeFormatterProfile();
        formatter.init( testStyleFile.toURL(), null );

        assertEquals( "format-1", formatter.getProfileName() );

        // see integration test on workspace-02 for content validation
    }
}


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>io.hawt</groupId>
    <artifactId>project</artifactId>
    <version>1.5-SNAPSHOT</version>
  </parent>

  <modelVersion>4.0.0</modelVersion>
  <artifactId>hawtio-kubernetes</artifactId>
  <name>${project.artifactId}</name>
  <description>hawtio :: hawtio-kubernetes</description>

  <properties>
  </properties>

  <dependencies>
    <!-- logging -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j-version}</version>
    </dependency>
    <dependency>
      <groupId>io.hawt</groupId>
      <artifactId>hawtio-core</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>io.hawt</groupId>
      <artifactId>hawtio-git</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.aries.blueprint</groupId>
      <artifactId>org.apache.aries.blueprint.web</artifactId>
      <version>${blueprint-web-version}</version>
      <scope>compile</scope>
      <exclusions>
        <exclusion>
          <groupId>org.apache.geronimo.specs</groupId>
          <artifactId>geronimo-servlet_2.5_spec</artifactId>
        </exclusion>
        <!-- ignore old versions -->
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <!-- testing -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit-version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j-version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j-version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
package cmdtest

import (
	"io/ioutil"
	"net/http"
	"testing"

	"gopkg.in/check.v1"
)

type S struct{}

var _ = check.Suite(S{})

func Test(t *testing.T) {
	check.TestingT(t)
}

func (S) TestTransport(c *check.C) {
	var t http.RoundTripper = &Transport{
		Message: "Ok",
		Status:  http.StatusOK,
		Headers: map[string][]string{"Authorization": {"something"}},
	}
	req, _ := http.NewRequest("GET", "/", nil)
	r, err := t.RoundTrip(req)
	c.Assert(err, check.IsNil)
	c.Assert(r.StatusCode, check.Equals, http.StatusOK)
	defer r.Body.Close()
	b, _ := ioutil.ReadAll(r.Body)
	c.Assert(string(b), check.Equals, "Ok")
	c.Assert(r.Header.Get("Authorization"), check.Equals, "something")
}

func (S) TestConditionalTransport(c *check.C) {
	var t http.RoundTripper = &ConditionalTransport{
		Transport: Transport{
			Message: "Ok",
			Status:  http.StatusOK,
		},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/something"
		},
	}
	req, _ := http.NewRequest("GET", "/something", nil)
	r, err := t.RoundTrip(req)
	c.Assert(err, check.IsNil)
	c.Assert(r.StatusCode, check.Equals, http.StatusOK)
	defer r.Body.Close()
	b, _ := ioutil.ReadAll(r.Body)
	c.Assert(string(b), check.Equals, "Ok")
	req, _ = http.NewRequest("GET", "/", nil)
	r, err = t.RoundTrip(req)
	c.Assert(err, check.NotNil)
	c.Assert(err.Error(), check.Equals, "condition failed")
	c.Assert(r.StatusCode, check.Equals, http.StatusInternalServerError)
}

func (S) TestMultiConditionalTransport(c *check.C) {
	t1 := ConditionalTransport{
		Transport: Transport{
			Message: "Unauthorized",
			Status:  http.StatusUnauthorized,
		},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/something"
		},
	}
	t2 := ConditionalTransport{
		Transport: Transport{
			Message: "OK",
			Status:  http.StatusOK,
		},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/something"
		},
	}
	m := MultiConditionalTransport{
		ConditionalTransports: []ConditionalTransport{t1, t2},
	}
	c.Assert(m.ConditionalTransports, check.HasLen, 2)
	req, _ := http.NewRequest("GET", "/something", nil)
	r, err := m.RoundTrip(req)
	c.Assert(err, check.IsNil)
	c.Assert(r.StatusCode, check.Equals, http.StatusUnauthorized)
	c.Assert(m.ConditionalTransports, check.HasLen, 1)
	r, err = m.RoundTrip(req)
	c.Assert(err, check.IsNil)
	c.Assert(r.StatusCode, check.Equals, http.StatusOK)
	c.Assert(m.ConditionalTransports, check.HasLen, 0)
}

func (S) TestAnyConditionalTransport(c *check.C) {
	t1 := ConditionalTransport{
		Transport: Transport{
			Message: "some response",
			Status:  http.StatusUnauthorized,
		},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/foo" && req.Method == http.MethodPost
		},
	}
	t2 := ConditionalTransport{
		Transport: Transport{
			Message: "something else",
			Status:  http.StatusOK,
		},
		CondFunc: func(req *http.Request) bool {
			return req.URL.Path == "/bar"
		},
	}
	a := AnyConditionalTransport{
		ConditionalTransports: []ConditionalTransport{t1, t2},
	}
	req, _ := http.NewRequest(http.MethodGet, "/bar", nil)
	r, err := a.RoundTrip(req)
	c.Assert(err, check.IsNil)
	c.Assert(r.StatusCode, check.Equals, http.StatusOK)
	body, _ := ioutil.ReadAll(r.Body)
	c.Assert(string(body), check.Equals, "something else")
	r, err = a.RoundTrip(req)
	c.Assert(err, check.IsNil)
	c.Assert(r.StatusCode, check.Equals, http.StatusOK)
	body, _ = ioutil.ReadAll(r.Body)
	c.Assert(string(body), check.Equals, "something else")
	req, _ = http.NewRequest(http.MethodGet, "/foo", nil)
	r, err = a.RoundTrip(req)
	c.Assert(err, check.NotNil)
	c.Assert(err.Error(), check.Equals, "all conditions failed")
	c.Assert(r.StatusCode, check.Equals, http.StatusInternalServerError)
	req, _ = http.NewRequest(http.MethodPost, "/foo", nil)
	r, err = a.RoundTrip(req)
	c.Assert(err, check.IsNil)
	c.Assert(r.StatusCode, check.Equals, http.StatusUnauthorized)
	body, _ = ioutil.ReadAll(r.Body)
	c.Assert(string(body), check.Equals, "some response")
}


text:
<?php

namespace OhCacheTests\Adapters;

use OhCache\Adapters\AdapterMemcached;
use PHPUnit\Framework\TestCase;

/**
 * AdapterMemcachedTest
 */
class AdapterMemcachedTest extends TestCase
{
    /**
     * @var AdapterMemcached
     */
    private $adapter = null;

    private $name = null;

    public function setUp()
    {
        if (!class_exists('\Memcached')) {
            $this->markTestSkipped(
                'Memcached class is not present. Try installing Memcached (and the PHP driver)'
            );
            return;
        }
        $this->name = md5(__CLASS__);
        $cacheConfig = array(
            'prefix' => 'TEST_',
            'servers' => array(
                array(
                    'host' => 'localhost',
                    'port' => 11211,
                    'timeout' => 60,
                    'weight' => 1
                )
            )
        );
        $this->adapter = new AdapterMemcached($cacheConfig);
        $this->adapter->flush();
    }

    public function testSetGet()
    {
        $this->assertTrue($this->adapter->set($this->name, 'foo', 10));
        $this->assertFalse($this->adapter->get('foobarfoo'));
        $this->assertEquals('foo', $this->adapter->get($this->name));
    }

    public function testSetGetTtlExpired()
    {
        $this->assertTrue($this->adapter->set($this->name, 'slept', 1));
        sleep(2);
        $this->assertFalse($this->adapter->get($this->name));
    }

    public function testSetIfNotExistsGet()
    {
        $str = md5(time());
        $this->assertTrue($this->adapter->setIfNotExists($str, 'foobar', 10));
        $this->assertFalse($this->adapter->setIfNotExists($str, 'barfoo', 10));
    }

    public function testSetRenew()
    {
        $this->assertTrue($this->adapter->set($this->name, 'bar', 10));
        $this->assertTrue($this->adapter->renew($this->name, 10));
        $this->assertFalse($this->adapter->renew(md5(microtime()), 100));
    }

    public function testHas()
    {
        $this->assertTrue($this->adapter->set($this->name, 'foobar', 10));
        $this->assertTrue($this->adapter->has($this->name));
        $this->assertEquals('foobar', $this->adapter->get($this->name));
        $this->assertTrue($this->adapter->remove($this->name));
        $this->assertFalse($this->adapter->has($this->name));
    }

    public function testRemove()
    {
        $this->assertTrue($this->adapter->set($this->name, 'barfoo', 10));
        $this->assertTrue($this->adapter->remove($this->name));
        $this->assertFalse($this->adapter->has($this->name));
    }
}


text:
var newAdapterName = 'Dome';

function testSetAdapterState() {
  chrome.bluetooth.getAdapterState(function(state) {
    chrome.test.assertNoLastError();
    chrome.test.assertFalse(state.powered);
    chrome.test.assertTrue(state.name != newAdapterName);
    // TODO(tengs): Check if adapter is discoverable when the attribute is
    // exposed to the chrome.bluetooth API.
    setAdapterState();
  });
}

function setAdapterState() {
  var newState = {
    name: newAdapterName,
    powered: true,
    discoverable: true
  };

  chrome.bluetoothPrivate.setAdapterState(newState, function() {
    chrome.test.assertNoLastError();
    if (chrome.runtime.lastError)
      chrome.test.fail(chrome.runtime.lastError);
    checkFinalAdapterState();
  });
}

var adapterStateSet = false;
function checkFinalAdapterState() {
  chrome.bluetooth.getAdapterState(function(state) {
    chrome.test.assertNoLastError();
    chrome.test.assertTrue(state.powered);
    chrome.test.assertTrue(state.name == newAdapterName);
    // TODO(tengs): Check if adapter is discoverable when the attribute is
    // exposed to the chrome.bluetooth API.
    if (!adapterStateSet) {
      adapterStateSet = true;
      // Check indempotence of bluetoothPrivate.setAdapterState.
      setAdapterState();
    } else {
      chrome.test.succeed();
    }
  });
}

chrome.test.runTests([ testSetAdapterState ]);


text:
package com.example.android.pmdb;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

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

import javax.annotation.Generated;

@Generated("org.jsonschema2pojo")
public class ReviewsResult {

    @SerializedName("page")
    @Expose
    private int page;
    @SerializedName("results")
    @Expose
    private List<Review> reviews = new ArrayList<Review>();
    @SerializedName("total_pages")
    @Expose
    private int totalPages;
    @SerializedName("total_results")
    @Expose
    private int totalResults;

    /**
     *
     * @return
     * The page
     */
    public int getPage() {
        return page;
    }

    /**
     *
     * @param page
     * The page
     */
    public void setPage(int page) {
        this.page = page;
    }

    /**
     *
     * @return
     * The reviews
     */
    public List<Review> getReviews() {
        return reviews;
    }

    /**
     *
     * @param reviews
     * The reviews
     */
    public void setReviews(List<Review> reviews) {
        this.reviews = reviews;
    }

    /**
     *
     * @return
     * The totalPages
     */
    public int getTotalPages() {
        return totalPages;
    }

    /**
     *
     * @param totalPages
     * The totalPages
     */
    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    /**
     *
     * @return
     * The totalPages
     */
    public int getTotalResults() {
        return totalResults;
    }

    /**
     *
     * @param totalResults
     * The totalPages
     */
    public void setTotalResults(int totalResults) {
        this.totalResults = totalResults;
    }
}


text:
from thumt.optimizers.optimizers import AdamOptimizer
from thumt.optimizers.optimizers import AdadeltaOptimizer
from thumt.optimizers.optimizers import SGDOptimizer
from thumt.optimizers.optimizers import MultiStepOptimizer
from thumt.optimizers.optimizers import LossScalingOptimizer
from thumt.optimizers.schedules import LinearWarmupRsqrtDecay
from thumt.optimizers.schedules import PiecewiseConstantDecay
from thumt.optimizers.schedules import LinearExponentialDecay
from thumt.optimizers.clipping import (
    adaptive_clipper, global_norm_clipper, value_clipper)