text:
@implementation IFDefaultTargetContainerBehaviour

@synthesize parentTargetContainer = _parentTargetContainer, namedTargets = _namedTargets, uriHandler = _uriHandler;

- (void)setNamedTargets:(NSDictionary *)namedTargets {
    _namedTargets = namedTargets;
    for (id name in [_namedTargets keyEnumerator]) {
        id target = [_namedTargets valueForKey:name];
        if ([target conformsToProtocol:@protocol(IFTargetContainer)]) {
            // TODO: Child target parent is this, or the behaviour owner?
            ((id<IFTargetContainer>)target).parentTargetContainer = self;
        }
    }
}

- (BOOL)dispatchURI:(NSString *)uri {
    IFCompoundURI *curi = nil;
    NSError *error;
    // Resolve the action URI.
    if ([uri hasPrefix:@"do:"]) {
        curi = [[IFCompoundURI alloc] initWithURI:uri error:&error];
    }
    if (!curi && _uriRewriteRules) {
        NSString *_uri = [_uriRewriteRules rewriteString:uri];
        if (_uri) {
            if ([_uri hasPrefix:@"do:"]) {
                curi = [[IFCompoundURI alloc] initWithURI:_uri error:&error];
            }
            else {
                DDLogWarn(@"%@: Rewritten URI not in 'do' scheme: %@ -> %@", LogTag, uri, _uri );
            }
        }
    }
    if (error) {
        DDLogError(@"%@: URI parse error %@", LogTag, error );
    }
    // Dispatch the action URI.
    BOOL dispatched = NO;
    if (curi) {
        // Resolve the action target.
        id target = [self targetForPath:curi.fragment];
        // If target resolved then dereference the URI and apply the resource to the target.
        if (target && [target conformsToProtocol:@protocol(IFTarget)]) {
            IFDoAction *action = (IFDoAction *)[self.uriHandler dereference:curi];
            [(id<IFTarget>)target doAction:action];
            dispatched = action.cancelled;
        }
    }
    // If unable to dispatch the URI then try sending to the parent container.
    if (!dispatched && _parentTargetContainer) {
        dispatched = [_parentTargetContainer dispatchURI:uri];
    }
    return dispatched;
}

- (id)targetForPath:(NSString *)targetPath {
    if (!targetPath || [targetPath length] == 0) {
        return _owner;
    }
    NSArray *components = [targetPath split:@"\\."];
    NSDictionary *targets = _namedTargets;
    id target = nil;
    for (NSInteger i = 0; i < [components count]; i++) {
        // If no named targets then don't continue.
        if (!targets) {
            target = nil;
            break;
        }
        // Resolve the next named target.
        NSString *name = [components objectAtIndex:i];
        target = [targets objectForKey:name];
        if (!target) {
            // Name not found, so don't continue.
            break;
        }
        // Check if next target is a container, and if so resolve its named children.
        if ([target conformsToProtocol:@protocol(IFTargetContainer)]) {
            targets = ((id<IFTargetContainer>)target).namedTargets;
        }
        else {
            // Can't resolved named children - this won't matter for the final path component,
            // but will for intermediate components, in which case the code at the head of the
            // loop will exit.
            targets = nil;
        }
    }
    return target;
}

@end


