text:
/**

  OXJSONTests.m
  SAXy

  Non-trivial JSON mapping example demonstrating how to:

  1) read and write JSON to and from domain objects
  2) map across inheritance hierarchies
  3) keep mapping declarations concise using the builder pattern
  4) register a default date formatter and apply other formatters individually
  5) register a global type transformer to avoid zero (false booleans in this case) scalar output
  6) flatten and expand a mapping using KVC paths (OXStudioLocation and OXStudioAddress respectively)
  7) map to common Objective-C scalar, object and container types

  The object hierarchy below (OXTuneEntity, OXStudioLocation, OXStudioAddress, OXCartoon and OXTune)
  and the sample JSON file (res/tunes.json) are designed to exercise as many of SAXy's capabilities
  as possible.

  SAXy's most important JSON mapping classes are:

  1) OXJSONReader          - used for reading JSON (unmarshalling) to class instances
  2) OXJSONWriter          - used for writing JSON (marshalling) from class instances
  3) OXJSONMapper          - high-level mapping of how to convert an JSON data to an object hierarchy
  4) OXJSONObjectMapper    - maps class properties to JSON data using KVC (Key-Value-Coding) paths

  Readers and writers are easy to use and understand, usually just requiring a mapper instance to do their job.
  OXJSONMapper instances basically contain list of object mappings, starting with a single root mapping.

  OXJSONObjectMapper instances associate each class property with a JSON KVC path, along with the relavent type
  information.

  In general, JSON mappings need only include information SAXy can't infer from self-reflection or inference.
  Conditions SAXy can't infer include:

  1) property names that don't match JSON key names
  2) expected child types in containers (NSArray, NSSet, etc.)
  3) expected scalar type in NSNumber properties
  4) non-string JSON input (i.e. you must tell SAXy where to expect NSNumber data)
  5) BOOL properties because they look like char types to Objective-C, use OX_ENCODED_BOOL as the scalar type

  Mapping tips: - use Xcode's automatic indentation (^I) to help make the builder code more readable.
                - getting wierd errors? verify you're calling a builder method that returns self.

  Created by Richard Easterling on 3/4/13.

 */
#import <SenTestingKit/SenTestingKit.h>
#import "OXUtil.h"
#import "OXJSONMapper.h"
#import "OXJSONObjectMapper.h"
#import "OXJSONPathMapper.h"
#import "OXContext.h"
#import "OXJSONReader.h"
#import "OXJSONWriter.h"

////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - test classes
////////////////////////////////////////////////////////////////////////////////////////

@interface OXTuneEntity : NSObject
@property (nonatomic, assign) long identifier;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSURL *url;
@end

@implementation OXTuneEntity  @end

@interface OXStudioLocation : NSObject
@property (nonatomic, assign) double latitude;
@property (nonatomic, assign) double longitude;
@end

@implementation OXStudioLocation  @end

@interface OXStudioAddress : OXTuneEntity
@property (nonatomic, strong) NSString *street;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSString *state;
@property (nonatomic, assign) NSUInteger zip;
@property (nonatomic, strong) NSString *country;
@property (nonatomic, strong) OXStudioLocation *location;
@end

@implementation OXStudioAddress
- (id)init
{
    if (self = [super init]) {
        _location = [[OXStudioLocation alloc] init];   //facilitates nested mapping
    }
    return self;
}
@end

@interface OXCartoon : OXTuneEntity
@property (nonatomic, assign) int year;
@end

@implementation OXCartoon  @end

@interface OXTune : OXTuneEntity
@property (nonatomic, strong) NSDate *firstAppearance;
@property (nonatomic, strong) NSSet *cartoonSeries;
@property (nonatomic, strong) NSOrderedSet *archRivals;
@property (nonatomic, strong) NSDictionary *buddies;
@property (nonatomic, strong) NSMutableArray *starredIn;
@property (nonatomic, strong) NSData *image;
@property (nonatomic, strong) OXStudioAddress *studio;
@property (nonatomic, assign) BOOL goldenAgeOfAnimationMember;
@property (nonatomic, strong) NSDecimalNumber *appearances;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, strong) NSArray *references;
@property (nonatomic, strong) NSDate *lastUpdated;
@end

@implementation OXTune
- (id)init
{
    if (self = [super init]) {
        _studio = [[OXStudioAddress alloc] init];   //facilitates nested mapping
    }
    return self;
}
@end

////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - tests
////////////////////////////////////////////////////////////////////////////////////////

@interface OXJSONTests : SenTestCase  @end

@implementation OXJSONTests
{
    OXJSONMapper *mapper;
    OXContext *context;
    NSDateFormatter *shortDateFormatter;
    NSDateFormatter *longDateFormatter;
}

