text:
//// [index.ts]
// esm format file
import * as cjs from "package/cjs";
import * as mjs from "package/mjs";
import * as type from "package";
cjs;
mjs;
type;
import * as cjsi from "inner/a";
import * as mjsi from "inner/b";
import * as typei from "inner";
import * as ts from "inner/types";
cjsi.mjsSource;
mjsi.mjsSource;
typei.mjsSource;
ts.mjsSource;
//// [index.mts]
// esm format file
import * as cjs from "package/cjs";
import * as mjs from "package/mjs";
import * as type from "package";
cjs;
mjs;
type;
import * as cjsi from "inner/a";
import * as mjsi from "inner/b";
import * as typei from "inner";
import * as ts from "inner/types";
cjsi.mjsSource;
mjsi.mjsSource;
typei.mjsSource;
ts.mjsSource;
//// [index.cts]
// cjs format file
import * as cjs from "package/cjs";
import * as mjs from "package/mjs";
import * as type from "package";
cjs;
mjs;
type;
import * as cjsi from "inner/a";
import * as mjsi from "inner/b";
import * as typei from "inner";
import * as ts from "inner/types";
cjsi.cjsSource;
mjsi.cjsSource;
typei.implicitCjsSource;
ts.cjsSource;
//// [index.d.ts]
// cjs format file
import * as cjs from "inner/a";
import * as mjs from "inner/b";
import * as type from "inner";
import * as ts from "inner/types";
export { cjs };
export { mjs };
export { type };
export { ts };
export const implicitCjsSource = true;
//// [index.d.mts]
// esm format file
import * as cjs from "inner/a";
import * as mjs from "inner/b";
import * as type from "inner";
import * as ts from "inner/types";
export { cjs };
export { mjs };
export { type };
export { ts };
export const mjsSource = true;
//// [index.d.cts]
// cjs format file
import * as cjs from "inner/a";
import * as mjs from "inner/b";
import * as type from "inner";
import * as ts from "inner/types";
export { cjs };
export { mjs };
export { type };
export { ts };
export const cjsSource = true;
//// [package.json]
{
    "name": "package",
    "private": true,
    "type": "module",
    "exports": {
        "./cjs": "./index.cjs",
        "./mjs": "./index.mjs",
        ".": "./index.js"
    }
}
//// [package.json]
{
    "name": "inner",
    "private": true,
    "exports": {
        "./a": {
            "require": "./index.cjs",
            "node": "./index.mjs"
        },
        "./b": {
            "import": "./index.mjs",
            "node": "./index.cjs"
        },
        ".": {
            "import": "./index.mjs",
            "node": "./index.js"
        },
        "./types": {
            "types": {
                "import": "./index.d.mts",
                "require": "./index.d.cts",
            },
            "node": {
                "import": "./index.mjs",
                "require": "./index.cjs"
            }
        }
    }
}

//// [index.mjs]
// esm format file
import * as cjs from "package/cjs";
import * as mjs from "package/mjs";
import * as type from "package";
cjs;
mjs;
type;
import * as cjsi from "inner/a";
import * as mjsi from "inner/b";
import * as typei from "inner";
import * as ts from "inner/types";
cjsi.mjsSource;
mjsi.mjsSource;
typei.mjsSource;
ts.mjsSource;
//// [index.cjs]
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
// cjs format file
const cjs = __importStar(require("package/cjs"));
const mjs = __importStar(require("package/mjs"));
const type = __importStar(require("package"));
cjs;
mjs;
type;
const cjsi = __importStar(require("inner/a"));
const mjsi = __importStar(require("inner/b"));
const typei = __importStar(require("inner"));
const ts = __importStar(require("inner/types"));
cjsi.cjsSource;
mjsi.cjsSource;
typei.implicitCjsSource;
ts.cjsSource;
//// [index.js]
// esm format file
import * as cjs from "package/cjs";
import * as mjs from "package/mjs";
import * as type from "package";
cjs;
mjs;
type;
import * as cjsi from "inner/a";
import * as mjsi from "inner/b";
import * as typei from "inner";
import * as ts from "inner/types";
cjsi.mjsSource;
mjsi.mjsSource;
typei.mjsSource;
ts.mjsSource;

//// [index.d.mts]
export {};
//// [index.d.cts]
export {};
//// [index.d.ts]
export {};


text:
template <auto V, typename... Ts, typename Parameters> static constexpr auto apply(pcre::push_property_name, ctll::term<V>, pcre_context<ctll::list<Ts...>, Parameters> subject) {
	return pcre_context{ctll::push_front(property_name<V>(), subject.stack), subject.parameters};
}
// push_property_name (concat)
template <auto... Str, auto V, typename... Ts, typename Parameters> static constexpr auto apply(pcre::push_property_name, ctll::term<V>, pcre_context<ctll::list<property_name<Str...>, Ts...>, Parameters> subject) {
	return pcre_context{ctll::push_front(property_name<Str..., V>(), ctll::list<Ts...>()), subject.parameters};
}

// push_property_value
template <auto V, typename... Ts, typename Parameters> static constexpr auto apply(pcre::push_property_value, ctll::term<V>, pcre_context<ctll::list<Ts...>, Parameters> subject) {
	return pcre_context{ctll::push_front(property_value<V>(), subject.stack), subject.parameters};
}
// push_property_value (concat)
template <auto... Str, auto V, typename... Ts, typename Parameters> static constexpr auto apply(pcre::push_property_value, ctll::term<V>, pcre_context<ctll::list<property_value<Str...>, Ts...>, Parameters> subject) {
	return pcre_context{ctll::push_front(property_value<Str..., V>(), ctll::list<Ts...>()), subject.parameters};
}

// make_property
template <auto V, auto... Name, typename... Ts, typename Parameters> static constexpr auto apply(pcre::make_property, ctll::term<V>, [[maybe_unused]] pcre_context<ctll::list<property_name<Name...>, Ts...>, Parameters> subject) {
	return ctll::reject{};
	//constexpr std::array<char, sizeof...(Name)> name{static_cast<char>(Name)...};
	//constexpr auto p = uni::__binary_prop_from_string(get_string_view(name));
    //
	//if constexpr (p == uni::__binary_prop::unknown) {
	//	return ctll::reject{};
	//} else {
	//	return pcre_context{ctll::push_front(binary_property<p>(), ctll::list<Ts...>()), subject.parameters};
	//}
}

// make_property
template <auto V, auto... Value, auto... Name, typename... Ts, typename Parameters> static constexpr auto apply(pcre::make_property, ctll::term<V>, [[maybe_unused]] pcre_context<ctll::list<property_value<Value...>, property_name<Name...>, Ts...>, Parameters> subject) {
	return ctll::reject{};
	//constexpr auto prop = property_builder<Name...>::template get<Value...>();
	//
	//if constexpr (std::is_same_v<decltype(prop), ctll::reject>) {
	//	return ctll::reject{};
	//} else {
	//	return pcre_context{ctll::push_front(prop, ctll::list<Ts...>()), subject.parameters};
	//}
}

// make_property_negative
template <auto V, auto... Name, typename... Ts, typename Parameters> static constexpr auto apply(pcre::make_property_negative, ctll::term<V>, [[maybe_unused]] pcre_context<ctll::list<property_name<Name...>, Ts...>, Parameters> subject) {
	return ctll::reject{};
	//constexpr std::array<char, sizeof...(Name)> name{static_cast<char>(Name)...};
	//constexpr auto p = uni::__binary_prop_from_string(get_string_view(name));
    //
	//if constexpr (p == uni::__binary_prop::unknown) {
	//	return ctll::reject{};
	//} else {
	//	return pcre_context{ctll::push_front(negate<binary_property<p>>(), ctll::list<Ts...>()), subject.parameters};
	//}
}

// make_property_negative
template <auto V, auto... Value, auto... Name, typename... Ts, typename Parameters> static constexpr auto apply(pcre::make_property_negative, ctll::term<V>, [[maybe_unused]] pcre_context<ctll::list<property_value<Value...>, property_name<Name...>, Ts...>, Parameters> subject) {
	return ctll::reject{};
	//constexpr auto prop = property_builder<Name...>::template get<Value...>();
	//
	//if constexpr (std::is_same_v<decltype(prop), ctll::reject>) {
	//	return ctll::reject{};
	//} else {
	//	return pcre_context{ctll::push_front(negate<decltype(prop)>(), ctll::list<Ts...>()), subject.parameters};
	//}
}

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

use Hydrastic\Service\Yaml as YamlService;
use Hydrastic\Service\Finder as FinderService;
use Hydrastic\Service\Util as UtilService;
use Hydrastic\Service\Twig as TwigService;
use Hydrastic\Service\TextProcessor as TextProcessorService;

class TextProcessorServiceTest extends PHPUnit_Framework_TestCase
{

	protected $dic = array();

	public function setUp() {

		$this->fixDir = __DIR__.'/../fixtures/set1/';

		$this->dic = new Pimple();
		$this->dic['yaml']   = $this->dic->share(function ($c) { return new YamlService($c); });
		$this->dic['conf'] = $this->dic['yaml']['parser']->parse(file_get_contents($this->fixDir.'hydrastic-conf-1.yml'));
		$this->dic['hydrastic_dir'] = __DIR__.'/../../../';
		$this->dic['working_directory'] = $this->fixDir;

		$this->dic['taxonomy'] = $this->dic->share(function ($c) { return new Taxonomy($c); });
		$this->dic['util'] = $this->dic->share(function ($c) { return new UtilService($c); });
		$this->dic['twig']   = $this->dic->share(function ($c) { return new TwigService($c); });
		$this->dic['textprocessor']   = $this->dic->share(function ($c) { return new TextProcessorService($c); });
		$this->dic['finder'] = $this->dic->share(function ($c) { return new FinderService($c); });

	}

