text:
package net.minecraft.src.nuclearcontrol;

import java.util.ArrayList;

import net.minecraft.client.Minecraft;
import net.minecraft.src.GuiButton;

import org.lwjgl.opengl.GL11;

public class GuiIC2ThermoSlider extends GuiButton
{
    public float sliderValue;
    public boolean dragging;
    private ArrayList<String> values;
    private String label;
    public int type;

    public GuiIC2ThermoSlider(int i, int j, int k, ArrayList<String> arraylist, String s, float f, int l)
    {
        super(i, j, k, 150, 20, s);
        sliderValue = 1.0F;
        dragging = false;
        values = arraylist;
        label = s;
        sliderValue = f;
        type = l;
        int i1 = values.size() - 1;
        displayString = String.format(label, new Object[]
                {
                    values.get((int)Math.floor((float)i1 * sliderValue))
                });
    }

    protected int getHoverState(boolean flag)
    {
        return 0;
    }

    protected void mouseDragged(Minecraft minecraft, int i, int j)
    {
        super.mouseDragged(minecraft, i, j);
        if (!drawButton)
        {
            return;
        }
        if (dragging)
        {
            sliderValue = (float)(i - (xPosition + 4)) / (float)(width - 8);
            if (sliderValue < 0.0F)
            {
                sliderValue = 0.0F;
            }
            if (sliderValue > 1.0F)
            {
                sliderValue = 1.0F;
            }
            int k = values.size() - 1;
            displayString = String.format(label, new Object[]
                    {
                        values.get((int)Math.floor((float)k * sliderValue))
                    });
            if (type != 0);
        }
        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
        drawTexturedModalRect(xPosition + (int)(sliderValue * (float)(width - 8)), yPosition, 0, 66, 4, 20);
        drawTexturedModalRect(xPosition + (int)(sliderValue * (float)(width - 8)) + 4, yPosition, 196, 66, 4, 20);
    }

    public boolean mousePressed(Minecraft minecraft, int i, int j)
    {
        if (super.mousePressed(minecraft, i, j))
        {
            sliderValue = (float)(i - (xPosition + 4)) / (float)(width - 8);
            if (sliderValue < 0.0F)
            {
                sliderValue = 0.0F;
            }
            if (sliderValue > 1.0F)
            {
                sliderValue = 1.0F;
            }
            int k = values.size() - 1;
            displayString = String.format(label, new Object[]
                    {
                        values.get((int)Math.floor((float)k * sliderValue))
                    });
            dragging = true;
            return true;
        }
        else
        {
            return false;
        }
    }

    public void mouseReleased(int i, int j)
    {
        super.mouseReleased(i, j);
        dragging = false;
    }
}


text: angular.module('stars', ['ngRoute','ngCookies','base64','ui.bootstrap']);

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.runtime.highavailability;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.HighAvailabilityOptions;
import org.apache.flink.runtime.concurrent.Executors;
import org.apache.flink.runtime.jobmanager.HighAvailabilityMode;
import org.apache.flink.util.TestLogger;

import org.junit.Test;

import java.util.concurrent.Executor;

import static org.junit.Assert.assertSame;

/**
 * Tests for the {@link HighAvailabilityServicesUtils} class.
 */
public class HighAvailabilityServicesUtilsTest extends TestLogger {

	@Test
	public void testCreateCustomHAServices() throws Exception {
		Configuration config = new Configuration();

		HighAvailabilityServices haServices = new TestingHighAvailabilityServices();
		TestHAFactory.haServices = haServices;

		Executor executor = Executors.directExecutor();

		config.setString(HighAvailabilityOptions.HA_MODE, TestHAFactory.class.getName());

		// when
		HighAvailabilityServices actualHaServices = HighAvailabilityServicesUtils.createAvailableOrEmbeddedServices(config, executor);

		// then
		assertSame(haServices, actualHaServices);

		// when
		actualHaServices = HighAvailabilityServicesUtils.createHighAvailabilityServices(config, executor,
			HighAvailabilityServicesUtils.AddressResolution.NO_ADDRESS_RESOLUTION);
		// then
		assertSame(haServices, actualHaServices);
	}

	@Test
	public void testCreateCustomClientHAServices() throws Exception {
		Configuration config = new Configuration();

		ClientHighAvailabilityServices clientHAServices = TestingClientHAServices.createClientHAServices();
		TestHAFactory.clientHAServices = clientHAServices;

		config.setString(HighAvailabilityOptions.HA_MODE, TestHAFactory.class.getName());

		// when
		ClientHighAvailabilityServices actualClientHAServices = HighAvailabilityServicesUtils.createClientHAService(config);

		// then
		assertSame(clientHAServices, actualClientHAServices);
	}

	@Test(expected = Exception.class)
	public void testCustomHAServicesFactoryNotDefined() throws Exception {
		Configuration config = new Configuration();

		Executor executor = Executors.directExecutor();

		config.setString(HighAvailabilityOptions.HA_MODE, HighAvailabilityMode.FACTORY_CLASS.name().toLowerCase());

		// expect
		HighAvailabilityServicesUtils.createAvailableOrEmbeddedServices(config, executor);
	}

	/**
	 * Testing class which needs to be public in order to be instantiatable.
	 */
	public static class TestHAFactory implements HighAvailabilityServicesFactory {

		static HighAvailabilityServices haServices;
		static ClientHighAvailabilityServices clientHAServices;

		@Override
		public HighAvailabilityServices createHAServices(Configuration configuration, Executor executor) {
			return haServices;
		}

		@Override
		public ClientHighAvailabilityServices createClientHAServices(Configuration configuration) throws Exception {
			return clientHAServices;
		}
	}
}


text:
#ifndef KeyframeEffectModel_h
#define KeyframeEffectModel_h

#include "core/CoreExport.h"
#include "core/animation/AnimationEffect.h"
#include "core/animation/EffectModel.h"
#include "core/animation/InterpolationEffect.h"
#include "core/animation/PropertyHandle.h"
#include "core/animation/StringKeyframe.h"
#include "core/animation/animatable/AnimatableValueKeyframe.h"
#include "platform/animation/TimingFunction.h"
#include "platform/heap/Handle.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/PassRefPtr.h"
#include "wtf/Vector.h"

namespace blink {

class Element;
class KeyframeEffectModelTest;

class CORE_EXPORT KeyframeEffectModelBase : public EffectModel {
public:
    // FIXME: Implement accumulation.

    using PropertySpecificKeyframeVector = Vector<RefPtr<Keyframe::PropertySpecificKeyframe>>;
    class PropertySpecificKeyframeGroup {
    public:
        void appendKeyframe(PassRefPtr<Keyframe::PropertySpecificKeyframe>);
        const PropertySpecificKeyframeVector& keyframes() const { return m_keyframes; }

    private:
        void removeRedundantKeyframes();
        bool addSyntheticKeyframeIfRequired(PassRefPtr<TimingFunction> zeroOffsetEasing);

        PropertySpecificKeyframeVector m_keyframes;

        friend class KeyframeEffectModelBase;
    };

    bool isReplaceOnly();

    PropertyHandleSet properties() const;

    using KeyframeVector = Vector<RefPtr<Keyframe>>;
    const KeyframeVector& getFrames() const { return m_keyframes; }
    void setFrames(KeyframeVector& keyframes);

    const PropertySpecificKeyframeVector& getPropertySpecificKeyframes(PropertyHandle property) const
    {
        ensureKeyframeGroups();
        return m_keyframeGroups->get(property)->keyframes();
    }

    using KeyframeGroupMap = HashMap<PropertyHandle, OwnPtr<PropertySpecificKeyframeGroup>>;
    const KeyframeGroupMap& getPropertySpecificKeyframeGroups() const
    {
        ensureKeyframeGroups();
        return *m_keyframeGroups;
    }

    // EffectModel implementation.
    bool sample(int iteration, double fraction, double iterationDuration, Vector<RefPtr<Interpolation>>&) const override;

    bool isKeyframeEffectModel() const override { return true; }

    virtual bool isAnimatableValueKeyframeEffectModel() const { return false; }
    virtual bool isStringKeyframeEffectModel() const { return false; }

    bool hasSyntheticKeyframes() const
    {
        ensureKeyframeGroups();
        return m_hasSyntheticKeyframes;
    }

    // FIXME: This is a hack used to resolve CSSValues to AnimatableValues while we have a valid handle on an element.
    // This should be removed once AnimatableValues are obsolete.
    void forceConversionsToAnimatableValues(Element&, const ComputedStyle* baseStyle);
    bool snapshotNeutralCompositorKeyframes(Element&, const ComputedStyle& oldStyle, const ComputedStyle& newStyle);
    bool snapshotAllCompositorKeyframes(Element&, const ComputedStyle* baseStyle);

    template<typename T>
    inline void forEachInterpolation(const T& callback) { m_interpolationEffect.forEachInterpolation(callback); }

    static KeyframeVector normalizedKeyframesForInspector(const KeyframeVector& keyframes) { return normalizedKeyframes(keyframes); }

    bool affects(PropertyHandle property) const override
    {
        ensureKeyframeGroups();
        return m_keyframeGroups->contains(property);
    }

    bool isTransformRelatedEffect() const override;

protected:
    KeyframeEffectModelBase(PassRefPtr<TimingFunction> defaultKeyframeEasing)
        : m_lastIteration(0)
        , m_lastFraction(std::numeric_limits<double>::quiet_NaN())
        , m_lastIterationDuration(0)
        , m_defaultKeyframeEasing(defaultKeyframeEasing)
        , m_hasSyntheticKeyframes(false)
    {
    }

    static KeyframeVector normalizedKeyframes(const KeyframeVector& keyframes);

    // Lazily computes the groups of property-specific keyframes.
    void ensureKeyframeGroups() const;
    void ensureInterpolationEffectPopulated(Element* = nullptr, const ComputedStyle* baseStyle = nullptr) const;

    KeyframeVector m_keyframes;
    // The spec describes filtering the normalized keyframes at sampling time
    // to get the 'property-specific keyframes'. For efficiency, we cache the
    // property-specific lists.
    mutable OwnPtr<KeyframeGroupMap> m_keyframeGroups;
    mutable InterpolationEffect m_interpolationEffect;
    mutable int m_lastIteration;
    mutable double m_lastFraction;
    mutable double m_lastIterationDuration;
    RefPtr<TimingFunction> m_defaultKeyframeEasing;

    mutable bool m_hasSyntheticKeyframes;

    friend class KeyframeEffectModelTest;
};

// Time independent representation of an Animation's keyframes.
template <class Keyframe>
class KeyframeEffectModel final : public KeyframeEffectModelBase {
public:
    using KeyframeVector = Vector<RefPtr<Keyframe>>;
    static KeyframeEffectModel<Keyframe>* create(const KeyframeVector& keyframes, PassRefPtr<TimingFunction> defaultKeyframeEasing = nullptr)
    {
        return new KeyframeEffectModel(keyframes, defaultKeyframeEasing);
    }

private:
    KeyframeEffectModel(const KeyframeVector& keyframes, PassRefPtr<TimingFunction> defaultKeyframeEasing)
        : KeyframeEffectModelBase(defaultKeyframeEasing)
    {
        m_keyframes.appendVector(keyframes);
    }