- (void)setUp
{
    [super setUp];
    mapper = [[OXJSONMapper mapper] objects:@[

              [OXJSONObjectMapper rootToManyClass:[OXTune class]]
              ,
              [[[[[[[[[[[[[[[OXJSONObjectMapper objectClass:[OXTune class]]
                            path:@"id" type:[NSNumber class] property:@"identifier"]
                           path:@"name"]
                          path:@"url"]
                         path:@"first_appearance" property:@"firstAppearance"]
                        path:@"cartoon_series" toMany:[NSString class] property:@"cartoonSeries"]
                       path:@"arch_rivals" toMany:[OXTune class] property:@"archRivals"]
                      path:@"buddies" toMany:[OXTune class] property:@"buddies" dictionaryKey:@"identifier"]
                     path:@"starred_in" toMany:[OXCartoon class] property:@"starredIn"]
                    path:@"appearances"]
                   path:@"golden_age_of_animation_member" property:@"goldenAgeOfAnimationMember" scalarType:OX_ENCODED_BOOL ]
                  path:@"studio"]
                 path:@"references" toMany:[NSURL class]]
                pathMapper:[[OXJSONPathMapper path:@"lastupdated" property:@"lastUpdated"]
                            formatter:OX_RFC3339_DATE_FORMATTER]]
               ignorePaths:@[@"age"]]
              ,
              [[[[[[[[[[[OXJSONObjectMapper objectClass:[OXStudioAddress class]]
                        path:@"id" type:[NSNumber class] property:@"identifier"]
                       path:@"name"]
                      path:@"url"]
                     path:@"address.street" type:[NSString class] property:@"street" propertyType:[NSString class]] //expaned mapping
                    path:@"address.city" type:[NSString class] property:@"city" propertyType:[NSString class]]
                   path:@"address.state" type:[NSString class] property:@"state" propertyType:[NSString class]]
                  path:@"address.zip" type:[NSNumber class] property:@"zip" scalarType:@encode(NSUInteger)]
                 path:@"address.country" type:[NSString class] property:@"country" propertyType:[NSString class]]
                path:@"latitude" type:[NSNumber class] property:@"location.latitude" scalarType:@encode(double)]    //flatten mapping
               path:@"longitude" type:[NSNumber class] property:@"location.longitude" scalarType:@encode(double)]
              ,
              [[[OXJSONObjectMapper objectClass:[OXCartoon class]]
                  path:@"id" type:[NSNumber class] property:@"identifier"]
                 //path:@"name"]
                //path:@"url"]
               path:@"year" type:[NSNumber class]]

    ]];

    context = [[OXContext alloc] init];
    longDateFormatter = [[NSDateFormatter alloc] init];
    [longDateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [longDateFormatter setDateFormat:@"MMMM d',' yyyy"];
    [context.transform registerDefaultDateFormatter:longDateFormatter];     //register a default date handler

    [context.transform registerFromScalar:OX_ENCODED_BOOL to:[NSString class] transformer:^(id value, OXContext *ctx) {
        return (value && [value boolValue]) ? @"true" : nil;    //register global transformer - ignores 'false' BOOl values in writer by returning nil
    }];

    NSDate *date = [longDateFormatter dateFromString:@"July 4, 1987"];
    STAssertNotNil(date, @"sanity check on date formatter");
}

- (void)testJSONMapper
{
    STAssertNotNil(mapper, @"mapper");
    [mapper configure:[[OXContext alloc] init]];

    //root
    OXJSONPathMapper *resultMapper = [mapper.rootMapper objectMapperByPath:OX_ROOT_PATH];
    STAssertNotNil(resultMapper, @"resultMapper by path");
    OXJSONPathMapper *resultMapper2 = [mapper.rootMapper objectMapperByProperty:@"result"];
    STAssertNotNil(resultMapper2, @"resultMapper by property");
    STAssertEqualObjects([NSMutableArray class], resultMapper.toType.type, @"self reflection assigned toType");
    STAssertEqualObjects([OXTune class], resultMapper.toType.containerChildType.type, @"container child type preserved");

    //OXTune
    OXJSONObjectMapper *tuneMapper = [mapper objectMapperForClass:[OXTune class]];
    STAssertNotNil(tuneMapper, @"tuneMapper");

    OXJSONPathMapper *idMapper = [tuneMapper objectMapperByPath:@"id"];
    STAssertNotNil(idMapper, @"idMapper");
    //STAssertNil(idMapper.toTransform, @"NSNumber to NSNumber needs no transform");
    STAssertEqualObjects([NSNumber class], idMapper.toType.type, @"self reflection assigned toType");

    OXJSONPathMapper *dateMapper = [tuneMapper objectMapperByPath:@"first_appearance"];
    STAssertNotNil(dateMapper, @"firstAppearance");
    STAssertNotNil(dateMapper.toTransform, @"string to date needs transform");
    STAssertNil(dateMapper.formatterName, @"default dates have no formatterName");
    STAssertEqualObjects([NSDate class], dateMapper.toType.type, @"self reflection assigned toType");

    OXJSONPathMapper *seriesMapper = [tuneMapper objectMapperByPath:@"cartoon_series"];
    STAssertNotNil(seriesMapper, @"cartoon_series");
    STAssertEqualObjects([NSSet class], seriesMapper.toType.type, @"self reflection assigned toType");
    STAssertEqualObjects([NSString class], seriesMapper.toType.containerChildType.type, @"self reflection assigned toType.containerChildType");

    OXJSONPathMapper *referencesMapper = [tuneMapper objectMapperByPath:@"references"];
    STAssertNotNil(referencesMapper, @"references");
    STAssertEqualObjects([NSArray class], referencesMapper.toType.type, @"self reflection assigned toType");
    STAssertEqualObjects([NSURL class], referencesMapper.toType.containerChildType.type, @"self reflection assigned toType.containerChildType");

    OXJSONPathMapper *studioMapper = [tuneMapper objectMapperByPath:@"studio"];
    STAssertNotNil(studioMapper, @"studio");
    STAssertEqualObjects([OXStudioAddress class], studioMapper.toType.type, @"self reflection assigned toType");

    //OXStudioAddress
    OXJSONObjectMapper *addressMapper = [mapper objectMapperForClass:[OXStudioAddress class]];
    STAssertNotNil(addressMapper, @"addressMapper");

    OXJSONPathMapper *idAddrMapper = [addressMapper objectMapperByPath:@"id"];
    STAssertNotNil(idAddrMapper, @"idAddrMapper");
    //STAssertNil(idAddrMapper.toTransform, @"NSNumber to NSNumber needs no transform");
    STAssertEqualObjects([NSNumber class], idAddrMapper.toType.type, @"self reflection assigned toType");

    OXJSONPathMapper *cityMapper = [addressMapper objectMapperByPath:@"city"];
    STAssertNotNil(cityMapper, @"cityMapper");
    STAssertNil(cityMapper.toTransform, @"string to string doesn't need a transform");
    STAssertEqualObjects([NSString class], cityMapper.toType.type, @"self reflection assigned toType");

}

- (void)testReader
{
    OXJSONReader *reader = [OXJSONReader readerWithMapper:mapper context:context];
    reader.context.logReaderStack = NO;

    NSArray *tunes = [reader readResourceFile:@"tunes.json"];
    STAssertNotNil(tunes, @"read tunes");
    STAssertEquals((NSUInteger)4, [tunes count], @"4 tunes read");

    //OXTunes
    OXTune *tune = [tunes objectAtIndex:0];
    STAssertNotNil(tune, @"read tune");
    STAssertEquals(100101l, tune.identifier, @"identifier long - read");
    STAssertEqualObjects(@"Daffy Duck", tune.name, @"name read");
    STAssertEqualObjects([longDateFormatter dateFromString:@"April 17, 1937"], tune.firstAppearance, @"read NSDate - firstAppearance");
    STAssertEqualObjects(@"http://en.wikipedia.org/wiki/Daffy_Duck", [tune.url absoluteString], @"read url");
    STAssertTrue(tune.goldenAgeOfAnimationMember, @"read BOOL - goldenAgeOfAnimationMember");
    STAssertEquals(133.0, [tune.appearances doubleValue], @"read NSDecimalNumber - appearances");

    //date:
    NSDateFormatter *lastupdatedFormatter = (NSDateFormatter *)[reader.context.transform formatterWithName:OX_RFC3339_DATE_FORMATTER];
    NSDate *lastupdated = [lastupdatedFormatter dateFromString:@"2013-03-07T12:30:00-0000"];
    STAssertEqualObjects(lastupdated, tune.lastUpdated, @"read created_at");
    //containers:
    STAssertNotNil(tune.cartoonSeries, @"read NSSet of NSStrings - cartoonSeries");
    STAssertEquals((NSUInteger)2, [tune.cartoonSeries count], @"read cartoonSeries");
    STAssertTrue([tune.cartoonSeries containsObject:@"Looney Tunes"], @"NSSet element - Looney Tunes");
    STAssertEqualObjects(@"Wile E. Coyote", [[tune.archRivals objectAtIndex:0] name], @"read 1st object in NSOrderedSet - Wile E. Coyote");
    STAssertEqualObjects(@"Porky Pig", [[tune.buddies objectForKey:[NSNumber numberWithLong:100104]] name], @"read NSDictionary of OXTune objects, keyed by id - Porky Pig");
    STAssertNotNil(tune.starredIn, @"read NSMutableArray of OXCartoon objects");
    STAssertEqualObjects(@"Duck Amuck", [[tune.starredIn lastObject] name], @"read NSMutableArray of OXCartoon objects, last object is - Duck Amuck");
    STAssertNotNil(tune.references, @"read NSArray of NSURL objects");
    STAssertEqualObjects(@"http://en.wikiquote.org/wiki/Daffy_Duck/", [[tune.references lastObject] absoluteString], @"read NSArray of NSURL objects, last object is - http://en.wikiquote.org/wiki/Daffy_Duck");
    //OXStudioAddress - expanded mapping
    STAssertNotNil(tune.studio, @"read nested OXStudioAddress - studio");
    STAssertEqualObjects(@"Warner Bros.", tune.studio.name, @"read nested studio name - Warner Bros.");
    STAssertEqualObjects(@"CA", tune.studio.state, @"read nested studio state - CA");
    STAssertEquals((NSUInteger)91522, tune.studio.zip, @"read nested zip - 91522");
    //OXStudioLocation - flattened mapping
    STAssertEquals(34.152141, tune.studio.location.latitude, @"read double from nested studio.location.latitude - 34.152141");
    STAssertEquals(-118.336852, tune.studio.location.longitude, @"read double from nested studio.location.longitude - -118.336852");

    //OXJSONWriter *writer = [[OXJSONWriter writerWithMapper:mapper context:context] writingOptions:NSJSONWritingPrettyPrinted];
    //NSLog(@"%@", [[writer writeAsText:tunes] stringByReplacingOccurrencesOfString:@"\\" withString:@""]);

}

- (void)testWriter
{
    NSString *json1 = @"[{\"id\":100103,\"name\":\"Bugs Bunny\",\"first_appearance\":\"April 30, 1938\",\"url\":\"http://en.wikipedia.org/wiki/Bugs_Bunny\",\"starred_in\":[{\"name\":\"A Wild Hare\",\"year\":1940,\"url\":\"http://en.wikipedia.org/wiki/A_Wild_Hare\"}],\"lastupdated\":\"2013-03-07T12:30:00+0000\"}]";

    OXJSONReader *reader = [OXJSONReader readerWithMapper:mapper context:context];
    NSArray *tunes = [reader readText:json1]; //lazy way to get the test data

    OXJSONWriter *writer = [OXJSONWriter writerWithMapper:mapper context:context];
    NSString *json2 = [[writer writeAsText:tunes] stringByReplacingOccurrencesOfString:@"\\" withString:@""];  //call reader and strip out '\' JavaScript encoding
    //what should be in output:
    STAssertTrue([json2 rangeOfString:@"\"id\":100103"].length > 0, @"\"id\":100103");
    STAssertTrue([json2 rangeOfString:@"\"name\":\"Bugs Bunny\""].length > 0, @"\"name\":\"Bugs Bunny\"");
    STAssertTrue([json2 rangeOfString:@"\"first_appearance\":\"April 30, 1938\""].length > 0, @"\"first_appearance\":\"April 30, 1938\"");
    STAssertTrue([json2 rangeOfString:@"\"url\":\"http://en.wikipedia.org/wiki/Bugs_Bunny\""].length > 0, @"\"url\":\"http://en.wikipedia.org/wiki/Bugs_Bunny\"");
    STAssertTrue([json2 rangeOfString:@"\"name\":\"A Wild Hare\""].length > 0, @"\"name\":\"A Wild Hare\"");
    STAssertTrue([json2 rangeOfString:@"\"year\":1940"].length > 0, @"\"year\":1940");
    STAssertTrue([json2 rangeOfString:@"\"lastupdated\":\"2013-03-07T12:30:00+0000\""].length > 0, @"OX_RFC3339_DATE_FORMATTER - \"lastupdated\":\"2013-03-07T12:30:00+0000\"");
    //what should not be there:
    STAssertFalse([json2 rangeOfString:@"\"age\":\"0\""].length > 0, @"ignorePaths working - \"age\":\"0\"");
    STAssertFalse([json2 rangeOfString:@"\"golden_age_of_animation_member\":\"false\""].length > 0, @"global transformer should eliminate 'false' BOOLs - \"golden_age_of_animation_member\":\"false\"");

}

@end

//
//  Copyright (c) 2013 Outsource Cafe, Inc. All rights reserved.
//
//  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.
//


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.password_manager.settings;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import androidx.annotation.IntDef;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.LooperMode;

import org.chromium.base.test.BaseRobolectricTestRunner;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * Tests for the {@link DialogManager} class.
 */
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
@LooperMode(LooperMode.Mode.LEGACY)
public class DialogManagerTest {
    @Rule
    public MockitoRule mMockitoRule = MockitoJUnit.rule();

    /**
     * Fake of {@link DialogFragment} allowing to detect calls to {@link DialogFragment#show} and
     * {@link DialogFragment#dismiss}.
     */
    private static class FakeDialogFragment extends DialogFragment {
        @Retention(RetentionPolicy.SOURCE)
        @IntDef({NEW, SHOWING, DISMISSED})
        public @interface DialogState {}
        /** The dialog has not been shown yet. */
        public static final int NEW = 0;
        /** The dialog is showing. */
        public static final int SHOWING = 1;
        /** The dialog has been dismissed. */
        public static final int DISMISSED = 2;

        @DialogState
        private int mState = NEW;

        @DialogState
        public int getState() {
            return mState;
        }

        @Override
        public void show(FragmentManager manager, String tag) {
            assert mState == NEW;
            mState = SHOWING;
        }

        @Override
        public void dismiss() {
            assert mState == SHOWING;
            mState = DISMISSED;
        }
    }

    /** Used to detect showing and hiding without actually triggering any UI. */
    private final FakeDialogFragment mDialogFragment = new FakeDialogFragment();

    /** Used to test reporting from DialogManager. */
    private final DialogManager.ActionsConsumer mMockActionsConsumer =
            mock(DialogManager.ActionsConsumer.class);

    /** The object under test. */
    private final DialogManager mDialogManager = new DialogManager(mMockActionsConsumer);

    /**
     * Delayer to replace the timed one in the tested class. This gives exact control over hiding
     * delays.
     */
    private final ManualCallbackDelayer mManualDelayer = new ManualCallbackDelayer();

    @Before
    public void setUp() {
        mDialogManager.replaceCallbackDelayerForTesting(mManualDelayer);
    }

    /**
     * Check that a dialog is hidden eventually but not before a prescribed delay.
     */
    @Test
    public void testHiddenEventually() {
        mDialogManager.show(mDialogFragment, null);

        Runnable callback = mock(Runnable.class);
        mDialogManager.hide(callback);
        Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
        verify(callback, never()).run();

        mManualDelayer.runCallbacksSynchronously();
        verify(callback, times(1)).run();
        assertEquals(FakeDialogFragment.DISMISSED, mDialogFragment.getState());
        verify(mMockActionsConsumer, times(1)).consume(DialogManager.HideActions.HIDING_DELAYED);
    }

    /**
     * Check that immediate hiding is notified properly.
     */
    @Test
    public void testNotification() {
        mDialogManager.show(mDialogFragment, null);

        Runnable callback = mock(Runnable.class);
        mManualDelayer.runCallbacksSynchronously();
        mDialogManager.hide(callback);
        Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
        verify(callback, times(1)).run();
        assertEquals(FakeDialogFragment.DISMISSED, mDialogFragment.getState());
        verify(mMockActionsConsumer, times(1))
                .consume(DialogManager.HideActions.HIDDEN_IMMEDIATELY);
    }

    /**
     * Check that the callback is called even if the dialog has not been shown at all.
     */
    @Test
    public void testCallbackCalled() {
        Runnable callback = mock(Runnable.class);
        mDialogManager.hide(callback);
        Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
        verify(callback, times(1)).run();
        assertEquals(FakeDialogFragment.NEW, mDialogFragment.getState());
        verify(mMockActionsConsumer, times(1)).consume(DialogManager.HideActions.NO_OP);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package cito.stomp.ws;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.nio.ByteBuffer;

import javax.websocket.EncodeException;

import org.junit.Before;
import org.junit.Test;

import cito.stomp.Frame;

/**
 * Unit test for {@link FrameEncoder}.
 *
 * @author Daniel Siviter
 * @since v1.0 [25 Jul 2016]
 */
public class FrameEncoderTest {
	private FrameEncoder.Binary binary;
	private FrameEncoder.Text text;

	@Before
	public void before() {
		this.binary = new FrameEncoder.Binary();
		this.text = new FrameEncoder.Text();
	}

	@Test
	public void encode_byteBuffer() throws EncodeException, IOException {
		final Frame frame = Frame.receipt("123").build();
		final ByteBuffer actual = this.binary.encode(frame);
		assertEquals(UTF_8.encode("RECEIPT\nreceipt-id:123\n\n\u0000"), actual);
	}

	@Test
	public void encode_string() throws EncodeException, IOException {
		final Frame frame = Frame.receipt("123").build();
		final String actual = this.text.encode(frame);
		assertEquals("RECEIPT\nreceipt-id:123\n\n\u0000", actual);
	}
}


text:
using System.Text;
using nHydrate.Generator.Models;

namespace nHydrate.Generator.PostgresInstaller.ProjectItemGenerators.Views
{
    class ViewsTemplate : BaseDbScriptTemplate
    {
        private StringBuilder sb = new StringBuilder();
        private CustomView _view;

        public ViewsTemplate(ModelRoot model, CustomView view)
            : base(model)
        {
            _view = view;
        }

        public override string FileContent
        {
            get
            {
                this.GenerateContent();
                return sb.ToString();
            }
        }

        public override string FileName => "Views.sql";

        private void GenerateContent()
        {
            sb.AppendLine($"--This SQL is generated for the model defined view [{_view.DatabaseName}]");
            sb.AppendLine();
            sb.Append(SQLEmit.GetSqlCreateView(_view, true));
        }
    }
}


text:
package de.tuberlin.orp.common.message;

import com.fasterxml.jackson.databind.JsonNode;

import java.io.Serializable;

public class OrpRequest implements Serializable {
  private OrpContext context;

  public OrpRequest(JsonNode jsonNode) {
    context = new OrpContext(jsonNode);
  }

  public OrpContext getContext() {
    return context;
  }
}


text:
This app is a collection of various UI design patterns written as JavaScript modules for Titanium Mobile.  This will show you how to develop and implement factory components for event driven mobile applications.

There are currently 2 UI modules in this version.

THIS IS FOR iOS ONLY.  Sorry.  Android support is coming next. :-)

<b>Required:</b> Titanium Mobile SDK 1.7.x
<http://developer.appcelerator.com/blog/2011/05/titanium-mobile-sdk-1-7-rc1.html>

For previous version, you may use the object literal modules instead (located in the modules folder).

![Screenshot 1](https://img.skitch.com/20110520-d1eeyexu28scp7xnpieenirwmd.jpg)

# The Modules

## 1. Heads Up Display (aka, HUD)
This is a basic implementation of an a heads up display, or modal view, that gracefully displays loading indicator and message.

![HUD Screen Shot](https://img.skitch.com/20110520-jmq5kfypf4q7gd5r2x95dbh286.jpg)

### Usage

```
var HUD = MyApp.mod.hud.init(MyApp.ui.win); // pass in the window to attach the HUD
HUD.show('YOUR MESSAGE');
setTimeout(function(){
	HUD.hide();
},2000);
```
### Methods

```
init(win);      // Properties: object - window  (required)
show(message);  // Properties: string - message (optional)
hide();         // Properties: none
```
1. Initialize the module using the `init()` method and pass in a window object to attached the HUD.
2. Show a HUD by calling `show()`, passing an optional message to the component.
3. You can remove a HUD by calling the `hide()` method.  This will call the remove() methods to the HUD on the window object.

Note: Replace 'MyApp' with your own app namespace.

## 2. Passcode Window
This module is designed to "lock down" an app by invoking a passcode screen and prompting a user to input a 4 digit code.  This is loosely based on Apple's internal passcode feature in iOS.

![Passcode Screen Shot](https://img.skitch.com/20110520-fd6mfdk1eypw2gseem11y4gj5w.jpg)

### Usage

```
var PIN = MyApp.mod.passcode.init({code:1234,barColor:'#0079C1'});
PIN.open({
	success:function(){
	// do something
},error:function(){
	// do something
}});
```

### Methods

```
init(code,barColor);  // Properties: integer - 4 digits (required); string - hex color value (optional)
open(success,error);  // Properties: object - success callback (optional), object - error callback (optional)
close();              // Properties: none
```
1. Initialize the module using the `init()` method and pass in a 4 digit number to validate against and optionally a color code.
2. Show a passcode window by calling `open()`.  You can optionally pass in two callbacks: "success" and "error" that will be executed on each event.  This is where you can choose to allow a user to continue or not.

Note: Replace 'MyApp' with your own app namespace.

# Accessing the Module APIs

To access these modules from JavaScript, you would extend your app namespace in app.js and import the module using the global require() method:

```
// Extend your existing app namespace for your modules to exist
MyApp.mod = {};
MyApp.mod.hud = require('modules/hud');
MyApp.mod.passcode = require('modules/passcode.mod');
```

# Author

Terry Martin
Master Trainer, Appcelerator. Founder of Semantic Press.

* <http://twitter.com/tzmartin>
* <http://linkedin.com/in/terryzmartin>
* <http://semanticpress.com>

More modules to come.  Follow me on Twitter or contact me if you need a module developed.

# License

This content is released under the  MIT License.
http://www.opensource.org/licenses/mit-license.php

Enjoy! Stay tuned for more modules being added to this project.

![Hi](http://c.statcounter.com/6897643/0/9890c16f/1/)


text:
package github

import (
	"fmt"

	qs "github.com/google/go-querystring/query"
)

// SearchService provides access to the search related functions
// in the GitHub API.
//
// GitHub API docs: http://developer.github.com/v3/search/
type SearchService service

// SearchOptions specifies optional parameters to the SearchService methods.
type SearchOptions struct {
	// How to sort the search results.  Possible values are:
	//   - for repositories: stars, fork, updated
	//   - for commits: author-date, committer-date
	//   - for code: indexed
	//   - for issues: comments, created, updated
	//   - for users: followers, repositories, joined
	//
	// Default is to sort by best match.
	Sort string `url:"sort,omitempty"`

	// Sort order if sort parameter is provided. Possible values are: asc,
	// desc. Default is desc.
	Order string `url:"order,omitempty"`

	// Whether to retrieve text match metadata with a query
	TextMatch bool `url:"-"`

	ListOptions
}

// RepositoriesSearchResult represents the result of a repositories search.
type RepositoriesSearchResult struct {
	Total             *int         `json:"total_count,omitempty"`
	IncompleteResults *bool        `json:"incomplete_results,omitempty"`
	Repositories      []Repository `json:"items,omitempty"`
}

// Repositories searches repositories via various criteria.
//
// GitHub API docs: http://developer.github.com/v3/search/#search-repositories
func (s *SearchService) Repositories(query string, opt *SearchOptions) (*RepositoriesSearchResult, *Response, error) {
	result := new(RepositoriesSearchResult)
	resp, err := s.search("repositories", query, opt, result)
	return result, resp, err
}

// CommitsSearchResult represents the result of a commits search.
type CommitsSearchResult struct {
	Total             *int            `json:"total_count,omitempty"`
	IncompleteResults *bool           `json:"incomplete_results,omitempty"`
	Commits           []*CommitResult `json:"items,omitempty"`
}

// CommitResult represents a commit object as returned in commit search endpoint response.
type CommitResult struct {
	Hash           *string     `json:"hash,omitempty"`
	Message        *string     `json:"message,omitempty"`
	AuthorID       *int        `json:"author_id,omitempty"`
	AuthorName     *string     `json:"author_name,omitempty"`
	AuthorEmail    *string     `json:"author_email,omitempty"`
	AuthorDate     *Timestamp  `json:"author_date,omitempty"`
	CommitterID    *int        `json:"committer_id,omitempty"`
	CommitterName  *string     `json:"committer_name,omitempty"`
	CommitterEmail *string     `json:"committer_email,omitempty"`
	CommitterDate  *Timestamp  `json:"committer_date,omitempty"`
	Repository     *Repository `json:"repository,omitempty"`
}

// Commits searches commits via various criteria.
//
// GitHub API Docs: https://developer.github.com/v3/search/#search-commits
func (s *SearchService) Commits(query string, opt *SearchOptions) (*CommitsSearchResult, *Response, error) {
	result := new(CommitsSearchResult)
	resp, err := s.search("commits", query, opt, result)
	return result, resp, err
}

// IssuesSearchResult represents the result of an issues search.
type IssuesSearchResult struct {
	Total             *int    `json:"total_count,omitempty"`
	IncompleteResults *bool   `json:"incomplete_results,omitempty"`
	Issues            []Issue `json:"items,omitempty"`
}

// Issues searches issues via various criteria.
//
// GitHub API docs: http://developer.github.com/v3/search/#search-issues
func (s *SearchService) Issues(query string, opt *SearchOptions) (*IssuesSearchResult, *Response, error) {
	result := new(IssuesSearchResult)
	resp, err := s.search("issues", query, opt, result)
	return result, resp, err
}

// UsersSearchResult represents the result of a users search.
type UsersSearchResult struct {
	Total             *int   `json:"total_count,omitempty"`
	IncompleteResults *bool  `json:"incomplete_results,omitempty"`
	Users             []User `json:"items,omitempty"`
}

// Users searches users via various criteria.
//
// GitHub API docs: http://developer.github.com/v3/search/#search-users
func (s *SearchService) Users(query string, opt *SearchOptions) (*UsersSearchResult, *Response, error) {
	result := new(UsersSearchResult)
	resp, err := s.search("users", query, opt, result)
	return result, resp, err
}

// Match represents a single text match.
type Match struct {
	Text    *string `json:"text,omitempty"`
	Indices []int   `json:"indices,omitempty"`
}

// TextMatch represents a text match for a SearchResult
type TextMatch struct {
	ObjectURL  *string `json:"object_url,omitempty"`
	ObjectType *string `json:"object_type,omitempty"`
	Property   *string `json:"property,omitempty"`
	Fragment   *string `json:"fragment,omitempty"`
	Matches    []Match `json:"matches,omitempty"`
}

func (tm TextMatch) String() string {
	return Stringify(tm)
}

// CodeSearchResult represents the result of a code search.
type CodeSearchResult struct {
	Total             *int         `json:"total_count,omitempty"`
	IncompleteResults *bool        `json:"incomplete_results,omitempty"`
	CodeResults       []CodeResult `json:"items,omitempty"`
}

// CodeResult represents a single search result.
type CodeResult struct {
	Name        *string     `json:"name,omitempty"`
	Path        *string     `json:"path,omitempty"`
	SHA         *string     `json:"sha,omitempty"`
	HTMLURL     *string     `json:"html_url,omitempty"`
	Repository  *Repository `json:"repository,omitempty"`
	TextMatches []TextMatch `json:"text_matches,omitempty"`
}

func (c CodeResult) String() string {
	return Stringify(c)
}

// Code searches code via various criteria.
//
// GitHub API docs: http://developer.github.com/v3/search/#search-code
func (s *SearchService) Code(query string, opt *SearchOptions) (*CodeSearchResult, *Response, error) {
	result := new(CodeSearchResult)
	resp, err := s.search("code", query, opt, result)
	return result, resp, err
}

// Helper function that executes search queries against different
// GitHub search types (repositories, commits, code, issues, users)
func (s *SearchService) search(searchType string, query string, opt *SearchOptions, result interface{}) (*Response, error) {
	params, err := qs.Values(opt)
	if err != nil {
		return nil, err
	}
	params.Add("q", query)
	u := fmt.Sprintf("search/%s?%s", searchType, params.Encode())

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, err
	}

	switch {
	case searchType == "commits":
		// Accept header for search commits preview endpoint
		// TODO: remove custom Accept header when this API fully launches.
		req.Header.Set("Accept", mediaTypeCommitSearchPreview)
	case opt != nil && opt.TextMatch:
		// Accept header defaults to "application/vnd.github.v3+json"
		// We change it here to fetch back text-match metadata
		req.Header.Set("Accept", "application/vnd.github.v3.text-match+json")
	}

	return s.client.Do(req, result)
}


text:
User Research Briefs
* [User Research Briefs](https://www.gov.uk/service-manual/user-centred-design/user-research/user-research-briefs) and [Example Briefs](https://www.gov.uk/service-manual/assets/documents/IDAQualBrief.pdf)

The Team
* [Recruitment](https://www.gov.uk/service-manual/the-team/recruitment/index.html)
* [The Team](https://www.gov.uk/service-manual/the-team/index.html)
* [Job Descriptions](https://www.gov.uk/service-manual/the-team/recruitment/job-descriptions.html)
* [Recruitment Hub](https://www.gov.uk/service-manual/the-team/recruitment/hub.html)
* [Working with Specialist Suppliers](https://www.gov.uk/service-manual/the-team/working-with-specialists.html)
* [Your Working Environment](https://www.gov.uk/service-manual/the-team/working-environment.html)
* [Technology Leadership](https://www.gov.uk/service-manual/the-team/recruitment/scs-orgdesign.html)
* [Accessibility Skills](https://www.gov.uk/service-manual/the-team/accessibility.html)

Roles
* [Chief Technology Officers Resources](https://www.gov.uk/service-manual/chief-technology-officers)
* [Technical Architect Resources](https://www.gov.uk/service-manual/technical-architects)
* [Service Managers Resources](https://www.gov.uk/service-manual/service-managers) and [Service Managers Skills](https://www.gov.uk/service-manual/the-team/service-manager.html)
* [Delivery Manager](https://www.gov.uk/service-manual/the-team/delivery-manager.html)
* [Developers Resources](https://www.gov.uk/service-manual/developers) and [Developer Skills](https://www.gov.uk/service-manual/the-team/developer.html)
* [Web Operations Resources](https://www.gov.uk/service-manual/web-ops) and [Web Operations Skills](https://www.gov.uk/service-manual/the-team/web-operations.html)
* [Designers Resources](https://www.gov.uk/service-manual/designers) and [Designer Skills](https://www.gov.uk/service-manual/the-team/designer.html)
* [Digital Leader](https://www.gov.uk/service-manual/the-team/digital-leader.html)
* [User Researchers Resources](https://www.gov.uk/service-manual/user-researchers) and [User Researcher Skills](https://www.gov.uk/service-manual/the-team/user-researcher.html)
* [Content Designers Resources](https://www.gov.uk/service-manual/content-designers) and [Content Designer Skills](https://www.gov.uk/service-manual/the-team/content-designer.html)
* [Performance Analysts Resources](https://www.gov.uk/service-manual/performance-analysts)

Project Management
* [Agile](https://www.gov.uk/service-manual/agile/index.html)
* [What Agile Looks Like](https://www.gov.uk/service-manual/agile/what-agile-looks-like.html)
* [Features of Agile](https://www.gov.uk/service-manual/agile/features-of-agile.html)
* [Training and Learning about Agile](https://www.gov.uk/service-manual/agile/training-and-learning.html)
* [Writing User Stories](https://www.gov.uk/service-manual/agile/writing-user-stories.html)
* [Continuous Delivery](https://www.gov.uk/service-manual/agile/continuous-delivery.html)
* [Quality](https://www.gov.uk/service-manual/agile/quality.html)
* [Testing in an Agile Environment](https://www.gov.uk/service-manual/making-software/testing-in-agile.html)
* [Running Retrospectives](https://www.gov.uk/service-manual/agile/running-retrospectives.html)

Scaling and Governance
* [When to Scale Up](https://www.gov.uk/service-manual/governance/when-to-scale-up.html)
* [Scaling a Service Team](https://www.gov.uk/service-manual/governance/scaling-a-service-team.html)
* [Governing a Service After Scaling Up](https://www.gov.uk/service-manual/governance/governing-a-service-after-scaling-up.html)

* [Government as a Platform](https://www.gov.uk/service-manual/technology/government-as-a-platform.html)
* [Service Integration and Management](https://www.gov.uk/service-manual/technology/service-integration.html)
* [Progressive Enhancement](https://www.gov.uk/service-manual/making-software/progressive-enhancement.html)
* [Standalone Mobile Apps](https://www.gov.uk/service-manual/making-software/standalone-apps.html)
* [Analytics Tools](https://www.gov.uk/service-manual/making-software/analytics-tools.html)
* [Creating a Culture that Supports Change](https://www.gov.uk/service-manual/technology/culture-that-supports-change.html)
* [End User Devices](https://www.gov.uk/service-manual/technology/end-user-devices.html)
* [User Stories for Web Operations](https://www.gov.uk/service-manual/operations/web-operations-stories.html)
* [Spending Controls](https://www.gov.uk/service-manual/technology/spending-controls.html)

Measurement
* [Measurement](https://www.gov.uk/service-manual/measurement/index.html)
* [Performance Platform](https://www.gov.uk/service-manual/measurement/performance-platform.html)
* [Using Data](https://www.gov.uk/service-manual/measurement/using-data.html)
* [Key Performance Indicators](https://www.gov.uk/service-manual/measurement/other-kpis.html)
* [Completion Rate](https://www.gov.uk/service-manual/measurement/completion-rate.html)
* [Digital Take-Up](https://www.gov.uk/service-manual/measurement/digital-takeup.html)
* [Measuring Cost Per Transaction](https://www.gov.uk/service-manual/measurement/cost-per-transaction.html)
* [User Satisfaction](https://www.gov.uk/service-manual/measurement/user-satisfaction.html)

## Development

Making Software
* [Making Software](https://www.gov.uk/service-manual/making-software/index.html)
* [Open Standards and Licensing](https://www.gov.uk/service-manual/making-software/open-standards-and-licensing.html)
* [Using Open Source Software](https://www.gov.uk/service-manual/making-software/open-source.html)
* [Open Data](https://www.gov.uk/service-manual/technology/open-data.html)
* [Version Control](https://www.gov.uk/service-manual/making-software/version-control.html)
* [Security as Enabler](https://www.gov.uk/service-manual/technology/security-as-enabler.html)
* [Information Security](https://www.gov.uk/service-manual/making-software/information-security.html)
* [Guidance for CTOs](https://www.gov.uk/service-manual/technology/index.html)
* [Choosing Technology](https://www.gov.uk/service-manual/making-software/choosing-technology.html)
* [Technology Architecture](https://www.gov.uk/service-manual/technology/architecture.html)
* [Technology Code of Practice](https://www.gov.uk/service-manual/technology/code-of-practice.html)
* [Configuration Management](https://www.gov.uk/service-manual/making-software/configuration-management.html)
* [Development Environments](https://www.gov.uk/service-manual/making-software/development-environment.html)
* [Sandbox and Staging Servers](https://www.gov.uk/service-manual/making-software/sandbox-and-staging-servers.html)
* [Managing Software Dependencies](https://www.gov.uk/service-manual/making-software/dependency-management.html)
* [Testing Code](https://www.gov.uk/service-manual/making-software/code-testing.html)
* [Exploratory Testing](https://www.gov.uk/service-manual/making-software/exploratory-testing.html)
* [Deploying Software](https://www.gov.uk/service-manual/making-software/deployment.html)
* [Releasing Software](https://www.gov.uk/service-manual/making-software/release-strategies.html)
* [APIs](https://www.gov.uk/service-manual/making-software/apis.html)
* [User Accounts and Logins](https://www.gov.uk/service-manual/making-software/logins.html)
* [Cookies](https://www.gov.uk/service-manual/making-software/cookies.html)
* [GOV.UK Verify Guidance](https://www.gov.uk/service-manual/identity-assurance/index.html)

Operations
* [Operating a Service](https://www.gov.uk/service-manual/operations/index.html)
* [Operating a service.gov.uk Subdomain](https://www.gov.uk/service-manual/operations/operating-servicegovuk-subdomains.html)
* [Hosting](https://www.gov.uk/service-manual/operations/hosting.html)
* [Cloud Security](https://www.gov.uk/service-manual/operations/cloud-security.html)
* [Monitoring](https://www.gov.uk/service-manual/operations/monitoring.html)
* [Uptime and Availability](https://www.gov.uk/service-manual/operations/uptime-and-availability.html)
* [Service Management](https://www.gov.uk/service-manual/operations/service-management.html)
* [Devops](https://www.gov.uk/service-manual/operations/devops.html)
* [Helpdesk](https://www.gov.uk/service-manual/operations/helpdesk.html)
* [Managing User Support](https://www.gov.uk/service-manual/operations/managing-user-support.html)
* [Load and Performance Testing](https://www.gov.uk/service-manual/operations/load-and-performance-testing.html)
* [Vulnerability and Penetration Testing](https://www.gov.uk/service-manual/operations/penetration-testing.html)

Websites
* [Domain Names](https://www.gov.uk/service-manual/domain-names/index.html)
* [Browsers and Devices](https://www.gov.uk/service-manual/user-centred-design/browsers-and-devices.html)
* [How Users Read](https://www.gov.uk/service-manual/user-centred-design/how-users-read.html)
* [GOV.UK Header and Footer](https://www.gov.uk/service-manual/user-centred-design/resources/header-footer.html)
* [Privacy Note Template for Services](https://www.gov.uk/service-manual/content-designers/privacy-note-template-for-services.html)
* [Print Forms](https://www.gov.uk/service-manual/user-centred-design/print-forms.html)
* [Print Form Template](https://www.gov.uk/service-manual/assets/documents/print-forms/template-form.pdf)
* [Data Visualisation](https://www.gov.uk/service-manual/user-centred-design/data-visualisation.html)
* [Choosing Appropriate Formats](https://www.gov.uk/service-manual/user-centred-design/choosing-appropriate-formats.html)
* [Design Patterns](https://www.gov.uk/service-manual/user-centred-design/resources/patterns/index.html)
* [Elements](https://www.gov.uk/service-manual/user-centred-design/resources/elements/index.html)


text:
package net.iskandar.examples.chat.app.client.to;

import com.google.gwt.user.client.rpc.IsSerializable;

public class ChatUserTo implements IsSerializable {

	private Integer id;
	private Integer chatId;
	private UserTo user;

	public Integer getId() {
		return id;
	}

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

	public Integer getChatId() {
		return chatId;
	}

	public void setChatId(Integer chatId) {
		this.chatId = chatId;
	}

	public UserTo getUser() {
		return user;
	}

	public void setUser(UserTo user) {
		this.user = user;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item
    	android:title="Choose Provider"
    	android:icon="@drawable/ic_menu_choose_provider"
    	android:id="@+id/provider_choice_online">
   	</item>
    <item
    	android:title="Change Floor"
    	android:icon="@drawable/ic_menu_change_floor"
    	android:id="@+id/floor_changer_online">
   	</item>
    <item
    	android:icon="@drawable/ic_menu_nearby"
    	android:title="What's Nearby?"
    	android:id="@+id/what_is_here_online">
   	</item>
   	<!-- Comment/uncomment w.r.t. Folia (who wants to supply their own search -->
   	<!--
   	<item
    	android:id="@+id/find_nearest"
    	android:title="Find Nearest..."
    	android:icon="@drawable/ic_menu_find_nearest">
   	</item>
   	 -->
   	<item
    	android:icon="@drawable/ic_menu_search"
    	android:title="Search"
    	android:id="@+id/search_online">
   	</item>
   	<item
    	android:id="@+id/clear_route"
    	android:title="Clear Route"
    	android:icon="@drawable/ic_menu_clear_route">
   	</item>
   	<!--
    <item
    	android:icon="@drawable/ic_menu_change_view"
    	android:title="Change View"
    	android:id="@+id/change_view_online">
   	</item>
   	 -->
   	<item
   		android:id="@+id/set_stracking_screen"
   		android:title="Enable/Disable Tracking">
 	</item>
 	<!-- Knapper til at tweake med -->
 	<!--
   	<item
    	android:title="Change Update Intvl."
    	android:id="@+id/change_update_interval_online">
   	</item>
   	<item
    	android:title="Change Update Threshold"
    	android:id="@+id/change_update_threshold_online">
   	</item>
   	 -->
   	<item
   		android:id="@+id/offline_mode"
   		android:icon="@drawable/ic_menu_off"
   		android:title="Offline Mode">
 	</item>
 	<item
   		android:id="@+id/about_screen"
   		android:title="About">
 	</item>
 	<!-- Uncomment for trusted parties -->
 	<!--
 	<item
   		android:id="@+id/menu_online_backdoor"
   		android:title="Backdoor">
 	</item>
 	 -->
</menu>


text:
#define BASE_DOUBLE
#include <gsl/templates_on.h>
#include <gsl/matrix/getset_source.c>
#include <gsl/templates_off.h>
#undef BASE_DOUBLE


text:
Develop: [![Build Status](https://travis-ci.org/cluttered-resume/polymer-client.svg?branch=develop)](https://travis-ci.org/cluttered-resume/polymer-client)

Master: [![Build Status](https://travis-ci.org/cluttered-resume/polymer-client.svg?branch=master)](https://travis-ci.org/cluttered-resume/polymer-client)

This template is a starting point for building apps using a drawer-based
layout. The layout is provided by `app-layout` elements.

This template, along with the `polymer-cli` toolchain, also demonstrates use
of the "PRPL pattern" This pattern allows fast first delivery and interaction with
the content at the initial route requested by the user, along with fast subsequent
navigation by pre-caching the remaining components required by the app and
progressively loading them on-demand as the user navigates through the app.

The PRPL pattern, in a nutshell:

* **Push** components required for the initial route
* **Render** initial route ASAP
* **Pre-cache** components for remaining routes
* **Lazy-load** and progressively upgrade next routes on-demand

### Setup

##### Prerequisites

First, install [Polymer CLI](https://github.com/Polymer/polymer-cli) using
[npm](https://www.npmjs.com) (we assume you have pre-installed [node.js](https://nodejs.org)).

    npm install -g bower polymer-cli

### Start the development server

This command serves the app at `http://localhost:8080` and provides basic URL
routing for the app:

    polymer serve --open

### Build

This command performs HTML, CSS, and JS minification on the application
dependencies, and generates a service-worker.js file with code to pre-cache the
dependencies based on the entrypoint and fragments specified in `polymer.json`.
The minified files are output to the `build/unbundled` folder, and are suitable
for serving from a HTTP/2+Push compatible server.

In addition the command also creates a fallback `build/bundled` folder,
generated using fragment bundling, suitable for serving from non
H2/push-compatible servers or to clients that do not support H2/Push.

    polymer build

### Preview the build

This command serves the minified version of the app at `http://localhost:8080`
in an unbundled state, as it would be served by a push-compatible server:

    polymer serve build/unbundled

This command serves the minified version of the app at `http://localhost:8080`
generated using fragment bundling:

    polymer serve build/bundled

### Run tests

This command will run [Web Component Tester](https://github.com/Polymer/web-component-tester)
against the browsers currently installed on your machine:

    polymer test


text:
angular.module('treehouseCourse', [])
  .controller('stageTwoCtrl', function ($scope) {
    $scope.user = {
      name: "world",
      email: "alex@mrvdot.com",
      age: 25,
      active: false,
      role: "anonymous"
    };
  });


text:
InstallExtensionHandler::InstallExtensionHandler() {
}

InstallExtensionHandler::~InstallExtensionHandler() {
}

void InstallExtensionHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);
  localized_strings->SetString(
      "extensionSettingsInstallDropTarget",
      l10n_util::GetStringUTF16(IDS_EXTENSIONS_INSTALL_DROP_TARGET));
  localized_strings->SetBoolean(
      "offStoreInstallEnabled",
      extensions::switch_utils::IsOffStoreInstallEnabled());
}

void InstallExtensionHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      "startDrag",
      base::Bind(&InstallExtensionHandler::HandleStartDragMessage,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "stopDrag",
      base::Bind(&InstallExtensionHandler::HandleStopDragMessage,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "installDroppedFile",
      base::Bind(&InstallExtensionHandler::HandleInstallMessage,
                 base::Unretained(this)));
}

void InstallExtensionHandler::HandleStartDragMessage(const ListValue* args) {
  WebDropData* drop_data = web_ui()->GetWebContents()->GetView()->GetDropData();
  if (!drop_data) {
    DLOG(ERROR) << "No current drop data.";
    return;
  }

  if (drop_data->filenames.empty()) {
    DLOG(ERROR) << "Current drop data contains no files.";
    return;
  }

  file_to_install_ = FilePath::FromWStringHack(
      UTF16ToWide(drop_data->filenames.front().path));
}

void InstallExtensionHandler::HandleStopDragMessage(const ListValue* args) {
  file_to_install_.clear();
}

void InstallExtensionHandler::HandleInstallMessage(const ListValue* args) {
  if (file_to_install_.empty()) {
    LOG(ERROR) << "No file captured to install.";
    return;
  }

  Profile* profile = Profile::FromWebUI(web_ui());
  scoped_refptr<CrxInstaller> crx_installer(
      CrxInstaller::Create(
          ExtensionSystem::Get(profile)->extension_service(),
          new ExtensionInstallUI(profile)));
  crx_installer->InstallCrx(file_to_install_);

  file_to_install_.clear();
}


text:
INSERT INTO #inclusionRuleCohorts (inclusion_rule_id, subject_id, cohort_start_date, cohort_end_date)
select @inclusion_rule_id as inclusion_rule_id, person_id as subject_id, start_date as cohort_start_date, end_date as cohort_end_date
FROM
(
  select person_id, start_date, end_date
  FROM #PrimaryCriteriaEvents pe
  @additionalCriteriaQuery
) Results
;


text:
package org.jabref.logic.bibtex.comparator;

import java.util.Optional;

import org.jabref.model.groups.GroupTreeNode;
import org.jabref.model.metadata.MetaData;

public class GroupDiff {
    private final GroupTreeNode originalGroupRoot;
    private final GroupTreeNode newGroupRoot;

    private GroupDiff(GroupTreeNode originalGroupRoot, GroupTreeNode newGroupRoot) {
        this.originalGroupRoot = originalGroupRoot;
        this.newGroupRoot = newGroupRoot;
    }

    /**
     * This method only detects whether a change took place or not. It does not determine the type of change. This would
     * be possible, but difficult to do properly, so we rather only report the change.
     */
    public static Optional<GroupDiff> compare(MetaData originalMetaData, MetaData newMetaData) {
        final Optional<GroupTreeNode> originalGroups = originalMetaData.getGroups();
        final Optional<GroupTreeNode> newGroups = newMetaData.getGroups();

        if (!originalGroups.equals(newGroups)) {
            return Optional.of(new GroupDiff(newGroups.orElse(null), originalGroups.orElse(null)));
        } else {
            return Optional.empty();
        }
    }

    public GroupTreeNode getOriginalGroupRoot() {
        return originalGroupRoot;
    }

    public GroupTreeNode getNewGroupRoot() {
        return newGroupRoot;
    }
}


text:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use SimpleBrowser;

class MiNubeController extends Controller
{
    //
    private $browser;

    public function __construct()
    {
        $this->browser = new SimpleBrowser();
    }

    public function getTownByName($name){
        $query = $this->browser->get(
            'http://papi.minube.com/cities',
            [
                'lang' => 'es',
                'country_id' => 63,
                'filter' => $name,
                'api_key' => env('MINUBE_APIKEY')
            ]
        );

        $data = json_decode($query, true);

        return ($data) ? array_first($data) : [];
    }

    public function getInterestPointsByTownId($townId){
        $query = $this->browser->get(
            'http://papi.minube.com/pois',
            [
                'lang' => 'es',
                'city_id' => $townId,
                'api_key' => env('MINUBE_APIKEY')
            ]
        );

        return json_decode($query, true) ?: [];
    }
}


text:
namespace SpecsFor.Demo.Domain
{
	public class ValidatingOrderProcessor : OrderProcessor
	{
		private readonly IValidator<Order> _validator;

		public ValidatingOrderProcessor(IValidator<Order> validator, IInventory inventory, IPublisher publisher)
			: base(inventory, publisher)
		{
			_validator = validator;
		}

		public override OrderResult Process(Order order)
		{
			if (_validator.Validate(order))
			{
				return base.Process(order);
			}
			else
			{
				return new OrderResult {WasAccepted = false};
			}
		}
	}
}


text:
package net.wohlfart.mercury.security.oauth;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

public class AccessTokenRetriever {

    private final AuthorizationCodeResourceDetails client;
    private String code;

    public AccessTokenRetriever(AuthorizationCodeResourceDetails client) {
        this.client = client;
    }

    public AccessTokenRetriever code(String code) {
        this.code = code;
        return this;
    }

    /*
     * Encoding and sending form: {
     *    grant_type=[authorization_code],
     *    code=[-gsdgsdgsdg-mnFWIYnAs875OrMt1nIjma8lRRC-syUreEgCxhV-EAHRSH3-KIQmTBW1W0E60MRI-ijuggwYjSrfaxXxijz1rUK9NyjzSK_17yQ9uVJDWcgx],
     *    redirect_uri=[http://localhost:8080/login/facebook],
     *    client_id=[1368363149952141],
     *    client_secret=[dfgsergsergseg]}
     */
    public ResponseEntity<HashMap> request() {
        MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
        form.add("client_id", client.getClientId());
        form.add("client_secret", client.getClientSecret());
        form.add("redirect_uri", client.getPreEstablishedRedirectUri());  // TODO: needed?
        form.add("code", this.code);
        form.add("grant_type", "authorization_code");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers);

        RestTemplate restTemplate = new RestTemplate();
        // TODO: update for springboot2
        return restTemplate.postForEntity(client.getAccessTokenUri(), request, HashMap.class);
    }

}


text:
<?php

namespace Dvsa\Mot\Frontend\PersonModule\Controller;

use Core\BackLink\BackLinkQueryParam;
use Core\Controller\AbstractAuthActionController;
use Dvsa\Mot\Frontend\PersonModule\Action\AnnualAssessmentCertificatesAction;
use Dvsa\Mot\Frontend\PersonModule\Action\VtsTestersAnnualAssessmentCertificatesAction;
use Dvsa\Mot\Frontend\PersonModule\Model\ViewAnnualAssessmentCertificatesFormContext;
use Dvsa\Mot\Frontend\PersonModule\Security\AnnualAssessmentCertificatesPermissions;
use Dvsa\Mot\Frontend\PersonModule\View\ContextProvider;
use DvsaCommon\Factory\AutoWire\AutoWireableInterface;

class ViewAnnualAssessmentCertificatesController extends AbstractAuthActionController implements AutoWireableInterface
{
    private $viewAction;

    private $vtsTestersViewAction;

    /**
     * @var ContextProvider
     */
    private $contextProvider;

    /** @var AnnualAssessmentCertificatesPermissions */
    private $certificatesPermissions;

    public function __construct(
        AnnualAssessmentCertificatesAction $viewAction,
        VtsTestersAnnualAssessmentCertificatesAction $vtsTestersViewAction,
        ContextProvider $contextProvider,
        AnnualAssessmentCertificatesPermissions $certificatesPermissions
    ) {
        $this->viewAction = $viewAction;
        $this->vtsTestersViewAction = $vtsTestersViewAction;
        $this->contextProvider = $contextProvider;
        $this->certificatesPermissions = $certificatesPermissions;
    }

    public function viewAction()
    {
        $context = $this->contextProvider->getContext();
        $personId = $this->getPersonId($context);

        $formContext = new ViewAnnualAssessmentCertificatesFormContext(
            $personId,
            $this->getIdentity()->getUserId(),
            $this,
            $this->params()->fromRoute("vehicleTestingStationId")
        );

        $backTo = $this->params()->fromQuery("backTo");

        if ($backTo === BackLinkQueryParam::VTS_TESTER_ASSESSMENTS || $backTo === BackLinkQueryParam::SERVICE_REPORTS) {
            $actionResult = $this->vtsTestersViewAction->execute($formContext, $this, $backTo);
        } else {
            $actionResult = $this->viewAction->execute($formContext, $this);
        }

        return $this->applyActionResult($actionResult);
    }

    /**
     * @param $context
     *
     * @return int
     */
    private function getPersonId($context)
    {
        return $context === ContextProvider::YOUR_PROFILE_CONTEXT ?
            $this->getIdentity()->getUserId() : (int) $this->params()->fromRoute('id');
    }
}


text:
(function() { // This prevents problems when concatenating scripts that aren't strict.
	'use strict';

	/**
	 * the namespace for core services for the KnAllEdge system
	 * @namespace knalledge.knalledgeMap.knalledgeMapDirectives
	 */

   angular.module('knalledgeMapDirectives')

	 .directive('knalledgeMapSelectItem', ['KnAllEdgeSelectItemService', function(KnAllEdgeSelectItemService) { // mcm_map_select_sub_entity
 		return {
 			restrict: 'AE',
 			// scope: {
 			// 	labels: '='
 			// },
 			// ng-if directive: http://docs.angularjs.org/api/ng.directive:ngIf
 			// expression: http://docs.angulajrs.org/guide/expression
 			templateUrl: 'components/knalledgeMap/partials/knalledgeMap-selectItem.tpl.html',
 			link: function($scope, $element) {
 				// https://api.jquery.com/focus/
 				$element.find(".item_name").focus();
 			},

 			controller: function($scope, $element) {

 				$scope.selectedItem = null;
 				$scope.title = "Select Item";
 				$scope.path = ".";
 				$scope.item = {
 					name: null
 				};

 				$scope.selectItem = function(item) {
 					$scope.selectedItem = item;
 					console.log("$scope.selectedItem = " + JSON.stringify(item.name));
 					if ($scope.shouldSubmitOnSelection) {
 						$scope.submitted();
 					}
 				};

 				var populateItems = function(subName) {
 					console.log("getItemsDescsByName(%s)", subName);
 					$scope.itemType = KnAllEdgeSelectItemService.itemType;
 					$scope.items = KnAllEdgeSelectItemService.getItemsDescsByName(subName);
 					var dataContentItems = KnAllEdgeSelectItemService.getItemsDescsByDataContent(subName);
 					var found = false;
 					for(var i=0; i< dataContentItems.length; i++){ //there must be no duplicates and both search methods can return some same elements
 						found = false;
 						for(var j=0; j< $scope.items.length; j++){
 							if(dataContentItems[i] == $scope.items[j]){
 								found = true;
 								continue;
 							}
 						}
 						if(!found){
 							$scope.items.push(dataContentItems[i]);
 						}
 					}
 					console.log("$scope.items IN: " + $scope.items);
 				};

 				populateItems("");

 				$scope.nameChanged = function() {
 					//console.log("New searching Item name: %s", $scope.item.name);
 					populateItems($scope.item.name);
 					console.log("$scope.items: " + $scope.items);
 				};
 				$scope.cancelled = function() {
 					unbindEvents();
 					console.log("[KnAllEdgeSelectItemService] Cancelled");
 					//console.log("Canceled");
 					$element.remove(); //TODO: sta je ovo?
 					$scope.selectingCanceled();
 				};

 				$scope.submitted = function() {
 					unbindEvents();
 					console.log("[KnAllEdgeSelectItemService] Submitted");
 					if ($scope.selectedItem !== null && $scope.selectedItem !== undefined) {
 						$scope.selectingSubmited($scope.selectedItem);
 						$element.remove();
 					} else {
 						window.alert('Please, select a Item');
 					}
 				};

 				var unbindEvents = function() {
 					// https://docs.angularjs.org/api/ng/function/angular.element
 					// http://api.jquery.com/unbind/
 					angular.element("body").unbind("keydown keypress", keyboardProcessing);
 					$element.unbind("keydown keypress", keyboardProcessing);
 				};

 				var keyboardProcessing = function(event) {
 					if (event.which === 27) { // ECAPE
 						$scope.$apply(function() {
 							$scope.cancelled();
 						});

 						event.preventDefault();
 					}

 					if (event.which === 13) { // ENTER
 						// scope.$apply(function (){
 						//     $scope.$eval(attrs.ngEnter);
 						// });

 						// event.preventDefault();
 					}
 				};

 				// https://docs.angularjs.org/api/ng/function/angular.element
 				// http://api.jquery.com/bind/
 				angular.element("body").bind("keydown keypress", keyboardProcessing);
 				// http://stackoverflow.com/questions/17470790/how-to-use-a-keypress-event-in-angularjs
 				$element.bind("keydown keypress", keyboardProcessing);
 			}
 		};
 	}]);

   }()); // end of 'use strict';


text:
//============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================
package org.talend.components.salesforce.runtime;

import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.IndexedRecord;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.talend.components.api.component.runtime.BoundedReader;
import org.talend.components.api.container.DefaultComponentRuntimeContainerImpl;
import org.talend.components.api.container.RuntimeContainer;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.api.test.ComponentTestUtils;
import org.talend.components.salesforce.SalesforceConnectionProperties;
import org.talend.components.salesforce.runtime.common.ConnectionHolder;
import org.talend.components.salesforce.test.SalesforceTestBase;
import org.talend.components.salesforce.tsalesforceconnection.TSalesforceConnectionDefinition;
import org.talend.components.salesforce.tsalesforceinput.TSalesforceInputDefinition;
import org.talend.components.salesforce.tsalesforceinput.TSalesforceInputProperties;
import org.talend.components.salesforce.tsalesforceoutput.TSalesforceOutputProperties;
import org.talend.daikon.properties.ValidationResult;
import org.talend.daikon.properties.presentation.Form;
import org.talend.daikon.properties.property.Property;
import org.talend.daikon.properties.test.PropertiesTestUtils;

import com.sforce.async.AsyncApiException;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.fault.ExceptionCode;
import com.sforce.soap.partner.fault.LoginFault;
import com.sforce.ws.ConnectionException;

/**
 * Test Salesforce connection session
 */
public class SalesforceSessionReuseTestIT extends SalesforceTestBase {
    @ClassRule
    public static final TestRule DISABLE_IF_NEEDED = new DisableIfMissingConfig();

    private static final Logger LOGGER = LoggerFactory.getLogger(SalesforceSessionReuseTestIT.class);

    private static final String WRONG_PWD = "WRONG_PWD";

    private static String randomizedValue;

    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();

    @BeforeClass
    public static void setup() throws Throwable {
        randomizedValue = "Name_Unit_" + createNewRandom();

        List<IndexedRecord> outputRows = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            GenericData.Record row = new GenericData.Record(getSchema(false));
            row.put("Name", randomizedValue);
            row.put("ShippingStreet", "123 Main Street");
            row.put("ShippingPostalCode", Integer.toString(i));
            row.put("BillingStreet", "123 Main Street");
            row.put("BillingState", "CA");
            row.put("BillingPostalCode", createNewRandom());
            outputRows.add(row);
        }
        TSalesforceOutputProperties props = (TSalesforceOutputProperties) new TSalesforceOutputProperties("foo").init();
        setupProps(props.connection);
        props.module.moduleName.setValue(EXISTING_MODULE_NAME);
        props.module.main.schema.setValue(getSchema(false));
        doWriteRows(props,outputRows);
    }

    @AfterClass
    public static void cleanup() throws Throwable {
        deleteAllAccountTestRows(randomizedValue);
    }

    /*
    * If the logic changes for this test please specify appropriate timeout.
    * The average execution time for this test in range 1 - 3 sec.
    */
    @Test(timeout = 30_000)
    public void testBasicLogin() throws Throwable {
        File sessionFolder = new File(tempFolder.getRoot().getPath() + "/tsalesforceconnection/");
        assertEquals(0, sessionFolder.getTotalSpace());
        LOGGER.debug("session folder: " + sessionFolder.getAbsolutePath());
        SalesforceConnectionProperties props = setupProps(null);
        // setup session function
        props.reuseSession.setValue(true);
        props.sessionDirectory.setValue(sessionFolder.getAbsolutePath());

        // Init session
        assertEquals(ValidationResult.Result.OK, testConnection(props).getStatus());
        assertNotEquals(0, sessionFolder.getTotalSpace());

        // Set wrong pwd to test reuse session from session folder
        props.userPassword.password.setValue(WRONG_PWD);
        assertEquals(ValidationResult.Result.OK, testConnection(props).getStatus());

    }

    @Ignore("Need to solve test failed randomly")
    @Test(timeout = 30_000)
    public void testUseExistingConnection() throws Throwable {
        File sessionFolder = new File(tempFolder.getRoot().getPath() + "/tsalesforceconnection_1/");
        assertEquals(0, sessionFolder.getTotalSpace());
        LOGGER.debug("session folder: " + sessionFolder.getAbsolutePath());
        SalesforceConnectionProperties connProps = (SalesforceConnectionProperties) getComponentService()
                .getComponentProperties(TSalesforceConnectionDefinition.COMPONENT_NAME);
        setupProps(connProps);
        // setup session function
        connProps.reuseSession.setValue(true);
        connProps.sessionDirectory.setValue(sessionFolder.getAbsolutePath());

        final String currentComponentName = TSalesforceConnectionDefinition.COMPONENT_NAME + "_1";
        final java.util.Map<String, Object> globalMap = new java.util.HashMap<String, Object>();
        RuntimeContainer connContainer = new DefaultComponentRuntimeContainerImpl() {

            @Override
            public String getCurrentComponentId() {
                return currentComponentName;
            }

            @Override
            public Object getComponentData(String componentId, String key) {
                return globalMap.get(componentId + "_" + key);
            }

            @Override
            public void setComponentData(String componentId, String key, Object data) {
                globalMap.put(componentId + "_" + key, data);
            }

            @Override
            public Object getGlobalData(String key) {
                return globalMap.get(key);
            }
        };
        // 1. salesforce connection would save the session to a session file
        SalesforceSourceOrSink salesforceSourceOrSink = new SalesforceSourceOrSink();
        salesforceSourceOrSink.initialize(connContainer, connProps);
        assertEquals(ValidationResult.Result.OK, salesforceSourceOrSink.validate(connContainer).getStatus());

        // 2. set a wrong pwd to connection properties
        connProps.userPassword.password.setValue(WRONG_PWD);

        // Input component get connection from the tSalesforceConnection
        TSalesforceInputProperties inProps = (TSalesforceInputProperties) getComponentService()
                .getComponentProperties(TSalesforceInputDefinition.COMPONENT_NAME);
        inProps.connection.referencedComponent.componentInstanceId.setValue(currentComponentName);
        inProps.connection.referencedComponent.setReference(connProps);
        checkAndAfter(inProps.connection.referencedComponent.getReference().getForm(Form.REFERENCE), "referencedComponent",
                inProps.connection);

        ComponentTestUtils.checkSerialize(inProps, errorCollector);

        assertEquals(2, inProps.getForms().size());
        Form f = inProps.module.getForm(Form.REFERENCE);
        assertTrue(f.getWidget("moduleName").isCallBeforeActivate());
        ComponentProperties moduleProps = (ComponentProperties) f.getProperties();

        try {
            // 3. input components would be get connection from connection session file
            moduleProps = (ComponentProperties) PropertiesTestUtils.checkAndBeforeActivate(getComponentService(), f, "moduleName",
                    moduleProps);

            Object connection = connContainer.getComponentData(currentComponentName, SalesforceSourceOrSink.KEY_CONNECTION);
            assertNotNull(connection);
            ((PartnerConnection) connection).getConfig().setPassword(WRONG_PWD);
            // Check whether the session disable by other test.
            ((PartnerConnection) connection).getUserInfo();

            Property<?> prop = (Property<?>) f.getWidget("moduleName").getContent();
            assertTrue(prop.getPossibleValues().size() > 100);
            LOGGER.debug(moduleProps.getValidationResult().toString());
            assertEquals(ValidationResult.Result.OK, moduleProps.getValidationResult().getStatus());

            invalidSession(connProps, null);
            // This means that the session is disabled by current test

            // 4. invalid the session, then the session should be renew based on reference connection information(wrong pwd)
            // connect would be fail

            moduleProps = (ComponentProperties) PropertiesTestUtils.checkAndBeforeActivate(getComponentService(), f, "moduleName",
                    moduleProps);
            assertEquals(ValidationResult.Result.ERROR, moduleProps.getValidationResult().getStatus());
            LOGGER.debug(moduleProps.getValidationResult().toString());
        } catch (ConnectionException e) {
            // Maybe get exception when same account run in parallel
            // The session maybe disabled by other test
            assertThat(e, instanceOf(LoginFault.class));
            assertEquals(ExceptionCode.INVALID_LOGIN, ((LoginFault) e).getExceptionCode());
            LOGGER.debug("session is disabled by other test!");
        }

        // 5.set correct pwd back
        setupProps(connProps);
        moduleProps = (ComponentProperties) PropertiesTestUtils.checkAndBeforeActivate(getComponentService(), f, "moduleName",
                moduleProps);
        assertEquals(ValidationResult.Result.OK, moduleProps.getValidationResult().getStatus());
        LOGGER.debug(moduleProps.getValidationResult().toString());

    }

    /*
    * If the logic changes for this test please specify appropriate timeout.
    * The average execution time for this test 3.2-4.7 sec.
    */
    @Test(timeout = 40_000)
    public void testInputReuseSession() throws Throwable {
        File sessionFolder = new File(tempFolder.getRoot().getPath() + "/tsalesforceinput/");
        assertEquals(0, sessionFolder.getTotalSpace());
        LOGGER.debug("session folder: " + sessionFolder.getAbsolutePath());

        TSalesforceInputProperties props = (TSalesforceInputProperties) new TSalesforceInputProperties("foo").init(); //$NON-NLS-1$
        props.module.moduleName.setValue(EXISTING_MODULE_NAME);
        props.module.main.schema.setValue(getMakeRowSchema(false));
        props.connection = setupProps(null);

        // setup session function
        props.connection.reuseSession.setValue(true);
        props.connection.sessionDirectory.setValue(sessionFolder.getAbsolutePath());

        // Init session
        assertEquals(ValidationResult.Result.OK, testConnection(props).getStatus());
        assertNotEquals(0, sessionFolder.getTotalSpace());

        // Invalid session, test whether it can be renew the session
        invalidSession(props.connection, null);

        List<IndexedRecord> records = readRows(props);
        assertNotNull(records);
        LOGGER.debug("current records number in module " + EXISTING_MODULE_NAME + ": " + records.size());
        assertNotEquals(0, records.size());

        // Set wrong pwd to test reuse session from session folder
        props.connection.userPassword.password.setValue(WRONG_PWD);

        try {
            testConnection(props);
            records = readRows(props);
            assertNotNull(records);
            LOGGER.debug("current records number in module " + EXISTING_MODULE_NAME + ": " + records.size());
            assertNotEquals(0, records.size());
            // Test reuse session fails with wrong pwd
            invalidSession(props.connection, null);
            // This means that the session is disabled by current test
        } catch (IOException e) {
            Throwable caused = e.getCause();
            // Maybe get exception when same account run in parallel
            // The session maybe disabled by other test
            assertThat(caused, instanceOf(LoginFault.class));
            assertEquals(ExceptionCode.INVALID_LOGIN, ((LoginFault) caused).getExceptionCode());
            LOGGER.debug("session is disabled by other test!");
        }

        try {
            readRows(props);
        } catch (IOException e) {
            Throwable caused = e.getCause();
            // Should login fails with wrong pwd
            assertThat(caused, instanceOf(ConnectionException.class));
            assertEquals("Connection was not created, invalid credentials or user locked out.", caused.getMessage());

            LOGGER.debug("expect login fails: " + e.getMessage());
        }

        // Disable reuse session function
        props.connection.reuseSession.setValue(false);
        LOGGER.debug("expect login fails:");
        assertEquals(ValidationResult.Result.ERROR, testConnection(props).getStatus());

    }

    @Test
    public void testBulkSessionRenew() throws Exception {

        TSalesforceInputProperties props = (TSalesforceInputProperties) new TSalesforceInputProperties("foo").init(); //$NON-NLS-1$
        props.module.moduleName.setValue(EXISTING_MODULE_NAME);
        props.module.main.schema.setValue(getMakeRowSchema(false));
        props.connection = setupProps(null);

        // setup session function
        props.connection.bulkConnection.setValue(true);
        props.queryMode.setValue(TSalesforceInputProperties.QueryMode.Bulk);
        props.condition.setValue("Name = '"+ randomizedValue + "'");
        // Init session
        assertEquals(ValidationResult.Result.OK, testConnection(props).getStatus());

        BoundedReader<?> reader = createBoundedReader(props);
        assertThat(reader, instanceOf(SalesforceBulkQueryInputReader.class));

        reader.start();
        // Invalid the session by session id
        String sessionIdBeforeRenew = ((SalesforceBulkQueryInputReader) reader).bulkRuntime.getBulkConnection().getConfig()
                .getSessionId();
        reader.close();

        Thread.sleep(1000);

        invalidSession(props.connection, sessionIdBeforeRenew);
        // Test renew session for bulk connections
        try {
            reader.start();
        } catch (IOException io) {
            if (io.getCause() instanceof AsyncApiException
                    && io.getMessage().contains("Unable to find any data to create batch")) {
                // This kind of error shows that connection is established well, but some issue with test data.
                // It happens in SalesforceBulkRuntime inside of method createBatchFromStream, after job was created.
                LOGGER.warn("Issue with getting prepared test data. Error msg - {}", io.getMessage());
            } else {
                throw io;
            }
        }
        // Check the renew session
        String sessionIdAfterRenew = ((SalesforceBulkQueryInputReader) reader).bulkRuntime.getBulkConnection().getConfig()
                .getSessionId();
        reader.close();
        assertNotEquals(sessionIdBeforeRenew, sessionIdAfterRenew);

    }

    @Ignore("Need to solve test failed randomly")
    @Test(timeout = 30_000)
    public void testOutputReuseSession() throws Throwable {
        File sessionFolder = new File(tempFolder.getRoot().getPath() + "/tsalesforceoutput/");
        assertEquals(0, sessionFolder.getTotalSpace());
        LOGGER.debug("session folder: " + sessionFolder.getAbsolutePath());

        TSalesforceOutputProperties props = (TSalesforceOutputProperties) new TSalesforceOutputProperties("foo").init(); //$NON-NLS-1$
        props.module.moduleName.setValue(EXISTING_MODULE_NAME);
        props.module.main.schema.setValue(getMakeRowSchema(false));
        props.connection = setupProps(null);

        // setup session function
        props.connection.reuseSession.setValue(true);
        props.connection.sessionDirectory.setValue(sessionFolder.getAbsolutePath());

        // Init session
        assertEquals(ValidationResult.Result.OK, testConnection(props).getStatus());
        assertNotEquals(0, sessionFolder.getTotalSpace());

        // Invalid session, test whether it can be renew the session
        invalidSession(props.connection, null);
        // length=260
        String invalidName = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        List<IndexedRecord> records = new ArrayList<>();
        IndexedRecord r1 = new GenericData.Record(props.module.main.schema.getValue());
        r1.put(0, invalidName);
        records.add(r1);
        try {
            doWriteRows(props, records);
        } catch (IOException e) {
            // means exception caused by "Name" too long
            assertTrue(e.getMessage().contains(invalidName));
            LOGGER.debug("expect exception: " + e.getMessage());
        }
        // Set wrong pwd to test reuse session from session folder
        props.connection.userPassword.password.setValue(WRONG_PWD);
        try {
            doWriteRows(props, records);
        } catch (IOException e) {
            Throwable caused = e.getCause();
            if (caused != null && caused instanceof LoginFault) {
                // Maybe throw exception when same account run in parallel
                // The session maybe disabled by other test
                assertEquals(ExceptionCode.INVALID_LOGIN, ((LoginFault) caused).getExceptionCode());
                LOGGER.debug("session is disabled by other test!");
            } else {
                // means exception caused by "Name" too long
                assertTrue(e.getMessage().contains(invalidName));
                LOGGER.debug("expect exception: " + e.getMessage());
                // This means that the session not disabled by other test

                invalidSession(props.connection, null);
                // This means that the session is disabled by current test
            }
        }

        // Test reuse session fails with wrong pwd
        try {
            doWriteRows(props, records);
        } catch (IOException e) {
            Throwable caused = e.getCause();
            // Should login fails with wrong pwd
            assertThat(caused, instanceOf(LoginFault.class));
            assertEquals(ExceptionCode.INVALID_LOGIN, ((LoginFault) caused).getExceptionCode());
            LOGGER.debug("expect login fails: " + e.getMessage());
        }

        // Disable reuse session function
        props.connection.reuseSession.setValue(false);
        LOGGER.debug("expect login fails:");
        assertEquals(ValidationResult.Result.ERROR, testConnection(props).getStatus());

    }

    protected ValidationResult testConnection(ComponentProperties props) {
        SalesforceSourceOrSink sourceOrSink = new SalesforceSourceOrSink();
        sourceOrSink.initialize(null, props);
        ValidationResult result = sourceOrSink.validate(null);
        return result;
    }

    protected void invalidSession(SalesforceConnectionProperties props, String sessionId) throws Exception {
        SalesforceSourceOrSink sourceOrSink = new SalesforceSourceOrSink();
        sourceOrSink.initialize(null, props);
        ConnectionHolder connectionHolder = sourceOrSink.connect(null);
        assertNotNull(connectionHolder.connection);
        if (sessionId != null) {
            connectionHolder.connection.invalidateSessions(new String[] { sessionId });
        }
        connectionHolder.connection.logout();
        LOGGER.debug("session \"" + connectionHolder.connection.getConfig().getSessionId() + "\" invalided!");
    }

}


text:
FOUNDATION_EXPORT double CHRequestVersionNumber;

//! Project version string for CHRequest.
FOUNDATION_EXPORT const unsigned char CHRequestVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <CHRequest/PublicHeader.h>


text:
module ShowExperienceItems

  def ShowExperienceItems.run(client, org)
    country = "can"

    puts "Fetching items localized to %s" % country

    client.experiences.get_items(org, :country => country, :limit => 10, :offset => 0).each do |item|
      puts "%s:" % item.number
      puts "  - base price: %s" % item.price.label
      item.local.prices.each do |price|
        puts "  - %s: %s" % [price.key, price.label]
      end
    end
  end

end


text:
using System.Threading;

namespace Aspose.Slides.Web.Core.Services.Comparison
{
	/// <summary>
	/// The abstraction for strategy of compare
	/// </summary>
	public interface IPresentationComparator
	{
		/// <summary>
		/// Compares two presentations and returns a string with differents.
		/// </summary>
		/// <param name="firstPresentationFile">A string path of the first presentation file</param>
		/// <param name="secondPresentationFile">A string path of the second presentation file</param>
		/// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete</param>
		/// <returns>String with differents</returns>
		string ComparePresentations(string firstPresentationFile, string secondPresentationFile, CancellationToken cancellationToken = default);
	}
}


text:
package org.bovinegenius.kurgan.types;

import org.bovinegenius.kurgan.ConfigTypeErrorException;
import org.bovinegenius.kurgan.yaml.YamlUtils;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.ScalarNode;

public class ConfigBool implements ConfigType {
    public static final ConfigBool value = new ConfigBool();

    @Override
    public Object coerce(Node node) {
        String value = YamlUtils.getValue((ScalarNode)node);
        if (value == null) {
            return null;
        } else {
            return value.equalsIgnoreCase("true");
        }
    }

    @Override
    public void typeCheck(Node node) throws ConfigTypeErrorException {
        if (!(node instanceof ScalarNode)) {
            throw new ConfigTypeErrorException(node, String.format("Expected %s, found %s",
                    this.toString(),
                    node.getNodeId()));
        }
        String value = YamlUtils.getValue((ScalarNode)node);
        if (value != null) {
            if (!value.equalsIgnoreCase("true") && !value.equalsIgnoreCase("false")) {
                throw new ConfigTypeErrorException(node, String.format("Expected %s, found %s",
                        this.toString(),
                        value));
            }
        }
    }

    @Override
    public String toString() {
        return "Boolean";
    }
}


text:
package org.osc.core.common.job;

public enum AcknowledgementStatus {

    PENDING_ACKNOWLEDGEMENT("Pending Acknowledgement"), ACKNOWLEDGED("Acknowledged");

    private final String text;

    private AcknowledgementStatus(final String text) {
        this.text = text;
    }

    @Override
    public String toString() {
        return this.text;
    }
}


text:
import Vue from 'vue'
import VueRouter, {RouteConfig} from 'vue-router'
import Dashboard from '../views/Dashboard.vue'
import Format from '../views/Format.vue'
import Clones from '../views/Clones.vue'

Vue.use(VueRouter)

const routes: Array<RouteConfig> = [
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard
  },
  {
    path: '/clones',
    name: 'Clones',
    component: Clones
  },
  {
    path: '/format/:format',
    name: 'Format',
    component: Format
  }
]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router


text:
namespace MassTransit.ActiveMqTransport.Configuration
{
    using System;
    using System.Collections.Generic;

    public class ActiveMqHostConfigurator :
        IActiveMqHostConfigurator
    {
        readonly ConfigurationHostSettings _settings;

        public ActiveMqHostConfigurator(Uri address)
        {
            _settings = new ConfigurationHostSettings(address);

            if (_settings.Port == 61617 || _settings.Host.EndsWith("amazonaws.com", StringComparison.OrdinalIgnoreCase))
                UseSsl();
        }

        public ActiveMqHostSettings Settings => _settings;

        public void Username(string username)
        {
            _settings.Username = username;
        }

        public void Password(string password)
        {
            _settings.Password = password;
        }

        public void UseSsl()
        {
            _settings.UseSsl = true;
            if (_settings.Port == 61616)
                _settings.Port = 61617;
        }

        public void FailoverHosts(string[] hosts)
        {
            _settings.FailoverHosts = hosts;
        }

        public void TransportOptions(IEnumerable<KeyValuePair<string, string>> options)
        {
            foreach (KeyValuePair<string, string> option in options)
                _settings.TransportOptions[option.Key] = option.Value;
        }

        public void EnableOptimizeAcknowledge()
        {
            _settings.TransportOptions["jms.optimizeAcknowledge"] = "true";
        }

        public void SetPrefetchPolicy(int limit)
        {
            _settings.TransportOptions["jms.prefetchPolicy.all"] = limit.ToString();
        }

        public void SetQueuePrefetchPolicy(int limit)
        {
            _settings.TransportOptions["jms.prefetchPolicy.queuePrefetch"] = limit.ToString();
        }
    }
}