	public function testRegisteringExtensions()
	{
		$processor = $this->dic['textprocessor']['markdown'];
		$this->assertTrue(in_array('md', $this->dic['txt_extensions_registered']), 'Markdown service registers .md extension');

		$processor = $this->dic['textprocessor']['texy'];
		$this->assertTrue(in_array('texy', $this->dic['txt_extensions_registered']), 'Texy service registers .texy extension is registered.');

		$processor = $this->dic['textprocessor']['markdown_extra'];
		$this->assertTrue(in_array('mdextra', $this->dic['txt_extensions_registered']), 'MarkdownExtra service registers .md extension');

		$processor = $this->dic['textprocessor']['restructuredtext'];
		$this->assertTrue(in_array('rest', $this->dic['txt_extensions_registered']), 'ReST service registers .rest extension');

		$processor = $this->dic['textprocessor']['textile'];
		$this->assertTrue(in_array('textile', $this->dic['txt_extensions_registered']), 'Textile service registers .textile extension');

	}
}


text:
#ifndef CRIMILD_RENDERING_RENDER_RESOURCE_
#define CRIMILD_RENDERING_RENDER_RESOURCE_

#include "Foundation/Containers/Map.hpp"
#include "Foundation/Containers/Set.hpp"
#include "Foundation/SharedObject.hpp"
#include "Foundation/Singleton.hpp"

namespace crimild {

    template< typename RenderResourceType >
    class [[deprecated]] RenderResourceManager {
    public:
        virtual ~RenderResourceManager( void ) noexcept
        {
            clear();
        }

        virtual crimild::Bool bind( RenderResourceType *resource ) noexcept
        {
            m_resources.insert( resource );
            return true;
        }

        virtual crimild::Bool unbind( RenderResourceType *resource ) noexcept
        {
            m_resources.remove( resource );
            return true;
        }

        virtual void clear( void ) noexcept
        {
            m_resources.each(
                [ this ]( RenderResourceType *resource ) {
                    unbind( resource );
                }
            );
            m_resources.clear();
        }

        inline RenderResourceType *first( void ) noexcept
        {
            return m_resources.first();
        }

    private:
        Set< RenderResourceType * > m_resources;
    };

    // TODO: deprecate this in favor of keeping track of renderables in managers and
    // using messaging for bind/update/unbind
    template< typename T >
    class [[deprecated]] RenderResourceImpl {
    public:
        virtual ~RenderResourceImpl( void ) noexcept
        {
            if ( manager != nullptr ) {
                manager->unbind( static_cast< T * >( this ) );
            }
        }

        RenderResourceManager< T > *manager = nullptr;
    };

    template< typename RenderResourceType >
    class [[deprecated]] RenderResourceLibrary : public StaticSingleton< RenderResourceLibrary< RenderResourceType > > {
    private:
        using Builder = std::function< SharedPointer< RenderResourceType >( void ) >;

    public:
        RenderResourceLibrary( void ) noexcept { }
        virtual ~RenderResourceLibrary( void ) = default;

        void add( std::string name, SharedPointer< RenderResourceType > const &shader )
        {
            m_resources[ name ] = shader;
        }

        void add( std::string name, Builder const &builder )
        {
            m_builders[ name ] = builder;
        }

        RenderResourceType *get( std::string name )
        {
            if ( !m_resources.contains( name ) && m_builders.contains( name ) ) {
                // Lazy create and add a new resource instance
                // if the resource does not exist but there's a builder registered
                add( name, m_builders[ name ]() );
            }

            // Check again, because we may have just added the resource
            if ( !m_resources.contains( name ) ) {
                return nullptr;
            }

            return crimild::get_ptr( m_resources[ name ] );
        }

    private:
        Map< std::string, SharedPointer< RenderResourceType > > m_resources;
        Map< std::string, Builder > m_builders;
    };

}

#endif


text:
package com.nathanson.meterreader.fragment;

import android.app.Activity;
import android.app.Fragment;

import com.nathanson.meterreader.activity.MainActivity;

public class BaseFragment extends Fragment {

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        ((MainActivity) activity).onSectionAttached(this);
    }

}


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

<title>Class Hierarchy</title>
<meta name="date" content="2016-02-03">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For All Packages

Package Hierarchies:

cycles,

servlets

Class Hierarchy

java.lang.Object

cycles.CycleDBHandler

servlets.CyclesServlet.Couple

servlets.CyclesServlet.Tuple

HttpServlet

servlets.LogoutServlet

HttpServlet

servlets.LoginServlet

HttpServlet

servlets.ModifyProfileServlet

HttpServlet

servlets.DeleteServlet

HttpServlet

servlets.CyclesServlet

HttpServlet

servlets.ProfileServlet

HttpServlet

servlets.RegisterUserServlet

HttpServlet

servlets.AdminServlet

HttpServlet

servlets.OfferServlet

HttpServlet

servlets.HomeServlet

HttpServlet

servlets.NeedServlet

HttpServlet

servlets.AddServiceServlet

HttpServlet

servlets.NewsFeedServlet

cycles.SQLCycleDB

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
import { useWith, identity } from 'ramda';
import { equals } from './internal/versionCompare';
import getOSVersion from './getOSVersion';

export default useWith(equals, [ identity, getOSVersion ]);


text:
cd /d %~dp0

@echo off

cd  NFMasterServer

echo Starting NFMasterServer...
start "" "NFPluginLoader_d.exe"

choice /t 2 /d y /n >nul
cd  ..
cd  NFWorldServer
echo Starting NFWorldServer...
start "" "NFPluginLoader_d.exe"

choice /t 5 /d y /n >nul

cd  ..
cd  NFLoginServer
echo Starting NFLoginServer...
start "" "NFPluginLoader_d.exe"

choice /t 2 /d y /n >nul

cd  ..
cd  NFGameServer1
echo Starting NFGameServer1...
start "" "NFPluginLoader_d.exe"

choice /t 4 /d y /n >nul

cd  ..
cd  NFProxyServer1
echo Starting NFProxyServer1...
start "" "NFPluginLoader_d.exe"


text:
package com.google.ads.googleads.v10.enums;

public final class KeywordPlanConceptGroupTypeProto {
  private KeywordPlanConceptGroupTypeProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v10_enums_KeywordPlanConceptGroupTypeEnum_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v10_enums_KeywordPlanConceptGroupTypeEnum_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\nDgoogle/ads/googleads/v10/enums/keyword" +
      "_plan_concept_group_type.proto\022\036google.a" +
      "ds.googleads.v10.enums\"\212\001\n\037KeywordPlanCo" +
      "nceptGroupTypeEnum\"g\n\033KeywordPlanConcept" +
      "GroupType\022\017\n\013UNSPECIFIED\020\000\022\013\n\007UNKNOWN\020\001\022" +
      "\t\n\005BRAND\020\002\022\020\n\014OTHER_BRANDS\020\003\022\r\n\tNON_BRAN" +
      "D\020\004B\372\001\n\"com.google.ads.googleads.v10.enu" +
      "msB KeywordPlanConceptGroupTypeProtoP\001ZC" +
      "google.golang.org/genproto/googleapis/ad" +
      "s/googleads/v10/enums;enums\242\002\003GAA\252\002\036Goog" +
      "le.Ads.GoogleAds.V10.Enums\312\002\036Google\\Ads\\" +
      "GoogleAds\\V10\\Enums\352\002\"Google::Ads::Googl" +
      "eAds::V10::Enumsb\006proto3"
    };
    descriptor = com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        });
    internal_static_google_ads_googleads_v10_enums_KeywordPlanConceptGroupTypeEnum_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_google_ads_googleads_v10_enums_KeywordPlanConceptGroupTypeEnum_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v10_enums_KeywordPlanConceptGroupTypeEnum_descriptor,
        new java.lang.String[] { });
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
@class AppState;
class Browser;
class GURL;
@protocol StartupInformation;
struct UrlLoadParams;
@class URLOpenerParams;

// Protocol for object that can open new tabs during application launch.
@protocol TabOpening<NSObject>

// Dismisses any modal view, excluding the omnibox if |dismissOmnibox| is NO,
// then opens either a normal or incognito tab with |url|. After opening |url|,
// run completion |handler| if it is not nil. After Tab is opened the virtual
// URL is set to the pending navigation item.
- (void)dismissModalsAndOpenSelectedTabInMode:
            (ApplicationModeForTabOpening)targetMode
                            withUrlLoadParams:
                                (const UrlLoadParams&)urlLoadParams
                               dismissOmnibox:(BOOL)dismissOmnibox
                                   completion:(ProceduralBlock)completion;

// Dismisses any modal view, excluding the omnibox if |dismissOmnibox| is NO,
// then opens the list of URLs in |URLs| in either normal or incognito.
// After opening the array of URLs, run completion |handler| if it not nil.
- (void)dismissModalsAndOpenMultipleTabsInMode:
            (ApplicationModeForTabOpening)targetMode
                                          URLs:(const std::vector<GURL>&)URLs
                                dismissOmnibox:(BOOL)dismissOmnibox
                                    completion:(ProceduralBlock)completion;

// Creates a new tab if the launch options are not null.
- (void)openTabFromLaunchWithParams:(URLOpenerParams*)params
                 startupInformation:(id<StartupInformation>)startupInformation
                           appState:(AppState*)appState;

// Returns whether an NTP tab should be opened when the specified browser is
// made current.
- (BOOL)shouldOpenNTPTabOnActivationOfBrowser:(Browser*)browser;

// Returns a block that can be executed on the new tab to trigger one of the
// commands. This block can be passed to
// |dismissModalsAndOpenSelectedTabInMode:withURL:transition:completion:|.
// This block must only be executed if new tab opened on NTP.
- (ProceduralBlock)completionBlockForTriggeringAction:
    (NTPTabOpeningPostOpeningAction)action;

// Whether the |URL| is already opened, in regular mode.
- (BOOL)URLIsOpenedInRegularMode:(const GURL&)URL;

@end

#endif  // IOS_CHROME_APP_APPLICATION_DELEGATE_TAB_OPENING_H_


text:
<?php