    virtual bool isAnimatableValueKeyframeEffectModel() const { return false; }
    virtual bool isStringKeyframeEffectModel() const { return false; }
};

using KeyframeVector = KeyframeEffectModelBase::KeyframeVector;
using PropertySpecificKeyframeVector = KeyframeEffectModelBase::PropertySpecificKeyframeVector;

using AnimatableValueKeyframeEffectModel = KeyframeEffectModel<AnimatableValueKeyframe>;
using AnimatableValueKeyframeVector = AnimatableValueKeyframeEffectModel::KeyframeVector;
using AnimatableValuePropertySpecificKeyframeVector = AnimatableValueKeyframeEffectModel::PropertySpecificKeyframeVector;

using StringKeyframeEffectModel = KeyframeEffectModel<StringKeyframe>;
using StringKeyframeVector = StringKeyframeEffectModel::KeyframeVector;
using StringPropertySpecificKeyframeVector = StringKeyframeEffectModel::PropertySpecificKeyframeVector;

DEFINE_TYPE_CASTS(KeyframeEffectModelBase, EffectModel, value, value->isKeyframeEffectModel(), value.isKeyframeEffectModel());
DEFINE_TYPE_CASTS(AnimatableValueKeyframeEffectModel, KeyframeEffectModelBase, value, value->isAnimatableValueKeyframeEffectModel(), value.isAnimatableValueKeyframeEffectModel());
DEFINE_TYPE_CASTS(StringKeyframeEffectModel, KeyframeEffectModelBase, value, value->isStringKeyframeEffectModel(), value.isStringKeyframeEffectModel());

inline const AnimatableValueKeyframeEffectModel* toAnimatableValueKeyframeEffectModel(const EffectModel* base)
{
    return toAnimatableValueKeyframeEffectModel(toKeyframeEffectModelBase(base));
}

inline AnimatableValueKeyframeEffectModel* toAnimatableValueKeyframeEffectModel(EffectModel* base)
{
    return toAnimatableValueKeyframeEffectModel(toKeyframeEffectModelBase(base));
}

inline const StringKeyframeEffectModel* toStringKeyframeEffectModel(const EffectModel* base)
{
    return toStringKeyframeEffectModel(toKeyframeEffectModelBase(base));
}

inline StringKeyframeEffectModel* toStringKeyframeEffectModel(EffectModel* base)
{
    return toStringKeyframeEffectModel(toKeyframeEffectModelBase(base));
}

template <>
inline bool KeyframeEffectModel<AnimatableValueKeyframe>::isAnimatableValueKeyframeEffectModel() const { return true; }

template <>
inline bool KeyframeEffectModel<StringKeyframe>::isStringKeyframeEffectModel() const { return true; }

} // namespace blink

#endif // KeyframeEffectModel_h


text:
@interface PeopleSearchViewController (Private)

- (void)promptToClearRecents;

@end

@implementation PeopleSearchViewController

@synthesize searchTerms = _searchTerms,
searchTokens = _searchTokens,
searchController = _searchController,
searchBar = _searchBar;

#pragma mark view

- (void)viewDidLoad {
	[super viewDidLoad];

    self.title = @"People";

    [_phoneDirectoryEntries release];
    _phoneDirectoryEntries = [[PersonContact directoryContacts] retain];
    if (!_phoneDirectoryEntries) {
        _request = [[KGORequestManager sharedManager] requestWithDelegate:self module:PeopleTag path:@"contacts" params:nil];
        _request.expectedResponseType = [NSDictionary class];
        [_request connect];
    }

    _searchBar = [[KGOSearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 44)];
    _searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	_searchBar.placeholder = NSLocalizedString(@"Search", nil);

    if (!_searchController) {
        _searchController = [[KGOSearchDisplayController alloc] initWithSearchBar:self.searchBar delegate:self contentsController:self];
    }

	if ([self.searchTerms length] > 0) {
		_searchBar.text = self.searchTerms;
        [_searchController executeSearch:self.searchTerms params:nil];
    }

    [self.view addSubview:_searchBar];
    CGRect frame = CGRectMake(0.0, _searchBar.frame.size.height,
                              self.view.frame.size.width,
                              self.view.frame.size.height - _searchBar.frame.size.height);
	self.tableView = [self addTableViewWithFrame:frame style:UITableViewStyleGrouped];

    // search hint
    NSString *searchHints = NSLocalizedString(@"Tip: You can search above by a person's first or last name or email address.", nil);
	UIFont *hintsFont = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertyBodyText];
    UILabel *hintsLabel = [UILabel multilineLabelWithText:searchHints font:hintsFont width:self.tableView.frame.size.width - 30];
    hintsLabel.frame = CGRectMake(15, 5, hintsLabel.frame.size.width, hintsLabel.frame.size.height);
    hintsLabel.textColor = [UIColor colorWithHexString:@"#404040"];
    UIView *hintsContainer = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.tableView.frame.size.width,
                                                                       hintsLabel.frame.size.height + 10.0)] autorelease];

	[hintsContainer addSubview:hintsLabel];

	self.tableView.tableHeaderView = hintsContainer;
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];

    _recentlyViewed = [[KGOPersonWrapper fetchRecentlyViewed] retain];
	[self reloadDataForTableView:self.tableView];
}

#pragma mark - KGORequestDelegate

- (void)requestWillTerminate:(KGORequest *)request
{
    _request = nil;
}

- (void)request:(KGORequest *)request didReceiveResult:(id)result
{
    NSArray *contacts = [result arrayForKey:@"results"];
    NSMutableArray *array = [NSMutableArray array];
    for (NSDictionary *contactDict in contacts) {
        PersonContact *aContact = [PersonContact personContactWithDictionary:contactDict
                                                                        type:[contactDict stringForKey:@"type" nilIfEmpty:YES]];
        [array addObject:aContact];
    }
    [_phoneDirectoryEntries release];
    _phoneDirectoryEntries = [array copy];

    [self reloadDataForTableView:self.tableView];
}

#pragma mark memory

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    if (_request) {
        [_request cancel];
    }
	[_searchTerms release];
	[_searchTokens release];
	[_searchController release];
    [_phoneDirectoryEntries release];
    [super dealloc];
}

#pragma mark -
#pragma mark Search methods

- (BOOL)searchControllerShouldShowSuggestions:(KGOSearchDisplayController *)controller {
    return YES;
}

- (NSArray *)searchControllerValidModules:(KGOSearchDisplayController *)controller {
    return [NSArray arrayWithObject:PeopleTag];
}

- (NSString *)searchControllerModuleTag:(KGOSearchDisplayController *)controller {
    return PeopleTag;
}

- (void)resultsHolder:(id<KGOSearchResultsHolder>)resultsHolder didSelectResult:(id<KGOSearchResult>)aResult {
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:aResult, @"person", nil];
    [KGO_SHARED_APP_DELEGATE() showPage:LocalPathPageNameDetail forModuleTag:PeopleTag params:params];
}

- (void)searchController:(KGOSearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView {
    [[CoreDataManager sharedManager] saveData];
    [KGOPersonWrapper clearOldResults];
}

#pragma mark -
#pragma mark KGODetailPagerController

- (NSInteger)numberOfSections:(KGODetailPager *)pager {
    return 1;
}

- (NSInteger)pager:(KGODetailPager *)pager numberOfPagesInSection:(NSInteger)section {
    return _recentlyViewed.count;
}

- (id<KGOSearchResult>)pager:(KGODetailPager *)pager contentForPageAtIndexPath:(NSIndexPath *)indexPath {
    return [_recentlyViewed objectAtIndex:indexPath.row];
}

#pragma mark -
#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger numRows = 1;
    if (_recentlyViewed.count)
        numRows += 2;
    return numRows;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0: // phone directory
            return _phoneDirectoryEntries.count;
        case 1: // recently viewed
            return _recentlyViewed.count;
        case 2: // clear recents
            return 1;
        default:
            return 0;
    }
}

- (NSArray *)tableView:(UITableView *)tableView viewsForCellAtIndexPath:(NSIndexPath *)indexPath {
    // making this button into a cell assumes that this table is being created as a grouped table view
    if (indexPath.section == 2) {
        UIFont *font = [[KGOTheme sharedTheme] fontForThemedProperty:KGOThemePropertyNavListTitle];
        NSString *title = NSLocalizedString(@"Clear Recents", nil);
        CGSize size = [title sizeWithFont:font];

        // 20 is internal padding of grouped table view
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(floor((tableView.frame.size.width - 20 - size.width) / 2),
                                                                    0, size.width, tableView.rowHeight)] autorelease];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        label.font = font;
        label.text = title;
        return [NSArray arrayWithObject:label];
    }
    return nil;
}

- (CellManipulator)tableView:(UITableView *)tableView manipulatorForCellAtIndexPath:(NSIndexPath *)indexPath {

    NSString *title = nil;
    NSString *detailText = nil;
    NSString *accessoryTag = nil;
    UIColor *backgroundColor = nil;
    UIView *backgroundView = nil;
    UIView *selectedBackgroundView = nil;

    switch (indexPath.section) {
        case 0:
        {
            PersonContact *contact = [_phoneDirectoryEntries objectAtIndex:indexPath.row];
            title = contact.label;
            detailText = contact.value;
            accessoryTag = KGOAccessoryTypePhone; // TODO: use the type to determine this
            backgroundColor = [[KGOTheme sharedTheme] backgroundColorForSecondaryCell];
            break;
        }
        case 1:
        {
            KGOPersonWrapper *person = [_recentlyViewed objectAtIndex:indexPath.row];
            title = [person title];
            detailText = [person subtitle];
            accessoryTag = KGOAccessoryTypeChevron;
            break;
        }
        case 2:
        {
            UIImage *backgroundImage = [[UIImage imageWithPathName:@"modules/people/redbutton2.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];
            UIImage *selectedBackgroundImage = [[UIImage imageWithPathName:@"modules/people/redbutton2highlighted.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0];

            backgroundView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, tableView.rowHeight)] autorelease];
            [(UIImageView *)backgroundView setImage:backgroundImage];

            selectedBackgroundView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, tableView.rowHeight)] autorelease];
            [(UIImageView *)selectedBackgroundView setImage:selectedBackgroundImage];
            break;
        }
        default:
            break;
    }

    return [[^(UITableViewCell *cell) {
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.textLabel.text = title;
        cell.detailTextLabel.text = detailText;
        cell.accessoryView = [[KGOTheme sharedTheme] accessoryViewForType:accessoryTag];
        if (backgroundColor) {
            cell.backgroundColor = backgroundColor;
        }
        if (backgroundView) {
            cell.backgroundView = backgroundView;
        }
        if (selectedBackgroundView) {
            cell.selectedBackgroundView = selectedBackgroundView;
        }
    } copy] autorelease];
}