text:
"""
MIT License

Copyright (c) 2016 William Tumeo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import asyncio
from ...plugins import Plugin
from .reminders import Reminder, ReminderTask

class ReminderPlugin(Plugin):

    reminder_dict = None
    reminder_list = None
    reminders = None

    def __init__(self, maid):
        super().__init__(maid, 'reminder', ['loop'])
        self.reminders = []

    def load(self):
        self.reminder_dict = self.maid.loader.load_yml(self.data.get('data'))
        self.reminder_list = list()

        for dayk in self.reminder_dict.keys():
            for hourk in self.reminder_dict[dayk].keys():
                for rem in self.reminder_dict[dayk][hourk]:
                    self.reminder_list.append(Reminder(dayk, hourk, rem))
        self.reminders.append(ReminderTask(self.interval, self.reminder_list, 3))

    def update_data(self):
        self.reminders[-1].stop = True
        self.load()
        self.tasks.append(self.maid.loop.create_task(self.loop_callback()))

    async def new_task(self):
        print("Starting new task")
        while not self.tasks[-1].done():
            print('Waiting for {0}'.format(self.tasks[-1]))
            await asyncio.sleep(60)
        self.load()
        self.tasks.append(self.maid.loop.create_task(self.loop_callback()))

    async def loop_callback(self):
        await self.reminders[-1].reminder_task(self._reminder_callback)

    async def _reminder_callback(self, rem):
        await self.maid.motivate(rem.msg)

redpajama_set_name: RedPajamaGithub


text:
<?php
require_once realpath(__DIR__ . '/..') . '/vendor/autoload.php';
require_once realpath(__DIR__ . '/..') . '/Utils.php';

use Aspose\Cells\CellsApi;
use Aspose\Cells\AsposeApp;

class FilterData {

	public $cells;

	public function __construct() {
	    AsposeApp::$appSID = Utils::appSID;
	    AsposeApp::$apiKey = Utils::apiKey;
	    $this->cells = new CellsApi();
	}

	public function putWorksheetFilterTop10() {
         // Upload file to Aspose Cloud Storage
         $name = "Book1.xlsx";
         Utils::uploadFile($name);

         $sheet_name = "Sheet1";
         $range="A1:B1";
         $field_index=0;
         $is_top="true";
         $item_count = 1;
         $match_blanks = "true";
         $is_percent = "true";

         $result = $this->cells->putWorksheetFilterTop10($name, $sheet_name, $range, $field_index, $is_top, $item_count, $is_percent, $match_blanks, $refresh=null, $folder=null);
         print_r($result);
	}
}

$filterData = new FilterData();
$filterData->putWorksheetFilterTop10();

?>
//ExEnd:


text:
package com.framework.response;

public class BaseResponse {

    private boolean success;

    private ResponseObject response;

    private String cause;

    private String messageId;

    private String identification;

    public static BaseResponse buildResponse(ResponseObject response) {
        return new BaseResponse(true, response);
    }

    public static BaseResponse buildResponse(ResponseObject response, String messageId) {
        return new BaseResponse(true, response, messageId);
    }

    public BaseResponse(boolean success, ResponseObject response) {
        this.success = success;
        this.response = response;
    }

    public BaseResponse(boolean success, ResponseObject response, String messageId) {
        this.success = success;
        this.response = response;
        this.messageId = messageId;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public ResponseObject getResponse() {
        return response;
    }

    public void setResponse(ResponseObject response) {
        this.response = response;
    }

    public String getCause() {
        return cause;
    }

    public void setCause(String cause) {
        this.cause = cause;
    }

    public String getMessageId() {
        return messageId;
    }

    public void setMessageId(String messageId) {
        this.messageId = messageId;
    }

    public String getIdentification() {
        return this.identification;
    }

    public void setIdentification(String identification) {
        this.identification = identification;
    }
}


text:
layout: post
author: agooch
title: Mandy's Pipes and Filters Exercise
---

# My Experience

I found this exercise to be relatively simple. I really enjoy working in command line, so this was great practice.

We did most of the assignment in class, which helped me to better understand some of the command line's functionality. I can definitely see how using some of these commands would be beneficial when dealing with large datasets or files. I particularly find the sort and redirect commands to be very useful. The sort command allows you to sort the contents of a file and you can further sort based on more specifics such as by number or position in the list of files. The redirect allows you to send a command's output to a designated file.

I think a bit more practice with pipes will help to cement the idea in my head, but I am understanding how a pipeline can be used to generate the input for the second command from the output of the first command.

Overall, I felt pretty confident throughout this exercise. I think the repetition really helps with command line, since it is really about getting down the syntax and understanding the vocabulary. Once you have those down, it isn't too difficult to move through various branches and files.

# Challenges

**1**

The *sort* command sorts the output numerically by the first integer; however, the *sort -n* command sorts the output numerically by the entire number due to the *-n*. Therefore instead of sorting the output by the first character, it instead recognizes the numbers and sorts those instead.

**2**

*wc -l < mydata.dat* is telling the program to send the input of mydata.dat to *wc -l*'s standard input.

*wc -l mydata.dat* is telling the program to open mydata.dat and generate the output of the wordcount of the lines.

**3**

*uniq* removes only adjacent duplicated lines in order to make reading through large datasets easier or save space. You can use additional commands to help read through larger data sets as well. For example, you can use the *uniq -c* command to count the occurences of lines in a file. Or, if you are looking for the data that is completely unique and not duplicated at all within a file you can use the *uniq -u* command.

If you wanted to combine the command with a pipe you could use something like *sort salmon.txt | uniq*. This will remove all adjacent duplicant lines.

**4**

2012-11-06,deer is at head -5; 2012-11-06,fox is at tail -3; *sort -r* reverses their order and *> final.txt* puts the output in a final.txt file. The output will be:

```

2012-11-06,fox
2012-11-06,deer

```

**5**

You could create this pipeline to see what animals are in this file and generate the output in a separate file: *cut -d , -f 2 animals.txt | sort | uniq > final.txt*


text:
module RailsAdmin
  module Config
    module Actions

      class << self
        def all(scope = nil, bindings = {})
          if scope.is_a?(Hash)
            bindings = scope
            scope = :all
          end
          scope ||= :all
          init_actions!
          actions = case scope
          when :all
            @@actions
          when :root
            @@actions.select(&:root?)
          when :collection
            @@actions.select(&:collection?)
          when :bulkable
            @@actions.select(&:bulkable?)
          when :member
            @@actions.select(&:member?)
          end
          actions = actions.map{ |action| action.with(bindings) }
          bindings[:controller] ? actions.select(&:visible?) : actions
        end

        def find custom_key, bindings = {}
          init_actions!
          action = @@actions.find{ |a| a.custom_key == custom_key }.try(:with, bindings)
          bindings[:controller] ? (action.try(:visible?) && action || nil) : action
        end

        def collection key, parent_class = :base, &block
          add_action key, parent_class, :collection, &block
        end

        def member key, parent_class = :base, &block
          add_action key, parent_class, :member, &block
        end

        def root key, parent_class = :base, &block
          add_action key, parent_class, :root, &block
        end

        def add_action key, parent_class, parent, &block
          a = "RailsAdmin::Config::Actions::#{parent_class.to_s.camelize}".constantize.new
          a.instance_eval(%{
            #{parent} true
            def key
              :#{key}
            end
          })
          a.instance_eval(&block) if block
          unless a.custom_key.in?((@@actions || []).map(&:custom_key))
            (@@actions ||= []) << a
          else
            raise "Action #{a.custom_key} already exist. Please change its custom key"
          end
        end

        def reset
          @@actions = nil
        end

        def register(name, klass = nil)
          if klass == nil && name.kind_of?(Class)
            klass = name
            name = klass.to_s.demodulize.underscore.to_sym
          end

          instance_eval %{
            def #{name}(&block)
              action = #{klass}.new
              action.instance_eval &block if block
              unless action.custom_key.in?((@@actions || []).map(&:custom_key))
                (@@actions ||= []) << action
              else
                raise "Action \#{action.custom_key} already exist. Please change its custom key"
              end
            end
          }
        end

        private

        def init_actions!
          @@actions ||= [
            Dashboard.new,
            Index.new,
            Show.new,
            New.new,
            Edit.new,
            Export.new,
            Delete.new,
            BulkDelete.new,
            HistoryShow.new,
            HistoryIndex.new,
            ShowInApp.new,
          ]
        end

      end
    end
  end
end

require 'rails_admin/config/actions/base'
require 'rails_admin/config/actions/dashboard'
require 'rails_admin/config/actions/index'
require 'rails_admin/config/actions/show'
require 'rails_admin/config/actions/show_in_app'
require 'rails_admin/config/actions/history_show'
require 'rails_admin/config/actions/history_index'
require 'rails_admin/config/actions/new'
require 'rails_admin/config/actions/edit'
require 'rails_admin/config/actions/export'
require 'rails_admin/config/actions/delete'
require 'rails_admin/config/actions/bulk_delete'


text:
package io.crate.expression.reference.sys.job;

import io.crate.auth.user.User;
import io.crate.planner.operators.StatementClassifier.Classification;

import javax.annotation.Nullable;
import java.util.UUID;

public class JobContext {

    private final UUID id;
    private final String username;
    private final String stmt;
    private final long started;
    @Nullable
    private final Classification classification;

    public JobContext(UUID id, String stmt, long started, User user, @Nullable Classification classification) {
        this.id = id;
        this.stmt = stmt;
        this.started = started;
        this.username = user.name();
        this.classification = classification;
    }

    public UUID id() {
        return id;
    }

    public String stmt() {
        return stmt;
    }

    public String username() {
        return username;
    }

    public long started() {
        return started;
    }

    @Nullable
    public Classification classification() {
        return classification;
    }

    @Override
    public String toString() {
        return "JobContext{" +
               "id=" + id +
               ", username='" + username + '\'' +
               ", stmt='" + stmt + '\'' +
               ", started=" + started +
               ", classification=" + classification +
               '}';
    }
}


text:
	<title>Maggie Alphonsi's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Maggie Alphonsi's panel show appearances

Maggie Alphonsi (born 1983-12-20[ref]) has appeared in 2 episodes between 2016-2017.  Maggie Alphonsi on Wikipedia.

2016

2017

2017-02-08 / A Question of Sport

2016-07-08 / A Question of Sport


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Caloplaca avium Imshaug

### Remarks
null


text:
package org.onesocialweb.openfire.model.activity;

import java.util.Date;

import org.onesocialweb.model.activity.ActivityFactory;
import org.onesocialweb.model.atom.DefaultAtomHelper;
import org.onesocialweb.openfire.model.acl.PersistentAclDomReader;
import org.onesocialweb.openfire.model.atom.PersistentAtomDomReader;
import org.onesocialweb.xml.dom.AclDomReader;
import org.onesocialweb.xml.dom.ActivityDomReader;
import org.onesocialweb.xml.dom.AtomDomReader;

public class PersistentActivityDomReader extends ActivityDomReader {

	@Override
	protected AclDomReader getAclDomReader() {
		return new PersistentAclDomReader();
	}

	@Override
	protected ActivityFactory getActivityFactory() {
		return new PersistentActivityFactory();
	}

	@Override
	protected AtomDomReader getAtomDomReader() {
		return new PersistentAtomDomReader();
	}

	@Override
	protected Date parseDate(String atomDate) {
		return DefaultAtomHelper.parseDate(atomDate);
	}

}


text:
"""
Example of script to parcellate mutli-subject data
author: Bertrand Thirion, 2005-2009
"""
import os.path as op
import cPickle
import tempfile

from nipy.neurospin.spatial_models.parcellation import Parcellation
from nipy.neurospin.spatial_models.parcel_io import *
from nipy.neurospin.spatial_models.hierarchical_parcellation import hparcel
import get_data_light

# Get the data
get_data_light.getIt()
nbsubj = 12
subj_id = range(nbsubj)
numbeta = [29]
data_dir = op.expanduser(op.join('~', '.nipy', 'tests', 'data',
                                 'group_t_images'))
mask_images = [op.join(data_dir,'mask_subj%02d.nii'%n)
               for n in range(nbsubj)]

learn_images =[[ op.join(data_dir,'spmT_%04d_subj_%02d.nii'%(nb,n))
                 for nb in numbeta]
                 for n in range(nbsubj)]
test_images=learn_images

nbeta = len(numbeta)

# parameter for the intersection of the mask
ths = nbsubj/2

# possibly, dimension reduction can performed on the input data
# (not recommended)
fdim = 3

# verbosity mode
verbose = 1

# number of parcels
nbparcel = 500

# write dir
swd = tempfile.mkdtemp()

# prepare the parcel structure
fpa,ldata,coord = parcel_input(mask_images,nbeta,learn_images,ths,fdim)
fpa.k = nbparcel

# run the algorithm
fpa = hparcel(fpa,ldata,coord)
#fpa,prfx0 = hparcel(fpa,ldata,coord,nbperm=200,niter=5,verbose)

#produce some output images
Parcellation_output(fpa,mask_images,learn_images,coord,subj_id,
                    verbose=1,swd=swd)

# do some parcellation-based analysis:
# take some test images whose parcel-based signal needs to be assessed
test_images=learn_images

# a design matrix for possibly subject-specific effects
DMtx = None

# compute and write the parcel-based statistics
Parcellation_based_analysis(fpa,test_images,numbeta,swd,DMtx,verbose)

print "Wrote everything in %s" %swd


text:
/**
 * Functions for working with the automagic URI/Slug generation with multipleslug support.
 *
 * @mixin
 * @namespace Bolt.fields.slug
 *
 * @param {Object} bolt - The Bolt module.
 * @param {Object} $ - jQuery.
 */
(function (bolt, $) {
    'use strict';

    /**
     * Field configuration.
     *
     * @typedef {Object} FieldConf
     * @memberof Bolt.fields.slug
     *
     * @property {string} bind - Always 'slug'.
     * @property {string|null} contentId - Content Id.
     * @property {boolean} isEmpty - Is not set?
     * @property {string} key - The field key
     * @property {string} slug - Content slug.
     * @property {Array} uses - Fields used to automatically generate a slug.
     */

    /**
     * Field data.
     *
     * @typedef {Object} FieldData
     * @memberof Bolt.fields.slug
     *
     * @property {Object} group - Group container.
     * @property {Object} show - Slug display.
     * @property {Object} data - Data field.
     * @property {Object} lock - Lock button.
     * @property {Object} unlock - Unlock button.
     * @property {Object} edit - Edit button.
     * @property {string} key - The field key
     * @property {Array} uses - Fields used to automatically generate a slug.
     * @property {string} slug - Content slug.
     * @property {string|null} id - Content Id.
     */

    /**
     * Bolt.fields.slug mixin container.
     *
     * @private
     * @type {Object}
     */
    var slug = {};

    /**
     * Bind slug field.
     *
     * @static
     * @function init
     * @memberof Bolt.fields.slug
     *
     * @param {Object} fieldset
     * @param {FieldConf} fconf
     */
    slug.init = function (fieldset, fconf) {
        var field = {
                group: $(fieldset).find('.input-group'),
                show: $(fieldset).find('em'),
                data: $(fieldset).find('input'),
                lock: $(fieldset).find('li.lock a'),
                unlock: $(fieldset).find('li.unlock a'),
                edit: $(fieldset).find('li.edit a'),
                key: fconf.key,
                uses: fconf.uses,
                slug: fconf.slug,
                id: fconf.contentId
            };

        field.lock.on('click', function () {
            lock(field);
        });

        field.unlock.on('click', function () {
            unlock(field, fconf.isEmpty);
        });

        field.edit.on('click', function () {
            edit(field);
        });

        if (fconf.isEmpty) {
            field.unlock.trigger('click');
        }
    };

    /**
     * Timeout.
     *
     * @private
     * @type {Array}
     * @memberof Bolt.fields.slug
     */
    var timeout = [];

    /**
     * Locks the slug field.
     *
     * @private
     * @function lock
     * @memberof Bolt.fields.slug
     *
     * @param {FieldData} field - Field data.
     */
    function lock(field) {
        field.group.removeClass('unlocked').addClass('locked');
        stopAutoGeneration(field);
    }

    /**
     * Unlocks the slug field.
     *
     * @private
     * @function unlock
     * @memberof Bolt.fields.slug
     *
     * @param {FieldData} field - Field data.
     * @param {boolean} wasEmpty - Slug is currently empty
     */
    function unlock(field, wasEmpty) {
        // "unlock" if it's currently empty, _or_ we've confirmed that we want to do so.
        if (wasEmpty || confirm(bolt.data('field.slug.message.unlock'))) {
            field.group.removeClass('locked').addClass('unlocked');
            startAutoGeneration(field);
        }
    }

    /**
     * Edit the slug.
     *
     * @private
     * @function edit
     * @memberof Bolt.fields.slug
     *
     * @param {FieldData} field - Field data.
     */
    function edit(field) {
        var newslug = prompt(bolt.data('field.slug.message.set'), field.data.val());

        if (newslug) {
            field.group.removeClass('unlocked').addClass('locked');
            stopAutoGeneration(field);
            getUriAjax(field, newslug);
        }
    }

    /**
     * Get URI for slug from remote.
     *
     * @private
     * @function getUriAjax
     * @memberof Bolt.fields.slug
     *
     * @param {FieldData} field - Field data.
     * @param {string} text - New slug text.
     */
    function getUriAjax(field, text) {
        $.ajax({
            url: bolt.conf('paths.async') + 'makeuri',
            type: 'GET',
            data: {
                title: text,
                contenttypeslug: field.slug,
                id: field.id,
                slugfield: field.key,
                fulluri: false
            },
            success: function (uri) {
                field.data.val(uri);
                field.show.html(uri);
            },
            error: function () {
                console.log('failed to get an URI');
            }
        });
    }

    /**
     * Start generating slugs from uses fields.
     *
     * @private
     * @function startAutoGeneration
     * @memberof Bolt.fields.slug
     *
     * @param {FieldData} field - Field data.
     */
    function startAutoGeneration(field) {
        $.each(field.uses, function (i, bindField) {
            $('#' + bindField).on('propertychange.bolt input.bolt change.bolt', function () {
                var usesValue = [];

                $.each(field.uses, function (i, useField) {
                    var field = $('#' + useField);

                    if (field.is('select')) {
                        field.find('option:selected').each(function(i, option) {
                            if (option.text !== '') {
                                usesValue.push(option.text);
                            }
                        });
                    } else if (field.val()) {
                        usesValue.push(field.val());
                    }
                });

                clearTimeout(timeout[field.key]);
                timeout[field.key] = setTimeout(
                    function () {
                        getUriAjax(field, usesValue.join(' '));
                    },
                    200
                );
            }).trigger('change.bolt');
        });
    }

    /**
     * Stop generating slugs from uses fields.
     *
     * @private
     * @function stopAutoGeneration
     * @memberof Bolt.fields.slug
     *
     * @param {FieldData} field - Field data.
     */
    function stopAutoGeneration(field) {
        $.each(field.uses, function (i, name) {
            $('#' + name).off('propertychange.bolt input.bolt change.bolt');
        });
        clearTimeout(timeout[field.key]);
    }

    // Apply mixin container
    bolt.fields.slug = slug;

})(Bolt || {}, jQuery);


text:
/*
Author: Håkan Arnoldson
For Web applications at Lernia YH
*/

!function (window,document,undefined) {
//main closure
"use strict";

window.usersLastConvInput = "";
//GLOBAL variable - prevents button spam by keeping track of last input

window.onresize = function() {
  /* Resize listener that removes bootstrap classes on media query activation for nav
  Bootstrap was too much and too specific CSS to override so I used this options
  It also caused a wierd conflict in Safari only with the 3d-animation that made the menu go invisible
  when just trying to solve this by CSS overrides

  This issue also comes from starting the design without Bootstrap. Since Bootstrap is overkill
  for my intended design. But later finding that using Bootstrap was requred by the assignment specs.

  It would have been easier to simply not use bootstrap and make my own dropdown.
  I tried using a bootstrap collapsable for the button only but it does not work well inline at all when the entire nav bar isnt bootstrap.
  Doing that much modification of Bootstrap also seemed a bit overkill, since you would probably not have used it in the first place in such a scenario
  */

  menuToggle();

};

// This function runs at start and on window resize and changes the menu from dropdown to list or vice versa. See listener above.
function menuToggle() {
  if (window.getComputedStyle(document.getElementsByClassName('nav-drop-btn')[0]).getPropertyValue('display') == 'none') {
    //if media query has activated to show hide the dropdown button

    document.getElementById('contactMenu').className = "menu-list";
    document.getElementById('dropdownToggle').className = "";
  } else {
    document.getElementById('contactMenu').className = "dropdown";
    document.getElementById('dropdownToggle').className = "dropdown-menu";
  }
}

window.onload = function() {

  menuToggle();  //sets the menu classes right for display width

  /*rewrite LinkedIn links if client language is set to prefer swedish */
  if (navigator.language.substring(0, 2) == "sv") {
    var els = Array.prototype.slice.call(document.getElementsByClassName('linkedin-link'));
    els.forEach(function(el,i) {
      els[i].setAttribute('href', 'https://www.linkedin.com/in/arnoldson/sv');
    });
  }

  /* get main data */
  $.when(
    $.ajax({
      url: "https://api.coinbase.com/v2/currencies",
      dataType: 'json'
    }),
    $.ajax({
      url: "https://ipinfo.io",
      dataType: 'json'
    }),
    $.ajax({
      url: "data/country-codes.csv",
      dataType: 'text'
  }))
  .done(function(curr, ip, codes) {

    printCurrencylists(curr[0]); //$.when creates a "success" array on top of the data. The regular response is at position 0

    //move on to try to help out by setting default currencies based on geo-location from ipinfo.io
    var arrValidCurrencies = curr[0].data.map( function (item) {
      return item.id.trim();
    });

    var arrContryCurrency = codes[0].split('\n'); //[0] because $.when adds an array to track success

    var successfull = false;  //we need to keep track if we managed to set a value of the currency coverted selectors. They need to have a inital value to prevent errors later.

    for (var i = 0; i < arrContryCurrency.length; i++) {
      arrContryCurrency[i] = arrContryCurrency[i].split(',');  //creates a multi-dimensional array arrContryCurrency[pair][0=country, 1=currency]

      //check right away so we dont need to iterate again, also checks if the currency is availiable from the API and in our values
      if ((arrContryCurrency[i][0].trim() == ip[0].country.trim()) && (arrValidCurrencies.indexOf(arrContryCurrency[i][1].trim()) != -1)) {
        document.getElementById('from-currency').value = arrContryCurrency[i][1].trim();
        document.getElementById('to-currency').value = arrContryCurrency[i][1].trim();
        successfull = true;
        break; //if found we can stop this thing
      };
    };

    if (successfull === false) {
      setDefaultInitalValuesinConverter(arrValidCurrencies[0]);
    };

    loadingComplete(); //removes loading screen and shows the site
  })
  .fail(function() {
    //if fail retry for main currency API ONLY
    $.ajax({
      url: "https://api.coinbase.com/v2/currencies",
      dataType: 'json'
    })
    .done(function(curr) {
      printCurrencylists(curr);

      var firstvalidcurrency = curr.data[0].id.trim();
      setDefaultInitalValuesinConverter(firstvalidcurrency);

      loadingComplete();
    })
    .fail(function() {

      loadingFailed();

    });
  });
  /* get main data ends */

  // Get the bitcoin spot price and print in our navbar
  $.getJSON("https://api.coinbase.com/v2/prices/BTC-USD/spot")
    .done(function(data) {
      eraseAllChildren(document.getElementById("bitcoin-price"));
      var price = data.data.amount;
      var t = document.createTextNode(price);
      document.getElementById("bitcoin-price").appendChild(t);
    })
    .fail(function() {
      eraseAllChildren(document.getElementById("bitcoin-price"));
      var t = document.createTextNode("n/a");
      document.getElementById("bitcoin-price").appendChild(t);
    });

  /* Initate listeners */

  document.getElementById('convert-btn').addEventListener("click", function (event) {
    event.preventDefault();
    //Lock it down immediatly to preven double clicking until after error handling or ajax
    event.target.disabled = true;
    event.target.style.boxShadow = "none";
    event.target.style.transform = "translateX(2px) translateY(2px)";

    //the button is passed along to be unlocked after we have done what we want
    convertCurrency(event.target);
  });

  document.getElementById('table-btn').addEventListener("click", function (event) {
    event.preventDefault();
    var goto = 'cross-rates.html?base=';
    var seloptions = selectedToArray(document.getElementById('base-currencies')); //returns selected options as array
    goto += seloptions.join(); //array to strong
    goto += "&pair=";
    var seloptions = selectedToArray(document.getElementById('pair-currencies'));
    goto += seloptions.join();

    window.location.href = goto;

  });

}
//end window.onload

/* - FUNCTIONS - */

/*
 Function: printCurrencylists
 Takes the json data from https://api.coinbase.com/v2/currencies
 Writes currency code and description into the DOM in every ul with class currencylist
*/
function printCurrencylists(curr) {
  //map ex {SEK: Swedish Kroner} from response to new array
  var currencies = curr.data.map(function(item) {
    var rObj = {};
    rObj[item.id] = item.name;
    return rObj;
  });
  for (var j = 0; j < document.getElementsByClassName('currencylist').length; j++) {
    for(var i = 0; i < currencies.length; i++) {
      var li = document.createElement("OPTION");
      li.setAttribute("value", Object.keys(currencies[i]));
      var text = Object.keys(currencies[i]) + " - " + currencies[i][Object.keys(currencies[i])];
      var t = document.createTextNode(text);
      li.appendChild(t);
      document.getElementsByClassName('currencylist')[j].appendChild(li);
    };
  };
};

/*
  Function loadingComplete
  Hides the loading section and displays the currency sections.
*/
function loadingComplete() {
  $("#main-header").fadeOut("fast");
  $(".loading").fadeOut("fast", function() {
    $("#main-nav").fadeIn("slow");
    $(".converter").fadeIn("slow");
    $(".crossrates").fadeIn("slow");
    $("#main-footer").fadeIn("slow");
  });
};

/*
  Function loadingFailed
  Ohh noes! The main currency API is down!
*/
function loadingFailed() {
  eraseAllChildren(document.getElementsByClassName('loading')[0]);
  var t1 = document.createTextNode ("Ohh no! Coinbase appears to be sleeping, please ");
  var t2 = document.createTextNode ("try again");
  var t3 = document.createTextNode (".");

  var a = document.createElement("A");
  a.setAttribute('href', '.');
  a.appendChild(t2);

  var h4 = document.createElement("H4");
  h4.appendChild(t1);
  h4.appendChild(a);
  h4.appendChild(t3);

  var i = document.createElement("I");
  i.setAttribute('class', 'fa fa-frown-o fa-5x'); //big sadface :(
  i.setAttribute('aria-hidden', 'true');

  document.getElementsByClassName('loading')[0].appendChild(i);
  document.getElementsByClassName('loading')[0].appendChild(h4);
};

/*
  Function convertCurrency
  This is the initalizer and error handling for the main conversion
*/
function convertCurrency(unlockme) {

  var amount = document.getElementById('from-currency-amount').value.trim();
  //remove common thousand separators
  amount = amount.replace(' ','');
  amount = amount.replace(',','');

  if (testIfIntorDec(amount)) {
    // we have something that looks like digits!
    // first return the input back to the user in our standard format.
    // this could be usefull if the user for instance used another decimal separator then . and got unexpected
    // results from our code removing the thousand seperators
    document.getElementById('from-currency-amount').value = accounting.formatNumber(accounting.toFixed(amount, decimalsCalc(amount)), decimalsCalc(amount), " ");

    //FROM->TO conversion
    convertCurrencyCalculator(amount, document.getElementById('from-currency').value, document.getElementById('to-currency').value, document.getElementById('answer-currency-amount'), unlockme);

  } else {
    //now we want to check if the user might have wanted to do a reverse convert and put something valid in the into field instead
    var amount = document.getElementById('answer-currency-amount').value.trim();
    amount = amount.replace(' ','');
    amount = amount.replace(',','');

    if (testIfIntorDec(amount)) {
      //again return the sanitized input back to its origin making sure output is correct
      document.getElementById('answer-currency-amount').value = accounting.formatNumber(accounting.toFixed(amount, decimalsCalc(amount)), decimalsCalc(amount), " ");

      //TO->FROM conversion
      convertCurrencyCalculator(amount, document.getElementById('to-currency').value, document.getElementById('from-currency').value, document.getElementById('from-currency-amount'), unlockme);

    } else {

      //We didnt find anything valid to convert. Tell the user and clear booth field.

      var elements = document.getElementsByClassName('form-in');

      for (var i = 0; i < elements.length; i++) {
        if (getComputedStyle(elements[i]).getPropertyValue("background-color") != "rgb(255, 0, 0)") { //doesnt run if already red. to not create multiple timeouts
          elements[i].style.backgroundColor = "red";
          setTimeout( function(e, o) {
            setBgColor(e, o);
          }, 2500, elements[i], null);
        };
      };
      var t = document.createTextNode("There is no valid input. Please enter a integer or decimal (using . as deceimal separator) in either the from or to currency field.");
      var p = document.createElement("P");
      p.setAttribute("class", "input-currency-error-message");
      p.appendChild(t);

      $('.input-currency-error-message').hide(); //hide already exisitng messages (only hide, dont delete. so they timer is not interruped causeing warnings)

      insertAfternojq(document.getElementById('convert-btn'), p);

      //reset invalid input to null
      document.getElementById('answer-currency-amount').value = "";
      document.getElementById('from-currency-amount').value = "";

      //either way make it expire
      setTimeout( function(e) {
        deleteMe(e); //deletes if exist
      }, 4500, p);

      //finally unlock button
      unlockme.disabled = false;
      unlockme.removeAttribute('style');

      //Ends error message on no valid input

    };
  };
};

/*
  Function convertCurrencyCalculator
  Does the actual conversion calculation and rate ajax call
*/

function convertCurrencyCalculator(amount, base, target, output, unlockme) {

  var inputcompare = accounting.formatNumber(accounting.toFixed(amount, decimalsCalc(amount)), decimalsCalc(amount), " ") + base + target + output.id;

  if (window.usersLastConvInput != inputcompare) {

    //lock input and show we are loading
    document.getElementById('answer-currency-amount').disabled = true;
    document.getElementById('from-currency-amount').disabled = true;
    document.getElementById('to-currency').disabled = true;
    document.getElementById('from-currency').disabled = true;

    var i = document.createElement("I");
    i.setAttribute("class", "fa fa-spinner fa-spin fa-3x fa-fw");
    var p = document.createElement("P");
    p.setAttribute("style", "color:orange; padding-top: 5px;");
    p.setAttribute("class", "input-currency-loading-message");
    p.appendChild(i);

    insertAfternojq(document.getElementById('convert-btn'), p);

    window.usersLastConvInput = inputcompare;

    $.getJSON("https://api.coinbase.com/v2/exchange-rates?currency=" + base)
      .done(function(data) {
        if (data.data.rates[target] != 0) { //the API is returning zero for all prices if the rates dont exist currently.
          var result = data.data.rates[target] * amount;
          output.value = accounting.formatNumber(accounting.toFixed(result, decimalsCalc(result)), decimalsCalc(result), " ");
        } else {
            output.value = "N/A"; //Prints N/A when the api gives us a rate of 0
        }
        unlockme.disabled = false;
        unlockme.removeAttribute('style');
        document.getElementById('answer-currency-amount').disabled = false;
        document.getElementById('from-currency-amount').disabled = false;
        document.getElementById('to-currency').disabled = false;
        document.getElementById('from-currency').disabled = false;
        $( ".input-currency-loading-message" ).remove();

      })
      .fail(function() {
        output.value = "ERROR!";
        unlockme.disabled = false;
        unlockme.removeAttribute('style');
        document.getElementById('answer-currency-amount').disabled = false;
        document.getElementById('from-currency-amount').disabled = false;
        document.getElementById('to-currency').disabled = false;
        document.getElementById('from-currency').disabled = false;
        $( ".input-currency-loading-message" ).remove();
      });

    } else {
      //nothing changed
      unlockme.disabled = false;
      unlockme.removeAttribute('style');

      // print error messagte
      var t = document.createTextNode("Seems you already asked for this conversion. Please change something and try again.");
      var p = document.createElement("P");
      p.setAttribute("class", "input-currency-error-message");
      p.appendChild(t);

      $('.input-currency-error-message').hide(); //hide already exisitng messages (only hide, dont delete. so they timer is not interruped causeing warnings)

      insertAfternojq(document.getElementById('convert-btn'), p);

      //make it expire
      setTimeout( function(e) {
        deleteMe(e); //deletes if exist
      }, 4000, p);

    }
};

/** Smaller help functions **/

function setBgColor(el, col) {
  el.style.backgroundColor = col;
};

function eraseAllChildren(node) {
  while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
  };
};

function testIfIntorDec(value) {
  if (/^\d*\.?\d+$/.test(value)) {
    return true;
  } else {
    return false;
  }
}

function deleteMe(el) {
  if (el != null) {
    el.parentNode.removeChild(el);
  };
};

function setDefaultInitalValuesinConverter(valid) {
  document.getElementById('from-currency').value = valid;
  document.getElementById('to-currency').value = valid;
}

function insertAfternojq(targetnode, el) {
  if (targetnode.nextSibling != null) {
  //if not last child
  targetnode.parentNode.insertBefore(el, targetnode.nextSibling);    //in parent of target -> insert p before what is after target (insertAfter does not exist in vanilla).
  } else {
  //we are at the last child and dont need insertAfter
  targetnode.parentNode.appendChild(el);                             //we are already last
  };
};

function selectedToArray(select) {
  var options = Array.prototype.slice.call(select.options); //collection -> array
  //filter and map only select options to seloptions
  var seloptions = options.filter(function (item) {
    return item.selected;
  }).map(function (item) {
    return item.value;
  });
  return seloptions;
}

function decimalsCalc(x) {
//return 2 if number is 1 or greater else return 4
  if (x < 1) {
    return 4;
  } else {
    return 2;
  }
}
//end main closure
} (this,document);


text:
<readable><title>2505360288_c972bd29c4</title><content>
A daschund with an open mouth appears to bark at a bubble making machine in the grass .
A dog trying to catch bubbles from a bubble machine in the grass .
a small brown dog in the grass trying to catch bubbles
A small brown dog playing with bubbles in grass .
A wiener dog bites at bubbles made by a bubble blowing machine .
</content></readable>


text:
package org.apache.lucene.index;

import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;

public class TestForTooMuchCloning extends LuceneTestCase {

  // Make sure we don't clone IndexInputs too frequently
  // during merging:
  public void test() throws Exception {
    // NOTE: if we see a fail on this test with "NestedPulsing" its because its
    // reuse isnt perfect (but reasonable). see TestPulsingReuse.testNestedPulsing
    // for more details
    final MockDirectoryWrapper dir = newMockDirectory();
    final TieredMergePolicy tmp = new TieredMergePolicy();
    tmp.setMaxMergeAtOnce(2);
    final RandomIndexWriter w = new RandomIndexWriter(random(), dir,
                                                      newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMaxBufferedDocs(2).setMergePolicy(tmp));
    final int numDocs = 20;
    for(int docs=0;docs<numDocs;docs++) {
      StringBuilder sb = new StringBuilder();
      for(int terms=0;terms<100;terms++) {
        sb.append(_TestUtil.randomRealisticUnicodeString(random()));
        sb.append(' ');
      }
      final Document doc = new Document();
      doc.add(new TextField("field", sb.toString(), Field.Store.NO));
      w.addDocument(doc);
    }
    final IndexReader r = w.getReader();
    w.close();

    final int cloneCount = dir.getInputCloneCount();
    //System.out.println("merge clone count=" + cloneCount);
    assertTrue("too many calls to IndexInput.clone during merging: " + dir.getInputCloneCount(), cloneCount < 500);

    final IndexSearcher s = newSearcher(r);

    // MTQ that matches all terms so the AUTO_REWRITE should
    // cutover to filter rewrite and reuse a single DocsEnum
    // across all terms;
    final TopDocs hits = s.search(new TermRangeQuery("field",
                                                     new BytesRef(),
                                                     new BytesRef("\uFFFF"),
                                                     true,
                                                     true), 10);
    assertTrue(hits.totalHits > 0);
    final int queryCloneCount = dir.getInputCloneCount() - cloneCount;
    //System.out.println("query clone count=" + queryCloneCount);
    assertTrue("too many calls to IndexInput.clone during TermRangeQuery: " + queryCloneCount, queryCloneCount < 50);
    r.close();
    dir.close();
  }
}


text:
#ifndef FFT_H
#define FFT_H
#include "FFT.h";

class FFT{

private:

	// Arrays
	float *twiddles, *invTwiddles, *halfTwiddles, *invHalfTwiddles, *scratch, *tempArray;

	// Variables
	int FFT_SIZE;

	// Methods
	void computeTwiddleFactors(float* twiddle, int fftLength, float sign);
	void FFTHelper(float* x, int fftLength, float* X, float* twiddle, int imagStart);
	void polarToComplex(float mag, float phase, float* ans);

public:

	FFT();
	FFT(int N);
	~FFT();

	// Methods

	void computeTwiddles();
	void complexFFT(float* x, float* output, int sign);
	void initFFT(int N);
	void realFFT(float* x, float *out, int sign);
	void pack(float* input);
	void unpackTime(float* input);
	void unpackFrequency(float* input);
};

#endif


text:
package dev.code_n_roll.gatling.jdbc.protocol

import io.gatling.core.protocol.ProtocolComponents
import io.gatling.core.session.Session

/**
  * Created by ronny on 10.05.17.
  */
case class JdbcComponents(protocol: JdbcProtocol) extends ProtocolComponents {

  override def onStart: Session => Session = ProtocolComponents.NoopOnStart

  override def onExit: Session => Unit = ProtocolComponents.NoopOnExit

}


text:
package com.rwxlicai.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Environment;

import com.activeandroid.ActiveAndroid;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.rwxlicai.R;
import com.umeng.socialize.PlatformConfig;

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

/**
 * Created by xuebing on 15/12/28.
 */
public class BaseApplication extends Application {

    protected ImageLoader imageLoader;
    public static Context applicationContext;
    public SharedPreferences sharedPreferences;
    public static final String APP_ID = "com.xem.mzbphoneapp";

    @Override
    public void onCreate() {
        super.onCreate();
        applicationContext = getApplicationContext();

//        activeAndroid初始化
        ActiveAndroid.initialize(this);

        //初始化键值对存储
        sharedPreferences = getSharedPreferences(APP_ID, MODE_PRIVATE);
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                this)
                .memoryCacheExtraOptions(480, 800)
                        // max width, max height,即保存的每个缓存文件的最大长宽
                .discCacheExtraOptions(480, 800, null)
                        // Can slow ImageLoader, use it carefully (Better don't use
                        // it)/设置缓存的详细信息,最好不要设置这个
                .threadPoolSize(3)
                        // 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
                        // You can pass your own memory cache
                        // implementation/你可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024)
                .discCacheSize(50 * 1024 * 1024)
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                        // 将保存的时候的URI名称用MD5 加密
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .discCacheFileCount(100)
                        // 缓存的文件数量
                .discCache(
                        new UnlimitedDiscCache(new File(Environment
                                .getExternalStorageDirectory()
                                + "/avater")))
                        // 自定义缓存路径
                .defaultDisplayImageOptions(getDisplayOptions())
                .imageDownloader(
                        new BaseImageDownloader(this, 5 * 1000, 30 * 1000))
                .writeDebugLogs() // Remove for release app
                .build();// 开始构建
        ImageLoader.getInstance().init(config);
    }

    private DisplayImageOptions getDisplayOptions() {
        DisplayImageOptions options;
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.launcher) // 设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.launcher)// 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.launcher) // 设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
                .considerExifParams(true) // 是否考虑JPEG图像EXIF参数(旋转,翻转)
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
                .resetViewBeforeLoading(true)// 设置图片在下载前是否重置,复位
                .displayer(new RoundedBitmapDisplayer(20))// 是否设置为圆角,弧度为多少
                .displayer(new FadeInBitmapDisplayer(100))// 是否图片加载好后渐入的动画时间
                .build();// 构建完成
        return options;
    }

    private List<Activity> mList = new LinkedList<Activity>();
    private static BaseApplication instance;
    public synchronized static BaseApplication getInstance() {
        if (null == instance) {
            instance = new BaseApplication();
        }
        return instance;
    }
    // add Activity
    public void addActivity(Activity activity) {
        mList.add(activity);
    }

    public void exit() {
        try {
            for (Activity activity : mList) {
                if (activity != null)
                    activity.finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }

    //各个平台的配置,建议放在全局Application或者程序入口
    {
        PlatformConfig.setWeixin("wxe4cbfd958d053f38", "9493b056c24b61db05141ec0ce55e425");

        PlatformConfig.setQQZone("1105149864", "KEYukI6WLtnZf9DWWq4");

    }
}


text:
module Paysio
  class Customer < Paysio::Resource
    include Paysio::Actions::List
    include Paysio::Actions::Create
    include Paysio::Actions::Update
    include Paysio::Actions::Destroy
    include Paysio::Actions::Find
    resource :customer
  end
end


text:
require 'spec_helper'

describe Mail::ContentTransferEncodingField do

  # Content-Transfer-Encoding Header Field
  #
  # Many media types which could be usefully transported via email are
  # represented, in their "natural" format, as 8bit character or binary
  # data.  Such data cannot be transmitted over some transfer protocols.
  # For example, RFC 821 (SMTP) restricts mail messages to 7bit US-ASCII
  # data with lines no longer than 1000 characters including any trailing
  # CRLF line separator.
  #
  # It is necessary, therefore, to define a standard mechanism for
  # encoding such data into a 7bit short line format.  Proper labelling
  # of unencoded material in less restrictive formats for direct use over
  # less restrictive transports is also desireable.  This document
  # specifies that such encodings will be indicated by a new "Content-
  # Transfer-Encoding" header field.  This field has not been defined by
  # any previous standard.
  #
  # 6.1.  Content-Transfer-Encoding Syntax
  #
  # The Content-Transfer-Encoding field's value is a single token
  # specifying the type of encoding, as enumerated below.  Formally:
  #
  #   encoding := "Content-Transfer-Encoding" ":" mechanism
  #
  #   mechanism := "7bit" / "8bit" / "binary" /
  #                "quoted-printable" / "base64" /
  #                ietf-token / x-token
  #
  # These values are not case sensitive -- Base64 and BASE64 and bAsE64
  # are all equivalent.  An encoding type of 7BIT requires that the body
  #
  # is already in a 7bit mail-ready representation.  This is the default
  # value -- that is, "Content-Transfer-Encoding: 7BIT" is assumed if the
  # Content-Transfer-Encoding header field is not present.
  #
  describe "initialization" do

    it "should initialize" do
      expect { Mail::ContentTransferEncodingField.new("Content-Transfer-Encoding: 7bit") }.not_to raise_error
    end

    it "should accept a string with the field name" do
      t = Mail::ContentTransferEncodingField.new('Content-Transfer-Encoding: 7bit')
      expect(t.name).to eq 'Content-Transfer-Encoding'
      expect(t.value).to eq '7bit'
    end

    it "should accept a string without the field name" do
      t = Mail::ContentTransferEncodingField.new('7bit')
      expect(t.name).to eq 'Content-Transfer-Encoding'
      expect(t.value).to eq '7bit'
    end

    it "should render an encoded field" do
      t = Mail::ContentTransferEncodingField.new('7bit')
      expect(t.encoded).to eq "Content-Transfer-Encoding: 7bit\r\n"
    end

    it "should render a decoded field" do
      t = Mail::ContentTransferEncodingField.new('7bit')
      expect(t.decoded).to eq '7bit'
    end

  end

  describe "parsing the value" do

    it "should return an encoding string" do
      ["7bit", "8bit", "binary", 'quoted-printable', "base64"].each do |encoding|
        t = Mail::ContentTransferEncodingField.new(encoding)
        expect(t.encoding).to eq encoding
      end
    end

    it "should treat 7bits/7-bit and 8bits/8-bit as 7bit and 8bit" do
      %w(7bits 7-bit).each do |mechanism|
        expect(Mail::ContentTransferEncodingField.new(mechanism).encoding).to eq '7bit'
      end

      %w(8bits 8-bit).each do |mechanism|
        expect(Mail::ContentTransferEncodingField.new(mechanism).encoding).to eq '8bit'
      end
    end

    it "should handle any valid 'x-token' value" do
      t = Mail::ContentTransferEncodingField.new('X-This-is_MY-encoding')
      expect(t.encoding).to eq 'x-this-is_my-encoding'
    end

    it "should handle an x-encoding" do
      t = Mail::ContentTransferEncodingField.new("x-uuencode")
      expect(t.encoding).to eq "x-uuencode"
    end

    it "should handle an ietf encoding (practically, any token)" do
      t = Mail::ContentTransferEncodingField.new("ietf-token")
      expect(t.encoding).to eq "ietf-token"
    end

    it "should replace the existing value" do
      t = Mail::ContentTransferEncodingField.new("7bit")
      t.parse("quoted-printable")
      expect(t.encoding).to eq 'quoted-printable'
    end

    it "should raise an error on bogus values" do
      expect { Mail::ContentTransferEncodingField.new("broken@foo") }.to raise_error
    end

    it "should handle an empty content transfer encoding" do
      t = Mail::ContentTransferEncodingField.new("")
      expect(t.encoding).to eq ""
    end

    it "should handle a hyphen" do
      t = Mail::ContentTransferEncodingField.new('7-bit')
      expect(t.decoded).to eq '7bit'
      t = Mail::ContentTransferEncodingField.new('8-bit')
      expect(t.decoded).to eq '8bit'
    end

  end

end


text:
Are you ready for a miracle?

Wayne is love, Wayne is life


text:
package replicant;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Container that defies a deferred action on listener set.
 */
final class DeferredListenerAction
{
  enum ActionType
  {
    ADD, REMOVE, PURGE
  }

  private final Object _key;
  private final EntityChangeListener _listener;
  private final ActionType _actionType;

  DeferredListenerAction( @Nullable final Object key,
                          @Nullable final EntityChangeListener listener,
                          @Nonnull final ActionType actionType )
  {
    _key = key;
    _listener = listener;
    _actionType = actionType;
  }

  @Nullable
  Object getKey()
  {
    return _key;
  }

  @Nullable
  EntityChangeListener getListener()
  {
    return _listener;
  }

  ActionType getActionType()
  {
    return _actionType;
  }

  boolean isRemove()
  {
    return ActionType.REMOVE == getActionType();
  }

  boolean isAdd()
  {
    return ActionType.ADD == getActionType();
  }

  boolean isPurge()
  {
    return ActionType.PURGE == getActionType();
  }
}


text:
'use strict';

var path = require('path');
var findPkg = require('find-pkg');
var assert = require('assert');
var ignore = require('./ignore');
var cache = {};

exports.hasProperties = function(obj, keys) {
  keys = Array.isArray(keys) ? keys : [keys];
  var len = keys.length;
  var idx = -1;
  while (++idx < len) {
    assert(obj.hasOwnProperty(keys[idx]));
  }
};

exports.doesNotHaveProperties = function(obj, keys) {
  keys = Array.isArray(keys) ? keys : [keys];
  var len = keys.length;
  var idx = -1;
  while (++idx < len) {
    assert(!obj.hasOwnProperty(keys[idx]));
  }
};

exports.containEql = function containEql(actual, expected) {
  if (Array.isArray(expected)) {
    var len = expected.length;
    while (len--) {
      exports.containEql(actual[len], expected[len]);
    }
  } else {
    for (var key in expected) {
      assert.deepEqual(actual[key], expected[key]);
    }
  }
};

exports.keys = function keys(obj) {
  var arr = [];
  for (var key in obj) {
    if (ignore.indexOf(key) === -1) {
      arr.push(key);
    }
  }
  return arr;
};

/**
 * Return true if the given value is a buffer
 */

exports.isBuffer = function (val) {
  if (val && val.constructor && typeof val.constructor.isBuffer === 'function') {
    return val.constructor.isBuffer(val);
  }
  return false;
};

exports.resolve = function(filepath) {
  filepath = filepath || '';
  var key = 'app:' + filepath;
  if (cache.hasOwnProperty(key)) {
    return cache[key];
  }

  var pkg = findPkg.sync(process.cwd());
  var prefix = pkg.name !== 'templates'
    ? 'templates'
    : '';

  var base = filepath
    ? path.join(prefix, filepath)
    : process.cwd();

  var fp = tryResolve(base);

  if (typeof fp === 'undefined') {
    throw new Error('cannot resolve: ' + fp);
  }
  return (cache[key] = require(fp));
};

function tryResolve(name) {
  try {
    return require.resolve(name);
  } catch(err) {}

  try {
    return require.resolve(path.resolve(name));
  } catch(err) {}
}


text:
extern "C" {
#endif
#include "tolua++.h"
#ifdef __cplusplus
}
#endif

#include "network/WebSocket.h"
class LuaWebSocket: public network::WebSocket,public network::WebSocket::Delegate
{
public:
    virtual ~LuaWebSocket();
    virtual void onOpen(WebSocket* ws);
    virtual void onMessage(WebSocket* ws, const WebSocket::Data& data);
    virtual void onClose(WebSocket* ws);
    virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error);

    enum WebSocketScriptHandlerType
    {
        kWebSocketScriptHandlerOpen,
        kWebSocketScriptHandlerMessage,
        kWebSocketScriptHandlerClose,
        kWebSocketScriptHandlerError,
    };
};

TOLUA_API int tolua_web_socket_open(lua_State* tolua_S);

#endif //(CC_TARGET_PLATFORM == CC_PLATFORM_IOS ...

#endif //__LUA_WEB_SOCKET_H__


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

namespace Java.Interop {

	partial class __TypeRegistrations {

		public static void RegisterPackages ()
		{
#if MONODROID_TIMING
			var start = DateTime.Now;
			Android.Util.Log.Info ("MonoDroid-Timing", "RegisterPackages start: " + (start - new DateTime (1970, 1, 1)).TotalMilliseconds);
#endif // def MONODROID_TIMING
			Java.Interop.TypeManager.RegisterPackages (
					new string[]{
						"com/squareup/okhttp/internal",
						"com/squareup/okhttp/internal/spdy",
					},
					new Converter<string, Type>[]{
						lookup_com_squareup_okhttp_internal_package,
						lookup_com_squareup_okhttp_internal_spdy_package,
					});
#if MONODROID_TIMING
			var end = DateTime.Now;
			Android.Util.Log.Info ("MonoDroid-Timing", "RegisterPackages time: " + (end - new DateTime (1970, 1, 1)).TotalMilliseconds + " [elapsed: " + (end - start).TotalMilliseconds + " ms]");
#endif // def MONODROID_TIMING
		}

		static Type Lookup (string[] mappings, string javaType)
		{
			string managedType = Java.Interop.TypeManager.LookupTypeMapping (mappings, javaType);
			if (managedType == null)
				return null;
			return Type.GetType (managedType);
		}

		static string[] package_com_squareup_okhttp_internal_mappings;
		static Type lookup_com_squareup_okhttp_internal_package (string klass)
		{
			if (package_com_squareup_okhttp_internal_mappings == null) {
				package_com_squareup_okhttp_internal_mappings = new string[]{
					"com/squareup/okhttp/internal/Dns$1:Com.Squareup.Okhttp.Internal.Dns1",
				};
			}

			return Lookup (package_com_squareup_okhttp_internal_mappings, klass);
		}

		static string[] package_com_squareup_okhttp_internal_spdy_mappings;
		static Type lookup_com_squareup_okhttp_internal_spdy_package (string klass)
		{
			if (package_com_squareup_okhttp_internal_spdy_mappings == null) {
				package_com_squareup_okhttp_internal_spdy_mappings = new string[]{
					"com/squareup/okhttp/internal/spdy/IncomingStreamHandler$1:Com.Squareup.Okhttp.Internal.Spdy.IncomingStreamHandler1",
				};
			}

			return Lookup (package_com_squareup_okhttp_internal_spdy_mappings, klass);
		}
	}
}


text:
""" Create Werewolve's Puzzle.