namespace Archmage\AdminBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Archmage\AdminBundle\Model\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class UserListener
{

    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof UserInterface) {
            $password = $this->encodePassword($entity, $entity->getPassword(), $entity->getSalt());
            $entity->setPassword($password, false);
        }
    }

    public function preUpdate(PreUpdateEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof UserInterface) {
            if ($args->hasChangedField('password')) {
                if ($entity->getPassword()) {
                    $password = $this->encodePassword($entity, $entity->getPassword(), $entity->getSalt());
                    $args->setNewValue('password', $password);
                } else {
                    $args->setNewValue('password', $args->getOldValue('password'));
                    $args->setNewValue('salt', $args->getOldValue('salt'));
                }
            }
        }
    }

    private function encodePassword($entity, $password, $salt)
    {
        $factory = $this->container->get('security.encoder_factory');
        $encoder = $factory->getEncoder($entity);
        return $encoder->encodePassword($password, $salt);
    }

}


text:
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------

/*
 * Created on Jul 21, 2006
 */
package org.globus.cog.karajan.util;

import java.util.ArrayList;

/**
 *
An implementation of a {@link java.util.List} that tracks
 * typical required capacities and initializes new instances
 * with average sizes inferred from historical information.

 *
 *
The constructor allows initialization with different contexts,
 * each of which represents a different set of historical
 * information

 *
 *
 * @author Mihael Hategan
 *
 */
public class AdaptiveArrayList<T> extends ArrayList<T> {
	private final Context context;

	public AdaptiveArrayList(Context context) {
		super(context.getSize());
		this.context = context;
		context.incLists();
	}

	public boolean add(T o) {
		context.incItems();
		return super.add(o);
	}

	public static class Context {
		private int lists, items;

		public Context() {
			lists = 1;
			items = 2;
		}

		public Context(int lists, int items) {
			this.lists = lists;
			this.items = items;
		}

		public int getSize() {
			return items / lists + 2;
		}

		public synchronized void incLists() {
			lists++;
		}