- (KGOTableCellStyle)tableView:(UITableView *)tableView styleForCellAtIndexPath:(NSIndexPath *)indexPath {
    return KGOTableCellStyleSubtitle;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return NSLocalizedString(@"Recently Viewed", nil);
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	[tableView deselectRowAtIndexPath:indexPath animated:YES];

    switch (indexPath.section) {
        case 0:
        {
            PersonContact *contact = [_phoneDirectoryEntries objectAtIndex:indexPath.row];
            NSString *urlString = [NSString stringWithFormat:@"tel:%@", contact.value];
            NSURL *externURL = [NSURL URLWithString:urlString];
            if ([[UIApplication sharedApplication] canOpenURL:externURL])
                [[UIApplication sharedApplication] openURL:externURL];

            break;
        }
        case 1: // recently viewed
        {
            KGOPersonWrapper *person = [_recentlyViewed objectAtIndex:indexPath.row];
            NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:person, @"person", self, @"pager", nil];
            [KGO_SHARED_APP_DELEGATE() showPage:LocalPathPageNameDetail forModuleTag:PeopleTag params:params];
            break;
        }
        case 2: // clear recents
            [self promptToClearRecents];
            break;
        default:
            break;
    }

}

#pragma mark -
#pragma mark Action sheet methods

- (void)promptToClearRecents
{
	UIActionSheet *sheet = [[[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"Clear Recents?", nil)
                                                        delegate:self
                                               cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                          destructiveButtonTitle:NSLocalizedString(@"Clear", nil)
                                               otherButtonTitles:nil] autorelease];
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	if ([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:NSLocalizedString(@"Clear", nil)]) {
        [_recentlyViewed release];
        _recentlyViewed = nil;
		[KGOPersonWrapper clearRecentlyViewed];
		self.tableView.tableFooterView.hidden = YES;
		[self reloadDataForTableView:self.tableView];
		[self.tableView scrollRectToVisible:CGRectMake(0.0, 0.0, 1.0, 1.0) animated:YES];
	}
}

@end


text:
I welcome contributions to this project. This guide outlines what's expected of you when you contribute, and what you can expect from me in return.