"""
import argparse

from result import WhiteResult, BlackResult
from player import Player
import strategy

def _index_to_alphabet(index):
    """ Convert the index to the alphabet.
    """
    return chr(ord("A") + index)

class PuzzleGenereator(object):
    """ The generator of puzzle.

    :param villager_number: the number of villagers.
    :param wolf_number: the number of wolves.
    :param lunatic_number: the number of lunatics.
    :param lang: language.
    :param strategy_mode: the mode of generation.
    """
    def __init__(self, villager_number, wolf_number, lunatic_number,
                 lang="en", strategy_mode=None):
        self.villager_number = villager_number
        self.wolf_number = wolf_number
        self.lunatic_number = lunatic_number

        if villager_number <= wolf_number + lunatic_number:
            raise ValueError("villager team  MUST be larger than the wolf one.")
        self.lang = lang.lower(); assert self.lang in ["en", "jp"]

        self.index_to_player = self._initialize_players()
        self.answer = None
        strategy_class = strategy.choose_strategy(strategy_mode)
        self.strategy = strategy_class(villager_number, wolf_number, lunatic_number)

    def generate_problem(self, max_iteration=100):
        """ Generate the problems.

        :param max_iteration: the maximum iterations.
        :return: ``True``, if generated, otherwise, ``False``.
        """
        self.answer = self.strategy.generate_problem(self.index_to_player, max_iteration)
        self.index_to_player = self._revise_person_id(self.index_to_player)
        self.answer = self.strategy.generate_problem(self.index_to_player, 1)

    def display_problems(self):
        """ Display the problems.
        """
        intro_text = self._create_introduction()
        claims_text = self._create_claims()
        return "\n".join([intro_text, claims_text])

    def display_answers(self):
        """ Display the answers.
        """
        assert self.answer
        if self.lang == "en":
            first_line = "## Answer  "
        elif self.lang == "jp":
            first_line = "## 解答  "
        answer_line = self.strategy.get_answer_line(self.answer, self.lang)
        return "\n".join([first_line, answer_line])

    def _initialize_players(self):
        total_players = self.villager_number + self.wolf_number + self.lunatic_number
        player_list = [Player(index) for index in range(total_players)]
        index_to_player = {index: elem for index, elem in enumerate(player_list)}

        return index_to_player

    def _create_introduction(self):

        person_number = len(self.index_to_player)
        if self.lang == "en":
            first_line = "## Problem"
            if self.lunatic_number == 0:
                role_line = "Roles:Villager/Wolf={v}/{w}".format(v=self.villager_number,
                                                                 w=self.wolf_number)
            else:
                role_line = "Roles:Villager/Wolf/Lunatic={v}/{w}/{l}".format(v=self.villager_number,
                                                                             w=self.wolf_number,
                                                                             l=self.lunatic_number)
            player_line = "PL:{first_pl}-{last_pl}".format(first_pl="A",
                                                           last_pl=_index_to_alphabet(person_number - 1))
            second_line = role_line + ", " + player_line
        elif self.lang == "jp":
            first_line = "## 問題"
            if self.lunatic_number == 0:
                role_line = "内訳:村陣営/狼={v}/{w}".format(v=self.villager_number,
                                                            w=self.wolf_number)
            else:
                role_line = "内訳:村陣営/狼/狂={v}/{w}/{l}".format(v=self.villager_number,
                                                                   w=self.wolf_number,
                                                                   l=self.lunatic_number)
            player_line = "PL:{first_pl}-{last_pl}".format(first_pl="A",
                                                           last_pl=_index_to_alphabet(person_number - 1))
            second_line = role_line + ", " + player_line

        return "\n".join([first_line, second_line])

    def _create_claims(self):
        def _has_result(person):
            return len(person.result) > 1

        indices = sorted(self.index_to_player.keys(),
                         key=lambda index: len(self.index_to_player[index].result),
                         reverse=True)

        text_lines = list()
        if self.lang == "en":
            text_lines.append("### Player's claims")
        elif self.lang == "jp":
            text_lines.append("### 各PLの主張")
        else:
            raise ValueError("Invalid language.", self.lang)

        text_lines += [_create_player_claim(self.index_to_player[index], self.lang)
                       for index in indices
                       if _has_result(self.index_to_player[index]) is True]

        return "\n".join(text_lines)

    def _revise_person_id(self, index_to_player):
        """ Sort the persons' id, by the order of the number of claims.

        :return: the changed index_to_player.

        """
        def _replace_player_result_ids(player, replace_map):
            player.index = replace_map[player.index]
            revised_result = dict()
            revised_result = {replace_map[prev_id]: result_id
                              for prev_id, result_id in player.result.items()}
            player.result = revised_result
            player.result[player.index] = WhiteResult.get_id()
            return player

        indices = self.index_to_player.keys()
        indices = sorted(indices,
                         key=lambda index: len(self.index_to_player[index].result.keys()),
                         reverse=True)

        replace_map = {original_id: index for index, original_id
                       in enumerate(indices)}

        revised_index_to_player = dict()
        for prev_index, person in self.index_to_player.items():
            person = _replace_player_result_ids(person, replace_map)

            next_index = replace_map[prev_index]
            revised_index_to_player[next_index] = person

        return revised_index_to_player

def _create_player_claim(person, lang="en"):
    def _index_to_result(index):
        alphabet = _index_to_alphabet(index)
        result_id = person.result[index]
        string_dict = {WhiteResult.get_id(): "○", BlackResult.get_id(): "●"}
        result_string = string_dict[result_id]
        return "{0}{1}".format(alphabet, result_string)

    indices = sorted(person.result.keys())
    indices = [index for index in indices if index != person.index]
    result_list = [_index_to_result(index) for index in indices]

    my_alphabet = _index_to_alphabet(person.index)

    if lang == "en":
        claim = "{0}'s claim".format(my_alphabet)
    elif lang == "jp":
        claim = "{0}の主張".format(my_alphabet)
    return "{0}:".format(claim) + ",".join(result_list)

def create_parser():
    """ Create argparser.
    """
    parser = argparse.ArgumentParser(description="Werewolves' Puzzle Generator.")
    parser.add_argument('-villager', '-v', type=int,
                        help="the number of villagers", default=4)

    parser.add_argument('-wolf', '-w', type=int,
                        help="the number of wolves", default=1)

    parser.add_argument('-lunatics', '-l', type=int,
                        help="the number of lunatics", default=2)

    parser.add_argument('-lang', type=str,
                        help="the language", default="en", choices=['en', 'jp'])

    parser.add_argument('-max_iteration', type=int,
                        help="the maximum iterations for generator",
                        default=100)
    mode_keys = strategy.get_strategy_map().keys()
    parser.add_argument('-strategy_mode', default=None,
                        help="the strategy_mode", choices=list(mode_keys) + [None])

    return parser

if __name__ == "__main__":
    parser = create_parser()
    args = parser.parse_args()

    villager_number = args.villager
    wolf_number = args.wolf
    lunatic_number = args.lunatics
    lang = args.lang
    max_iter = args.max_iteration
    strategy_mode = args.strategy_mode

    puzzle_generator = PuzzleGenereator(villager_number, wolf_number, lunatic_number,
                                        lang, strategy_mode)
    puzzle_generator.generate_problem(max_iteration=max_iter)
    problem_text = puzzle_generator.display_problems()
    answer_text = puzzle_generator.display_answers()
    print(problem_text)
    print(answer_text)


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.templates.subsystems.Drive;
import edu.wpi.first.wpilibj.templates.OI;

/**
 *
 * @author 1014
 */
public class DriveWithJoystick extends CommandBase {

    private Drive mech;

    public DriveWithJoystick()
    {
        mech = Drive.getInstance();
        requires(mech);
        System.out.println("DrvWthJystkInit");
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        mech.mechDrive(OI.getInstance().getLeftJoy(), OI.getInstance().getRightJoy());
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}


text:
FROM dockerfile/java:oracle-java8
MAINTAINER haljik

ADD ./build/libs/spring-boot-cluster-examples-0.1.0.jar ./app.jar

EXPOSE 8080

CMD ["java", "-jar", "app.jar",\
    "--session.store.type=redis",\
    "--spring.redis.host=${REDIS_PORT_6379_TCP_ADDR}",\
    "--spring.redis.port=${REDIS_PORT_6379_TCP_PORT}"]


text:
package org.innovateuk.ifs.organisation.builder;

import org.innovateuk.ifs.BaseBuilder;
import org.innovateuk.ifs.organisation.resource.OrganisationExecutiveOfficerResource;
import org.innovateuk.ifs.organisation.resource.OrganisationAddressResource;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.organisation.resource.OrganisationSicCodeResource;

import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.function.BiConsumer;

import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.*;

/**
 * Builder for OrganisationResource entities.
 */
public class OrganisationResourceBuilder extends BaseBuilder<OrganisationResource, OrganisationResourceBuilder> {

    private OrganisationResourceBuilder(List<BiConsumer<Integer, OrganisationResource>> multiActions) {
        super(multiActions);
    }

    public static OrganisationResourceBuilder newOrganisationResource() {
        return new OrganisationResourceBuilder(emptyList()).
                with(uniqueIds()).
                with(idBasedNames("OrganisationResource "));
    }

    @Override
    protected OrganisationResourceBuilder createNewBuilderWithActions(List<BiConsumer<Integer, OrganisationResource>> actions) {
        return new OrganisationResourceBuilder(actions);
    }

    @Override
    protected OrganisationResource createInitial() {
        return new OrganisationResource();
    }

    public OrganisationResourceBuilder withId(Long... ids) {
        return withArray((id, organisation) -> setField("id", id, organisation), ids);
    }

    public OrganisationResourceBuilder withName(String... names) {
        return withArray((name, organisation) -> setField("name", name, organisation), names);
    }

    public OrganisationResourceBuilder withCompaniesHouseNumber(String... numbers) {
        return withArray((number, organisation) -> setField("companiesHouseNumber", number, organisation), numbers);
    }

    public OrganisationResourceBuilder withOrganisationType(Long... organisationTypeIds) {
        return withArray((organisationTypeId, organisation) -> setField("organisationType", organisationTypeId, organisation), organisationTypeIds);
    }

    public OrganisationResourceBuilder withOrganisationTypeName(String... organisationTypeNames) {
        return withArray((organisationTypeName, organisation) -> setField("organisationTypeName", organisationTypeName, organisation), organisationTypeNames);
    }

    public OrganisationResourceBuilder withIsInternational(Boolean... isInternationals) {
        return withArraySetFieldByReflection("isInternational", isInternationals);
    }

    public OrganisationResourceBuilder withInternationalRegistrationNumber(String... internationalRegistrationNumbers) {
        return  withArraySetFieldByReflection("internationalRegistrationNumber", internationalRegistrationNumbers);
    }
    public OrganisationResourceBuilder withAddresses(List<OrganisationAddressResource>... addresses) {
        return  withArraySetFieldByReflection("addresses", addresses);
    }
    public OrganisationResourceBuilder withOrganisationNumber(String... organisationNumber) {
        return  withArraySetFieldByReflection("organisationNumber", organisationNumber);
    }
    public OrganisationResourceBuilder withBusinessType(String... businessType) {
        return  withArraySetFieldByReflection("businessType", businessType);
    }
    public OrganisationResourceBuilder withDateOfIncorporation(LocalDate... dateOfIncorporation) {
        return  withArraySetFieldByReflection("dateOfIncorporation", dateOfIncorporation);
    }
    public OrganisationResourceBuilder withSicCodes(List<OrganisationSicCodeResource>... sicCodes) {
        return  withArraySetFieldByReflection("sicCodes", sicCodes);
    }
    public OrganisationResourceBuilder withExecutiveOfficers(List<OrganisationExecutiveOfficerResource>... executiveOfficers) {
        return  withArraySetFieldByReflection("executiveOfficers", executiveOfficers);
    }
}


text:
package com.plugtree.solrmeter.model.extractor;

import java.util.List;

import com.plugtree.solrmeter.model.FieldExtractor;

public class FileFieldExtractor implements FieldExtractor{

	private FileStringExtractor fileExtractor;

	public FileFieldExtractor(String filePath) {
		fileExtractor = new FileStringExtractor(filePath);
	}

	@Override
	public List<String> getFields() {
		return fileExtractor.getAllStrings();
	}

	@Override
	public String getRandomFacetField() {
		return fileExtractor.getRandomString();
	}

	/**
	 * Considering all fields as 'facet-ables'
	 */
	@Override
	public List<String> getFacetFields() {
		return fileExtractor.getAllStrings();
	}

}


text:
import math
import m5
from m5.objects import *
from m5.defines import buildEnv
from m5.util import addToPath, fatal

import MemConfig
addToPath('../topologies')

def define_options(parser):
    # By default, ruby uses the simple timing cpu
    parser.set_defaults(cpu_type="timing")

    parser.add_option("--ruby-clock", action="store", type="string",
                      default='2GHz',
                      help="Clock for blocks running at Ruby system's speed")

    parser.add_option("--access-backing-store", action="store_true", default=False,
                      help="Should ruby maintain a second copy of memory")

    # Options related to cache structure
    parser.add_option("--ports", action="store", type="int", default=4,
                      help="used of transitions per cycle which is a proxy \
                            for the number of ports.")

    # ruby network options
    parser.add_option("--topology", type="string", default="Crossbar",
                 help="check src/mem/ruby/network/topologies for complete set")
    parser.add_option("--mesh-rows", type="int", default=1,
                      help="the number of rows in the mesh topology")
    parser.add_option("--garnet-network", type="choice",
                      choices=['fixed', 'flexible'], help="'fixed'|'flexible'")
    parser.add_option("--network-fault-model", action="store_true", default=False,
                      help="enable network fault model: see src/mem/ruby/network/fault_model/")

    # ruby mapping options
    parser.add_option("--numa-high-bit", type="int", default=0,
                      help="high order address bit to use for numa mapping. " \
                           "0 = highest bit, not specified = lowest bit")

    parser.add_option("--recycle-latency", type="int", default=10,
                      help="Recycle latency for ruby controller input buffers")

    parser.add_option("--random_seed", type="int", default=1234,
                      help="Used for seeding the random number generator")

    protocol = buildEnv['PROTOCOL']
    exec "import %s" % protocol
    eval("%s.define_options(parser)" % protocol)

def setup_memory_controllers(system, ruby, dir_cntrls, dma_cntrls, options):
    ruby.block_size_bytes = options.cacheline_size
    ruby.memory_size_bits = 48
    block_size_bits = int(math.log(options.cacheline_size, 2))

    if options.numa_high_bit:
        numa_bit = options.numa_high_bit
    else:
        # if the numa_bit is not specified, set the directory bits as the
        # lowest bits above the block offset bits, and the numa_bit as the
        # highest of those directory bits
        dir_bits = int(math.log(options.num_dirs, 2))
        numa_bit = block_size_bits + dir_bits - 1

    index = 0
    mem_ctrls = []
    crossbars = []

    # Sets bits to be used for interleaving.  Creates memory controllers
    # attached to a directory controller.  A separate controller is created
    # for each address range as the abstract memory can handle only one
    # contiguous address range as of now.
    systemBus = IOXBar(width=options.xbar_width)
    crossbars.append(systemBus)
    for dma_cntrl in dma_cntrls:
        dma_cntrl.memory = systemBus.slave

    dir_cntrl = dir_cntrls[0]
    dir_cntrl.directory.numa_high_bit = numa_bit

    #if len(system.mem_ranges) > 1:
    dir_cntrl.memory = systemBus.slave
    for i in xrange(options.num_mems):
        for r in system.mem_ranges:
            mem_ctrl = MemConfig.create_mem_ctrl(
                MemConfig.get(options.mem_type), r, index, options.num_mems,
                int(math.log(options.num_mems, 2)), options.cacheline_size)
            mem_ctrls.append(mem_ctrl)

            mem_ctrl.port = systemBus.master

            '''
            if crossbar != None:
                mem_ctrl.port = crossbar.master
            else:
                mem_ctrl.port = dir_cntrl.memory
            '''
        index += 1

    system.mem_ctrls = mem_ctrls

    if len(crossbars) > 0:
        ruby.crossbars = crossbars

def create_topology(controllers, options):
    """ Called from create_system in configs/ruby/<protocol>.py
        Must return an object which is a subclass of BaseTopology
        found in configs/topologies/BaseTopology.py
        This is a wrapper for the legacy topologies.
    """
    exec "import %s as Topo" % options.topology
    topology = eval("Topo.%s(controllers)" % options.topology)
    return topology

def create_system(options, full_system, system, piobus = None, dma_ports = []):

    system.ruby = RubySystem()
    ruby = system.ruby

    # Set the network classes based on the command line options
    if options.garnet_network == "fixed":
        NetworkClass = GarnetNetwork_d
        IntLinkClass = GarnetIntLink_d
        ExtLinkClass = GarnetExtLink_d
        RouterClass = GarnetRouter_d
        InterfaceClass = GarnetNetworkInterface_d

    elif options.garnet_network == "flexible":
        NetworkClass = GarnetNetwork
        IntLinkClass = GarnetIntLink
        ExtLinkClass = GarnetExtLink
        RouterClass = GarnetRouter
        InterfaceClass = GarnetNetworkInterface

    else:
        NetworkClass = SimpleNetwork
        IntLinkClass = SimpleIntLink
        ExtLinkClass = SimpleExtLink
        RouterClass = Switch
        InterfaceClass = None

    # Instantiate the network object so that the controllers can connect to it.
    network = NetworkClass(ruby_system = ruby, topology = options.topology,
            routers = [], ext_links = [], int_links = [], netifs = [])
    ruby.network = network

    protocol = buildEnv['PROTOCOL']
    exec "import %s" % protocol
    try:
        (cpu_sequencers, accel_sequencers, dir_cntrls, dma_cntrls, topology) = \
             eval("%s.create_system(options, full_system, system, dma_ports,\
                                    ruby)"
                  % protocol)
    except:
        print "Error: could not create sytem for ruby protocol %s" % protocol
        raise

    # Create a port proxy for connecting the system port. This is
    # independent of the protocol and kept in the protocol-agnostic
    # part (i.e. here).
    sys_port_proxy = RubyPortProxy(ruby_system = ruby)

    # Give the system port proxy a SimObject parent without creating a
    # full-fledged controller
    system.sys_port_proxy = sys_port_proxy

    # Connect the system port for loading of binaries etc
    system.system_port = system.sys_port_proxy.slave

    # Create the network topology
    topology.makeTopology(options, network, IntLinkClass, ExtLinkClass,
            RouterClass)

    if InterfaceClass != None:
        netifs = [InterfaceClass(id=i) for (i,n) in enumerate(network.ext_links)]
        network.netifs = netifs

    if options.network_fault_model:
        assert(options.garnet_network == "fixed")
        network.enable_fault_model = True
        network.fault_model = FaultModel()

    setup_memory_controllers(system, ruby, dir_cntrls, dma_cntrls, options)

    # Connect the cpu sequencers and the piobus
    if piobus != None:
        for cpu_seq in cpu_sequencers:
            cpu_seq.pio_master_port = piobus.slave
            cpu_seq.mem_master_port = piobus.slave

            if buildEnv['TARGET_ISA'] == "x86":
                cpu_seq.pio_slave_port = piobus.master
    ruby._cpu_ruby_ports = cpu_sequencers
    ruby._accel_ruby_ports = accel_sequencers
    ruby.num_of_sequencers = len(cpu_sequencers)
    ruby.random_seed    = options.random_seed

    # Create a backing copy of physical memory in case required
    if options.access_backing_store:
        ruby.access_backing_store = True
        ruby.phys_mem = SimpleMemory(range=system.mem_ranges[0],
                                     in_addr_map=False)

def send_evicts(options):
    # currently, 2 scenarios warrant forwarding evictions to the CPU:
    # 1. The O3 model must keep the LSQ coherent with the caches
    # 2. The x86 mwait instruction is built on top of coherence invalidations
    if options.cpu_type == "detailed" or buildEnv['TARGET_ISA'] == 'x86':
        return True
    return False