		public synchronized void incItems() {
			items++;
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Govt Forest Exp. Stn Meguro 105: 93 (1958)

#### Original name
Cladosporium carpesii Sawada

### Remarks
null


text:
package org.elasticsearch.xpack.sql.cli;

import org.elasticsearch.Version;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.sql.client.ClientVersion;

public class VersionTests extends ESTestCase {
    public void testVersionIsCurrent() {
        /* This test will only work properly in gradle because in gradle we run the tests
         * using the jar. */
        assertEquals(Version.CURRENT.major, ClientVersion.CURRENT.major);
        assertEquals(Version.CURRENT.minor, ClientVersion.CURRENT.minor);
        assertEquals(Version.CURRENT.revision, ClientVersion.CURRENT.revision);
    }

}


text:
import java.util.Scanner;
import java.text.DecimalFormat;

public class TheSmallestOf3Nums {

	public static void main(String[] args) {
		DecimalFormat format = new DecimalFormat();
        format.setDecimalSeparatorAlwaysShown(false);

            Scanner in = new Scanner(System.in);
            double a = in.nextDouble();
            double b = in.nextDouble();
            double c = in.nextDouble();

            if (a<b && a<c) {
                System.out.println(format.format(a));
            }
            else if (b<a && b<c) {
                System.out.println(format.format(b));
            }
            else {
                System.out.println(format.format(c));
            }

	}

}


text:
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <stdbool.h>
#include <stdio.h>

enum {
    SCREEN_WIDTH = 640,
    SCREEN_HEIGHT = 480,
};

/* Start up SDL and creates window */
static bool init();
/* Loads media */
static bool load_media();
/* Frees media and shuts down SDL */
static void close();
/* Loads individual image */
static SDL_Surface * load_surface(const char *path);

SDL_Window *g_window = NULL;
SDL_Surface *g_screensurface = NULL;
SDL_Surface *g_imgsurface = NULL;

static bool
init()
{
    if(SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("SDL could not initialize! SDL Error: %s\n",
               SDL_GetError());
        return false;
    }
    /* Create window */
    g_window = SDL_CreateWindow("SDL Tutorial",
                                SDL_WINDOWPOS_UNDEFINED,
                                SDL_WINDOWPOS_UNDEFINED,
                                SCREEN_WIDTH,
                                SCREEN_HEIGHT,
                                SDL_WINDOW_SHOWN);
    if(g_window == NULL) {
        printf("Window could not be created! SDL Error: %s\n",
               SDL_GetError());
        return false;
    }

    int img_flags = IMG_INIT_PNG;
    /* see IMG_Init doc */
    if((IMG_Init(img_flags) & img_flags) != img_flags) {
        printf("SDL_image could not initialize! SDL_image Error: %s\n",
               IMG_GetError());
        return false;
    }

    /* Get window surface */
    g_screensurface = SDL_GetWindowSurface(g_window);
    return true;
}

static bool
load_media()
{
    const char *img_path = "loadingpng.png";
    g_imgsurface = load_surface(img_path);
    if(g_imgsurface == NULL) {
        printf("Failed to load image %s!\n", img_path);
        return false;
    }
    return true;
}

static void
close()
{
    SDL_FreeSurface(g_imgsurface);
    g_imgsurface = NULL;

    SDL_DestroyWindow(g_window);
    g_window = NULL;

    IMG_Quit();
    SDL_Quit();
}

static SDL_Surface *
load_surface(const char *path)
{
    SDL_Surface *optimized_surface = NULL;

    SDL_Surface *surface = IMG_Load(path);
    if(surface == NULL) {
        printf("Unable to load image %s! SDL_image Error: %s\n",
               path, IMG_GetError());
    } else {
        optimized_surface = SDL_ConvertSurface(surface,
                                               g_screensurface->format,
                                               0);
        if(optimized_surface == NULL) {
            printf("Unable to optimize image %s! SDL Error: %s\n",
                   path, SDL_GetError());
        }
        SDL_FreeSurface(surface);
    }
    return optimized_surface;
}

int main(int argc, char *argv[])
{
    if(init() == false) {
        printf("Failed to initialize!\n");
        return 1;
    }
    if(load_media() == false) {
        printf("Failed to load media!\n");
        return 1;
    }
    bool quit = false;
    SDL_Event e;

    while(!quit) {
        while(SDL_PollEvent(&e) != 0) {
            if(e.type == SDL_QUIT) {
                quit = true;
            }
        }

        SDL_BlitSurface(g_imgsurface, NULL, g_screensurface, NULL);
        SDL_UpdateWindowSurface(g_window);
    }
    close();
    return 0;
}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Settings'
        db.create_table(u'sync_settings', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('action', self.gf('django.db.models.fields.PositiveSmallIntegerField')(db_index=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=100)),
            ('start_col', self.gf('django.db.models.fields.CharField')(max_length=10, blank=True)),
            ('start_row', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
            ('end_col', self.gf('django.db.models.fields.CharField')(max_length=10, blank=True)),
            ('end_row', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
            ('main_model', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('created_at', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('updated_at', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('processor', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('worksheet', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('include_header', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('filename', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('buffer_file', self.gf('django.db.models.fields.files.FileField')(db_index=True, max_length=100, blank=True)),
            ('queryset', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('data_action', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
        ))
        db.send_create_signal(u'sync', ['Settings'])

        # Adding model 'Field'
        db.create_table(u'sync_field', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('position', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
            ('attribute', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('skip', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('converters', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('settings', self.gf('django.db.models.fields.related.ForeignKey')(related_name='fields', to=orm['sync.Settings'])),
        ))
        db.send_create_signal(u'sync', ['Field'])

        # Adding model 'Report'
        db.create_table(u'sync_report', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('action', self.gf('django.db.models.fields.PositiveSmallIntegerField')(db_index=True)),
            ('buffer_file', self.gf('django.db.models.fields.files.FileField')(db_index=True, max_length=100, blank=True)),
            ('status', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=1)),
            ('started_at', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('completed_at', self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True)),
            ('updated_at', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('settings', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='reports', null=True, to=orm['sync.Settings'])),
        ))
        db.send_create_signal(u'sync', ['Report'])

        # Adding model 'Error'
        db.create_table(u'sync_error', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('position', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True)),
            ('report', self.gf('django.db.models.fields.related.ForeignKey')(related_name='errors', to=orm['sync.Report'])),
            ('message', self.gf('django.db.models.fields.TextField')(max_length=10000)),
            ('step', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=10)),
            ('input_position', self.gf('django.db.models.fields.CharField')(max_length=10, blank=True)),
            ('input_value', self.gf('django.db.models.fields.TextField')(max_length=60000, null=True, blank=True)),
        ))
        db.send_create_signal(u'sync', ['Error'])

    def backwards(self, orm):
        # Deleting model 'Settings'
        db.delete_table(u'sync_settings')

        # Deleting model 'Field'
        db.delete_table(u'sync_field')

        # Deleting model 'Report'
        db.delete_table(u'sync_report')

        # Deleting model 'Error'
        db.delete_table(u'sync_error')

    models = {
        u'sync.error': {
            'Meta': {'object_name': 'Error'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'input_position': ('django.db.models.fields.CharField', [], {'max_length': '10', 'blank': 'True'}),
            'input_value': ('django.db.models.fields.TextField', [], {'max_length': '60000', 'null': 'True', 'blank': 'True'}),
            'message': ('django.db.models.fields.TextField', [], {'max_length': '10000'}),
            'position': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'report': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'errors'", 'to': u"orm['sync.Report']"}),
            'step': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '10'})
        },
        u'sync.field': {
            'Meta': {'ordering': "['position']", 'object_name': 'Field'},
            'attribute': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'converters': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'position': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'settings': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'fields'", 'to': u"orm['sync.Settings']"}),
            'skip': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
        },
        u'sync.report': {
            'Meta': {'ordering': "('-id',)", 'object_name': 'Report'},
            'action': ('django.db.models.fields.PositiveSmallIntegerField', [], {'db_index': 'True'}),
            'buffer_file': ('django.db.models.fields.files.FileField', [], {'db_index': 'True', 'max_length': '100', 'blank': 'True'}),
            'completed_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'settings': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'reports'", 'null': 'True', 'to': u"orm['sync.Settings']"}),
            'started_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1'}),
            'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
        },
        u'sync.settings': {
            'Meta': {'ordering': "('-id',)", 'object_name': 'Settings'},
            'action': ('django.db.models.fields.PositiveSmallIntegerField', [], {'db_index': 'True'}),
            'buffer_file': ('django.db.models.fields.files.FileField', [], {'db_index': 'True', 'max_length': '100', 'blank': 'True'}),
            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'data_action': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'end_col': ('django.db.models.fields.CharField', [], {'max_length': '10', 'blank': 'True'}),
            'end_row': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'include_header': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'main_model': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'processor': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'queryset': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
            'start_col': ('django.db.models.fields.CharField', [], {'max_length': '10', 'blank': 'True'}),
            'start_row': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'worksheet': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
        }
    }

    complete_apps = ['sync']


text:
<?php

namespace Magento\Store\Model\Config\Reader\Source\Dynamic;

use Magento\Framework\App\Config\Scope\Converter;
use Magento\Store\Model\ResourceModel\Config\Collection\ScopedFactory;
use Magento\Framework\App\Config\Reader\Source\SourceInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\WebsiteFactory;

/**
 * Class for retrieving configuration from DB by website scope
 */
class Website implements SourceInterface
{
    /**
     * @var ScopedFactory
     */
    private $collectionFactory;

    /**
     * @var Converter
     */
    private $converter;

    /**
     * @var WebsiteFactory
     */
    private $websiteFactory;

    /**
     * @var DefaultScope
     */
    private $defaultScope;

    /**
     * @param ScopedFactory $collectionFactory
     * @param Converter $converter
     * @param WebsiteFactory $websiteFactory
     * @param DefaultScope $defaultScope
     */
    public function __construct(
        ScopedFactory $collectionFactory,
        Converter $converter,
        WebsiteFactory $websiteFactory,
        DefaultScope $defaultScope
    ) {
        $this->collectionFactory = $collectionFactory;
        $this->converter = $converter;
        $this->websiteFactory = $websiteFactory;
        $this->defaultScope = $defaultScope;
    }

    /**
     * Retrieve config by website scope
     *
     * @param string|null $scopeCode
     * @return array
     */
    public function get($scopeCode = null)
    {
        try {
            $website = $this->websiteFactory->create();
            $website->load($scopeCode);
            $collection = $this->collectionFactory->create(
                ['scope' => ScopeInterface::SCOPE_WEBSITES, 'scopeId' => $website->getId()]
            );
            $config = [];
            foreach ($collection as $item) {
                $config[$item->getPath()] = $item->getValue();
            }
            return array_replace_recursive($this->defaultScope->get(), $this->converter->convert($config));
        } catch (\DomainException $e) {
            return [];
        }
    }
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Streams;
using UnitTests.GrainInterfaces;

namespace UnitTests.Grains
{

    [ImplicitStreamSubscription("red")]
    [ImplicitStreamSubscription("blue")]
    public class MultipleImplicitSubscriptionGrain : Grain, IMultipleImplicitSubscriptionGrain
    {
        private ILogger logger;
        private IAsyncStream<int> redStream, blueStream;
        private int redCounter, blueCounter;

        public MultipleImplicitSubscriptionGrain(ILoggerFactory loggerFactory)
        {
            this.logger = loggerFactory.CreateLogger("MultipleImplicitSubscriptionGrain " + base.IdentityString);
        }

        public override async Task OnActivateAsync(CancellationToken cancellationToken)
        {
            logger.LogInformation("OnActivateAsync");

            var streamProvider = this.GetStreamProvider("SMSProvider");
            redStream = streamProvider.GetStream<int>(this.GetPrimaryKey(), "red");
            blueStream = streamProvider.GetStream<int>(this.GetPrimaryKey(), "blue");

            await redStream.SubscribeAsync(
                (e, t) =>
                {
                    logger.LogInformation("Received a red event {Event}", e);
                    redCounter++;
                    return Task.CompletedTask;
                });

            await blueStream.SubscribeAsync(
                (e, t) =>
                {
                    logger.LogInformation("Received a blue event {Event}", e);
                    blueCounter++;
                    return Task.CompletedTask;
                });
        }

        public Task<Tuple<int, int>> GetCounters()
        {
            return Task.FromResult(new Tuple<int, int>(redCounter, blueCounter));
        }
    }
}


text:
package net.researchgate.restdsl.util;

import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

//TODO: prettify
public final class BeanUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(BeanUtils.class);

    private BeanUtils() {
    }

    /*
     * Copies the values of the merge Properties from the right hand side bean to the left side if the left bean's value
     * is null. Properties that don't have a getter or a setter will be ignored.
     *
     * @param target          target
     * @param from            from
     * @param mergeProperties merge props
     * @throws Exception when sth. went wrong
     */
    public static <T> boolean merge(T target, T from, Set<String> mergeProperties) throws Exception {
        return merge(target, from, mergeProperties, NewValueNotNullAndOldValueIsNullPredicate.INSTANCE);
    }

    /*
     * Copies the values of the merge Properties from the right hand side bean to the left side if the copyPredicate returns
     * true. Properties that don't have a getter or a setter will be ignored.
     * The triple of the predicate has: The name of the property, the old value and the new value
     * @param target          target
     * @param from            from
     * @param mergeProperties merge props
     * @param copyPredicate the field will be copy if this predicate returns true
     * @throws Exception when sth. went wrong
     */
    public static <T> boolean merge(T target, T from, Set<String> mergeProperties, Predicate<PropertyChange> copyPredicate) throws Exception {
        LOGGER.debug("* merging target '{}' with data from '{}'", target, from);
        BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());

        boolean updated = false;

        // Iterate over all the attributes
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            String propertyName = descriptor.getName();
            if (mergeProperties != null && !mergeProperties.contains(propertyName)) {
                // LOGGER.debug("+ skipping property '{}' which is not in mergeProperties", propertyName);
                continue;
            }

            Method readMethod = descriptor.getReadMethod();
            Method writeMethod = descriptor.getWriteMethod();
            if (readMethod == null || writeMethod == null) {
                // LOGGER.debug("+ skipping property '{}' with getter '{}' and setter '{}'", new Object[] {
                // propertyName, readMethod, writeMethod });
                continue;
            }

            // LOGGER.debug("+ merging property '{}': getter='{}', setter='{}'", new Object[] { propertyName,
            // readMethod, writeMethod });
            Object originalValue = readMethod.invoke(target);
            Object newValue = readMethod.invoke(from);

            if (copyPredicate.apply(new PropertyChange(propertyName, originalValue, newValue))) {
                writeMethod.invoke(target, newValue);
                updated = true;
            }
        }
        return updated;
    }

    public static <T> boolean deepMerge(T target, T from, Map<String, MergeConfig> mergeProperties) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());

        boolean updated = false;

        boolean includeAllKeys = mergeProperties.containsKey("*");

        // Iterate over all the attributes
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            String propertyName = descriptor.getName();
            if (!includeAllKeys && !mergeProperties.keySet().contains(propertyName)) {
                // LOGGER.debug("+ skipping property '{}' which is not in mergeProperties", propertyName);
                continue;
            }

            Method readMethod = descriptor.getReadMethod();
            Method writeMethod = descriptor.getWriteMethod();
            if (readMethod == null || writeMethod == null) {
                // LOGGER.debug("+ skipping property '{}' with getter '{}' and setter '{}'", new Object[] {
                // propertyName, readMethod, writeMethod });
                continue;
            }

            // LOGGER.debug("+ merging property '{}': getter='{}', setter='{}'", new Object[] { propertyName,
            // readMethod, writeMethod });
            Object originalValue = readMethod.invoke(target);
            Object newValue = readMethod.invoke(from);

            MergeConfig propertyConfig = mergeProperties.get(propertyName);
            Predicate<PropertyChange> copyPredicate = getCopyPredicate(propertyConfig);

            if (copyPredicate.apply(new PropertyChange(propertyName, originalValue, newValue))) {
                if (originalValue != null && propertyConfig != null && propertyConfig.getKeys() != null) {
                    if (deepMerge(originalValue, newValue, propertyConfig.getKeys())) {
                        updated = true;
                    }
                }
                else {
                    writeMethod.invoke(target, newValue);
                    updated = true;
                }
            }
        }
        return updated;
    }

    private static Predicate<PropertyChange> getCopyPredicate(MergeConfig propertyConfig) {
        Predicate<PropertyChange> copyPredicate;

        if (propertyConfig != null) {
            if (propertyConfig.getCopyPredicate() != null) {
                copyPredicate = propertyConfig.getCopyPredicate();
            }
            else if (propertyConfig.getKeys() != null) {
                copyPredicate = NewValueNotNullPredicate.INSTANCE;
            } else {
                copyPredicate = NewValueNotNullAndOldValueIsNullPredicate.INSTANCE;
            }
        } else {
            copyPredicate = NewValueNotNullAndOldValueIsNullPredicate.INSTANCE;
        }
        return copyPredicate;
    }

    private static class NewValueNotNullAndOldValueIsNullPredicate implements Predicate<PropertyChange> {

        public static final NewValueNotNullAndOldValueIsNullPredicate INSTANCE = new NewValueNotNullAndOldValueIsNullPredicate();

        @Override
        public boolean apply(PropertyChange input) {
            return input.getNewValue() != null && input.getOldValue() == null;
        }
    }

    private static class NewValueNotNullPredicate implements Predicate<PropertyChange> {

        public static final NewValueNotNullPredicate INSTANCE = new NewValueNotNullPredicate();

        @Override
        public boolean apply(PropertyChange input) {
            return input.getNewValue() != null;
        }
    }

    public static class MergeConfig {

        private Map<String, MergeConfig> keys;
        private Predicate<PropertyChange> copyPredicate;

        public MergeConfig(Map<String, MergeConfig> keys) {
            this(keys, null);
        }

        public MergeConfig(Map<String, MergeConfig> keys, Predicate<PropertyChange> copyPredicate) {
            this.keys = keys;
            this.copyPredicate = copyPredicate;
        }

        public Map<String, MergeConfig> getKeys() {
            return keys;
        }

        public Predicate<PropertyChange> getCopyPredicate() {
            return copyPredicate;
        }
    }

    public static class MergeConfigBuilder {

        private Map<String, MergeConfig> keys = new HashMap<>();
        private Predicate<PropertyChange> copyPredicate;

        public MergeConfigBuilder addKey(String key, MergeConfig config) {
            keys.put(key, config);
            return this;
        }

        public MergeConfigBuilder addKey(String key) {
            return addKey(key, null);
        }

        public MergeConfigBuilder withCopyPredicate(Predicate<PropertyChange> copyPredicate) {
            this.copyPredicate = copyPredicate;
            return this;
        }

        public MergeConfig build() {
            return new MergeConfig(keys.isEmpty() ? null : keys, copyPredicate);
        }

    }

    public static class PropertyChange {

        private String property;
        private Object oldValue;
        private Object newValue;

        public PropertyChange(String property, Object oldValue, Object newValue) {
            this.property = property;
            this.oldValue = oldValue;
            this.newValue = newValue;
        }

        public String getProperty() {
            return property;
        }

        public Object getOldValue() {
            return oldValue;
        }

        public Object getNewValue() {
            return newValue;
        }
    }

    /*
     * Retrieves an objects value by dot notation.
     *
     * @param obj      (The object to search within for the given property)
     * @param property (dot separated hierarchy of fields)
     * @return The requested object's value
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static Object retrieveObjectValue(Object obj, String property) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
            InvocationTargetException {
        if (property.contains(".")) {
            // We need to recurse down to the final object
            String props[] = property.split("\\.");
            Method method = obj.getClass().getMethod(getGetterMethodName(props[0], false));
            Object value = method.invoke(obj);
            if (value == null) {
                return null;
            }
            return retrieveObjectValue(value, property.substring(props[0].length() + 1));
        } else {
            Method method = obj.getClass().getMethod(getGetterMethodName(property, false));
            return method.invoke(obj);
        }
    }

    public static Method getWriteMethod(Object obj, String propertyName) throws IntrospectionException {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());

        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            if (descriptor.getName().equals(propertyName)) {
                return descriptor.getWriteMethod();
            }
        }

        return null;
    }

    /*
     * Set an objects value by dot notation.
     *
     * @param obj
     * @param property (dot separated hierarchy of fields)
     * @param newValue
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public static Object setObjectValue(Object obj, String property, Object newValue) throws SecurityException, NoSuchMethodException,
            IllegalArgumentException, IllegalAccessException,
            InvocationTargetException, IntrospectionException {

        if (!property.contains(".")) {
            Method method = getWriteMethod(obj, property);
            method.setAccessible(true);
            return method.invoke(obj, newValue);
        }

        // We need to recurse down to the final object
        String props[] = property.split("\\.");
        Method method = obj.getClass().getMethod(getGetterMethodName(props[0], false));
        Object value = method.invoke(obj);
        if (value == null) {
            return null;
        }

        if (!(value instanceof List)) {
            return setObjectValue(value, property.substring(props[0].length() + 1), newValue);
        }
        Integer listIndex = Integer.parseInt(props[1]);
        // multi-value object processing
        List multiValuedObj = ((List) value);

        // check if the request is to set new value to the item itself in the list
        if (props.length == 2) {
            multiValuedObj.set(listIndex, newValue);
            return null;
        }
        // recall over the specific item in the array
        int beginIndex = props[0].length() + 1 + props[1].length() + 1;
        return setObjectValue(multiValuedObj.get(listIndex), property.substring(beginIndex), newValue);
    }

    /*
     * Set an objects value by dot notation.
     *
     * @param obj
     * @param property
     *            (dot separated hierarchy of fields)
     * @param newValueType
     * @param newValue
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @Deprecated
    public static Object setObjectValue(Object obj, String property, Class<?> newValueType, Object newValue) throws SecurityException, NoSuchMethodException,
            IllegalArgumentException, IllegalAccessException,
            InvocationTargetException {
        if (property.contains(".")) {
            // We need to recurse down to the final object
            String props[] = property.split("\\.");
            Method method = obj.getClass().getMethod(getGetterMethodName(props[0], false));
            Object value = method.invoke(obj);
            if (value == null) {
                return null;
            }
            return setObjectValue(value, property.substring(props[0].length() + 1), newValueType, newValue);
        } else {
            Method method = obj.getClass().getMethod(getSetterMethodName(property), newValueType);
            method.setAccessible(true);
            return method.invoke(obj, new Object[] { newValue });
        }
    }

    /*
     * Unsets the field in an object using dot notation.  If the property description is for a field within a list, it will traverse into
     * the list and unset the appropriate fields
     * @param obj
     * @param property
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws IntrospectionException
     */
    public static void unsetObjectFields(Object obj, String property) throws SecurityException, NoSuchMethodException,
            IllegalArgumentException, IllegalAccessException,
            InvocationTargetException, IntrospectionException {

        if (!property.contains(".")) {

            java.lang.reflect.Field prop;
            try {
                prop = obj.getClass().getDeclaredField(property);
            } catch (NoSuchFieldException e) {
                return;
            }
            if (prop == null) {
                return;
            }
            prop.setAccessible(true);
            prop.set(obj, null);
            return;
        }

        // We need to recurse down to the final object
        String props[] = property.split("\\.");
        Method method = obj.getClass().getMethod(BeanUtils.getGetterMethodName(props[0], false));
        Object value = method.invoke(obj);
        if (value == null) {
            return;
        }

        if (!(value instanceof List)) {
            unsetObjectFields(value, property.substring(props[0].length() + 1));
            return;
        }

        // The property is a field within a list of objects, so apply the unset to each object within the list
        List multiValuedObj = ((List) value);
        int beginIndex = props[0].length() + 1;
        for (Object o : multiValuedObj) {
            unsetObjectFields(o, property.substring(beginIndex));
        }
    }

    private static Integer getInteger(String s) {
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    public static String getSetterMethodName(String property) {
        StringBuilder sb = new StringBuilder();
        sb.append(property);
        if (Character.isLowerCase(sb.charAt(0))) {
            if (sb.length() == 1 || !Character.isUpperCase(sb.charAt(1))) {
                sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
            }
        }
        sb.insert(0, "set");
        return sb.toString();
    }

    public static String getGetterMethodName(String property, boolean booleanValue) {
        StringBuilder sb = new StringBuilder();
        sb.append(property);
        if (Character.isLowerCase(sb.charAt(0))) {
            if (sb.length() == 1 || !Character.isUpperCase(sb.charAt(1))) {
                sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
            }
        }

        if (booleanValue) {
            sb.insert(0, "is");
        } else {
            sb.insert(0, "get");
        }
        return sb.toString();
    }

    public static <T> T getPropertyValue(Class<T> requiredType, String propertyName, Object instance) {
        if (requiredType == null) {
            throw new IllegalArgumentException("Invalid argument. requiredType must NOT be null!");
        }
        if (propertyName == null) {
            throw new IllegalArgumentException("Invalid argument. PropertyName must NOT be null!");
        }
        if (instance == null) {
            throw new IllegalArgumentException("Invalid argument. Object instance must NOT be null!");
        }
        T returnValue = null;
        try {
            PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, instance.getClass());
            Method readMethod = descriptor.getReadMethod();
            if (readMethod == null) {
                throw new IllegalStateException("Property '" + propertyName + "' of " + instance.getClass().getName() + " is NOT readable!");
            }
            if (requiredType.isAssignableFrom(readMethod.getReturnType())) {
                try {
                    Object propertyValue = readMethod.invoke(instance);
                    returnValue = requiredType.cast(propertyValue);
                } catch (Exception e) {
                    e.printStackTrace(); // unable to invoke readMethod
                }
            }
        } catch (IntrospectionException e) {
            throw new IllegalArgumentException("Property '" + propertyName + "' is NOT defined in " + instance.getClass().getName() + "!", e);
        }
        return returnValue;
    }

    /*
     * Returns a set of non-null fields from a bean. If a property is in the ignoreFields set or does not have a getter
     * it will be ignored.
     *
     * @param bean
     * @param ignoreFields
     * @return set of non-null field names
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    public static <T> Set<String> getNonNullFields(T bean, Set<String> ignoreFields) throws IntrospectionException, IllegalArgumentException, IllegalAccessException,
            InvocationTargetException {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
        Set<String> nonNullFields = new HashSet<>();
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            String propertyName = descriptor.getName();
            Method readMethod = descriptor.getReadMethod();
            if (ignoreFields.contains(propertyName) || readMethod == null) {
                continue;
            }
            Object value = readMethod.invoke(bean);
            if (value != null) {
                nonNullFields.add(propertyName);
            }
        }
        return nonNullFields;
    }

    public static <T> Map<String, Object> shallowDifferences(T oldBean, T newBean) throws Exception {
        Set<String> ignoreProperties = Collections.emptySet();
        return shallowDifferences(oldBean, newBean, ignoreProperties, false, false);
    }

    public static <T> Map<String, Object> shallowDifferences(T oldBean, T newBean, Set<String> ignoreProperties, boolean ignoreNewNulls, boolean ignoreEmptyCollections) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        return shallowDifferences(oldBean, newBean, ignoreProperties, ignoreNewNulls, ignoreEmptyCollections, true);
    }

    /*
     * Computes the shallow difference of read/write properties between oldBean (left hand side) and newBean (right hand side).
     * It will compare all properties that are in/not in properties (depends on the value of ignore. If they differ, the value of the newBean (right hand side)
     * will be reported in the result.
     *
     * @param oldBean
     * @param newBean
     * @param properties
     * @param ignoreNewNulls
     * @param ignoreEmptyCollections (set to true if null should be considered the same as an empty collection)
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static <T> Map<String, Object> shallowDifferences(T oldBean, T newBean, Set<String> properties, boolean ignoreNewNulls, boolean ignoreEmptyCollections, boolean ignore) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        LOGGER.debug("* calculating shallow differences between oldBean='{}' and newBean='{}'", oldBean, newBean);

        Map<String, Object> changes = new HashMap<>();
        BeanInfo beanInfo = Introspector.getBeanInfo(oldBean.getClass());

        // Iterate over all the attributes
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            String propertyName = descriptor.getName();
            boolean contains = properties.contains(propertyName);
            if ((contains && ignore) || (!contains && !ignore)) {
                // LOGGER.debug("+ skipping property '{}' which is in properties", propertyName);
                continue;
            }

            Method readMethod = descriptor.getReadMethod();
            Method writeMethod = descriptor.getWriteMethod();
            if (readMethod == null || writeMethod == null) {
                // LOGGER.debug("+ skipping property '{}' with getter '{}' and setter '{}'", new Object[] {
                // propertyName, readMethod, writeMethod });
                continue;
            }

            // LOGGER.debug("+ comparing property '{}': getter='{}', setter='{}'", new Object[] { propertyName,
            // readMethod, writeMethod });
            Object oldValue = readMethod.invoke(oldBean);
            Object newValue = readMethod.invoke(newBean);

            if (ignoreNewNulls && newValue == null) {
                continue;
            }

            if (ignoreEmptyCollections) {
                // null should be treated the same as an empty collection
                if (oldValue != null && oldValue instanceof Collection<?> && newValue == null) {
                    Collection<?> oldCollection = (Collection<?>) oldValue;
                    if (oldCollection.isEmpty()) {
                        continue;
                    }
                } else if (newValue != null && newValue instanceof Collection<?> && oldValue == null) {
                    Collection<?> newCollection = (Collection<?>) newValue;
                    if (newCollection.isEmpty()) {
                        continue;
                    }
                }
            }

            if (!Objects.equal(oldValue, newValue)) {
                changes.put(propertyName, newValue);
            }
        }

        return changes;
    }

    /*
     * Patches bean (left hand side) with all not-null values from patches (right hand side).
     * Takes into account only read-write properties that are not in ignoreProperties.
     * Only touches the bean (left hand side) if the properties are not equal.
     *
     * @param bean
     * @param patches
     * @param ignoreProperties
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static <T> void patch(T bean, T patches, Set<String> ignoreProperties) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        LOGGER.debug("* patching bean='{}' with not-null values from patches='{}'", bean, patches);

        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());

        // Iterate over all the attributes
        for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
            String propertyName = descriptor.getName();
            if (ignoreProperties.contains(propertyName)) {
                // LOGGER.debug("+ skipping property '{}' which is in ignoreProperties", propertyName);
                continue;
            }

            Method readMethod = descriptor.getReadMethod();
            Method writeMethod = descriptor.getWriteMethod();
            if (readMethod == null || writeMethod == null) {
                // LOGGER.debug("+ skipping property '{}' with getter '{}' and setter '{}'", new Object[] {
                // propertyName, readMethod, writeMethod });
                continue;
            }

            // LOGGER.debug("+ comparing property '{}': getter='{}', setter='{}'", new Object[] { propertyName,
            // readMethod, writeMethod });
            Object oldValue = readMethod.invoke(bean);
            Object newValue = readMethod.invoke(patches);

            if (newValue == null) {
                continue;
            }

            if (!Objects.equal(oldValue, newValue)) {
                writeMethod.invoke(bean, newValue);
            }
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getAnnotationParameter(Annotation annotation, String parameterName, Class<T> type) {
        try {
            Method m = annotation.getClass().getMethod(parameterName);
            Object o = m.invoke(annotation);
            if (o.getClass().getName().equals(type.getName())) {
                return (T) o;
            } else {
                String msg = "Wrong parameter type. Expected: " + type.getName() + " Actual: " + o.getClass().getName();
                throw new RuntimeException(msg);
            }
        } catch (NoSuchMethodException e) {
            String msg = "The specified annotation defines no parameter '" + parameterName + "'.";
            throw new RuntimeException(msg, e);
        } catch (IllegalAccessException e) {
            String msg = "Unable to get '" + parameterName + "' from " + annotation.getClass().getName();
            throw new RuntimeException(msg, e);
        } catch (InvocationTargetException e) {
            String msg = "Unable to get '" + parameterName + "' from " + annotation.getClass().getName();
            throw new RuntimeException(msg, e);
        }
    }

    /*
     * Performs a deep copy of one object to the target which should be a new instance.  The 'target' and 'from' objects do not need to be of
     * the same type. i.e. 'target' could be a Publication, and 'from' a StructuredCitation.  Classes within each of the classes that are not directly
     * assignable should have a no-argument constructor available.
     * @param target
     * @param from
     * @param <T>
     * @throws Exception
     */
    public static <T> void deepCopy(T target, T from) throws Exception {
        BeanInfo beanFromInfo = Introspector.getBeanInfo(from.getClass());
        BeanInfo beanToInfo = Introspector.getBeanInfo(target.getClass());

        Map<String, PropertyDescriptor> toPropertyDescriptors = Maps.newHashMap();
        for (PropertyDescriptor descriptor : beanToInfo.getPropertyDescriptors()) {
            toPropertyDescriptors.put(descriptor.getName(), descriptor);
        }

        for (PropertyDescriptor descriptor : beanFromInfo.getPropertyDescriptors()) {

            PropertyDescriptor toPropertyDesc = toPropertyDescriptors.get(descriptor.getName());
            if (toPropertyDesc == null) {
                continue;
            }

            Method fromReadMethod = descriptor.getReadMethod();
            Method toWriteMethod = toPropertyDesc.getWriteMethod();
            Method toReadMethod = toPropertyDesc.getReadMethod();
            if (fromReadMethod == null || toWriteMethod == null) {
                continue;
            }

            Object newValue = fromReadMethod.invoke(from);
            if (newValue == null) {
                continue;
            }

            if (fromReadMethod.getReturnType().isAssignableFrom(toReadMethod.getReturnType())) {
                toWriteMethod.invoke(target, newValue);
            } else {
                // The types are not compatible so create a new instance of the target type and apply the deep merge using that
                Object instance = toReadMethod.getReturnType().newInstance();
                deepCopy(instance, newValue);
                toWriteMethod.invoke(target, instance);
            }
        }
    }

}


text:
package net.auxesia;

import java.util.Random;

/**
 * This class is used to define a chromosome for the gentic algorithm
 * simulation.
 *
 * This class is essentially nothing more than a container for the details
 * of the chromosome, namely the gene (the string that represents our target
 * string) and the fitness (how close the gene is to the target string).
 *
 * Note that this class is immutable.  Calling mate(Chromsome)
 * or mutate will result in a new Chromosome
 * instance being created.
 *
 * @author John Svazic
 * @version 1.0
 */
public class Chromosome implements Comparable<Chromosome> {
	private final String gene;
	private final int fitness;

	/** The target gene, converted to an array for convenience. */
	private static final char[] TARGET_GENE = "Hello, world!".toCharArray();

	/** Convenience randomizer. */
	private static final Random rand = new Random(System.currentTimeMillis());

	/**
	 * Default constructor.
	 *
	 * @param gene The gene representing this Chromosome.
	 */
	public Chromosome(String gene) {
		this.gene    = gene;
		this.fitness = calculateFitness(gene);
	}

	/**
	 * Method to retrieve the gene for this Chromosome.
	 *
	 * @return The gene for this Chromosome.
	 */
	public String getGene() {
		return gene;
	}

	/**
	 * Method to retrieve the fitness of this Chromosome.  Note
	 * that a lower fitness indicates a better Chromosome for the
	 * solution.
	 *
	 * @return The fitness of this Chromosome.
	 */
	public int getFitness() {
		return fitness;
	}

	/**
	 * Helper method used to calculate the fitness for a given gene.  The
	 * fitness is defined as being the sum of the absolute value of the
	 * difference between the current gene and the target gene.
	 *
	 * @param gene The gene to calculate the fitness for.
	 *
	 * @return The calculated fitness of the given gene.
	 */
	private static int calculateFitness(String gene) {
		int fitness = 0;
		char[] arr  = gene.toCharArray();
		for (int i = 0; i < arr.length; i++) {
			fitness += Math.abs(((int) arr[i]) - ((int) TARGET_GENE[i]));
		}

		return fitness;
	}

	/**
	 * Method to generate a new Chromosome that is a random
	 * mutation of this Chromosome.  This method randomly
	 * selects one character in the Chromosomes gene, then
	 * replaces it with another random (but valid) character.  Note that
	 * this method returns a new Chromosome, it does not
	 * modify the existing Chromosome.
	 *
	 * @return A mutated version of this Chromosome.
	 */
	public Chromosome mutate() {
		char[] arr  = gene.toCharArray();
		int idx     = rand.nextInt(arr.length);
		int delta   = (rand.nextInt() % 90) + 32;
		arr[idx]    = (char) ((arr[idx] + delta) % 122);

		return new Chromosome(String.valueOf(arr));
	}

	/**
	 * Method used to mate this Chromosome with another.  The
	 * resulting child Chromosomes are returned.
	 *
	 * @param mate The Chromosome to mate with.
	 *
	 * @return The resulting Chromosome children.
	 */
	public Chromosome[] mate(Chromosome mate) {
		// Convert the genes to arrays to make thing easier.
		char[] arr1  = gene.toCharArray();
		char[] arr2  = mate.gene.toCharArray();

		// Select a random pivot point for the mating
		int pivot    = rand.nextInt(arr1.length);

		// Provide a container for the child gene data
		char[] child1 = new char[gene.length()];
		char[] child2 = new char[gene.length()];

		// Copy the data from each gene to the first child.
		System.arraycopy(arr1, 0, child1, 0, pivot);
		System.arraycopy(arr2, pivot, child1, pivot, (child1.length - pivot));

		// Repeat for the second child, but in reverse order.
		System.arraycopy(arr2, 0, child2, 0, pivot);
		System.arraycopy(arr1, pivot, child2, pivot, (child2.length - pivot));

		return new Chromosome[] { new Chromosome(String.valueOf(child1)),
				new Chromosome(String.valueOf(child2))};
	}

	/**
	 * A convenience method to generate a randome Chromosome.
	 *
	 * @return A randomly generated Chromosome.
	 */
	/* package */ static Chromosome generateRandom() {
		char[] arr = new char[TARGET_GENE.length];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (char) (rand.nextInt(90) + 32);
		}

		return new Chromosome(String.valueOf(arr));
	}

	/**
	 * Method to allow for comparing Chromosome objects with
	 * one another based on fitness.  Chromosome ordering is
	 * based on the natural ordering of the fitnesses of the
	 * Chromosomes.
	 */
	@Override
	public int compareTo(Chromosome c) {
		if (fitness < c.fitness) {
			return -1;
		} else if (fitness > c.fitness) {
			return 1;
		}

		return 0;
	}

	/**
	 * @see Object#equals(Object)
	 */
	@Override
	public boolean equals(Object o) {
		if (!(o instanceof Chromosome)) {
			return false;
		}

		Chromosome c = (Chromosome) o;
		return (gene.equals(c.gene) && fitness == c.fitness);
	}

	/**
	 * @see Object#hashCode()
	 */
	@Override
	public int hashCode() {
		return new StringBuilder().append(gene).append(fitness)
				.toString().hashCode();
	}
}


text:
import os
import signal
import sys
import time

#test
from rmake_test import rmakehelp

#conary
from conary.deps import deps
from conary.repository import errors as repoerrors

#rmake
from rmake import errors
from rmake.lib import apirpc
from rmake.lib import apiutils
from rmake.lib.apiutils import api, api_parameters, api_return, api_forking, api_nonforking
from rmake.lib.rpcproxy import ShimAddress

class TestServer(apirpc.XMLApiServer):
    def __init__(self, *args, **kw):
        apirpc.XMLApiServer.__init__(self, *args, **kw)
        self._delayed = []