## Table of Contents

  * [What I expect from you](#what-i-expect-from-you)
  * [What you can expect from me](#what-you-can-expect-from-me)
  * [Technical](#technical)

## What I expect from you

If you're going to contribute to this project, thanks! I have a few expectations of contributors:

  1. [Follow the code of conduct](code_of_conduct.md)
  2. [Follow the technical contribution guidelines](#technical)
  3. Be respectful of the time and energy that me and other contributors offer

## What you can expect from me

If you're a contributor to this project, you can expect the following from me:

  1. I will enforce [this project's code of conduct](code_of_conduct.md)
  2. If I decide not to implement a feature or accept a PR, I will explain why

Contributing to this project **does not**:

  1. Guarantee you my (or any other contributor's) attention or time – I work on this in my free time and I make no promises about how quickly somebody will get back to you on a PR, Issue, or general query
  2. Mean your contribution will be accepted

## Technical

To contribute to this project's code, clone this repo locally and commit your work on a separate branch. Open a pull-request to get your changes merged. If you're doing any large feature work, please make sure to have a discussion in an issue first – I'd rather not waste your time if it's not a feature I want to add to this project 🙂

I don't offer any guarantees on how long it will take me to review a PR or respond to an issue, [as outlined here](#what-you-can-expect-from-me).

### Linting

this project is linted using [ESLint](https://eslint.org/), configured in the way I normally write JavaScript. Please keep to the existing style.

ESLint errors will fail the build on any PRs. Most editors have an ESLint plugin which will pick up errors, but you can also run the linter manually with the following command:

```
npm run verify
```

### Unit tests

This project has unit tests with good coverage, and failing unit tests will fail the build on any PRs. If you add or remove features, please update the tests to match.

You can run tests manually with the following command:

```
npm run test:unit
```

### Integration tests

This project has end to end integration tests, and these tests can fail the build on PRs. If you add or remove features, please update the tests to match.

You can run integration tests manually with the following command:

```
npm run test:integration
```


text:
package wordtrend

import (
	"sync"
	"strings"
	"regexp"
	"log"
	"github.com/agonopol/go-stem/stemmer"
)

var trending = make(map[string]int)

var mutex = &sync.Mutex{}

const alpha = "[^A-Za-z]+"

var reg = regexp.MustCompile(alpha)

func setStemAndCount(word string) {
	cleanedWord := reg.ReplaceAllString(word, "")

	w := string(stemmer.Stem([]byte(cleanedWord)))

	mutex.Lock()
	trending[w] = trending[w] + 1
	mutex.Unlock()
}

func SetWords(sentence string) []string {
	words := strings.Fields(sentence)
	wordLen := len(words)

	for i := 0; i <= wordLen - 1; i++ {
		setStemAndCount(words[i])
	}

	return words
}

func GetTrending() map[string]int {
	log.Println(trending)
	return trending
}


text:
package cl.rgaticav94.shelke.resource.cliente.service;

import cl.rgaticav94.shelke.resource.cliente.domain.Cliente;
import cl.rgaticav94.shelke.resource.cliente.domain.ClienteDTO;
import cl.rgaticav94.shelke.resource.cliente.domain.ClienteEntity;
import cl.rgaticav94.shelke.resource.cliente.domain.ClienteFactory;
import cl.rgaticav94.shelke.resource.cliente.repository.ClienteRepository;
import cl.rgaticav94.shelke.resource.common.exception.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * shelke.
 * Created by rgaticav94 on 25-06-2017.
 */
@Service
public class ClienteServiceImpl implements ClienteService {

    private final ClienteRepository clienteRepository;

    @Autowired
    public ClienteServiceImpl(ClienteRepository clienteRepository) {
        this.clienteRepository = clienteRepository;
    }

    @Override
    public Cliente findByRut(String rut) throws NotFoundException {
        ClienteEntity e = clienteRepository.findByRut(rut);

        if (e == null) {
            throw new NotFoundException();
        } else {
            return new ClienteDTO(ClienteFactory.createDTO(e));
        }
    }

    @Override
    public Collection<Cliente> findAll() {
        return this.clienteRepository.findAll().stream()
                .map(ClienteDTO::new)
                .collect(Collectors.toList());
    }
}


text:
package TinyOS::Util::TestBedConfig;

use 5.008;
use strict;
use warnings;
use Carp;

## Module to read a simple configuration file for testbeds, and provinding calls to get information from it
## Author: Rodrigo Fonseca (rfonseca at cs.berkeley.edu)

our $VERSION = '0.02';

# Preloaded methods go here.
# parameter: a file name to read from
sub new {
  my ($class,$filename) = @_;
  if (! defined $filename) {
    print STDERR "TestBedConfig->new called without filename object\n";
    return undef;
  }
  my $self = {
    motes => undef,
    platform => undef
  };
  bless $self,$class;

  if (! $self->parse_file($filename) ) {
    croak "TestBedConfig->new : cannot parse file $filename\n";
    return undef;
  }
  return $self;
}

sub getNumberOfMotes {
  return scalar @{$_[0]->{motes}};
}

sub getMote {
  my ($self,$i) = @_;
  if (! defined $i || $i < 0 || $i > scalar @{$self->{motes}}) {
    return undef;
  }
  return ${$self->{motes}}[$i];
}

#Receives an array reference, and makes the referent a copy of the motes array.
sub getMotes {
  my ($self,$aref) = @_;
  if (ref $aref ne "ARRAY") {
    croak "Reference must be to an array.\n";
  }
  @{$aref} = @{$self->{motes}};
}

sub getPlatform {
  return ($_[0]->{platform});
}

#opens filename and reads the mote information into the motes array

sub parse_file {
  my $self = shift;
  my $filename = shift;
  my @line;
  my $line = 0;
  my ($id,$address,$x,$y);

  if (! (open FH, $filename)) {
    croak "Cannot open $filename\n";
    return undef;
  }

  while (<FH>) {
    $id = 0;
    $address = "0.0.0.0";
    $x = 0.0;
    $y = 0.0;
    $line++;
    chomp;
    if (s/^mote\s+//) {
      @line = split;
      if (scalar @line < 2) {
        croak "Warning: parse error at line $line\n";
        next;
      }
      $id = $line[0];
      $address = $line[1];
      if (scalar @line == 4) {
        $x = $line[2];
        $y = $line[3];
      }
      print "TesbedConfig::parse_file: read mote id $id address $address x $x y $y\n";
      push @{$self->{motes}}, {id => $id, address => $address, x => $x, y => $y};
    } elsif (/^platform\s+(\S+)/) {
      $self->{platform} = $1;
    }
  }
  1;
}

#@motes is an array of hash references
#The hashes represent a ADT for motes, with the following structure
#  ind id
#  string address
#  double x
#  double y

# Autoload methods go after =cut, and are processed by the autosplit program.

1;
__END__

=head1 Short Description

   use TinyOS::Util::TestBedConfig;
   $cfg = TinyOS::Util::TestBedConfig->new($config_file);
   $n = cfg->getNumberOfMotes();

Iterating over the motes

   my @mote_array;
   $cfg->getMotes(\@mote_array);
   for $mote (@mote_array) {
      $address = $mote->{'address'};
      $id      = $mote->{'id'};
      $x       = $mote->{'x'};
      $y       = $mote->{'y'};
      #do whatever you want
   }

Other calls:

   $moteref = getMote($id);
   getMotes(\@array);
   $n = getNumberOfMotes();
   $platform = getPlatform();

The array of motes returned by getMotes() is an array of hash references with the following keys:

=item 'address' is the ip address or host name of the mote
=item 'id' is the mote id (TOS_LOCAL_ADDRESS for the mote)
=item 'x' is the x coordinate of the mote in the testbed
=item 'y' is the y coordinate of the mote in the testbed

=head2 Extending
The file format can be extended in a backwards compatible way if fields are added after the existing ones

=cut


text:
/**
 * Main JS file for Casper behaviours
 */

/*globals jQuery, document */
(function ($) {
    "use strict";

    $(document).ready(function(){

        $(".post-content").fitVids();

        function casperFullImg() {
            $("img").each( function() {
                var contentWidth = $(".post-content").outerWidth(); // Width of the content
                var imageWidth = $(this)[0].naturalWidth; // Original image resolution

                if (imageWidth >= contentWidth) {
                    $(this).addClass('full-img');
                } else {
                    $(this).removeClass('full-img');
                }
            });
        };

        casperFullImg();
        $(window).smartresize(casperFullImg);

    });

    //Search
    var siteSearch =
      $("#site-search").ghostHunter({
        results: "#site-search-results",
        onKeyUp: true,
        info_template: "
{{amount}} tutorials found.
",
        result_template : "
{{title}}
{{pubDate}}",
        before: function(){
          $("#site-search-results").addClass('active');
        }
      });

    $(document).on("click", "#clear-results", function(){
      event.preventDefault();
      siteSearch.clear();
      $("#site-search-results").removeClass('active');
    });

    //Smooth Scroll
    $('a[href*=#]:not([href=#])').click(function() {
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 200);
          return false;
        }
      }
    });

    //Hide Header
    var myElement = document.querySelector("#site-nav");
    var headroom  = new Headroom(myElement);
    headroom.init();

    //Details of post
    var postDetails = $("#post-details")
    var postSubtitle = postDetails.data("subtitle");
    var postNext = postDetails.data("post-next");
    var postPrev = postDetails.data("post-prev");

    $('.post-subtitle').html(postSubtitle);
    $('#previous-lesson').attr('href', postPrev);
    $('#next-lesson').attr('href', postNext);

}(jQuery));

(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
  // smartresize
  jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');


text:
import { first, last } from 'lodash/fp';
import { Pattern, CaptureElement, CaptureWildcard } from '../modules/patternMatcher';
import type { Transformer } from '../modules/transformer/types';
import { basePercentage } from '../modules/math/types';
import type { PercentageNode } from '../modules/math/types'; // eslint-disable-line
import { TOKEN_NUMBER, TOKEN_PERCENTAGE } from '../tokenTypes';
import { uncastArray } from '../util';

const entityTransform: Transformer = {
  // TODO: Could be made more efficient
  pattern: new Pattern([
    new CaptureElement(TOKEN_NUMBER).negate().lazy().any(),
    new Pattern([
      new CaptureElement(TOKEN_NUMBER),
      new CaptureElement(TOKEN_PERCENTAGE),
      new CaptureWildcard().lazy().any(),
    ]),
  ]),
  transform: (captureGroups, transform) => transform([
    captureGroups[0],
    captureGroups[3],
  ], segments => {
    const value: number = captureGroups[1][0].value;
    const percentage: PercentageNode = { ...basePercentage, value };

    const concatSegments = [].concat(
      first(segments),
      percentage,
      last(segments)
    );
    return uncastArray(concatSegments);
  }),
};
export default entityTransform;


text:
package com.navercorp.pinpoint.plugin.httpclient4.interceptor;

import java.net.URI;

import org.apache.http.HttpRequest;
import org.apache.http.client.methods.HttpUriRequest;

import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.interceptor.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.interceptor.group.InterceptorGroup;
import com.navercorp.pinpoint.bootstrap.pair.NameIntValuePair;
import com.navercorp.pinpoint.bootstrap.plugin.annotation.Group;
import com.navercorp.pinpoint.plugin.httpclient4.HttpClient4Constants;

/**
 * MethodInfo interceptor
 *

 *

 *
 *

 * org.apache.http.impl.client.AbstractHttpClient.
 * public final HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException
 *

 * @author emeroad
 * @author minwoo.jung
 * @author jaehong.kim
 */
@Group(HttpClient4Constants.HTTP_CLIENT4_SCOPE)
public class HttpClientExecuteMethodWithHttpUriRequestInterceptor extends AbstractHttpClientExecuteMethodInterceptor {

    private static final int HTTP_URI_REQUEST_INDEX = 0;

    public HttpClientExecuteMethodWithHttpUriRequestInterceptor(boolean isHasCallbackParam, TraceContext context, MethodDescriptor methodDescriptor, InterceptorGroup interceptorGroup) {
        super(HttpClientExecuteMethodWithHttpUriRequestInterceptor.class, isHasCallbackParam, context, methodDescriptor, interceptorGroup);
    }

    @Override
    protected NameIntValuePair<String> getHost(Object[] args) {
        final HttpUriRequest httpUriRequest = getHttpUriRequest(args);
        if (httpUriRequest == null) {
            return null;
        }
        final URI uri = httpUriRequest.getURI();
        return extractHost(uri);
    }

    @Override
    protected HttpRequest getHttpRequest(Object[] args) {
        return getHttpUriRequest(args);
    }

    private HttpUriRequest getHttpUriRequest(Object[] args) {
        final Object arg = args[HTTP_URI_REQUEST_INDEX];
        if (arg instanceof HttpUriRequest) {
            return (HttpUriRequest) arg;
        }
        return null;
    }

    /**
     * copy
     * org.apache.http.client.utils.URIUtils#extractHost(java.net.URI)
     * @param uri
     * @return
     */
    private NameIntValuePair<String> extractHost(final URI uri) {
        if (uri == null) {
            return null;
        }
        NameIntValuePair<String> target = null;
        if (uri.isAbsolute()) {
            int port = uri.getPort(); // may be overridden later
            String host = uri.getHost();
            if (host == null) { // normal parse failed; let's do it ourselves
                // authority does not seem to care about the valid character-set
                // for host names
                host = uri.getAuthority();
                if (host != null) {
                    // Strip off any leading user credentials
                    int at = host.indexOf('@');
                    if (at >= 0) {
                        if (host.length() > at + 1) {
                            host = host.substring(at + 1);
                        } else {
                            host = null; // @ on its own
                        }
                    }
                    // Extract the port suffix, if present
                    if (host != null) {
                        int colon = host.indexOf(':');
                        if (colon >= 0) {
                            int pos = colon + 1;
                            int len = 0;
                            for (int i = pos; i < host.length(); i++) {
                                if (Character.isDigit(host.charAt(i))) {
                                    len++;
                                } else {
                                    break;
                                }
                            }
                            if (len > 0) {
                                try {
                                    port = Integer.parseInt(host.substring(pos, pos + len));
                                } catch (NumberFormatException ignore) {
                                    // skip
                                }
                            }
                            host = host.substring(0, colon);
                        }
                    }
                }
            }
            if (host != null) {
                target = new NameIntValuePair<String>(host, port);
            }
        }
        return target;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.iit.sat.itmd4515.yzhan214.fp.domain;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 *
 * @author ln1878
 */
@Entity
@Table(name = "payment")
@NamedQueries({
    @NamedQuery(name="Transaction.findById",query="select p from Transaction p where p.id= :id"),
    @NamedQuery(name = "Transaction.findAll", query = "select r from Transaction r")
})
public class Transaction extends BaseEntity implements Serializable{
    @Column(precision = 9,scale=2)
    private BigDecimal payment;
    private String message;
    @Temporal(TemporalType.DATE)
    private Date pDate;

    /**
     *  Constructor
     */
    public Transaction() {
    }

    /**
    * Constructor.
    *
    * @param payment value of payment
    * @param message detail of payment
    * @param pDate date of payment
    *
    */
    public Transaction(BigDecimal payment, String message, Date pDate) {
        this.payment = payment;
        this.message = message;
        this.pDate = GregorianCalendar.getInstance().getTime();
    }

    /**
     *
     * @return  the amount of payment
     */
    public BigDecimal getPayment() {
        return payment;
    }

    /**
     *
     * @return the value of message
     */
    public String getMessage() {
        return message;
    }

    /**
     *
     * @return the payment date
     */
    public Date getpDate() {
        return pDate;
    }

    /**
     *
     * @param payment
     */
    public void setPayment(BigDecimal payment) {
        this.payment = payment;
    }

    /**
     *
     * @param message
     */
    public void setMessage(String message) {
        this.message = message;
    }

    /**
     *
     * @param pDate
     */
    public void setpDate(Date pDate) {
        this.pDate = pDate;
    }

}


text:
package com.kbhit.orangebox.api.gateway;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kbhit.orangebox.api.gateway.domain.model.ApiCatalog;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.assertj.core.api.Assertions.assertThat;

public class ApiCatalogMappingsTest extends IntegrationTest {

    @Autowired
    private ObjectMapper objectMapper;

    @Test
    public void canSerializeApiCatalog() {
        assertThat(objectMapper.canSerialize(ApiCatalog.class)).isTrue();
    }

}


text:
'use strict';

angular.module('notes').controller('NotesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Notes', 'Insects',
	function($scope, $stateParams, $location, Authentication, Notes, Insects) {
		$scope.authentication = Authentication;

		// If user is not signed in then redirect back home
		//if (!$scope.user) $location.path('/');

		$scope.createPage = function() {
			$scope.insects = [];
			$scope.insects = Insects.query({limit: 100, userId: Authentication.user._id});
		};

		$scope.create = function() {
			var ids = [];
			for (var i = 0; i < this.selectedInsects.length; i++) {
				ids.push(this.selectedInsects[i]._id);
			}

			var note = new Notes({
				title: this.title,
				content: this.content,
				insects: ids
			});
			note.$save(function(response) {
				$location.path('notes/' + response._id);

				$scope.title = '';
				$scope.content = '';
				$scope.selectedInsects = [];
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.remove = function(note) {
			if (note) {
				note.$remove();

				for (var i in $scope.notes) {
					if ($scope.notes[i] === note) {
						$scope.notes.splice(i, 1);
					}
				}
			} else {
				$scope.note.$remove(function() {
					$location.path('notes');
				});
			}
		};

		$scope.updatePage = function() {
			$scope.insects = [];
			$scope.insects = Insects.query({limit: 100, userId: Authentication.user._id});
		};

		$scope.update = function() {
			var ids = [];
			for (var i = 0; i < this.selectedInsects.length; i++) {
				ids.push(this.selectedInsects[i]._id);
			}

			var note = new Notes({
				_id: $scope.note._id,
				name: $scope.note.title,
				content: $scope.note.content,
				insects: ids
			});

			note.$update(function() {
				$location.path('notes/' + note._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.find = function() {
			$scope.loading = true;

			$scope.notes = Notes.query(function() {
				$scope.loading = false;
			});
		};

		$scope.findOne = function() {
			$scope.loading = true;

			$scope.note = Notes.get({
				noteId: $stateParams.noteId
			}, function() {
				$scope.loading = false;
			}, function(err) {
				$scope.error = err.data.message;
				$scope.loading = false;
			});
		};
	}
]);


text:
package msgio

import (
	"encoding/binary"
	"io"
	"sync"

	mpool "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-msgio/mpool"
)

// NBO is NetworkByteOrder
var NBO = binary.BigEndian

const lengthSize = 4

// Writer is the msgio Writer interface. It writes len-framed messages.
type Writer interface {

	// Write writes passed in buffer as a single message.
	Write([]byte) (int, error)

	// WriteMsg writes the msg in the passed in buffer.
	WriteMsg([]byte) error
}

// WriteCloser is a Writer + Closer interface. Like in `golang/pkg/io`
type WriteCloser interface {
	Writer
	io.Closer
}

// Reader is the msgio Reader interface. It reads len-framed messages.
type Reader interface {

	// Read reads the next message from the Reader.
	// The client must pass a buffer large enough, or io.ErrShortBuffer will be
	// returned.
	Read([]byte) (int, error)

	// ReadMsg reads the next message from the Reader.
	// Uses a mpool.Pool internally to reuse buffers. io.ErrShortBuffer will
	// be returned if the Pool.Get(...) returns nil.
	// User may call ReleaseMsg(msg) to signal a buffer can be reused.
	ReadMsg() ([]byte, error)

	// ReleaseMsg signals a buffer can be reused.
	ReleaseMsg([]byte)

	// NextMsgLen returns the length of the next (peeked) message. Does
	// not destroy the message or have other adverse effects
	NextMsgLen() (int, error)
}

// ReadCloser combines a Reader and Closer.
type ReadCloser interface {
	Reader
	io.Closer
}

// ReadWriter combines a Reader and Writer.
type ReadWriter interface {
	Reader
	Writer
}

// ReadWriteCloser combines a Reader, a Writer, and Closer.
type ReadWriteCloser interface {
	Reader
	Writer
	io.Closer
}

// writer is the underlying type that implements the Writer interface.
type writer struct {
	W io.Writer

	lock sync.Locker
}

// NewWriter wraps an io.Writer with a msgio framed writer. The msgio.Writer
// will write the length prefix of every message written.
func NewWriter(w io.Writer) WriteCloser {
	return &writer{W: w, lock: new(sync.Mutex)}
}

func (s *writer) Write(msg []byte) (int, error) {
	err := s.WriteMsg(msg)
	if err != nil {
		return 0, err
	}
	return len(msg), nil
}

func (s *writer) WriteMsg(msg []byte) (err error) {
	s.lock.Lock()
	defer s.lock.Unlock()

	length := uint32(len(msg))
	if err := binary.Write(s.W, NBO, &length); err != nil {
		return err
	}
	_, err = s.W.Write(msg)
	return err
}

func (s *writer) Close() error {
	s.lock.Lock()
	defer s.lock.Unlock()

	if c, ok := s.W.(io.Closer); ok {
		return c.Close()
	}
	return nil
}

// reader is the underlying type that implements the Reader interface.
type reader struct {
	R io.Reader

	lbuf []byte
	next int
	pool *mpool.Pool
	lock sync.Locker
}

// NewReader wraps an io.Reader with a msgio framed reader. The msgio.Reader
// will read whole messages at a time (using the length). Assumes an equivalent
// writer on the other side.
func NewReader(r io.Reader) ReadCloser {
	return NewReaderWithPool(r, &mpool.ByteSlicePool)
}

// NewReaderWithPool wraps an io.Reader with a msgio framed reader. The msgio.Reader
// will read whole messages at a time (using the length). Assumes an equivalent
// writer on the other side.  It uses a given mpool.Pool
func NewReaderWithPool(r io.Reader, p *mpool.Pool) ReadCloser {
	if p == nil {
		panic("nil pool")
	}
	return &reader{
		R:    r,
		lbuf: make([]byte, lengthSize),
		next: -1,
		pool: p,
		lock: new(sync.Mutex),
	}
}

// NextMsgLen reads the length of the next msg into s.lbuf, and returns it.
// WARNING: like Read, NextMsgLen is destructive. It reads from the internal
// reader.
func (s *reader) NextMsgLen() (int, error) {
	s.lock.Lock()
	defer s.lock.Unlock()
	return s.nextMsgLen()
}

func (s *reader) nextMsgLen() (int, error) {
	if s.next == -1 {
		if _, err := io.ReadFull(s.R, s.lbuf); err != nil {
			return 0, err
		}
		s.next = int(NBO.Uint32(s.lbuf))
	}
	return s.next, nil
}

func (s *reader) Read(msg []byte) (int, error) {
	s.lock.Lock()
	defer s.lock.Unlock()

	length, err := s.nextMsgLen()
	if err != nil {
		return 0, err
	}

	if length > len(msg) {
		return 0, io.ErrShortBuffer
	}
	_, err = io.ReadFull(s.R, msg[:length])
	s.next = -1 // signal we've consumed this msg
	return length, err
}

func (s *reader) ReadMsg() ([]byte, error) {
	s.lock.Lock()
	defer s.lock.Unlock()

	length, err := s.nextMsgLen()
	if err != nil {
		return nil, err
	}

	msgb := s.pool.Get(uint32(length))
	if msgb == nil {
		return nil, io.ErrShortBuffer
	}
	msg := msgb.([]byte)[:length]
	_, err = io.ReadFull(s.R, msg)
	s.next = -1 // signal we've consumed this msg
	return msg, err
}

func (s *reader) ReleaseMsg(msg []byte) {
	s.pool.Put(uint32(cap(msg)), msg)
}

func (s *reader) Close() error {
	s.lock.Lock()
	defer s.lock.Unlock()

	if c, ok := s.R.(io.Closer); ok {
		return c.Close()
	}
	return nil
}

// readWriter is the underlying type that implements a ReadWriter.
type readWriter struct {
	Reader
	Writer
}

// NewReadWriter wraps an io.ReadWriter with a msgio.ReadWriter. Writing
// and Reading will be appropriately framed.
func NewReadWriter(rw io.ReadWriter) ReadWriteCloser {
	return &readWriter{
		Reader: NewReader(rw),
		Writer: NewWriter(rw),
	}
}

// Combine wraps a pair of msgio.Writer and msgio.Reader with a msgio.ReadWriter.
func Combine(w Writer, r Reader) ReadWriteCloser {
	return &readWriter{Reader: r, Writer: w}
}

func (rw *readWriter) Close() error {
	var errs []error

	if w, ok := rw.Writer.(WriteCloser); ok {
		if err := w.Close(); err != nil {
			errs = append(errs, err)
		}
	}
	if r, ok := rw.Reader.(ReadCloser); ok {
		if err := r.Close(); err != nil {
			errs = append(errs, err)
		}
	}

	if len(errs) > 0 {
		return multiErr(errs)
	}
	return nil
}

// multiErr is a util to return multiple errors
type multiErr []error

func (m multiErr) Error() string {
	if len(m) == 0 {
		return "no errors"
	}

	s := "Multiple errors: "
	for i, e := range m {
		if i != 0 {
			s += ", "
		}
		s += e.Error()
	}
	return s
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.job.service.impl.cmd;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.flowable.common.engine.impl.Page;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.job.service.impl.asyncexecutor.AcquiredTimerJobEntities;
import org.flowable.job.service.impl.asyncexecutor.AsyncExecutor;
import org.flowable.job.service.impl.persistence.entity.TimerJobEntity;
import org.flowable.job.service.impl.util.CommandContextUtil;

/**
 * @author Tijs Rademakers
 */
public class AcquireTimerJobsCmd implements Command<AcquiredTimerJobEntities> {

    private final AsyncExecutor asyncExecutor;

    public AcquireTimerJobsCmd(AsyncExecutor asyncExecutor) {
        this.asyncExecutor = asyncExecutor;
    }

    @Override
    public AcquiredTimerJobEntities execute(CommandContext commandContext) {
        AcquiredTimerJobEntities acquiredJobs = new AcquiredTimerJobEntities();
        List<TimerJobEntity> timerJobs = CommandContextUtil.getTimerJobEntityManager(commandContext)
                .findTimerJobsToExecute(new Page(0, asyncExecutor.getMaxAsyncJobsDuePerAcquisition()));

        for (TimerJobEntity job : timerJobs) {
            lockJob(commandContext, job, asyncExecutor.getAsyncJobLockTimeInMillis());
            acquiredJobs.addJob(job);
        }

        return acquiredJobs;
    }

    protected void lockJob(CommandContext commandContext, TimerJobEntity job, int lockTimeInMillis) {

        // This will trigger an optimistic locking exception when two concurrent executors
        // try to lock, as the revision will not match.

        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(CommandContextUtil.getJobServiceConfiguration(commandContext).getClock().getCurrentTime());
        gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis);
        job.setLockOwner(asyncExecutor.getLockOwner());
        job.setLockExpirationTime(gregorianCalendar.getTime());
    }
}


text:
class WordDictionaryLengthMap {
    constructor() {
        this.lengthMap = new Map();
    }
    /**
     * Adds a word into the data structure.
     * @param {string} word
     * @return {void}
     */
    addWord(word) {
        let letterPosMap = this.lengthMap.get(word.length);
        if (!letterPosMap) {
            letterPosMap = new Map();
            this.lengthMap.set(word.length, letterPosMap);
        }
        for (let i = 0; i < word.length; ++i) {
            let key = word[i] + i;
            let wordsCol = letterPosMap.get(key);
            if (!wordsCol) {
                letterPosMap.set(key, [word]);
            } else {
                wordsCol.push(word);
            }
        }
    }
    /**
     * Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
     * @param {string} word
     * @return {boolean}
     */
    search(word) {
        let letterPosMap = this.lengthMap.get(word.length);
        if (!letterPosMap) {
            return false;
        }
        let i = 0;
        while (i < word.length && word[i] === '.') {
            ++i;
        }
        if (i === word.length) {
            return true;
        }
        let key = word[i] + i;
        let wordsCol = letterPosMap.get(key);
        if (!wordsCol) {
            return false;
        }
        let regex = new RegExp('^' + word + '$', '');
        for (let w of wordsCol) {
            if (w.match(regex)) {
                return true;
            }
        }
        return false;
    }
}

const CHAR_CODE_A = 'a'.charCodeAt(0);

class TrieNode {
    constructor() {
        this.children = [];
        this.hasWord = false;
    }
}

// Use Trie and backtracking
class WordDictionary {
    constructor() {
        this.trieRoot = new TrieNode();
    }
    /**
     * Adds a word into the data structure.
     * @param {string} word
     * @return {void}
     */
    addWord(word) {
        let node = this.trieRoot;
        for (let i = 0; i < word.length; ++i) {
            let chIdx = word.charCodeAt(i) - CHAR_CODE_A;
            if (!node.children[chIdx]) {
                node.children[chIdx] = new TrieNode();
            }
            node = node.children[chIdx];
        }
        node.hasWord = true;
    }
    /**
     * Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
     * @param {string} word
     * @return {boolean}
     */
    search(word) {
        return this.backTrack(this.trieRoot, word, 0);
    }
    backTrack(node, word, idx) {
        if (!node) {
            return false;
        }
        if (idx === word.length) {
            return node.hasWord;
        }
        if (word[idx] === '.') {
            for (let child of node.children) {
                if (this.backTrack(child, word, idx + 1)) {
                    return true;
                }
            }
            return false;
        }
        let chIdx = word.charCodeAt(idx) - CHAR_CODE_A;
        return node.children[chIdx] ? this.backTrack(node.children[chIdx], word, idx + 1) : false;
    }
}

module.exports = WordDictionary;

/**
 * Your WordDictionary object will be instantiated and called as such:
 * var obj = Object.create(WordDictionary).createNew()
 * obj.addWord(word)
 * var param_2 = obj.search(word)
 */


text:
package org.cirdles.squid.parameters.matrices;

import Jama.Matrix;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author James F. Bowring
 */
public abstract class AbstractMatrixModel implements Serializable {

    private static final long serialVersionUID = -1858833405279253150L;
    /**
     *
     */
    protected String levelName;
    /**
     *
     */
    protected Map<Integer, String> rows;
    /**
     *
     */
    protected Map<String, Integer> cols;
    /**
     *
     */
    protected Matrix matrix;

    /**
     * @param levelName
     */
    public AbstractMatrixModel(
            String levelName) {

        this.levelName = levelName;
        rows = new HashMap<>();
        cols = new HashMap<>();
        matrix = new Matrix(0, 0);
    }

    /**
     * @return
     */
    public abstract AbstractMatrixModel copy();

    /**
     * @param row
     * @param col
     * @param value
     */
    public abstract void setValueAt(int row, int col, double value);

    /**
     * @param matrixModel
     */
    public void copyValuesFrom(AbstractMatrixModel matrixModel) {

        rows = matrixModel.getRows();
        cols = matrixModel.getCols();
        matrix = matrixModel.matrix.copy();
    }

    /**
     * @return
     */
    public boolean isCovMatrixSymmetricAndPositiveDefinite() {
        try {
            return matrix.chol().isSPD();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @return
     */
    public String toStringWithLabels() {
        String formatCell = "%1$-23s";

        String retVal = String.format(formatCell, "MATRIX#=" + getLevelName());

        // make an inverse map of columns
        Map<Integer, String> tempCols = new HashMap<Integer, String>();
        Iterator<String> colKeys = getCols().keySet().iterator();
        while (colKeys.hasNext()) {
            String colKey = colKeys.next();
//            retVal += String.format( formatCell, colKey );
            tempCols.put(getCols().get(colKey), colKey);
        }

        for (int i = 0; i < tempCols.size(); i++) {
            retVal += String.format(formatCell, (String) tempCols.get(i));
        }

        retVal += "\n";

        NumberFormat formatter = new DecimalFormat("0.000000000E00");

        for (int row = 0; row < rows.size(); row++) {
            retVal += String.format(formatCell, (String) rows.get(row));
            try {
                for (int col = 0; col < matrix.getColumnDimension(); col++) {
                    retVal += String.format(formatCell, formatter.format(matrix.get(row, col)));
                }
            } catch (Exception e) {
            }
            retVal += "\n";
        }

        return retVal;
    }

    /**
     * @return the rows
     */
    public Map<Integer, String> getRows() {
        return rows;
    }

    /**
     * @param rowNames
     */
    public void setRows(String[] rowNames) {
        Map<Integer, String> myRows = new HashMap<Integer, String>();
        for (int i = 0; i < rowNames.length; i++) {
            myRows.put((Integer) i, rowNames[i]);
        }
        this.rows = myRows;
    }

    /**
     * @param myRows
     */
    public void setRows(Map<Integer, String> myRows) {
        this.rows = myRows;
    }

    /**
     * @return the cols
     */
    public Map<String, Integer> getCols() {
        return cols;
    }

    /**
     * @param rowMap
     */
    public void setCols(Map<Integer, String> rowMap) {
        this.cols = invertRowMap(rowMap);
    }

    /**
     * @param rowMap
     * @return
     */
    public static Map<String, Integer> invertRowMap(Map<Integer, String> rowMap) {
        Map<String, Integer> myCols = new HashMap<String, Integer>();
        Iterator<Entry<Integer, String>> entries = rowMap.entrySet().iterator();
        while (entries.hasNext()) {
            Entry<Integer, String> entry = entries.next();
            myCols.put(entry.getValue(), entry.getKey());
        }
        return myCols;
    }

    /**
     * Inverts column map (Name, col number) to row map (number, Name).
     *
     * @param colMap
     * @return
     */
    public static Map<Integer, String> invertColMap(Map<String, Integer> colMap) {
        Map<Integer, String> myRows = new HashMap<>();
        Iterator<String> keys = colMap.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            myRows.put(colMap.get(key), key);
        }

        return myRows;
    }

    /**
     * @param colMap
     */
    public void copyCols(Map<String, Integer> colMap) {
        cols = colMap;
    }

    /**
     * @return the lerow
     */
    public String getLevelName() {
        return levelName;
    }

    /**
     * @param levelName the levelName to set
     */
    public void setLevelName(String levelName) {
        this.levelName = levelName;
    }

    /**
     * @return the matrix
     */
    public Matrix getMatrix() {
        return matrix;
    }

    /**
     * @param matrix the matrix to set
     */
    public void setMatrix(Matrix matrix) {
        this.matrix = matrix;
    }

    /**
     *
     */
    public void initializeMatrix() {
        try {
            matrix = new Matrix(new double[rows.size()][cols.size()]);
        } catch (Exception e) {
            //Jan 2015 jama won't take 0,0
            matrix = new Matrix(new double[1][1]);
        }
    }

    /**
     * @return
     */
    public double[] sumOfRowsMatrix() {
        double[] retval = new double[matrix.getRowDimension()];

        for (int i = 0; i < matrix.getRowDimension(); i++) {
            for (int j = 0; j < matrix.getColumnDimension(); j++) {
                retval[i] += matrix.get(i, j);
            }
        }

        return retval;
    }

    /**
     * @param parentModel
     */
    public void initializeMatrixModelFromMatrixModel(AbstractMatrixModel parentModel) {
        // requires that rows be identical; we are slicing out columns
        boolean retVal = !(getRows().isEmpty() || getCols().isEmpty());
        if (retVal) {
            initializeMatrix();
            Iterator<String> colNames = parentModel.getCols().keySet().iterator();
            while (colNames.hasNext()) {
                String colName = colNames.next();
                Integer col = getCols().get(colName);
                if (col != null) {
                    //copy values from this column
                    matrix.setMatrix(0, matrix.getRowDimension() - 1, new int[]{(int) col}, parentModel.matrix.getMatrix(0, matrix.getRowDimension() - 1, new int[]{parentModel.getCols().get(colName)}));
                }
            }
        }
    }

    /**
     * @param variableName
     * @return
     */
    protected String createPartialDerivName(String variableName) {
        return "d" + variableName.substring(0, 1).toUpperCase(Locale.ENGLISH) + variableName.substring(1);
    }

}


text:
(function() {
    'use strict';

    angular
        .module('login')
        .controller('LoginCtrl', LoginCtrl);

    LoginCtrl.$inject = [
        '$rootScope',
        '$scope',
        '$location',
        '$window',
        'Auth',
        'toaster'
    ];

    function LoginCtrl($rootScope, $scope, $location, $window, Auth, toaster) {
        var vm = this;

        vm.rememberme = true;
        vm.login = login;

        function login() {
            Auth.login(vm.name, vm.password).then(function (res) {
                $location.path('/home');
                toaster.pop('success', 'Login successful!', 'Welcome ' + vm.name);

            }).catch(function (err) {
                toaster.pop('error', 'Login failed', 'Incorrect username or password, please try again!');
                $location.path('/login');

            });
        }
    }

})();


text:
"""A switch driver for the Nexus 5500

Currently the driver uses telnet to connect to the switch's console; in the
long term we want to be using SNMP.
"""

import re
from schema import Schema, Optional, And, Use
import logging

from hil.model import db, Switch
from hil.ext.switches import _console
from hil.errors import BadArgumentError
from os.path import join, dirname
from hil.migrations import paths
from hil.model import BigIntegerType
from hil.config import core_schema, string_is_bool
from hil.ext.switches.common import parse_vlans

logger = logging.getLogger(__name__)

paths[__name__] = join(dirname(__file__), 'migrations', 'nexus')

core_schema[__name__] = {
    Optional('save'): string_is_bool
}

class Nexus(Switch):
    """A Cisco Nexus switch."""

    api_name = 'http://schema.massopencloud.org/haas/v0/switches/nexus'

    __mapper_args__ = {
        'polymorphic_identity': api_name,
    }

    id = db.Column(BigIntegerType,
                   db.ForeignKey('switch.id'), primary_key=True)
    hostname = db.Column(db.String, nullable=False)
    username = db.Column(db.String, nullable=False)
    password = db.Column(db.String, nullable=False)
    dummy_vlan = db.Column(db.String, nullable=False)

    @staticmethod
    def validate(kwargs):
        Schema({
            'username': basestring,
            'hostname': basestring,
            'password': basestring,
            'dummy_vlan': And(Use(int),
                              lambda v: 0 < v and v <= 4096,
                              Use(str)),
        }).validate(kwargs)

    def session(self):
        return _Session.connect(self)

    @staticmethod
    def validate_port_name(port):
        """
        Valid port names for this switch are of the form: Ethernet1/12,
        ethernet1/12, Ethernet1/0/10, or ethernet1/0/10
        """

        val = re.compile(r'^(E|e)thernet\d+/\d+(/\d+)?$')
        if not val.match(port):
            raise BadArgumentError("Invalid port name. Valid port names for "
                                   "this switch are of the form: Ethernet1/12"
                                   " ethernet1/12, Ethernet1/0/10, or"
                                   " ethernet1/0/10")
        return

    def get_capabilities(self):
        return ['nativeless-trunk-mode']

class _Session(_console.Session):

    def __init__(self, config_prompt, if_prompt, main_prompt, switch, console,
                 dummy_vlan):
        self.config_prompt = config_prompt
        self.if_prompt = if_prompt
        self.main_prompt = main_prompt
        self.switch = switch
        self.console = console
        self.dummy_vlan = dummy_vlan

    def enter_if_prompt(self, interface):
        self._sendline('config terminal')
        self._sendline('int %s' % interface)

    def exit_if_prompt(self):
        self._sendline('exit')
        self._sendline('exit')

    def enable_vlan(self, vlan_id):
        self._sendline('sw')
        self._sendline('sw mode trunk')
        self._sendline('sw trunk allowed vlan add %s' % vlan_id)

    def disable_vlan(self, vlan_id):
        self._sendline('sw trunk allowed vlan remove %s' % vlan_id)

    def set_native(self, old, new):
        if old is not None:
            self.disable_vlan(old)
        self._sendline('sw trunk native vlan %s' % new)
        self.enable_vlan(new)

    def disable_native(self, vlan_id):
        self.disable_vlan(vlan_id)
        self._sendline('sw trunk native vlan ' + self.dummy_vlan)

    @staticmethod
    def connect(switch):
        """Connect to the switch."""

        console = _console.login(switch)

        # send a new line so that we can "expect" a prompt again if we already
        # matched when logged in using pubkey
        console.sendline('')
        prompts = _console.get_prompts(console)

        return _Session(console=console,
                        dummy_vlan=switch.dummy_vlan,
                        switch=switch,
                        **prompts)

    def _port_configs(self, ports):
        alternatives = [
            re.escape(r'--More--'),
            r'Name:[^\n]*\n',
            r'  [A-Z][^:]*:[^\n]*\n',
            r'[\r\n]+.+# ',
        ]
        self._sendline('show int sw')

        # Find the first interface name
        self.console.expect(alternatives[1])

        _, interface = self.console.after.split(':', 1)
        interface = interface.strip()
        info = {interface: {}}

        while True:
            index = self.console.expect(alternatives)
            if index == 0:
                self.console.send(' ')
            elif index == 1:
                _, interface = self.console.after.split(':', 1)
                interface = interface.strip()
                info[interface] = {}
            elif index == 2:
                k, v = self.console.after.split(':', 1)
                info[interface][k.strip()] = v.strip()
            elif index == 3:
                break

        # The output of show int sw calls things "EthernetX/YY", but
        # everything else calls things "ethernet X/YY". Let's do the conversion
        # here.
        names_result = {}
        pattern = re.compile(r'Ethernet(\d+)/(\d+)')
        for k, v in info.iteritems():
            match = re.match(pattern, k)
            # sometimes switch has custom interface names, so we skip those
            if match is None:
                continue
            # TODO: We should verify there is in fact a match (there always
            # should be, but let's be paranoid).
            switch, port = match.groups()
            names_result['Ethernet%s/%s' % (switch, port)] = v

        result = {}
        for port in ports:
            result[port] = names_result[port.label]

        return result

    def get_port_networks(self, ports):
        '''Returns dictionary of ports, each containing a list of related
        VLANs.'''
        port_configs = self._port_configs(ports)
        result = {}

        for k, v in port_configs.iteritems():
            network_list = []
            non_native_list = []
            if 'Trunking Native Mode VLAN' not in v:
                # XXX (probable BUG): For some reason the last port on the
                # switch sometimes isn't read correctly. For now just don't use
                # that port for the test suite, and will skip it if this
                # happens.
                continue
            # Get native vlan then remove junk if native is not None or Dummy
            native_vlan = v['Trunking Native Mode VLAN'].strip()
            if int(native_vlan.split(' ')[0]) == int(self.switch.dummy_vlan):
                native_vlan = None
            elif native_vlan != 'none':
                native_vlan = native_vlan.split(' ')[0]
            else:
                native_vlan = None
            # Get other vlans
            trunk_vlans = v['Trunking VLANs Allowed'].strip()
            if trunk_vlans != 'none':
                non_native_list = parse_vlans(trunk_vlans)
            if native_vlan is not None:
                # Ensure that native vlan is not in the non-native list
                non_native_list.remove(native_vlan)
                network_list.append(('vlan/native', int(native_vlan)))
            for v in (non_native_list):
                network_list.append(('vlan/%s' % v, int(v)))
            result[k] = network_list
        return result

    def save_running_config(self):
        self._sendline('copy running-config startup-config')
        self.console.expect('Copy complete')
        logger.debug('Copy succeeded')

    def get_config(self, config_type):
        self._set_terminal_lines('unlimited')
        self.console.expect(r'[\r\n]+.+# ')
        self._sendline('show ' + config_type + '-config')
        self.console.expect(r'[\r\n]+.+# ')
        config = self.console.after

        # The config files always have some lines in the beginning that we
        # need to remove otherwise the comparison would fail. Here's a sample:
        # !Command: show running-config
        # !Time: Tue Apr 25 16:36:40 2017
        # version 6.0(2)A1(1a)
        # hostname the-switch
        # feature telnet
        # username admin password 5 XXXXXXXX  role network-admin
        # ssh key rsa 2048
        lines_to_remove = 0
        for line in config.splitlines():
            if 'username' in line:
                break
            lines_to_remove += 1

        config = config.split("\n", lines_to_remove)[lines_to_remove]
        self._set_terminal_lines('default')
        return config

    def disable_port(self):
        self._sendline('sw trunk allowed vlan none')
        self._sendline('sw trunk native vlan ' + self.dummy_vlan)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
using HoloToolkit.Unity.InputModule;

namespace HoloToolkit.Unity.SharingWithUNET
{

    public class JoinSelectedSessionButton : MonoBehaviour, IInputClickHandler
    {
        /// <summary>
        /// Shader property id for the text color so we can change it when selected.
        /// </summary>
        private int textColorId;

        /// <summary>
        /// The text mesh so we can change the text to show the session name.
        /// </summary>
        private TextMesh textMesh;

        /// <summary>
        /// The material for the text so we can change the text color.
        /// </summary>
        private Material textMaterial;

        /// <summary>
        /// The control that manages which session is selected.
        /// </summary>
        private ScrollingSessionListUIController scrollingUIControl;

        /// <summary>
        /// Script which manages finding and joining sessions.
        /// </summary>
        private NetworkDiscoveryWithAnchors networkDiscovery;

        private void Start()
        {
            scrollingUIControl = ScrollingSessionListUIController.Instance;
            textMesh = transform.parent.GetComponentInChildren<TextMesh>();
            textMaterial = textMesh.GetComponent<MeshRenderer>().material;
            textColorId = Shader.PropertyToID("_Color");
            textMaterial.SetColor(textColorId, Color.grey);
            networkDiscovery = NetworkDiscoveryWithAnchors.Instance;
        }

        private void Update()
        {
            // If we are the client and have a selected session make the button text blue,
            // otherwise make the button text grey to indicate that the button is inactive.
            if (networkDiscovery.running && networkDiscovery.isClient)
            {
                if (scrollingUIControl.SelectedSession != null)
                {
                    textMaterial.SetColor(textColorId, Color.blue);
                }
                else
                {
                    textMaterial.SetColor(textColorId, Color.grey);
                }
            }
            else
            {
                textMaterial.SetColor(textColorId, Color.grey);
            }
        }

        /// <summary>
        /// Called by unity when the object is destroyed.
        /// </summary>
        private void OnDestroy()
        {
            if (textMaterial != null)
            {
                Destroy(textMaterial);
                textMaterial = null;
            }
        }

        /// <summary>
        /// When the button is clicked try to join the selected session
        /// </summary>
        /// <param name="eventData"></param>
        public void OnInputClicked(InputClickedEventData eventData)
        {
            ScrollingSessionListUIController.Instance.JoinSelectedSession();
            eventData.Use();
        }
    }
}


text:
import os
import sys
sys.path.insert(0, '../')

import unittest
import membership_pb2
import utils
import models

class TokenTest(utils.TestCase):

  SERVICE_PLATFORM = models.service_platform()
  PROTOCOL_VERSION = models.protocol_version()

  def setUp(self):
    app = models.app(app_id=1)
    self.APP_NAME = app['app_name']
    self.APP_KEY = app['app_key']
    self.APP_SECRET = app['app_secret']
    self.FACEBOOK_APP_ID = app['facebook_app_id']
    self.FACEBOOK_APP_SECRET = app['facebook_app_secret']
    self.FACEBOOK_API_VERSION = app['facebook_api_version']

  def tearDown(self):
    pass

  # 이미 등록된 사용자의 Token정보 갱신
  def test_token_exist_member(self):
    request = self.protocol_members(udid='meRRnWrYWKvIgLgRLcUzULqe03MjzYEVWl+rHPa63NlVtCILyPvFe4M4TnvzJKcPDxmGPqBv17Bb/DT/udOzGg==')
    response = self.post('/members', data=self.make_request(request))
    assert response.status_code == 200

    res = self.make_response(response.content)
    assert res.expire_time > 0
    assert res.access_token

    request = self.protocol_token(udid=request.members.udid)
    response = self.post('/token', data=self.make_request(request))
    assert response.status_code == 200

  # 새로운 멤버의 Token정보 갱신
  def test_token_new_member(self):
    request = self.protocol_members()
    response = self.post('/members', data=self.make_request(request))
    assert response.status_code == 200

    res = self.make_response(response.content)
    assert res.expire_time > 0
    assert res.access_token

    request = self.protocol_token(udid=request.members.udid)
    response = self.post('/token', data=self.make_request(request))
    assert response.status_code == 200


text:
package com.tlongdev.spicio.module;

import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.tlongdev.spicio.util.AndroidLogger;
import com.tlongdev.spicio.util.Logger;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

/**
 * @author Long
 * @since 2016. 02. 25.
 */
@Module
public class SpicioAppModule {

    private Application mApplication;

    public SpicioAppModule(Application application) {
        this.mApplication = application;
    }

    @Provides
    @Singleton
    Application provideApplication() {
        return mApplication;
    }

    @Provides
    @Singleton
    Logger provideLogger() {
        return new AndroidLogger();
    }

    @Provides
    @Singleton
    SharedPreferences provideSharedPreferences(Application application) {
        return PreferenceManager.getDefaultSharedPreferences(application);
    }

    @Provides
    @Singleton
    SharedPreferences.Editor provideEditor(SharedPreferences preferences) {
        return preferences.edit();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">

  <id>assembly-drools</id>
  <formats>
    <format>dir</format>
    <format>zip</format>
  </formats>

  <includeBaseDirectory>true</includeBaseDirectory>

  <fileSets>
    <fileSet><!-- Note: going outside the module dir is bad, but it is not fetching generated files -->
      <includes>
        <include>../LICENSE-ASL-2.0.txt</include>
      </includes>
      <outputDirectory/>
    </fileSet>
    <fileSet>
      <directory>src/main/assembly/scripts</directory>
      <lineEnding>unix</lineEnding>
      <filtered>true</filtered>
      <outputDirectory>examples</outputDirectory>
      <includes>
        <include>**/*.sh</include>
      </includes>
      <fileMode>755</fileMode>
    </fileSet>
    <fileSet>
      <directory>src/main/assembly/scripts</directory>
      <lineEnding>dos</lineEnding>
      <filtered>true</filtered>
      <outputDirectory>examples</outputDirectory>
      <includes>
        <include>**/*.bat</include>
      </includes>
    </fileSet>
    <fileSet>
      <directory>src/main/assembly/filtered-resources</directory>
      <filtered>true</filtered>
      <outputDirectory/>
    </fileSet>
    <!-- Examples -->
    <fileSet><!-- Note: going outside the module dir is bad, but it is not fetching generated files -->
      <directory>../drools-examples</directory>
      <outputDirectory>examples/sources</outputDirectory>
      <excludes>
        <exclude>target/**</exclude>
        <exclude>local/**</exclude>
        <exclude>.*/**</exclude>
        <exclude>nbproject/**</exclude>
        <exclude>*.ipr</exclude>
        <exclude>*.iws</exclude>
        <exclude>*.iml</exclude>
        <exclude>.git/**</exclude>
      </excludes>
    </fileSet>
  </fileSets>

  <dependencySets>
    <dependencySet>
      <excludes>
        <exclude>org.drools:drools-examples</exclude>
        <exclude>com.miglayout:miglayout</exclude><!-- Examples dependency -->
        <exclude>commons-io:commons-io</exclude><!-- Examples dependency -->
        <exclude>ch.qos.logback:logback-core</exclude><!-- Examples dependency -->
        <exclude>ch.qos.logback:logback-classic</exclude><!-- Examples dependency -->
        <exclude>org.drools:drools-expert-docs</exclude>
        <exclude>org.drools:drools-fusion-docs</exclude>
        <exclude>*:*:jar:javadoc</exclude>
        <exclude>*:*:jar:sources</exclude>
      </excludes>
      <outputDirectory>binaries</outputDirectory>
      <useStrictFiltering>true</useStrictFiltering>
    </dependencySet>
    <dependencySet>
      <includes>
        <include>org.drools:drools-examples:jar</include>
        <include>com.miglayout:miglayout:jar</include><!-- Examples dependency -->
        <include>commons-io:commons-io:jar</include><!-- Examples dependency -->
        <include>ch.qos.logback:logback-core</include><!-- Examples dependency -->
        <include>ch.qos.logback:logback-classic</include><!-- Examples dependency -->
      </includes>
      <excludes>
        <exclude>*:sources</exclude>
      </excludes>
      <outputDirectory>examples/binaries</outputDirectory>
      <useStrictFiltering>true</useStrictFiltering>
    </dependencySet>
    <dependencySet>
      <includes>
        <include>org.drools:knowledge-api:jar:javadoc</include>
      </includes>
      <outputDirectory>javadoc/public</outputDirectory>
      <unpack>true</unpack>
      <useStrictFiltering>true</useStrictFiltering>
    </dependencySet>
    <!-- TODO internal api javadocs: note that they must be added as dependencies in the pom too -->
    <!--<dependencySet>-->
      <!--<includes>-->
        <!--<include>org.drools:*:jar:javadoc</include>-->
      <!--</includes>-->
      <!--<excludes>-->
        <!--<exclude>org.drools:knowledge-api:jar:javadoc</exclude>-->
      <!--</excludes>-->
      <!--<outputDirectory>javadoc/internal</outputDirectory>-->
      <!--<unpack>true</unpack>-->
      <!--<useStrictFiltering>true</useStrictFiltering>-->
    <!--</dependencySet>-->
    <!-- Reference manual -->
    <dependencySet>
      <includes>
        <include>org.drools:droolsjbpm-introduction-docs:jdocbook</include>
      </includes>
      <outputDirectory>reference_manual/droolsjbpm-introduction-docs</outputDirectory>
      <unpack>true</unpack>
      <unpackOptions>
        <excludes>
          <exclude>META-INF/**</exclude>
        </excludes>
      </unpackOptions>
      <useStrictFiltering>true</useStrictFiltering>
    </dependencySet>
    <dependencySet>
      <includes>
        <include>org.drools:drools-expert-docs:jdocbook</include>
      </includes>
      <outputDirectory>reference_manual/drools-expert-docs</outputDirectory>
      <unpack>true</unpack>
      <unpackOptions>
        <excludes>
          <exclude>META-INF/**</exclude>
        </excludes>
      </unpackOptions>
      <useStrictFiltering>true</useStrictFiltering>
    </dependencySet>
    <dependencySet>
      <includes>
        <include>org.drools:drools-fusion-docs:jdocbook</include>
      </includes>
      <outputDirectory>reference_manual/drools-fusion-docs</outputDirectory>
      <unpack>true</unpack>
      <unpackOptions>
        <excludes>
          <exclude>META-INF/**</exclude>
        </excludes>
      </unpackOptions>
      <useStrictFiltering>true</useStrictFiltering>
    </dependencySet>
    <dependencySet>
      <includes>
        <include>org.drools:*:jar:sources</include>
      </includes>
      <excludes>
        <exclude>org.drools:drools-examples:jar:sources</exclude>
      </excludes>
      <outputDirectory>sources</outputDirectory>
      <unpack>false</unpack>
      <useStrictFiltering>true</useStrictFiltering>
    </dependencySet>
  </dependencySets>

</assembly>


text:
.class public final Lorg/codehaus/jackson/map/ser/std/StdJdkSerializers$AtomicBooleanSerializer;
.super Lorg/codehaus/jackson/map/ser/std/ScalarSerializerBase;
.source "StdJdkSerializers.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lorg/codehaus/jackson/map/ser/std/StdJdkSerializers;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "AtomicBooleanSerializer"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Lorg/codehaus/jackson/map/ser/std/ScalarSerializerBase",
        "<",
        "Ljava/util/concurrent/atomic/AtomicBoolean;",
        ">;"
    }
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 2

    .prologue
    .line 71
    const-class v0, Ljava/util/concurrent/atomic/AtomicBoolean;

    const/4 v1, 0x0

    invoke-direct {p0, v0, v1}, Lorg/codehaus/jackson/map/ser/std/ScalarSerializerBase;-><init>(Ljava/lang/Class;Z)V

    return-void
.end method

# virtual methods
.method public getSchema(Lorg/codehaus/jackson/map/SerializerProvider;Ljava/lang/reflect/Type;)Lorg/codehaus/jackson/JsonNode;
    .locals 2
    .param p1, "provider"    # Lorg/codehaus/jackson/map/SerializerProvider;
    .param p2, "typeHint"    # Ljava/lang/reflect/Type;

    .prologue
    .line 83
    const-string v0, "boolean"

    const/4 v1, 0x1

    invoke-virtual {p0, v0, v1}, Lorg/codehaus/jackson/map/ser/std/StdJdkSerializers$AtomicBooleanSerializer;->createSchemaNode(Ljava/lang/String;Z)Lorg/codehaus/jackson/node/ObjectNode;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic serialize(Ljava/lang/Object;Lorg/codehaus/jackson/JsonGenerator;Lorg/codehaus/jackson/map/SerializerProvider;)V
    .locals 0
    .param p1, "x0"    # Ljava/lang/Object;
    .param p2, "x1"    # Lorg/codehaus/jackson/JsonGenerator;
    .param p3, "x2"    # Lorg/codehaus/jackson/map/SerializerProvider;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;,
            Lorg/codehaus/jackson/JsonGenerationException;
        }
    .end annotation

    .prologue
    .line 68
    check-cast p1, Ljava/util/concurrent/atomic/AtomicBoolean;

    .end local p1    # "x0":Ljava/lang/Object;
    invoke-virtual {p0, p1, p2, p3}, Lorg/codehaus/jackson/map/ser/std/StdJdkSerializers$AtomicBooleanSerializer;->serialize(Ljava/util/concurrent/atomic/AtomicBoolean;Lorg/codehaus/jackson/JsonGenerator;Lorg/codehaus/jackson/map/SerializerProvider;)V

    return-void
.end method

.method public serialize(Ljava/util/concurrent/atomic/AtomicBoolean;Lorg/codehaus/jackson/JsonGenerator;Lorg/codehaus/jackson/map/SerializerProvider;)V
    .locals 1
    .param p1, "value"    # Ljava/util/concurrent/atomic/AtomicBoolean;
    .param p2, "jgen"    # Lorg/codehaus/jackson/JsonGenerator;
    .param p3, "provider"    # Lorg/codehaus/jackson/map/SerializerProvider;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;,
            Lorg/codehaus/jackson/JsonGenerationException;
        }
    .end annotation

    .prologue
    .line 77
    invoke-virtual {p1}, Ljava/util/concurrent/atomic/AtomicBoolean;->get()Z

    move-result v0

    invoke-virtual {p2, v0}, Lorg/codehaus/jackson/JsonGenerator;->writeBoolean(Z)V

    .line 78
    return-void
.end method


text:
using KafkaNet;
using KafkaNet.Model;
using KafkaNet.Protocol;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using TWCore.Messaging.Configuration;
using TWCore.Messaging.Server;
using TWCore.Threading;

// ReSharper disable InconsistentNaming

namespace TWCore.Messaging.Kafka
{
    /// <inheritdoc />
    /// <summary>
    /// Kafka Server Implementation
    /// </summary>
    public class KafkaQueueServer : MQueueServerBase
    {
        private readonly ConcurrentDictionary<string, Producer> _rQueue = new ConcurrentDictionary<string, Producer>();

        /// <inheritdoc />
        /// <summary>
        /// On Create all server listeners
        /// </summary>
        /// <param name="connection">Queue server listener</param>
        /// <param name="responseServer">true if the server is going to act as a response server</param>
        /// <returns>IMQueueServerListener</returns>
        protected override IMQueueServerListener OnCreateQueueServerListener(MQConnection connection, bool responseServer = false)
            => new KafkaQueueServerListener(connection, this, responseServer);

        /// <inheritdoc />
        /// <summary>
        /// On Send message data
        /// </summary>
        /// <param name="message">Response message instance</param>
        /// <param name="e">Event Args</param>
        protected override async Task<int> OnSendAsync(ResponseMessage message, RequestReceivedEventArgs e)
        {
            if (e.ResponseQueues?.Any() != true)
                return -1;

            var senderOptions = Config.ResponseOptions.ServerSenderOptions;
            if (senderOptions is null)
                throw new NullReferenceException("ServerSenderOptions is null.");

            var data = SenderSerializer.Serialize(message);

            var response = true;
            foreach (var queue in e.ResponseQueues)
            {
                try
                {
                    var producer = _rQueue.GetOrAdd(queue.Route, qRoute =>
                    {
                        Core.Log.LibVerbose("New Producer from QueueClient");
                        if (string.IsNullOrEmpty(qRoute))
                            throw new UriFormatException($"The route for the connection to {qRoute} is null.");
                        var options = new KafkaOptions(new Uri(qRoute));
                        var router = new BrokerRouter(options);
                        return Extensions.InvokeWithRetry(() => new Producer(router), 5000, int.MaxValue).WaitAsync();
                    });
                    Core.Log.LibVerbose("Sending {0} bytes to the Queue '{1}/{2}' with CorrelationId={3}", data.Count, queue.Route, queue.Name, message.CorrelationId);
                    await producer.SendMessageAsync(queue.Name, new[] { new Message { Key = message.CorrelationId.ToByteArray(), Value = data.AsArray() } }).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    response = false;
                    Core.Log.Write(ex);
                }
            }
            return response ? data.Count : -1;
        }
    }
}


text:
package org.elasticsearch.benchmark.counter;

import org.elasticsearch.common.StopWatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;

/**
 *
 */
public class SimpleCounterBenchmark {

    private static long NUMBER_OF_ITERATIONS = 10000000;
    private static int NUMBER_OF_THREADS = 100;

    public static void main(String[] args) throws Exception {
        final AtomicLong counter = new AtomicLong();
        StopWatch stopWatch = new StopWatch().start();
        System.out.println("Running " + NUMBER_OF_ITERATIONS);
        for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) {
            counter.incrementAndGet();
        }
        System.out.println("Took " + stopWatch.stop().totalTime() + " TP Millis " + (NUMBER_OF_ITERATIONS / stopWatch.totalTime().millisFrac()));

        System.out.println("Running using " + NUMBER_OF_THREADS + " threads with " + NUMBER_OF_ITERATIONS + " iterations");
        final CountDownLatch latch = new CountDownLatch(NUMBER_OF_THREADS);
        Thread[] threads = new Thread[NUMBER_OF_THREADS];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (long i = 0; i < NUMBER_OF_ITERATIONS; i++) {
                        counter.incrementAndGet();
                    }
                    latch.countDown();
                }
            });
        }
        stopWatch = new StopWatch().start();
        for (Thread thread : threads) {
            thread.start();
        }
        latch.await();
        stopWatch.stop();
        System.out.println("Took " + stopWatch.totalTime() + " TP Millis " + ((NUMBER_OF_ITERATIONS * NUMBER_OF_THREADS) / stopWatch.totalTime().millisFrac()));
    }
}


text:
module Hbc
  class CLI
    class Audit < AbstractCommand
      option "--download",        :download,        false
      option "--token-conflicts", :token_conflicts, false

      def self.help
        "verifies installability of Casks"
      end

      def run
        failed_casks = casks(alternative: -> { Cask.to_a })
                       .reject { |cask| audit(cask) }

        return if failed_casks.empty?
        raise CaskError, "audit failed for casks: #{failed_casks.join(" ")}"
      end

      def audit(cask)
        odebug "Auditing Cask #{cask}"
        Auditor.audit(cask, audit_download: download?, check_token_conflicts: token_conflicts?)
      end
    end
  end
end


text:
<?php

namespace My\RssBundle\Controller;

/**
 * This code has been auto-generated by the JMSDiExtraBundle.
 *
 * Manual changes to it will be lost.
 */
class SourceController__JMSInjector
{
    public static function inject($container) {
        $instance = new \My\RssBundle\Controller\SourceController();
        return $instance;
    }
}


text:
<?php

use yii\db\Migration;
use yii\db\Schema;

//тип замінює цей перелік
///// img`s path
//// обложка
//'cover_img' => Schema::TYPE_STRING,
//// мініатюра
//'thumbnail_img' => Schema::TYPE_STRING,
//// мініатюра меню
//'thumbnails_img' => Schema::TYPE_STRING,

// перелік самих типів
class m170312_132021_image_types extends Migration
{
    public function up()
    {
        $tableOptions = null;

        $this->createTable('{{%image_types}}', [
            'id' => Schema::TYPE_BIGPK,

            'name' => Schema::TYPE_STRING,
            'description' => Schema::TYPE_STRING,

            'is_action' => Schema::TYPE_BOOLEAN,

            'created_at' => Schema::TYPE_INTEGER,
            'updated_at' => Schema::TYPE_INTEGER,
        ], $tableOptions);
    }

    public function down()
    {
        echo "m170312_132021_image_types cannot be reverted.\n";
        $this->dropTable('{{%image_types}}');
        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}