    @api(version=1)
    @api_parameters(1, 'bool')
    @api_return(1, 'bool')
    def ping(self, callData, b):
        return b

    @api(version=1)
    @api_parameters(1, 'flavor')
    @api_return(1, 'flavor')
    def ping2(self, callData, flavor):
        return flavor

    @api(version=1)
    def getPid(self, callData):
        return os.getpid()

    @api_forking
    @api(version=1)
    def getPidForking(self, callData):
        return os.getpid()

    @api_nonforking
    @api(version=1)
    def getPidNoForking(self, callData):
        return os.getpid()

    @api(version=1)
    @api_parameters(1)
    @api_return(1, None)
    def getAuth(self, callData):
        auth = callData.getAuth()
        return (auth.pid, auth.uid, auth.gid)

    @api_nonforking
    @api(version=1)
    @api_parameters(1, 'int')
    def delayed(self, callData, val):
        self._delayed.append((callData, val))
        return callData.delay()

    @api_nonforking
    @api(version=1)
    def release(self, callData):
        delayed = self._delayed
        self._delayed = []
        for callData, delayedVal in delayed:
            if delayedVal < 0:
                callData.respondWithException(
                                errors.RmakeError('Cannot accept %s' % delayedVal))
            else:
                callData.respond(delayedVal)
        return len(delayed)

class TestClient(object):
    def __init__(self, uri):
        self.proxy = apirpc.XMLApiProxy(TestServer, uri)

    def ping(self, b):
        return self.proxy.ping(b)

    def ping2(self, flavor):
        return self.proxy.ping2(flavor)

    def getAuth(self):
        return self.proxy.getAuth()

    def getPid(self):
        return self.proxy.getPid()

    def getPidNoForking(self):
        return self.proxy.getPidNoForking()

    def getPidForking(self):
        return self.proxy.getPidForking()

    def delayed(self, val):
        return self.proxy.delayed(val)

    def release(self):
        return self.proxy.release()

class ApiRPCTest(rmakehelp.RmakeHelper):
    def testApiRpcServe(self):
        self._testApiRpcServe(False)

    def testApiRpcServeForking(self):
        self._testApiRpcServe(True)

    def _testApiRpcServe(self, forking):

        port = testsuite.findPorts(1)[0]
        uri = 'http://localhost:%s/conary/' % port
        server = TestServer(uri, forkByDefault=forking)
        client = TestClient(uri)

        pid = os.fork()
        if not pid:
            time.sleep(.1)
            client.ping(True)
            os._exit(0)
        else:
            server.server.handle_request()
            self.waitThenKill(pid)

        pid = os.fork()
        if not pid:
            try:
                server.server.handle_request()
                server.server.handle_request()
                server.server.handle_request()
            finally:
                os._exit(0)
        else:
            assert((client.getPid() == pid) == (not forking))
            assert(client.getPidForking() != pid)
            assert(client.getPidNoForking() == pid)
            self.waitThenKill(pid)

        uri = 'unix://%s/socket' % self.workDir
        server = TestServer(uri)
        client = TestClient(uri)
        pid = os.fork()
        if not pid:
            time.sleep(.1)
            client.ping2(deps.parseFlavor('foo'))
            os._exit(0)
        else:
            server.server.handle_request()
            self.waitThenKill(pid)

        # verify that the unix SO_PEERCRED authentication gets the client
        # side pid,uid,gid as the peer credentials
        uri = 'unix://%s/socket2' % self.workDir
        server = TestServer(uri, forkByDefault=forking)
        client = TestClient(uri)
        pid = os.fork()
        if not pid:
            time.sleep(.1)
            server.server.handle_request()
            os._exit(0)
        else:
            time.sleep(.1)
            auth = tuple(client.getAuth())
            self.failUnless(auth == (os.getpid(), os.getuid(), os.getgid()))
            self.waitThenKill(pid)

    def testApiRpcParams(self):
        server = TestServer()
        client = TestClient(ShimAddress(server))
        assert(client.ping(True))
        assert(client.ping2(deps.parseFlavor('foo')) == deps.parseFlavor('foo'))
        self.assertRaises(apirpc.ApiError, client.proxy.ping, True, False)

        self.assertRaises(apirpc.ApiError, client.proxy.foobar)

    def testApiMajorVersionMismatch(self):
        server = TestServer()
        client = TestClient(ShimAddress(server))
        client.proxy._apiMajorVersion = '123123'
        tgt = "while the client runs API version 123123"
        try:
            client.ping(True)
        except errors.RmakeError, e:
            self.failUnlessIn(tgt, str(e))
        else:
            raise Exeption("ApiError not raised")

    def testFreezeThaw(self):
        @api(version=1)
        @api_parameters(1, None)
        @api_return(1, None)
        def testFunc(self, foo):
            return 0

        assert(list(apirpc._freezeParams(testFunc, [0], 1)) == [0])
        assert(apirpc._thawReturn(testFunc, 0, 1) == 0)

    def testFreezeThawException(self):
        @api(version=1)
        @api_parameters(1, None)
        @api_return(1, None)
        def testFunc(self, foo):
            return 0

        sys.exc_clear()
        frz = apirpc._freezeException(repoerrors.OpenError('foo'))
        self.assertEquals(str(apiutils.thaw(*frz)),
        'Exception from server:\n'
        'conary.repository.errors.OpenError: foo\n'
        'None\n')
        # this is rmake's internal error
        frz = apirpc._freezeException(errors.OpenError('foo'))
        self.assertEquals(str(apiutils.thaw(*frz)), 'foo')

    def testApiDelayed(self):
        def _forkCall(client, val):
            pid = os.fork()
            if pid:
                return pid
            try:
                if val < 0:
                    self.assertRaises(errors.RmakeError, client.delayed, val)
                else:
                    assert(val == client.delayed(val))
                os._exit(0)
            finally:
                os._exit(1)

        port = testsuite.findPorts(1)[0]
        uri = 'http://localhost:%s/conary/' % port
        server = TestServer(uri)

        pid = os.fork()
        if not pid:
            try:
                server.serve_forever()
            finally:
                os._exit(0)
        try:
            serverPid = pid
            client = TestClient(uri)
            pids = []
            pids.append(_forkCall(client, 1))
            pids.append(_forkCall(client, 2))
            pids.append(_forkCall(client, -1))
            import time
            time.sleep(1)
            for pid in pids:
                assert(not os.waitpid(pid, os.WNOHANG)[0])
            assert(client.release() == 3)
            for pid in pids:
                pid, status  = self.waitThenKill(pid)
                assert(not status)
        finally:
            os.kill(serverPid, 9)
            self.waitThenKill(serverPid)


text:
package core

import javax.swing.JOptionPane

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import core.algorithms.naive.NaiveQuadraticMethod
import core.gui.JavaGUI
import core.http.HttpRoute
import core.universe.{SimulationActor, SystemState, UniverseConstants}

object Main extends App with HttpRoute {

  val config = ConfigFactory.load()

  implicit val system = ActorSystem("NBody", config)
  implicit val materializer = ActorMaterializer()
  implicit val executionContext = system.dispatcher

  val host = config.getString("http.interface")
  val port = config.getInt("http.port")
  val bindingFuture = Http().bindAndHandle(route, host, port)

  val numBodies = JOptionPane.showInputDialog(null, "Enter amount of bodies").toInt

  val systemState = new SystemState //shared between GUI and processing

  val naiveQuadraticMethod = new NaiveQuadraticMethod
  val simulationActor = system.actorOf(SimulationActor.props(numBodies, naiveQuadraticMethod, systemState))
  val gui = new JavaGUI(systemState, UniverseConstants.UNIVERSE_RADIUS)
}


text:
var it = require('../tools/it.js');

function arrayEquals(arr1, arr2) {
    if (arr1.length !== arr2.length) {
        return false;
    }
    return arr2.every(function(element, index) {
        return element == arr2[index];
    });
}

function arrayToList(values) {
    var list = null;
    while(values.length > 0) {
        list = {
            value: values.pop(),
            next: list
        };
    }
    return list;

}

function listToArray(list) {
    var current = list;
    var result = [];
    do {
        result.push(current.value);
        current = current.next;
    } while(current != null);

    return result;
}

function listNth(aList, position) {
    var current = 1;
    while(current < position) {
        if(aList.next == null) {
            return;
        }
            aList = aList.next;
            current++;
    }
    return aList.value;
}

var aList = arrayToList([1]);
it('Creates a list from array with 1 value', aList.value == 1 && aList.next == null);

var aList = arrayToList([1, 2]);
it('Creates a list from array with 2 values', (aList.value == 1) && (aList.next.value == 2) && aList.next.next == null);

var aList = arrayToList([1, 2, 3]);
it('Creates a list from array with 3 values', (aList.value == 1) && (aList.next.value == 2) && aList.next.next.value == 3);

aList = {value: 1, next: null};
it('Creates an array from a 1 member list', arrayEquals(listToArray(aList),[1]));

aList = {value: 1, next: {value: 2, next: null}};
it('Creates an array from a 2 members list', arrayEquals(listToArray(aList),[1, 2]));

aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Creates an array from a 3 members list', arrayEquals(listToArray(aList),[1, 2, 3]));

aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Can return the 1st element value', listNth(aList, 1) == 1);

aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Can return the 2nd element value', listNth(aList, 2) == 2);

aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Can return the 3rd element value', listNth(aList, 3) == 3);

aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Returns undefined if not  found', typeof listNth(aList, 5) == 'undefined');


text:
package org.springframework.boot.actuate.endpoint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * Strategy that should be used by endpoint implementations to sanitize potentially
 * sensitive keys.
 *
 * @author Christian Dupuis
 * @author Toshiaki Maki
 * @author Phillip Webb
 * @author Nicolas Lejeune
 * @author Stephane Nicoll
 * @author HaiTao Zhang
 * @author Chris Bono
 * @author David Good
 * @author Madhura Bhave
 * @since 2.0.0
 */
public class Sanitizer {

	private static final String[] REGEX_PARTS = { "*", "$", "^", "+" };

	private static final Set<String> DEFAULT_KEYS_TO_SANITIZE = new LinkedHashSet<>(
			Arrays.asList("password", "secret", "key", "token", ".*credentials.*", "vcap_services",
					"^vcap\\.services.*$", "sun.java.command", "^spring[._]application[._]json$"));

	private static final Set<String> URI_USERINFO_KEYS = new LinkedHashSet<>(
			Arrays.asList("uri", "uris", "url", "urls", "address", "addresses"));

	private static final Pattern URI_USERINFO_PATTERN = Pattern
			.compile("^\\[?[A-Za-z][A-Za-z0-9\\+\\.\\-]+://.+:(.*)@.+$");

	private Pattern[] keysToSanitize;

	private final List<SanitizingFunction> sanitizingFunctions = new ArrayList<>();

	static {
		DEFAULT_KEYS_TO_SANITIZE.addAll(URI_USERINFO_KEYS);
	}

	/**
	 * Create a new {@link Sanitizer} instance with a default set of keys to sanitize.
	 */
	public Sanitizer() {
		this(DEFAULT_KEYS_TO_SANITIZE.toArray(new String[0]));
	}

	/**
	 * Create a new {@link Sanitizer} instance with specific keys to sanitize.
	 * @param keysToSanitize the keys to sanitize
	 */
	public Sanitizer(String... keysToSanitize) {
		this(Collections.emptyList(), keysToSanitize);
	}

	/**
	 * Create a new {@link Sanitizer} instance with a default set of keys to sanitize and
	 * additional sanitizing functions.
	 * @param sanitizingFunctions the sanitizing functions to apply
	 * @since 2.6.0
	 */
	public Sanitizer(Iterable<SanitizingFunction> sanitizingFunctions) {
		this(sanitizingFunctions, DEFAULT_KEYS_TO_SANITIZE.toArray(new String[0]));
	}

	/**
	 * Create a new {@link Sanitizer} instance with specific keys to sanitize and
	 * additional sanitizing functions.
	 * @param sanitizingFunctions the sanitizing functions to apply
	 * @param keysToSanitize the keys to sanitize
	 * @since 2.6.0
	 */
	public Sanitizer(Iterable<SanitizingFunction> sanitizingFunctions, String... keysToSanitize) {
		sanitizingFunctions.forEach(this.sanitizingFunctions::add);
		this.sanitizingFunctions.add(getDefaultSanitizingFunction());
		setKeysToSanitize(keysToSanitize);
	}

	private SanitizingFunction getDefaultSanitizingFunction() {
		return (data) -> {
			Object sanitizedValue = sanitize(data.getKey(), data.getValue());
			return data.withValue(sanitizedValue);
		};
	}

	/**
	 * Set the keys that should be sanitized, overwriting any existing configuration. Keys
	 * can be simple strings that the property ends with or regular expressions.
	 * @param keysToSanitize the keys to sanitize
	 */
	public void setKeysToSanitize(String... keysToSanitize) {
		Assert.notNull(keysToSanitize, "KeysToSanitize must not be null");
		this.keysToSanitize = new Pattern[keysToSanitize.length];
		for (int i = 0; i < keysToSanitize.length; i++) {
			this.keysToSanitize[i] = getPattern(keysToSanitize[i]);
		}
	}

	/**
	 * Adds keys that should be sanitized. Keys can be simple strings that the property
	 * ends with or regular expressions.
	 * @param keysToSanitize the keys to sanitize
	 * @since 2.5.0
	 */
	public void keysToSanitize(String... keysToSanitize) {
		Assert.notNull(keysToSanitize, "KeysToSanitize must not be null");
		int existingKeys = this.keysToSanitize.length;
		this.keysToSanitize = Arrays.copyOf(this.keysToSanitize, this.keysToSanitize.length + keysToSanitize.length);
		for (int i = 0; i < keysToSanitize.length; i++) {
			this.keysToSanitize[i + existingKeys] = getPattern(keysToSanitize[i]);
		}
	}

	private Pattern getPattern(String value) {
		if (isRegex(value)) {
			return Pattern.compile(value, Pattern.CASE_INSENSITIVE);
		}
		return Pattern.compile(".*" + value + "$", Pattern.CASE_INSENSITIVE);
	}

	private boolean isRegex(String value) {
		for (String part : REGEX_PARTS) {
			if (value.contains(part)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Sanitize the given value if necessary.
	 * @param key the key to sanitize
	 * @param value the value
	 * @return the potentially sanitized value
	 */
	public Object sanitize(String key, Object value) {
		if (value == null) {
			return null;
		}
		for (Pattern pattern : this.keysToSanitize) {
			if (pattern.matcher(key).matches()) {
				if (keyIsUriWithUserInfo(pattern)) {
					return sanitizeUris(value.toString());
				}
				return SanitizableData.SANITIZED_VALUE;
			}
		}
		return value;
	}

	/**
	 * Sanitize the value from the given {@link SanitizableData} using the available
	 * {@link SanitizingFunction}s.
	 * @param data the sanitizable data
	 * @return the potentially updated data
	 * @since 2.6.0
	 */
	public Object sanitize(SanitizableData data) {
		if (data.getValue() == null) {
			return null;
		}
		for (SanitizingFunction sanitizingFunction : this.sanitizingFunctions) {
			data = sanitizingFunction.apply(data);
		}
		return data.getValue();
	}

	private boolean keyIsUriWithUserInfo(Pattern pattern) {
		for (String uriKey : URI_USERINFO_KEYS) {
			if (pattern.matcher(uriKey).matches()) {
				return true;
			}
		}
		return false;
	}

	private Object sanitizeUris(String value) {
		return Arrays.stream(value.split(",")).map(this::sanitizeUri).collect(Collectors.joining(","));
	}

	private String sanitizeUri(String value) {
		Matcher matcher = URI_USERINFO_PATTERN.matcher(value);
		String password = matcher.matches() ? matcher.group(1) : null;
		if (password != null) {
			return StringUtils.replace(value, ":" + password + "@", ":" + SanitizableData.SANITIZED_VALUE + "@");
		}
		return value;
	}

}


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">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.kie.workbench.screens</groupId>
    <artifactId>kie-wb-common-search-screen</artifactId>
    <version>6.4.0-SNAPSHOT</version>
  </parent>

  <artifactId>kie-wb-common-search-screen-backend</artifactId>
  <packaging>jar</packaging>

  <name>Kie Workbench - Common - Search Screen Backend</name>
  <description>Kie Workbench - Common - Search Screen Backend</description>

  <dependencies>

    <!-- dependencies added because of new illegal transitive dependency check -->
    <dependency>
      <groupId>org.guvnor</groupId>
      <artifactId>guvnor-services-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.guvnor</groupId>
      <artifactId>guvnor-structure-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-bus</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-backend-server</artifactId>
    </dependency>
    <dependency>
      <groupId>org.guvnor</groupId>
      <artifactId>guvnor-services-backend</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-io</artifactId>
    </dependency>
    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-nio2-model</artifactId>
    </dependency>
    <dependency>
      <groupId>org.jboss.errai</groupId>
      <artifactId>errai-security-server</artifactId>
    </dependency>

    <dependency>
      <groupId>org.uberfire</groupId>
      <artifactId>uberfire-metadata-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.services</groupId>
      <artifactId>kie-wb-common-services-backend</artifactId>
    </dependency>

    <dependency>
      <groupId>org.kie.workbench.screens</groupId>
      <artifactId>kie-wb-common-search-screen-api</artifactId>
    </dependency>
  </dependencies>

</project>


text:
require 'httpclient'
require 'google_play_search/search'
module GooglePlaySearch
end


text:
Shindo.tests('Fog::Compute[:profitbricks] | flavor request', ['profitbricks', 'compute']) do

  @flavor_format = {
    'flavorId'   => String,
    'flavorName' => String,
    'ram'        => Integer,
    'cores'      => Integer
  }

  service = Fog::Compute[:profitbricks]

  tests('success') do

    # Not yet implemented
    # tests('#create_flavor').formats(@flavor_format) do
    #   puts '#create_flavor'
    #   data = service.create_flavor('FogFlavorTest', 4096, 2)
    #   data.body['createFlavorResponse']
    # end

    tests('#get_all_flavors').formats(@flavor_format) do
      # puts '#get_all_flavors'
      data = service.get_all_flavors
      @flavor_id = data.body['getAllFlavorsResponse'][0]['flavorId']
      data.body['getAllFlavorsResponse'][0]
    end

    tests('#get_flavor').formats(@flavor_format) do
      # puts '#get_flavor'
      data = service.get_flavor(@flavor_id)
      data.body['getFlavorResponse']
    end

  end

  tests('failure') do
    tests('#get_flavor').raises(Fog::Errors::NotFound) do
      # puts '#get_flavor'
      data = service.get_flavor('00000000-0000-0000-0000-000000000000')
      data.body['getRegionResponse']
    end
  end
end