text:
import $ from "jquery";

const Tooltip = {

    hide: function (e, tooltipId) {
        if ($(e.target).closest('.div-tooltip').length === 0) {
            $('[data-tooltip]').attr('data-tooltip-toggle', "false");
            $('.div-tooltip').hide();
            $(document).off('click', 'body', Tooltip.hide);
        }
    },

    prepare: function (options) {

        let s;
        if (options && options.selector) {
            s = options.selector;
        } else {
            s = '[data-tooltip]';
        }

        let show = function (e) {
            let element = $(this);
            let text = element.attr('data-tooltip');
            let isHtml = element.attr('data-tooltip-html');
            let isOpen = element.attr('data-tooltip-toggle');
            if (options && options.event === 'click' && isOpen && isOpen === "true") {
                element.attr('data-tooltip-toggle', "false");
                $('.div-tooltip').remove();
                $(document).off('click', 'body', Tooltip.hide);
            } else {
                element.attr('data-tooltip-toggle', "true");
                if (isHtml !== undefined) {
                    if (text && text !== '') {
                        $('.div-tooltip').remove();
                        $(document).off('click', 'body', Tooltip.hide);
                        $('

').append(text).appendTo('body').fadeIn('fast');
                        if (e.type === "click") {
                            setTimeout(function () {
                                $(document).on('click', 'body', Tooltip.hide);
                            }, 100);
                        }
                    }
                } else {
                    if (text && text !== '') {
                        $('.div-tooltip').remove();
                        $(document).off('click', 'body', Tooltip.hide);
                        $('

').text(text).appendTo('body').fadeIn('fast');
                    }
                }
                mousemove(e);
            }
        };
        let remove = function () {
            $('.div-tooltip').remove();
            $(document).off('click', 'body', Tooltip.hide);
        };
        let mousemove = function (e) {
            let y = $(this).attr('data-tooltip-y');
            let top = y ? e.pageY + parseInt(y) : e.pageY - 45;
            let x = $(this).attr('data-tooltip-x');
            let fromTheLeft = $(this).attr('data-tooltip-fromtheright');
            let left = x ? e.pageX + parseInt(x) : e.pageX + 10;
            let width = $(this).attr('data-tooltip-width');
            let css;
            if (width) {
                css = {top: top, left: left, "maxWidth": parseInt(width)};
            } else if (!fromTheLeft ){
                css = {top: top, left: left};
            } else {
                css = {top: top, left: left - ($(".div-tooltip").width())};
            }
            $('.div-tooltip').css(css);
        };
        if (options && options.event === 'click') {
            $(s).off('click', show);
            $(s).on('click', show);
        } else {
            $(s).hover(show, remove).mousemove(mousemove);
        }
    }
};
export default Tooltip;


text:
'''
Created on 21.12.2016

@author: martin
'''
# standard libraries
from datetime import timedelta

# third-party libraries

# own libraries
from financial_life.financing import accounts as a
from financial_life.tax import germany as tax_ger

def controller_tax(s):
    """ This is a controller function that calculates annual tax rates
    's' is the simulation object
    """
    # perform tax calculation always on 15th of February, just to
    # reflect the fact that tax payments for the previous year are
    # never made on the 1st of January, which has an impact on
    # interests as well
    if ((s.current_date.month == 2) and
       (s.current_date.day == 15)):
        # account class for payments
        account = s.accounts[0]

        # filter for all transactions that occured in the previous year
        # and of type 'income'
        income_report = s.report.subset(lambda st: (st.date.year == (s.current_date.year-1)) and
                                                   (st.meta.get('type','') == 'income'))

        # using list comprehensions, we can easily calculate a few sums
        #m_income = sum(income.value)
        m_brutto = sum(payment.meta['tax']['brutto'] for payment in income_report)
        m_paid = sum(payment.meta['tax']['paid'] for payment in income_report)

        # get all accounts which have the field tax.outcome == 'yearly_interests'
        loans = [account for account in s.accounts
                 if account.meta.get('tax', {}).get('outcome','') == 'yearly_interests']
        # get only the reports of last year
        interests_reports = [loan.report.subset(lambda st: st.date.year == (s.current_date.year-1))
                             for loan in loans]
        # sum up all interests from all interests reports
        m_interests = sum(sum(report.interest) for report in interests_reports)

        # as interests for loans are negative, we effectively
        # subtract the payed interests from the brutto we earned in the last year
        m_tax_relevant_money = m_brutto + m_interests
        # now, we apply german tax rules from 2016 to the tax-relevant money
        m_tax, m_tax_percentage = tax_ger.tax_to_pay(2016, m_tax_relevant_money)
        # this is the money we either receive from the state (positive value
        # or we need to pay (negative value)
        m_diff = m_paid - m_tax

        s.add_unique('State', account, m_diff,
                     date = s.current_date + timedelta(days=1),
                     name = 'Tax',
                     fixed = True,
                     meta = {
                             'taxpayment': {
                                            'tax_relevant_money': m_tax_relevant_money,
                                            'tax_to_pay': m_tax,
                                            'tax_percentage': m_tax_percentage,
                                            'paid': m_paid,
                                            'difference': m_diff
                                            }
                             }
                     )

def example_meta_controller(print_it = True):
    """ This example shows, how meta-information for payments and account data could
    be used to calculate annual tax-return """
    account = a.Bank_Account(amount = 1000, interest = 0.001, name = 'Main account', date="01.09.2016")

    # define meta-data for accounts. here: some fields that are relevant for
    # tax calculations
    loan = a.Loan(amount = 100000, interest = 0.01, name = 'House Credit', date="01.09.2016",
                  meta = {'tax': {
                                  'outcome': 'yearly_interests'
                                  }
                          }
                  )

    # add these accounts to the simulation
    simulation = a.Simulation(account, loan, date='01.09.2016')

    # our employee receives monthly 2000 netto, coming from 2500 brutto,
    # 310 are subtracted directly from the loan, which is less than she
    # needs to pay. 190 are paid for insurance
    simulation.add_regular('Income', account, 2000,
                           interval = 'monthly',
                           date_start="01.09.2016",
                           meta={'type': 'income',
                                 'tax': {
                                         'brutto': 2500,
                                         'paid': 310,
                                         'insurance': 190
                                         }
                                }
                           )

    simulation.add_regular(account, loan, lambda: min(1500, -loan.account),
                           interval = 'monthly',
                           date_start="01.09.2016")
    simulation.add_controller(controller_tax)

    # simulate for ten years
    simulation.simulate(delta = timedelta(days=365*10))

    # this function is also part of a unittest. Therefore, we want to be able to
    # control, whether we print some information or not
    if print_it:
        # print reports summarized in years
        print(account.report.with_meta())
        #print(loan.report.with_meta())
    return simulation

if __name__ == '__main__':
    example_meta_controller()

redpajama_set_name: RedPajamaGithub


text:
id: version-4.0.0-monorepo
title: Monorepo
original_id: monorepo
---

### What and Why?

A monorepo is a project structure in which many small interconnected projects are all part of a single repo. The more
common alternative is to have every project be its own repo.

The reason for using a monorepo is so that -- whilst working on two projects together -- you never accidentally push a
commit to one but not the other. It's very easy to break a project for others without a monorepo. With a monorepo, all
changes get committed together.

### Understanding the concepts

<!-- Before reading further it's strongly recommended to read thoroughly the following. -->

While monorepos are mostly a version control concept, there are some changes to configuration required to rock one in
FuseBox. This is largely because **you can not access files above your `homeDir`**.

Fortunately, there is an `entry` property, so you can move your `homeDir` to any parent folder and then work your
`entry` property back down.

---

## Example Project

To see an example monorepo project [click here](https://github.com/fuse-box/fuse-mono).

---

## Monorepo Setup Synopsis

The following are explained in detail further down the page.

1. Set `homeDir` field to the root of your repository, and `entry` field to your main project file.
2. Add/set up `tsconfig.json` with `paths` and `baseUrl` fields. FuseBox pulls these values from `tsconfig.json` as part
   of its own configuration _(even if there is no TypeScript involved)_.

3. Every other package you include from the repo should contain `local:main` field in the `package.json` which should
   point to your source _(instead of `dist`)_.

---

## 1. homeDir and entry

You project `homeDir` must be set to the root of the parent repository. For example, if you had this project folder
structure

```
- monorepo
  - packages
    - foo
    - bar
```

`homeDir` should point to `monorepo` folder

```ts
fusebox({
  target: 'browser',
  output: '../../dist/project',
  homeDir: '../../', // we are going all the way up to "monorepo" folder
  entry: 'packages/foo/index.ts', // entry is relative to "monorepo" folder
});
```

---

## 2. Configuring paths

Simply put, your `tsconfig` must have a `baseUrl` field which points to your local src and a `paths` field which routes
to your packages.

All full page on [how to set paths here can be found here](./paths). _(note: aliasing will not work)_

```json
{
  "compilerOptions": {
    "baseUrl": ".", // should point to your local src
    "paths": {
      "@org/*": ["../../packages/*"]
    }
  }
}
```

---

## 3. local:main

All node packages naturally contains `main` or `module` fields by default in their `package.json`. Unfortunately, **both
of these point to the projects `dist` folder**.

It's likely you'll not be compiling these projects, but instead wanting to simply include the source code.

To achieve that, you should add `local:main` field to your `package,json`.

This field will only be used if the folder isn't located in `node_modules`.

```js
// package.json
{
  // settings omitted...
  "main": "index.js",
  "name": "fuse-box",
  "local:main": "./src/index.ts",
}
```


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import "MOZUURLComponents.h"

@interface MOZUSubscriptionURLComponents : NSObject

//
#pragma mark -
#pragma mark Get Operations
#pragma mark -
//

/**
Resource Url Components for getSubscriptions
@param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a `pageSize `of 25, to get the 51st through the 75th items, use `startIndex=3`.
@param pageSize The number of results to display on each page when creating paged results from a query. The amount is divided and displayed on the `pageCount `amount of pages. The default is 20 and maximum value is 200 per page.
@param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional.
@param filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true"
@param responseFields Use this field to include those fields which are not included by default.
*/
+ (MOZUURLComponents *)URLComponentsForGetSubscriptionsOperationWithStartIndex:(NSNumber *)startIndex pageSize:(NSNumber *)pageSize sortBy:(NSString *)sortBy filter:(NSString *)filter responseFields:(NSString *)responseFields;

//
#pragma mark -
#pragma mark POST Operations
#pragma mark -
//

//
#pragma mark -
#pragma mark PUT Operations
#pragma mark -
//

//
#pragma mark -
#pragma mark Delete Operations
#pragma mark -
//

@end


text:
package com.github.terma.gigaspacewebconsole.core;

import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.io.Writer;
import java.util.List;

public class JsonExecuteResponseStream implements ExecuteResponseStream {

    private final JsonWriter jsonWriter;

    public JsonExecuteResponseStream(final Writer writer) {
        jsonWriter = new JsonWriter(writer);
    }

    @Override
    public void writeHeader(final List<String> columns) throws IOException {
        jsonWriter.beginObject();

        jsonWriter.name("columns");
        writeArray(columns);

        jsonWriter.name("data");
        jsonWriter.beginArray();
    }

    @Override
    public void writeRow(final List<String> values, final List<String> types) throws IOException {
        jsonWriter.beginArray();
        writeArrayItems(values);
        writeArray(types);
        jsonWriter.endArray();
    }

    @Override
    public void close() throws IOException {
        jsonWriter.endArray();
        jsonWriter.endObject();
    }

    private void writeArray(final List<String> values) throws IOException {
        jsonWriter.beginArray();
        writeArrayItems(values);
        jsonWriter.endArray();
    }

    private void writeArrayItems(final List<String> values) throws IOException {
        for (final String value : values) jsonWriter.value(value);
    }

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SI.cs" company="QuantityTypes">
//   Copyright (c) 2014 QuantityTypes contributors
// </copyright>
// <summary>
//   Defines SI units.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace QuantityTypes.Dynamic
{
    using QuantityTypes;

    /// <summary>
    /// Defines SI units.
    /// </summary>
    public static class SI
    {
        /// <summary>
        /// Gets the kilogram.
        /// </summary>
        /// <value>The kilogram.</value>
        [Unit("kg")]
        public static DynamicQuantity Kilogram
        {
            get
            {
                return kilogram;
            }
        }

        /// <summary>
        /// Gets the meter unit.
        /// </summary>
        /// <value>The meter unit.</value>
        [Unit("m", true)]
        public static DynamicQuantity Metre
        {
            get
            {
                return metre;
            }
        }

        /// <summary>
        /// Gets the meter per second.
        /// </summary>
        /// <value>The meter per second.</value>
        [Unit("m/s", true)]
        public static DynamicQuantity MetrePerSecond
        {
            get
            {
                return metrePerSecond;
            }
        }

        /// <summary>
        /// Gets the kilometer per hour.
        /// </summary>
        /// <value>The kilometer per hour.</value>
        [Unit("km/h")]
        public static DynamicQuantity KilometrePerHour
        {
            get
            {
                return kilometrePerHour;
            }
        }

        /// <summary>
        /// The kilogram unit
        /// </summary>
        public static readonly DynamicQuantity kilogram = new DynamicQuantity(1, new Dimensions(1, 0, 0));

        /// <summary>
        /// The meter unit
        /// </summary>
        public static readonly DynamicQuantity metre = new DynamicQuantity(1, new Dimensions(0, 1, 0));

        /// <summary>
        /// The kilometer unit
        /// </summary>
        public static readonly DynamicQuantity Kilometre = 1000 * Metre;

        /// <summary>
        /// The centimeter unit
        /// </summary>
        public static readonly DynamicQuantity Centimetre = 0.01 * Metre;

        /// <summary>
        /// The millimeter unit
        /// </summary>
        public static readonly DynamicQuantity Millimetre = 0.001 * Metre;

        /// <summary>
        /// The second unit
        /// </summary>
        public static readonly DynamicQuantity Second = new DynamicQuantity(1, new Dimensions(0, 0, 1));

        /// <summary>
        /// The minute unit
        /// </summary>
        public static readonly DynamicQuantity Minute = 60 * Second;

        /// <summary>
        /// The hour unit
        /// </summary>
        public static readonly DynamicQuantity Hour = 60 * Minute;

        /// <summary>
        /// The m/s unit
        /// </summary>
        public static readonly DynamicQuantity metrePerSecond = Metre / Second;

        /// <summary>
        /// The km/h unit
        /// </summary>
        public static readonly DynamicQuantity kilometrePerHour = Kilometre / Hour;

        /// <summary>
        /// The m/s^2 unit
        /// </summary>
        public static readonly DynamicQuantity MetrePerSecondSquared = Metre / (Second * Second);

        /// <summary>
        /// The m^2 unit
        /// </summary>
        public static readonly DynamicQuantity SquareMetre = new DynamicQuantity(1, new Dimensions(0, 2, 0));

        /// <summary>
        /// The m^3 unit
        /// </summary>
        public static readonly DynamicQuantity CubicMetre = new DynamicQuantity(1, new Dimensions(0, 3, 0));

        /// <summary>
        /// The dm^3 unit
        /// </summary>
        public static readonly DynamicQuantity CubicDecimetre = new DynamicQuantity(0.001, new Dimensions(0, 3, 0));

        /// <summary>
        /// The liter unit
        /// </summary>
        public static readonly DynamicQuantity Litre = CubicDecimetre;
    }
}


text:
@implementation BYTheme

+(BYTheme *)fromDictionary:(NSDictionary *)dict {
    BYTheme* theme = [self validateAndReturnThemeFromDictionary:dict];
    return theme;
}

+(BYTheme*)fromFile:(NSString *)file {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:file ofType:@"json"];
    NSData *json = [NSData dataWithContentsOfFile:filePath];

    BYTheme *theme;
    if (json) {
        NSError *jsonError;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:json options:NSJSONReadingAllowFragments
                                                               error:&jsonError];
        if (jsonError) {
            NSLog(@"Error: Could not parse JSON! %@", jsonError.debugDescription);
        }
        else {
            theme = [self validateAndReturnThemeFromDictionary:dict];
        }
    }
    else {
        NSLog(@"[BYTheme fromFile] failed - Unable to load file");
    }
    return theme;
}

-(BOOL)__isJSONModelSubClass:(Class)class {
    if([NSStringFromClass(class) isEqualToString:NSStringFromClass([BYSwitchStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYButtonStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYSliderStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYLabelStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYViewControllerStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYTextFieldStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYNavigationBarStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYTableViewCellStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYImageViewStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYBarButtonStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYTabBarStyle class])] ||
       [NSStringFromClass(class) isEqualToString:NSStringFromClass([BYSearchBarStyle class])]) {
        return YES;
    }
    return NO;
}

+(BYTheme*)validateAndReturnThemeFromDictionary:(NSDictionary*)dict {
    // Find the version of the JSON file being passed in.
    BYTheme *theme;
    NSString *fileVersion = dict[SCHEMA_VERSION_KEY];

    // Compare it to the current version. If they aren't equal, we can't continue and should log an error.
    if(![fileVersion isEqualToString:JSON_SCHEMA_VERSION]) {
        NSLog(@"[BYTheme fromFile] failed - The version of the file (%@) was invalid. Expecting %@", fileVersion, JSON_SCHEMA_VERSION);
        return nil;
    }

    NSError *parseError;
    theme = [[BYTheme alloc] initWithDictionary:dict[THEME_KEY] error:&parseError];
    if(parseError) {
        NSLog(@"Parse error when reading the JSON - %@", parseError.debugDescription);
        return nil;
    }
    else {
        return theme;
    }
    return theme;
}

-(instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError *__autoreleasing *)err {
    if(!dict) {
        return nil;
    }

    if(dict.allKeys.count == 0) {
        return [BYTheme new];
    }

    BYTheme *theme = [super initWithDictionary:dict error:err];
    if(theme == nil) {
        theme = [BYTheme new];
    }
    return theme;
}

-(instancetype)init {
    if (self = [super init]) {
        self.buttonStyle = [BYButtonStyle defaultSystemStyle];
        self.switchStyle = [BYSwitchStyle defaultStyle];
        self.labelStyle = [BYLabelStyle defaultStyle];
        self.viewControllerStyle = [BYViewControllerStyle defaultStyle];
        self.textFieldStyle = [BYTextFieldStyle defaultStyle];
        self.navigationBarStyle = [BYNavigationBarStyle defaultStyle];
        self.tableViewCellStyle = [BYTableViewCellStyle defaultStyle];
        self.imageViewStyle = [BYImageViewStyle defaultStyle];
        self.barButtonItemStyle = [BYBarButtonStyle defaultStyle];
        self.backButtonItemStyle = [BYBarButtonStyle defaultBackButtonStyle];
        self.sliderStyle = [BYSliderStyle defaultStyle];
        self.tabBarStyle = [BYTabBarStyle defaultStyle];
        self.searchBarStyle = [BYSearchBarStyle defaultStyle];
    }
    return self;
}

-(id)copyWithZone:(NSZone *)zone {
    BYTheme *theme = [[[self class] allocWithZone:zone] init];
    theme.buttonStyle = self.buttonStyle.copy;
    theme.switchStyle = self.switchStyle.copy;
    theme.labelStyle = self.labelStyle.copy;
    theme.viewControllerStyle = self.viewControllerStyle.copy;
    theme.textFieldStyle = self.textFieldStyle.copy;
    theme.navigationBarStyle = self.navigationBarStyle.copy;
    theme.tableViewCellStyle = self.tableViewCellStyle.copy;
    theme.imageViewStyle = self.imageViewStyle.copy;
    theme.barButtonItemStyle = self.barButtonItemStyle.copy;
    theme.backButtonItemStyle = self.backButtonItemStyle.copy;
    theme.sliderStyle = self.sliderStyle.copy;
    theme.tabBarStyle = self.tabBarStyle.copy;
    return theme;
}

-(NSDictionary*)toDictionary {
    // Get the dictionary that we need to wrap in the version number.
    NSDictionary *dict = [super toDictionary];

    // Wrap the dictionary in "theme" property as well as adding the current schema version.
    NSMutableDictionary *wrapperDict = [NSMutableDictionary new];
    wrapperDict[SCHEMA_VERSION_KEY] = JSON_SCHEMA_VERSION;
    wrapperDict[THEME_KEY] = dict;
    return wrapperDict;
}

@end


text:
package br.ufsc.bridge.res.service.repository.parser;

import java.util.Date;
import java.util.List;

import javax.xml.bind.JAXBElement;

import br.ufsc.bridge.res.service.builder.IdentifiableTypeBuilder;
import br.ufsc.bridge.res.service.dto.repository.RepositorySaveDTO;
import br.ufsc.bridge.res.util.RDateUtil;
import br.ufsc.bridge.res.util.XDSbUtil;

import ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType;

public class SubmissionSetParser {

	public static String SUBMISSIONSET_ID = "ss1";

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void parser(RepositorySaveDTO dto, ProvideAndRegisterDocumentSetRequestType provideRegister) {
		List<JAXBElement<?>> identifiables = (List) provideRegister.getSubmitObjectsRequest().getRegistryObjectList().getIdentifiable();

		String creationTime = RDateUtil.dateToISOXDSb(new Date());
		String[] nomeProf = XDSbUtil.nameToXDSbName(dto.getNomeProfissional());
		//@formatter:off
		new IdentifiableTypeBuilder(identifiables)
		.buildClassification()
			.id("sscl1")
			.classificationNode("urn:uuid:a54d6aa5-d40d-43f9-88c5-b4633d873bdd")
			.classifiedObject(SUBMISSIONSET_ID)
		.addClassificationEnd()
		.buildRegistryPackage()
			.id(SUBMISSIONSET_ID)
			//submissionTime
			.buildSlot()
				.name("submissionTime").value(creationTime)
			.addSlotEnd()
			//author
			.buildClassification()
				.classificationScheme("urn:uuid:a7058bb9-b4e4-4307-ba5b-e3f0ab85e12d")
				.id("sscl2")
				.nodeRepresentation("")
				.buildSlot()
					.name("authorPerson").value(dto.getCnsProfissional() + "^" + nomeProf[2] + "^" + nomeProf[0] + "^" + nomeProf[1] + "^^^^^&1.2.840.113619.6.197&ISO")
				.addSlot()
				    .name("authorInstitution").value(dto.getNomeUnidadeSaude() + "^^^^^&1.2.3.4.5.678&ISO^^^^" + dto.getCnesUnidadeSaude())
			    .addSlot()
				    .name("authorRole").value("")
				.addSlot()
				    .name("authorSpecialty").value(dto.getCboProfissional() + "^^^&1.2.840..113619.6.197&ISO")
				.addSlotEnd()
			.addClassificationEnd()
			//contentTypeCode
			.buildClassification()
				.classificationScheme("urn:uuid:aa543740-bdda-424e-8c96-df4873be8500")
				.id("sscl3")
				.nodeRepresentation(dto.getContentTypeCode().getCode())
				.buildSlot()
					.name("codingScheme").value(dto.getContentTypeCode().getCodingScheme())
				.addSlotEnd()
				.buildInternationalString()
					.value("Summarization of Episode Note")
				.addInternationalStringEnd()
			.addClassificationEnd()
			//patientId
			.buildExternalIdentifier()
				.identificationScheme("urn:uuid:6b5aea1a-874d-4603-a4bc-96a0a7b38446")
				.value(dto.getPatientId())
				.id("ssei1")
				.buildInternationalString()
					.value("XDSSubmissionSet.patientId")
				.addInternationalStringEnd()
			.addExternalIdentifierEnd()
			//sourceId
			.buildExternalIdentifier()
				.identificationScheme("urn:uuid:554ac39e-e3fe-47fe-b233-965d2a147832")
				.value(dto.getIdInstalacao())
				.id("ssei2")
				.buildInternationalString()
					.value("XDSSubmissionSet.sourceId")
				.addInternationalStringEnd()
			.addExternalIdentifierEnd()
			//uniqueId
			.buildExternalIdentifier()
				.identificationScheme("urn:uuid:96fdda7c-d067-4183-912e-bf5ee74998a8")
				.value(dto.getSubmissionSetId())
				.id("ssei3")
				.buildInternationalString()
					.value("XDSSubmissionSet.uniqueId")
				.addInternationalStringEnd()
			.addExternalIdentifierEnd()
		.addRegistryPackageEnd();
		//intendedRecipient
		//@formatter:on
	}
}


text:
"""
Tests the Jabsorb conversion module

:author: Thomas Calmant
"""

# Pelix
import pelix.misc.jabsorb as jabsorb

# Standard library
import uuid
try:
    import unittest2 as unittest
except ImportError:
    import unittest

# ------------------------------------------------------------------------------

__version__ = "1.0.0"

# ------------------------------------------------------------------------------

class JabsorbConverterTest(unittest.TestCase):
    """
    Tests the Jabsorb conversion module
    """
    def testIsBuiltin(self):
        """
        Tests the _is_builtin() method
        """
        for item in (int, 42, str, "toto", bool, True, float, 3.14,
                     dict, {"a": "b"}, set, set([12]), tuple, (1, 2, 3),
                     list, [4, 5, 6]):
            self.assertTrue(jabsorb._is_builtin(item),
                            "Item {0} should be built-in".format(item))

        for item in (unittest.TestCase, jabsorb, jabsorb.to_jabsorb):
            self.assertFalse(jabsorb._is_builtin(item),
                             "Item {0} should not be built-in".format(item))

    def testMirror(self):
        """
        Tests the result of to_jabsorb + from_jabsorb
        """
        value = {"list": [1, 2, 3],
                 "tuple": (1, 2, 3),
                 "set": set((1, 2, 3)),
                 "dict": {"a": "b", "c": "d"},
                 "int": 42,
                 "float": 3.14,
                 None: None,
                 3.10: 51}

        # Convert to Jabsorb
        jabsorb_value = jabsorb.to_jabsorb(value)

        # ... back to "normal" Python
        revert_value = jabsorb.from_jabsorb(jabsorb_value)

        # Check content
        self.assertDictEqual(revert_value, value)

    def testCustomClass(self):
        """
        Tests the conversion of a custom class
        """
        # Basic class
        class Custom(object):
            javaClass = "test.Custom"

            def __init__(self):
                self.value = str(uuid.uuid4())
                self._value = str(uuid.uuid4())
                self.__value = str(uuid.uuid4())

        # Convert it
        value = Custom()
        jabsorb_value = jabsorb.to_jabsorb(value)
        revert = jabsorb.from_jabsorb(jabsorb_value)

        # Check Jabsorb public value
        self.assertEqual(jabsorb_value[jabsorb.JAVA_CLASS], Custom.javaClass)
        self.assertEqual(jabsorb_value['value'], value.value)

        # Check absence of private value
        self.assertNotIn('_value', jabsorb_value)
        self.assertNotIn('__value', jabsorb_value)
        self.assertNotIn('_Custom__value', jabsorb_value)

        # Check revert value
        self.assertEqual(revert[jabsorb.JAVA_CLASS], Custom.javaClass)
        self.assertEqual(revert['value'], value.value)
        self.assertEqual(revert.javaClass, Custom.javaClass)
        self.assertEqual(revert.value, value.value)

    def testBeanInTheMiddle(self):
        """
        Tests the conversion of the content of a bean (half parsed stream)
        """
        class Bean(object):

            def __init__(self):
                self.list = jabsorb.to_jabsorb([1, 2, 3])
                self.tuple = jabsorb.to_jabsorb((1, 2, 3))
                self.set = jabsorb.to_jabsorb(set((1, 2, 3)))

            def __eq__(self, other):
                return self.list == other.list \
                    and self.tuple == other.tuple \
                    and self.set == other.set

        # Prepare the bean
        bean = Bean()

        # Parse its content
        revert = jabsorb.from_jabsorb(bean)
        self.assertIs(revert, bean)
        self.assertEqual(revert.list, [1, 2, 3])
        self.assertEqual(revert.tuple, (1, 2, 3))
        self.assertEqual(revert.set, set((1, 2, 3)))

    def testHashableType(self):
        """
        Tests the behavior of hashable types
        """
        # Prepare items
        hash_dict = jabsorb.HashableDict(((1, 2), (3, 4)))
        hash_attrmap = jabsorb.AttributeMap(hash_dict.items())
        hash_set = jabsorb.HashableSet((1, 2, 3))
        hash_list = jabsorb.HashableList((1, 2, 3))

        # Group'em
        hash_values = [hash_dict, hash_attrmap, hash_set, hash_list]

        # Try to put them in a set
        in_set = set(hash_values)
        self.assertEqual(len(in_set), len(hash_values))

        # Try to put them in a dictionary
        dico = {}
        for value in in_set:
            dico[value] = 42
        self.assertEqual(len(dico), len(hash_values))

    def testDoubleConvert(self):
        """
        Checks the beheavior after a second call to to_jabsorb
        """
        value = {"list": [1, 2, 3],
                 "tuple": (1, 2, 3),
                 "set": set((1, 2, 3)),
                 "dict": {"a": "b", "c": "d"},
                 "int": 42,
                 "float": 3.14,
                 None: None,
                 3.10: 51}

        # Double conversion: no modification on second pass
        first = jabsorb.to_jabsorb(value)
        second = jabsorb.to_jabsorb(first)
        self.assertDictEqual(second, first)

        # Double revert
        revert_second = jabsorb.from_jabsorb(second)
        revert_first = jabsorb.from_jabsorb(revert_second)

        # Check results
        self.assertDictEqual(revert_second, value)
        self.assertDictEqual(revert_first, value)

    def testJsonAndJavaClass(self):
        """
        Tests the conservation of the __jsonclass__ attribute
        """
        for has_json in (True, False):
            for has_java in (True, False):
                if not any((has_json, has_java)):
                    # Out of the scope of this test
                    continue

                # Prepare a fake bean
                value = {"list": [1, 2, 3],
                         "tuple": (1, 2, 3),
                         "set": set((1, 2, 3)),
                         "dict": {"a": "b", "c": "d"},
                         "int": 42,
                         "float": 3.14,
                         None: None,
                         3.10: 51}

                if has_json:
                    value[jabsorb.JSON_CLASS] = [1, 2, 3, [4, 5]]

                if has_java:
                    value[jabsorb.JAVA_CLASS] = 'test.Bean'

                # Convert it
                jabsorb_value = jabsorb.to_jabsorb(value)

                # Check the value of the JSON class
                if has_json:
                    self.assertEqual(jabsorb_value[jabsorb.JSON_CLASS],
                                     value[jabsorb.JSON_CLASS])

                if has_java:
                    self.assertEqual(jabsorb_value[jabsorb.JAVA_CLASS],
                                     value[jabsorb.JAVA_CLASS])

                # Revert
                revert = jabsorb.from_jabsorb(jabsorb_value)
                self.assertDictEqual(revert, value)


text:
VACUUM;

--
-- sanity check, if we don't have indices the test will take years to
-- complete.  But skip TOAST relations (since they will have varying
-- names depending on the current OID counter) as well as temp tables
-- of other backends (to avoid timing-dependent behavior).
--

-- temporarily disable fancy output, so catalog changes create less diff noise
\a\t

SELECT relname, relhasindex
   FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = relnamespace
   WHERE relkind IN ('r', 'p') AND (nspname ~ '^pg_temp_') IS NOT TRUE
   ORDER BY relname;

-- restore normal output mode
\a\t

--
-- another sanity check: every system catalog that has OIDs should have
-- a unique index on OID.  This ensures that the OIDs will be unique,
-- even after the OID counter wraps around.
-- We exclude non-system tables from the check by looking at nspname.
--
SELECT relname, nspname
 FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = relnamespace JOIN pg_attribute a ON (attrelid = c.oid AND attname = 'oid')
 WHERE relkind = 'r' and c.oid < 16384
     AND ((nspname ~ '^pg_') IS NOT FALSE)
     AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE indrelid = c.oid
                     AND indkey[0] = a.attnum AND indnatts = 1
                     AND indisunique AND indimmediate);

-- check that relations without storage don't have relfilenode
SELECT relname, relkind
  FROM pg_class
 WHERE relkind IN ('v', 'c', 'f', 'p', 'I')
       AND relfilenode <> 0;


text:
package puzzle.domain;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import com.google.common.base.Stopwatch;

/**
 * Manage words cache. This class has a dictionary HashMap for searching and a file which
 * stores all words. When sorting the words list, this class puts all keys into an arrayList
 * and sort them.
 * @author CDT
 *
 */
public class Dictionary {
	private HashMap<String,String> dictionary;//All uppercase
	private File file;//stores words
	private int count;//the total amount of words
	public static final String FILE_NAME="dict/dictCache.txt";

	/**
	 * Initiate a cache object. Check whether dictionary cache exists and is updated.
	 * If cache exists and is updated, read the cache file.
	 * Otherwise, create a new cache file.
	 */
	public Dictionary(){
		//Initiate the dictionary
		dictionary=new HashMap<String,String>(1000000);
		//Initiate the file
		file=new File(FILE_NAME);

		//Fill out the dictionary map
		if(file.exists()&&checkUpdate()){
			System.out.println("No Update");
			readCache();
		}else{
			createDictCache();
		}
		count=dictionary.size();
	}

	/**
	 * Check whether a specific word exists in the dictionary cache
	 * @param word
	 * @return
	 */
	public boolean wordExists(String word){
		word=word.toUpperCase();
		return dictionary.get(word)!=null;
	}

	/**
	 * Check whether the cache file is updated.
	 * @return
	 */
	public boolean checkUpdate(){
		if(file.exists()){
			long date=file.lastModified();
			File[] dictList=new File("dict").listFiles();
			for(File f:dictList){
				if(f.lastModified()>date){
					System.out.println("Update");
					return false;
				}
			}
			return true;
		}
		System.out.println("Need to create the file");
		return false;
	}

	/**
	 * Read the cache file and generate the dictionary map
	 */
	public void readCache(){
		dictionary.clear();

		try (FileReader fr = new FileReader(file);
				BufferedReader br = new BufferedReader(fr);){

			String str = br.readLine(); //the first line is a number
			str = br.readLine();
			while (str!= null) {
				str=str.toUpperCase();
				dictionary.put(str, str);
				str = br.readLine();
			}
		}  catch (IOException ex) {
			System.err.println("WordList init error");

		}

	}

	/**
	 * Create a new dictionary cache file, write cache to the file, and generate
	 * dictionary hashmaps
	 */
	public void createDictCache(){
		Stopwatch timer = Stopwatch.createStarted();
		//Read all dictionary files
		readAllDictFiles();//ReadAllDictFiles put all words in the dictionary map without repetition
		//sort all words
		ArrayList<String> allwords=sortWords();
		//put words into a new cache file
		writeFile(allwords);
		//display elapsed time for complete process
		System.out.println("Cached the dictionary in " +timer.stop()+ ".");
	}

	/**
	 * Read all words form all dictionary files into the dictionary map
	 * @return
	 */
	public void readAllDictFiles(){
		dictionary.clear();
		File[] dictList=new File("dict").listFiles();
		for(File f:dictList){
			if(f.isFile() && f.getName().endsWith(".txt"))
			readSpecialFile(f);
		}
	}

	/**
	 * Read a dictionary in which each line could contain multiple words
	 */
	public void readSpecialFile(File f){
		ArrayList<String> allwords=new ArrayList<String>();

		//Get all words into an arrayList of String
		try(FileReader fr1=new FileReader(f);
				BufferedReader br1=new BufferedReader(fr1);){

			String str=br1.readLine();
			while(str!=null){
				allwords.add(str);
				str=br1.readLine();
			}

		}catch(IOException e){
			System.err.println("Special Dictionary Reading Error");
		}

		//Split each String in the arrayList and put new words in the dictionary map
		for(String wordString:allwords){
			String[] wordArray=wordString.split(" ");
			for(String str:wordArray){
				str=str.toUpperCase();//All words in the dictionary map are uppercase
				if(isWordValid(str)&&dictionary.get(str)==null){
					dictionary.put(str,str);
				}
			}
		}

	}

	/**
	 * Check whether the current word is a valid word
	 */
	public boolean isWordValid(String word){
		if(word.length()<2){
			return false;
		}
		char[] wordChar=word.toCharArray();
		for(char c:wordChar){
			if(!Character.isLetter(c)){
				return false;
			}
		}
		return true;
	}

	/**
	 * Sort keys of a hashmap<String,String>
	 * @return
	 */
	public ArrayList<String> sortWords(){
		/*
		 * Transform keys of a hashmap into an arraylist
		 * The following line is retrieved from http://www.java2s.com/Code/Java/Collections-Data-Structure/SortkeysinanHashtable.htm
		 */

		ArrayList<String> wordsList=new ArrayList<String>(dictionary.keySet());

		/*
		 * Sort a list alphabetically
		 * retrieved from http://stackoverflow.com/questions/11176227/simple-way-to-sort-strings-in-the-case-sensitive-alphabetical-order
		 */

		Collections.sort(wordsList,String.CASE_INSENSITIVE_ORDER);
		return wordsList;
	}

	/**
	 * Write contents to the cache file
	 */
	public void writeFile(ArrayList<String> allwords){
		//check whether the file exists.
		try {
			file.createNewFile();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//write the arrayList into the file
		try (
				FileWriter fw = new FileWriter(file);
				BufferedWriter bw = new BufferedWriter(fw);
				PrintWriter pw = new PrintWriter(bw);){
			pw.println(allwords.size());//print the total amount of words

			for(String str:allwords){
				pw.println(str);
			}

		}
		catch (IOException ex) {
			System.err.println("trouble with file :"+ex.getMessage());
		}
	}

	/**
	 * Getters and Setters
	 */

	public HashMap<String,String> getDictionary() {
		return dictionary;
	}
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public int getCount() {
		return count;
	}

}


text:
package org.jboss.resteasy.plugins.providers.atom;

import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
import org.jboss.resteasy.plugins.providers.jaxb.JAXBContextFinder;
import org.jboss.resteasy.plugins.providers.jaxb.JAXBMarshalException;
import org.jboss.resteasy.plugins.providers.jaxb.JAXBUnmarshalException;

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.Providers;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashSet;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
@Provider
@Produces("application/atom+*")
@Consumes("application/atom+*")
public class AtomFeedProvider implements MessageBodyReader<Feed>, MessageBodyWriter<Feed>
{
   @Context
   protected Providers providers;

   protected JAXBContextFinder getFinder(MediaType type)
   {
      ContextResolver<JAXBContextFinder> resolver = providers.getContextResolver(JAXBContextFinder.class, type);
      if (resolver == null) return null;
      return resolver.getContext(null);
   }

   public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
   {
      return Feed.class.isAssignableFrom(type);
   }

   public Feed readFrom(Class<Feed> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
   {
      JAXBContextFinder finder = getFinder(mediaType);
      if (finder == null)
      {
         throw new JAXBUnmarshalException("Unable to find JAXBContext for media type: " + mediaType);
      }

      try
      {
         JAXBContext ctx = finder.findCachedContext(Feed.class, mediaType, annotations);
         Feed feed = (Feed) ctx.createUnmarshaller().unmarshal(entityStream);
         for (Entry entry : feed.getEntries())
         {
            if (entry.getContent() != null) entry.getContent().setFinder(finder);
         }
         return feed;
      }
      catch (JAXBException e)
      {
         throw new JAXBUnmarshalException("Unable to unmarshal: " + mediaType, e);
      }
   }

   public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
   {
      return Feed.class.isAssignableFrom(type);
   }

   public long getSize(Feed feed, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType)
   {
      return -1;
   }

   public void writeTo(Feed feed, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException
   {
      JAXBContextFinder finder = getFinder(mediaType);
      if (finder == null)
      {
         throw new JAXBMarshalException("Unable to find JAXBContext for media type: " + mediaType);
      }
      HashSet<Class> set = new HashSet<Class>();
      set.add(Feed.class);
      for (Entry entry : feed.getEntries())
      {
         if (entry.getAnyOtherJAXBObject() != null)
         {
            set.add(entry.getAnyOtherJAXBObject().getClass());
         }
         if (entry.getContent() != null && entry.getContent().getJAXBObject() != null)
         {
            set.add(entry.getContent().getJAXBObject().getClass());
         }
      }
      try
      {
         JAXBContext ctx = finder.findCacheContext(mediaType, annotations, set.toArray(new Class[set.size()]));
         Marshaller marshaller = ctx.createMarshaller();
         NamespacePrefixMapper mapper = new NamespacePrefixMapper()
         {
            public String getPreferredPrefix(String namespace, String s1, boolean b)
            {
               if (namespace.equals("http://www.w3.org/2005/Atom")) return "atom";
               else return s1;
            }
         };

         marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);

         marshaller.marshal(feed, entityStream);
      }
      catch (JAXBException e)
      {
         throw new JAXBMarshalException("Unable to marshal: " + mediaType, e);
      }
   }
}


text:
package com.fernandocejas.android10.sample.presentation.internal.di.components;

import com.fernandocejas.android10.sample.presentation.internal.di.PerFragment;
import com.fernandocejas.android10.sample.presentation.view.ShopActivityView;
import com.fernandocejas.android10.sample.presentation.view.activity.ShopActivity;

import javax.inject.Named;

import dagger.BindsInstance;
import dagger.Component;

@Component(dependencies = ApplicationComponent.class)
@PerFragment
public interface ShopActivityComponent {
    void inject(ShopActivity in);

    @Component.Builder
    interface Builder {
        Builder appComponent(ApplicationComponent appComponent);

        @BindsInstance
        Builder view(ShopActivityView view);

        @BindsInstance
        Builder backgroundColor(@Named("backgroundColor") int backgroundColor);
        @BindsInstance
        Builder textColor(@Named("textColor") int textColor);

        @BindsInstance
        Builder accentColor(@Named("accentColor") int accentColor);

        ShopActivityComponent build();
    }
}


text:
contract('SydEth', function(accounts) {
	it("should add different certificates", function(done) {
		let meta = SydEth.deployed();

		let certificateArray = [{
			issuerName: 'issuer1',
			courseName: 'course1',
			beneficiaryName: 'name1',
			beneficiaryAddress: accounts[1]
		}, {
			issuerName: 'issuer2',
			courseName: 'course with space',
			beneficiaryName: 'name2',
			beneficiaryAddress: accounts[2]
		}, {
			issuerName: 'issuer3',
			courseName: 'course with special .,!@#$%',
			beneficiaryName: 'name3',
			beneficiaryAddress: accounts[3]
		}, {
			issuerName: 'issuer4',
			courseName: 'course4',
			beneficiaryName: 'Name with ümlaut',
			beneficiaryAddress: accounts[4]
		}, {
			issuerName: 'issuer5',
			courseName: 'course5',
			beneficiaryName: 'name5',
			beneficiaryAddress: accounts[5]
		}, ];

		for (let certificate of certificateArray)
			meta.addCertificate(certificate.issuerName, certificate.courseName, certificate.beneficiaryName, certificate.beneficiaryAddress, {
				from: accounts[1]
			});

		meta.getLength().then(function(length) {
			assert.equal(length.c[0], certificateArray.length, 'Assert fail: not all certificates added');
		}).then(done).catch(done);
	});

	it("should find certificates", function(done) {
		let meta = SydEth.deployed();
		let findName = 'Name with ümlaut';

		meta.findCertificate(findName).then(function(index) {
			assert.equal(index.c[0], 4, 'Assert fail: certificate not found');
		}).then(done).catch(done);
	});

	it("should not find non-existing certificates", function(done) {
		let meta = SydEth.deployed();
		let findName = 'Name with umlaut';

		meta.findCertificate(findName).then(function(index) {
			assert.equal(index.c[0], 0, 'Assert fail: certificate found');
		}).then(done).catch(done);
	});

	it("should allow name change", function(done) {
		let meta = SydEth.deployed();
		let oldName = 'name5';
		let newName = 'New name';

		meta.changeName(oldName, newName, {
			from: accounts[5]
		}).then(function() {
			meta.findCertificate(newName).then(function(index) {
				assert.equal(index.c[0], 5, 'Assert fail: certificate name not changed');
			}).then(done).catch(done);
		});
	});
	it("should not allow name change", function(done) {
		let meta = SydEth.deployed();
		let oldName = 'name1';
		let newName = 'New name';

		meta.changeName(oldName, newName, {
			from: accounts[5]
		}).then(function() {
			meta.findCertificate(oldName).then(function(index) {
				assert.equal(index.c[0], 1, 'Assert fail: certificate name changed');
			}).then(done).catch(done);
		});
	});
});


text:
<?php

Yii::import('malmo.vendors.mobile-detect.Mobile_Detect', true);

class CustomMMultiSiteMobileRule extends MMultiSiteMobileRule
{
    protected function getMobileDetect()
    {
        return new Mobile_Detect();
    }
}

/**
 * Simple test case for nultisite mobile rule
 * More test available in included library Mobile Detect
 */
class MobileRuleTest extends CTestCase
{
    public function testMobile()
    {
        $_SERVER['HTTP_USER_AGENT'] = 'BlackBerry7100i/4.1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 VendorID/103';
        $rule = new MMultiSiteMobileRule;
        $this->assertTrue($rule->getIsMath());
    }

    public function testNoMobile()
    {
        $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17';
        $rule = new CustomMMultiSiteMobileRule;
        $this->assertFalse($rule->getIsMath());
    }
}


text:
#include "mbed_assert.h"
#include "pinmap.h"
#include "PortNames.h"
#include "PeripheralNames.h"
#include "mbed_error.h"

/**
 * Configure pin multi-function
 */
void pin_function(PinName pin, int data)
{
    MBED_ASSERT(pin != (PinName)NC);
    uint32_t pin_index = NU_PINNAME_TO_PIN(pin);
    uint32_t port_index = NU_PINNAME_TO_PORT(pin);
    __IO uint32_t *Px_x_MFP = ((__IO uint32_t *) &SYS->PA_L_MFP) + port_index * 2 + (pin_index / 8);
    uint32_t MFP_Msk = NU_MFP_MSK(pin_index);

    // E.g.: SYS->PA_L_MFP  = (SYS->PA_L_MFP & (~SYS_PA_L_MFP_PA0_MFP_Msk) ) | SYS_PA_L_MFP_PA0_MFP_SC0_CD  ;
    *Px_x_MFP  = (*Px_x_MFP & (~MFP_Msk)) | data;
}

/**
 * Configure pin pull-up/pull-down
 */
void pin_mode(PinName pin, PinMode mode)
{
    MBED_ASSERT(pin != (PinName)NC);
    uint32_t pin_index = NU_PINNAME_TO_PIN(pin);
    uint32_t port_index = NU_PINNAME_TO_PORT(pin);
    GPIO_T *gpio_base = NU_PORT_BASE(port_index);

    uint32_t mode_intern;

    switch (mode) {
        case InputOnly:
            mode_intern = GPIO_PMD_INPUT;
            break;

        case PushPullOutput:
            mode_intern = GPIO_PMD_OUTPUT;
            break;

        case OpenDrain:
            mode_intern = GPIO_PMD_OPEN_DRAIN;
            break;

        default:
            /* H/W doesn't support separate configuration for input pull mode/direction.
             * We expect upper layer would have translated input pull mode/direction
             * to I/O mode */
            return;
    }

    GPIO_SetMode(gpio_base, 1 << pin_index, mode_intern);

    /* Invalid combinations of PinMode/PinDirection
     *
     * We assume developer would avoid the following combinations of PinMode/PinDirection
     * which are invalid:
     * 1. InputOnly/PIN_OUTPUT
     * 2. PushPullOutput/PIN_INPUT
     */
}

/* List of peripherals excluded from testing */
const PeripheralList *pinmap_restricted_peripherals()
{
    static const int perifs[] = {
        STDIO_UART          // Dedicated to USB VCOM
    };

    static const PeripheralList peripheral_list = {
        sizeof(perifs) / sizeof(perifs[0]),
        perifs
    };

    return &peripheral_list;
}


text:
<!DOCTYPE html>
<html>
    <head>
        <!--Import Google Icon Font-->
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <!--Import materialize.css-->
        <link type="text/css" rel="stylesheet" href="static/css/home.css">
        <link rel="icon" href="favicon.ico">

        <!--Let browser know website is optimized for mobile-->
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <title>Home | Olahfisik</title>
    </head>

    <body>
        <div class="cari">
			<form>
				<input type="text" name="search" placeholder="Lokasi Anda">
			</form>
		</div>

        <!--Import jQuery before materialize.js-->
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script type="text/javascript" src="static/js/materialize.min.js"></script>
    </body>
</html>


text:
#import "CreateGroupViewController.h"

#import "ContactSelectionViewController.h"
#import "EMTextView.h"

@interface CreateGroupViewController ()<UITextFieldDelegate, UITextViewDelegate, EMChooseViewDelegate>

@property (strong, nonatomic) UIView *switchView;
@property (strong, nonatomic) UIBarButtonItem *rightItem;
@property (strong, nonatomic) UITextField *textField;
@property (strong, nonatomic) EMTextView *textView;

@property (nonatomic) BOOL isPublic;
@property (strong, nonatomic) UILabel *groupTypeLabel;//群组类型

@property (nonatomic) BOOL isMemberOn;
@property (strong, nonatomic) UILabel *groupMemberTitleLabel;
@property (strong, nonatomic) UISwitch *groupMemberSwitch;
@property (strong, nonatomic) UILabel *groupMemberLabel;

@end

@implementation CreateGroupViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _isPublic = NO;
        _isMemberOn = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    self.title = NSLocalizedString(@"title.createGroup", @"Create a group");
    self.view.backgroundColor = [UIColor colorWithRed:0.88 green:0.88 blue:0.88 alpha:1.0];

    UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    addButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [addButton setTitle:NSLocalizedString(@"group.create.addOccupant", @"add members") forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor colorWithRed:32 / 255.0 green:134 / 255.0 blue:158 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [addButton addTarget:self action:@selector(addContacts:) forControlEvents:UIControlEventTouchUpInside];
    _rightItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    [self.navigationItem setRightBarButtonItem:_rightItem];

    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [backButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [backButton addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem setLeftBarButtonItem:backItem];

    [self.view addSubview:self.textField];
    [self.view addSubview:self.textView];
    [self.view addSubview:self.switchView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - getter

- (UITextField *)textField
{
    if (_textField == nil) {
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 300, 40)];
        _textField.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        _textField.layer.borderWidth = 0.5;
        _textField.layer.cornerRadius = 3;
        _textField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 30)];
        _textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.font = [UIFont systemFontOfSize:15.0];
        _textField.backgroundColor = [UIColor whiteColor];
        _textField.placeholder = NSLocalizedString(@"group.create.inputName", @"please enter the group name");
        _textField.returnKeyType = UIReturnKeyDone;
        _textField.delegate = self;
    }

    return _textField;
}

- (EMTextView *)textView
{
    if (_textView == nil) {
        _textView = [[EMTextView alloc] initWithFrame:CGRectMake(10, 70, 300, 80)];
        _textView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        _textView.layer.borderWidth = 0.5;
        _textView.layer.cornerRadius = 3;
        _textView.font = [UIFont systemFontOfSize:14.0];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.placeholder = NSLocalizedString(@"group.create.inputDescribe", @"please enter a group description");
        _textView.returnKeyType = UIReturnKeyDone;
        _textView.delegate = self;
    }

    return _textView;
}

- (UIView *)switchView
{
    if (_switchView == nil) {
        _switchView = [[UIView alloc] initWithFrame:CGRectMake(10, 160, 300, 90)];
        _switchView.backgroundColor = [UIColor clearColor];

        CGFloat oY = 0;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, oY, 100, 35)];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:14.0];
        label.numberOfLines = 2;
        label.text = NSLocalizedString(@"group.create.groupPermission", @"group permission");
        [_switchView addSubview:label];

        UISwitch *switchControl = [[UISwitch alloc] initWithFrame:CGRectMake(100, oY, 50, _switchView.frame.size.height)];
        [switchControl addTarget:self action:@selector(groupTypeChange:) forControlEvents:UIControlEventValueChanged];
        [_switchView addSubview:switchControl];

        _groupTypeLabel = [[UILabel alloc] initWithFrame:CGRectMake(switchControl.frame.origin.x + switchControl.frame.size.width + 5, oY, 100, 35)];
        _groupTypeLabel.backgroundColor = [UIColor clearColor];
        _groupTypeLabel.font = [UIFont systemFontOfSize:12.0];
        _groupTypeLabel.textColor = [UIColor grayColor];
        _groupTypeLabel.text = NSLocalizedString(@"group.create.private", @"private group");
        _groupTypeLabel.numberOfLines = 2;
        [_switchView addSubview:_groupTypeLabel];

        oY += (35 + 20);
        _groupMemberTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, oY, 100, 35)];
        _groupMemberTitleLabel.font = [UIFont systemFontOfSize:14.0];
        _groupMemberTitleLabel.backgroundColor = [UIColor clearColor];
        _groupMemberTitleLabel.text = NSLocalizedString(@"group.create.occupantPermissions", @"members invite permissions");
        _groupMemberTitleLabel.numberOfLines = 2;
        [_switchView addSubview:_groupMemberTitleLabel];

        _groupMemberSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, oY, 50, 35)];
        [_groupMemberSwitch addTarget:self action:@selector(groupMemberChange:) forControlEvents:UIControlEventValueChanged];
        [_switchView addSubview:_groupMemberSwitch];

        _groupMemberLabel = [[UILabel alloc] initWithFrame:CGRectMake(_groupMemberSwitch.frame.origin.x + _groupMemberSwitch.frame.size.width + 5, oY, 150, 35)];
        _groupMemberLabel.backgroundColor = [UIColor clearColor];
        _groupMemberLabel.font = [UIFont systemFontOfSize:12.0];
        _groupMemberLabel.textColor = [UIColor grayColor];
        _groupMemberLabel.numberOfLines = 2;
        _groupMemberLabel.text = NSLocalizedString(@"group.create.unallowedOccupantInvite", @"don't allow group members to invite others");
        [_switchView addSubview:_groupMemberLabel];
    }

    return _switchView;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {

        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}

#pragma mark - EMChooseViewDelegate

- (BOOL)viewController:(EMChooseViewController *)viewController didFinishSelectedSources:(NSArray *)selectedSources
{
    NSInteger maxUsersCount = 200;
    if ([selectedSources count] > (maxUsersCount - 1)) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"group.maxUserCount", nil) message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
        [alertView show];

        return NO;
    }

    [self showHudInView:self.view hint:NSLocalizedString(@"group.create.ongoing", @"create a group...")];

    NSMutableArray *source = [NSMutableArray array];
    for (NSString *username in selectedSources) {
        [source addObject:username];
    }

    EMGroupOptions *setting = [[EMGroupOptions alloc] init];
    setting.maxUsersCount = maxUsersCount;

    if (_isPublic) {
        if(_isMemberOn)
        {
            setting.style = EMGroupStylePublicOpenJoin;
        }
        else{
            setting.style = EMGroupStylePublicJoinNeedApproval;
        }
    }
    else{
        if(_isMemberOn)
        {
            setting.style = EMGroupStylePrivateMemberCanInvite;
        }
        else{
            setting.style = EMGroupStylePrivateOnlyOwnerInvite;
        }
    }

    __weak CreateGroupViewController *weakSelf = self;
    NSString *username = [[EMClient sharedClient] currentUsername];
    NSString *messageStr = [NSString stringWithFormat:NSLocalizedString(@"group.somebodyInvite", @"%@ invite you to join groups \'%@\'"), username, self.textField.text];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = nil;
        EMGroup *group = [[EMClient sharedClient].groupManager createGroupWithSubject:self.textField.text description:self.textView.text invitees:source message:messageStr setting:setting error:&error];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf hideHud];
            if (group && !error) {
                [weakSelf showHint:NSLocalizedString(@"group.create.success", @"create group success")];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
            else{
                [weakSelf showHint:NSLocalizedString(@"group.create.fail", @"Failed to create a group, please operate again")];
            }
        });
    });
    return YES;
}

#pragma mark - action

- (void)groupTypeChange:(UISwitch *)control
{
    _isPublic = control.isOn;

    [_groupMemberSwitch setOn:NO animated:NO];
    [self groupMemberChange:_groupMemberSwitch];

    if (control.isOn) {
        _groupTypeLabel.text = NSLocalizedString(@"group.create.public", @"public group");
    }
    else{
        _groupTypeLabel.text = NSLocalizedString(@"group.create.private", @"private group");
    }
}

- (void)groupMemberChange:(UISwitch *)control
{
    if (_isPublic) {
        _groupMemberTitleLabel.text = NSLocalizedString(@"group.create.occupantJoinPermissions", @"members join permissions");
        if(control.isOn)
        {
            _groupMemberLabel.text = NSLocalizedString(@"group.create.open", @"random join");
        }
        else{
            _groupMemberLabel.text = NSLocalizedString(@"group.create.needApply", @"you need administrator agreed to join the group");
        }
    }
    else{
        _groupMemberTitleLabel.text = NSLocalizedString(@"group.create.occupantPermissions", @"members invite permissions");
        if(control.isOn)
        {
            _groupMemberLabel.text = NSLocalizedString(@"group.create.allowedOccupantInvite", @"allows group members to invite others");
        }
        else{
            _groupMemberLabel.text = NSLocalizedString(@"group.create.unallowedOccupantInvite", @"don't allow group members to invite others");
        }
    }

    _isMemberOn = control.isOn;
}

- (void)addContacts:(id)sender
{
    if (self.textField.text.length == 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"group.create.inputName", @"please enter the group name") delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }

    [self.view endEditing:YES];

    ContactSelectionViewController *selectionController = [[ContactSelectionViewController alloc] init];
    selectionController.delegate = self;
    [self.navigationController pushViewController:selectionController animated:YES];
}

@end


text:
package edu.mit.spacenet.gui.command;

import edu.mit.spacenet.gui.mission.MissionsTab;
import edu.mit.spacenet.scenario.Mission;

/**
 * The command to edit a mission.
 *
 * @author Paul Grogan
 */
public class EditMissionCommand implements I_Command {
	private MissionsTab missionsTab;
	private Mission mission;

	/**
	 * The constructor.
	 *
	 * @param missionsTab the missions tab component.
	 * @param mission the mission to edit
	 */
	public EditMissionCommand(MissionsTab missionsTab, Mission mission) {
		this.missionsTab = missionsTab;
		this.mission = mission;
	}

	/* (non-Javadoc)
	 * @see edu.mit.spacenet.gui.command.I_Command#execute()
	 */
	public void execute() {
		missionsTab.editMission(mission);
	}
}


text:
require "spec_helper"

describe User, "spam" do

  it "flags users with a high spam count as spammers" do
    u = User.make!
    expect(u.spammer?).to be false
    3.times{ Flag.make!(flaggable: Observation.make!(user: u), flag: Flag::SPAM) }
    u.reload
    expect(u.spammer?).to be true
  end

  it "suspends spammers" do
    u = User.make!
    expect(u.suspended_at).to be_nil
    3.times{ Flag.make!(flaggable: Observation.make!(user: u), flag: Flag::SPAM) }
    u.reload
    expect(u.suspended_at).to_not be_nil
  end

  it "knows what content has been flagged as spam" do
    u = User.make!
    expect(u.content_flagged_as_spam.count).to be 0
    3.times{ Flag.make!(flaggable: Observation.make!(user: u), flag: Flag::SPAM) }
    expect(u.content_flagged_as_spam.count).to be 3
  end

  it "doesn't count resolved flags toward spam content" do
    u = User.make!
    expect(u.content_flagged_as_spam.count).to be 0
    3.times{ Flag.make!(flaggable: Observation.make!(user: u), flag: Flag::SPAM) }
    expect(u.content_flagged_as_spam.count).to be 3
    Flag.last.update_column(:resolved, true)
    expect(u.content_flagged_as_spam.count).to be 2
  end

  it "updates spam count when content is flagged" do
    u = User.make!
    expect(u.spam_count).to be 0
    3.times{ Flag.make!(flaggable: Observation.make!(user: u), flag: Flag::SPAM) }
    u.reload
    expect(u.spam_count).to be 3
  end

  it "decrements spam count when flags are resolved" do
    u = User.make!
    expect(u.spam_count).to be 0
    3.times{ Flag.make!(flaggable: Observation.make!(user: u), flag: Flag::SPAM) }
    u.reload
    expect(u.spam_count).to be 3
    Flag.last.update(resolved: true, resolver: u)
    u.reload
    expect(u.content_flagged_as_spam.count).to be 2
  end

  it "knows all the spam flags on a users content" do
    u = User.make!
    expect(u.flags_on_spam_content.count).to eq 0
    3.times do
      obs = Observation.make!(user: u)
      Flag.make!(flaggable: obs, flag: Flag::SPAM)
      Flag.make!(flaggable: obs, flag: "something else")
    end
    expect(u.flags_on_spam_content.count).to eq 3
  end

  it "does not consider spam flags on a user a flag on another users content" do
    u = User.make!
    u2 = User.make!
    Flag.make!(flaggable: u2, flag: Flag::SPAM)
    expect(u.flags_on_spam_content.count).to eq 0
  end

  it "does not check for spam if description is blank" do
    u = User.make(email: 'foo+bar20150301@inaturalist.org')
    expect(u.description).to be_blank
    expect(u).to_not receive(:spam?)
    u.save
    expect(u).not_to be_flagged_as_spam
    expect(u).not_to be_suspended
    expect(u).not_to be_spammer
  end

  describe "set_as_non_spammer_if_meets_criteria" do
    it "should set spammer to false after 3 research grade observations" do
      u = User.make!
      make_research_grade_observation( user: u )
      expect( u.spammer ).to be nil
      make_research_grade_observation( user: u )
      expect( u.spammer ).to be nil
      make_research_grade_observation( user: u )
      u.reload
      expect( u.spammer ).to be false
    end
  end
end


text:
module Jekyll
  class Document
    include Comparable

    attr_reader :path, :site, :extname, :collection
    attr_accessor :content, :output

    YAML_FRONT_MATTER_REGEXP = %r!\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)!m
    DATELESS_FILENAME_MATCHER = %r!^(?:.+/)*(.*)(\.[^.]+)$!
    DATE_FILENAME_MATCHER = %r!^(?:.+/)*(\d+-\d+-\d+)-(.*)(\.[^.]+)$!

    # Create a new Document.
    #
    # path - the path to the file
    # relations - a hash with keys :site and :collection, the values of which
    #             are the Jekyll::Site and Jekyll::Collection to which this
    #             Document belong.
    #
    # Returns nothing.
    def initialize(path, relations = {})
      @site = relations[:site]
      @path = path
      @extname = File.extname(path)
      @collection = relations[:collection]
      @has_yaml_header = nil

      if draft?
        categories_from_path("_drafts")
      else
        categories_from_path(collection.relative_directory)
      end

      data.default_proc = proc do |_, key|
        site.frontmatter_defaults.find(relative_path, collection.label, key)
      end

      trigger_hooks(:post_init)
    end

    # Fetch the Document's data.
    #
    # Returns a Hash containing the data. An empty hash is returned if
    #   no data was read.
    def data
      @data ||= {}
    end

    # Merge some data in with this document's data.
    #
    # Returns the merged data.
    def merge_data!(other, source: "YAML front matter")
      merge_categories!(other)
      Utils.deep_merge_hashes!(data, other)
      merge_date!(source)
      data
    end

    def date
      data["date"] ||= (draft? ? source_file_mtime : site.time)
    end

    def source_file_mtime
      @source_file_mtime ||= File.mtime(path)
    end

    # Returns whether the document is a draft. This is only the case if
    # the document is in the 'posts' collection but in a different
    # directory than '_posts'.
    #
    # Returns whether the document is a draft.
    def draft?
      data["draft"] ||= relative_path.index(collection.relative_directory).nil? &&
        collection.label == "posts"
    end

    # The path to the document, relative to the site source.
    #
    # Returns a String path which represents the relative path
    #   from the site source to this document
    def relative_path
      @relative_path ||= Pathutil.new(path).relative_path_from(site.source).to_s
    end

    # The output extension of the document.
    #
    # Returns the output extension
    def output_ext
      Jekyll::Renderer.new(site, self).output_ext
    end

    # The base filename of the document, without the file extname.
    #
    # Returns the basename without the file extname.
    def basename_without_ext
      @basename_without_ext ||= File.basename(path, ".*")
    end

    # The base filename of the document.
    #
    # Returns the base filename of the document.
    def basename
      @basename ||= File.basename(path)
    end

    # Produces a "cleaned" relative path.
    # The "cleaned" relative path is the relative path without the extname
    #   and with the collection's directory removed as well.
    # This method is useful when building the URL of the document.
    #
    # Examples:
    #   When relative_path is "_methods/site/generate.md":
    #     cleaned_relative_path
    #     # => "/site/generate"
    #
    # Returns the cleaned relative path of the document.
    def cleaned_relative_path
      @cleaned_relative_path ||=
        relative_path[0..-extname.length - 1].sub(collection.relative_directory, "")
    end

    # Determine whether the document is a YAML file.
    #
    # Returns true if the extname is either .yml or .yaml, false otherwise.
    def yaml_file?
      %w(.yaml .yml).include?(extname)
    end

    # Determine whether the document is an asset file.
    # Asset files include CoffeeScript files and Sass/SCSS files.
    #
    # Returns true if the extname belongs to the set of extensions
    #   that asset files use.
    def asset_file?
      sass_file? || coffeescript_file?
    end

    # Determine whether the document is a Sass file.
    #
    # Returns true if extname == .sass or .scss, false otherwise.
    def sass_file?
      %w(.sass .scss).include?(extname)
    end

    # Determine whether the document is a CoffeeScript file.
    #
    # Returns true if extname == .coffee, false otherwise.
    def coffeescript_file?
      ".coffee" == extname
    end

    # Determine whether the file should be rendered with Liquid.
    #
    # Returns false if the document is either an asset file or a yaml file,
    #   true otherwise.
    def render_with_liquid?
      !(coffeescript_file? || yaml_file?)
    end

    # Determine whether the file should be placed into layouts.
    #
    # Returns false if the document is either an asset file or a yaml file,
    #   true otherwise.
    def place_in_layout?
      !(asset_file? || yaml_file?)
    end

    # The URL template where the document would be accessible.
    #
    # Returns the URL template for the document.
    def url_template
      collection.url_template
    end

    # Construct a Hash of key-value pairs which contain a mapping between
    #   a key in the URL template and the corresponding value for this document.
    #
    # Returns the Hash of key-value pairs for replacement in the URL.
    def url_placeholders
      @url_placeholders ||= Drops::UrlDrop.new(self)
    end

    # The permalink for this Document.
    # Permalink is set via the data Hash.
    #
    # Returns the permalink or nil if no permalink was set in the data.
    def permalink
      data && data.is_a?(Hash) && data["permalink"]
    end

    # The computed URL for the document. See `Jekyll::URL#to_s` for more details.
    #
    # Returns the computed URL for the document.
    def url
      @url = URL.new({
        :template     => url_template,
        :placeholders => url_placeholders,
        :permalink    => permalink
      }).to_s
    end

    def [](key)
      data[key]
    end

    # The full path to the output file.
    #
    # base_directory - the base path of the output directory
    #
    # Returns the full path to the output file of this document.
    def destination(base_directory)
      dest = site.in_dest_dir(base_directory)
      path = site.in_dest_dir(dest, URL.unescape_path(url))
      if url.end_with? "/"
        path = File.join(path, "index.html")
      else
        path << output_ext unless path.end_with? output_ext
      end
      path
    end

    # Write the generated Document file to the destination directory.
    #
    # dest - The String path to the destination dir.
    #
    # Returns nothing.
    def write(dest)
      path = destination(dest)
      FileUtils.mkdir_p(File.dirname(path))
      File.write(path, output, :mode => "wb")

      trigger_hooks(:post_write)
    end

    # Whether the file is published or not, as indicated in YAML front-matter
    #
    # Returns 'false' if the 'published' key is specified in the
    # YAML front-matter and is 'false'. Otherwise returns 'true'.
    def published?
      !(data.key?("published") && data["published"] == false)
    end

    # Read in the file and assign the content and data based on the file contents.
    # Merge the frontmatter of the file with the frontmatter default
    # values
    #
    # Returns nothing.
    def read(opts = {})
      Jekyll.logger.debug "Reading:", relative_path

      if yaml_file?
        @data = SafeYAML.load_file(path)
      else
        begin
          merge_defaults
          read_content(opts)
          read_post_data
        rescue SyntaxError => e
          Jekyll.logger.error "Error:", "YAML Exception reading #{path}: #{e.message}"
        rescue => e
          raise e if e.is_a? Jekyll::Errors::FatalException
          Jekyll.logger.error "Error:", "could not read file #{path}: #{e.message}"
        end
      end
    end

    # Create a Liquid-understandable version of this Document.
    #
    # Returns a Hash representing this Document's data.
    def to_liquid
      @to_liquid ||= Drops::DocumentDrop.new(self)
    end

    # The inspect string for this document.
    # Includes the relative path and the collection label.
    #
    # Returns the inspect string for this document.
    def inspect
      "#<Jekyll::Document #{relative_path} collection=#{collection.label}>"
    end

    # The string representation for this document.
    #
    # Returns the content of the document
    def to_s
      output || content || "NO CONTENT"
    end

    # Compare this document against another document.
    # Comparison is a comparison between the 2 paths of the documents.
    #
    # Returns -1, 0, +1 or nil depending on whether this doc's path is less than,
    #   equal or greater than the other doc's path. See String#<=> for more details.
    def <=>(other)
      return nil unless other.respond_to?(:data)
      cmp = data["date"] <=> other.data["date"]
      cmp = path <=> other.path if cmp.nil? || cmp.zero?
      cmp
    end

    # Determine whether this document should be written.
    # Based on the Collection to which it belongs.
    #
    # True if the document has a collection and if that collection's #write?
    #   method returns true, otherwise false.
    def write?
      collection && collection.write?
    end

    # The Document excerpt_separator, from the YAML Front-Matter or site
    # default excerpt_separator value
    #
    # Returns the document excerpt_separator
    def excerpt_separator
      (data["excerpt_separator"] || site.config["excerpt_separator"]).to_s
    end

    # Whether to generate an excerpt
    #
    # Returns true if the excerpt separator is configured.
    def generate_excerpt?
      !excerpt_separator.empty?
    end

    def next_doc
      pos = collection.docs.index { |post| post.equal?(self) }
      if pos && pos < collection.docs.length - 1
        collection.docs[pos + 1]
      end
    end

    def previous_doc
      pos = collection.docs.index { |post| post.equal?(self) }
      if pos && pos > 0
        collection.docs[pos - 1]
      end
    end

    def trigger_hooks(hook_name, *args)
      Jekyll::Hooks.trigger collection.label.to_sym, hook_name, self, *args if collection
      Jekyll::Hooks.trigger :documents, hook_name, self, *args
    end

    def id
      @id ||= File.join(File.dirname(url), (data["slug"] || basename_without_ext).to_s)
    end

    # Calculate related posts.
    #
    # Returns an Array of related Posts.
    def related_posts
      Jekyll::RelatedPosts.new(self).build
    end

    # Override of normal respond_to? to match method_missing's logic for
    # looking in @data.
    def respond_to?(method, include_private = false)
      data.key?(method.to_s) || super
    end

    # Override of method_missing to check in @data for the key.
    def method_missing(method, *args, &blck)
      if data.key?(method.to_s)
        Jekyll::Deprecator.deprecation_message "Document##{method} is now a key "\
                           "in the #data hash."
        Jekyll::Deprecator.deprecation_message "Called by #{caller.first}."
        data[method.to_s]
      else
        super
      end
    end

    def respond_to_missing?(method, *)
      data.key?(method.to_s) || super
    end

    private
    def merge_categories!(other)
      if other.key?("categories") && !other["categories"].nil?
        if other["categories"].is_a?(String)
          other["categories"] = other["categories"].split(%r!\s+!).map(&:strip)
        end
        other["categories"] = (data["categories"] || []) | other["categories"]
      end
    end

    private
    def merge_date!(source)
      if data.key?("date") && !data["date"].is_a?(Time)
        data["date"] = Utils.parse_date(
          data["date"].to_s,
          "Document '#{relative_path}' does not have a valid date in the #{source}."
        )
      end
    end

    private
    def merge_defaults
      defaults = @site.frontmatter_defaults.all(
        relative_path,
        collection.label.to_sym
      )
      merge_data!(defaults, :source => "front matter defaults") unless defaults.empty?
    end

    private
    def read_content(opts)
      self.content = File.read(path, Utils.merged_file_read_opts(site, opts))
      if content =~ YAML_FRONT_MATTER_REGEXP
        self.content = $POSTMATCH
        data_file = SafeYAML.load(Regexp.last_match(1))
        merge_data!(data_file, :source => "YAML front matter") if data_file
      end
    end

    private
    def read_post_data
      populate_title
      populate_categories
      populate_tags
      generate_excerpt
    end

    private
    def populate_title
      if relative_path =~ DATE_FILENAME_MATCHER
        date, slug, ext = Regexp.last_match.captures
        modify_date(date)
      elsif relative_path =~ DATELESS_FILENAME_MATCHER
        slug, ext = Regexp.last_match.captures
      end

      # Try to ensure the user gets a title.
      data["title"] ||= Utils.titleize_slug(slug)
      # Only overwrite slug & ext if they aren't specified.
      data["slug"]  ||= slug
      data["ext"]   ||= ext
    end

    private
    def modify_date(date)
      if !data["date"] || data["date"].to_i == site.time.to_i
        merge_data!({ "date" => date }, :source => "filename")
      end
    end

    # Add superdirectories of the special_dir to categories.
    # In the case of es/_posts, 'es' is added as a category.
    # In the case of _posts/es, 'es' is NOT added as a category.
    #
    # Returns nothing.
    private
    def categories_from_path(special_dir)
      superdirs = relative_path.sub(%r!#{special_dir}(.*)!, "")
        .split(File::SEPARATOR)
        .reject do |c|
        c.empty? || c == special_dir || c == basename
      end
      merge_data!({ "categories" => superdirs }, :source => "file path")
    end

    private
    def populate_categories
      merge_data!({
        "categories" => (
        Array(data["categories"]) + Utils.pluralized_array_from_hash(
          data,
          "category",
          "categories"
        )
        ).map(&:to_s).flatten.uniq
      })
    end

    private
    def populate_tags
      merge_data!({
        "tags" => Utils.pluralized_array_from_hash(data, "tag", "tags").flatten
      })
    end

    private
    def generate_excerpt
      if generate_excerpt?
        data["excerpt"] ||= Jekyll::Excerpt.new(self)
      end
    end
  end
end


text:
groupme-bot
==============

A GroupMe bot written in Go


text:
@implementation APIResourceNamer

- (id)init;
{
    return [self initWithInflector:nil];
}

- (id)initWithInflector:(APIInflector *)inflector;
{
    if (self = [super init]) {
        _inflector = inflector;
    }

    return self;
}

- (NSString *)nameForResource:(Class)resource;
{
    return [self.inflector underscore:[self stringByRemovingPrefixFromResource:resource]];
}

- (NSString *)pluralizedNameForResource:(Class)resource;
{
    return [self.inflector pluralize:[self nameForResource:resource]];
}

- (NSString *)stringByRemovingPrefixFromResource:(Class)resource;
{
    NSString *className = NSStringFromClass(resource);
    NSRegularExpression *prefixRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Z]+" options:0 error:nil];
    NSRange capitalsRange = [prefixRegularExpression rangeOfFirstMatchInString:className options:0 range:NSMakeRange(0, className.length)];
    NSRange prefixRange = NSMakeRange(0, capitalsRange.length - 1);
    return [className substringFromIndex:prefixRange.length];
}

- (APIInflector *)inflector;
{
    if (!_inflector) {
        _inflector = [[APIInflector alloc] init];
    }

    return _inflector;
}

@end


text:
<?php

/**
 * sfGuardForgotPassword
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    OfficeMerits
 * @subpackage model
 * @author     Joshua Estes
 * @version    SVN: $Id$
 */
class sfGuardForgotPassword extends PluginsfGuardForgotPassword
{
}


text:
<?php

namespace Dummy\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

class BlogRepository extends EntityRepository
{
    public function findAllOrderedByDate()
    {
        return $this->getEntityManager()
            ->createQuery('SELECT b FROM DummyBlogBundle:Blog b ORDER BY b.created ASC')
            ->getResult();
    }

    public function findAllInCategory($id)
    {
        return $this->getEntityManager()
            ->createQuery('SELECT b FROM DummyBlogBundle:Blog b WHERE b.category=:id ORDER BY b.created ASC')
            ->setParameter('id', $id)
            ->getResult();
    }
}


text:
/*
 * ObserverTest.cpp
 *
 *  Created on: 2016年8月4日
 *      Author: Maibenben
 */

#include "ObserverTest.h"

namespace stock_logic {

ObserverTest::ObserverTest(stock_logic::Subject* subject) {
  // YGTODO Auto-generated constructor stub
  name_ = "ObserverTest";
  subject_ = subject;
}

ObserverTest::~ObserverTest() {
  // YGTODO Auto-generated destructor stub
}

void ObserverTest::Update(int opcode, stock_logic::Subject*) {

}

base_logic::DictionaryValue* ObserverTest::Request(base_logic::DictionaryValue* params) {
  std::string start_date = ",2016-07-01";
    bool r = true;
    r = params->GetString(L"start_date", &start_date);
    if (true == r) {
      LOG_MSG2("get start_date=%s", start_date.c_str());
    }
    if (start_date.size() > 1)
      start_date.erase(start_date.begin());
    LOG_MSG2("start_date=%s", start_date.c_str());
    base_logic::DictionaryValue* dict = new base_logic::DictionaryValue();
    dict->SetString(L"start_date", start_date);

    return dict;
}

} /* namespace stock_logic */


text:
using Newtonsoft.Json;
using OfficeDevPnP.Core.Utilities;
using OfficeDevPnP.Core.WebAPI;
using Provisioning.Common;
using Provisioning.Common.Authentication;
using Provisioning.Common.Configuration;
using Provisioning.Common.Data;
using Provisioning.Common.Data.SiteRequests;
using Provisioning.Common.Data.Templates;
using Provisioning.Common.Utilities;
using Provisioning.UX.AppWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Provisioning.UX.AppWeb.Controllers
{
    /// <summary>
    /// Class
    /// </summary>
    public class ProvisioningController : ApiController
    {

        #region Public Members
        [HttpPut]
        public void Register(WebAPIContext sharePointServiceContext)
        {
            WebAPIHelper.AddToCache(sharePointServiceContext);
        }

        /// <summary>
        /// Returns a list of available site policies
        /// </summary>
        /// <returns></returns>
        [Route("api/provisioning/availableSitePolicies")]
        [WebAPIContextFilter]
        [HttpGet]
        public List<SitePolicyResults> GetSitePolicies()
        {
            var _returnResults = new List<SitePolicyResults>();
            ConfigManager _manager = new ConfigManager();

            AbstractSiteProvisioningService _siteService = new Office365SiteProvisioningService();
            var _auth = new AppOnlyAuthenticationTenant();
            _auth.SiteUrl = _manager.GetAppSettingsKey("SPHost");

            var _sitePolicies = _siteService.GetAvailablePolicies();
            foreach(var _sitePolicyEntity in _sitePolicies)
            {
                var _policy = new SitePolicyResults();
                _policy.Key = _sitePolicyEntity.Name;
                _policy.Value = _sitePolicyEntity.Description;
                _returnResults.Add(_policy);
            }
            return _returnResults;
        }
        #endregion

        [Route("api/provisioning/externalSharingEnabled")]
        [WebAPIContextFilter]
        [HttpPost]
        public ExternalSharingRequest IsExternalSharingEnabled([FromBody]string value)
        {
            var _request = JsonConvert.DeserializeObject<ExternalSharingRequest>(value);
            _request.Success = false;

            try
            {
                AppOnlyAuthenticationTenant _auth = new AppOnlyAuthenticationTenant();
                _auth.TenantAdminUrl = _request.TenantAdminUrl;
                var _service = new Office365SiteProvisioningService();
                _service.Authentication = _auth;
                _request.ExternalSharingEnabled = _service.IsTenantExternalSharingEnabled(_request.TenantAdminUrl);
                _request.Success = true;
                return _request;
            }
            catch(Exception _ex)
            {
               _request.ErrorMessage = _ex.Message;
                OfficeDevPnP.Core.Diagnostics.Log.Error("ProvisioningController.IsExternalSharingEnabled",
                   "There was an error processing the request. Exception: {0}",
                   _ex);
               return _request;
            }

        }

        [Route("api/provisioning/isSiteUrlProviderUsed")]
        [WebAPIContextFilter]
        [HttpPost]
        public SiteUrlCheckRequest IsSiteUrlProviderUsed([FromBody]string value)
        {
            var _request = JsonConvert.DeserializeObject<SiteUrlCheckRequest>(value);

            ReflectionManager rm = new ReflectionManager();

            var siteUrlProvider = rm.GetSiteUrlProvider("SiteUrlProvider");
            if (siteUrlProvider != null)
            {
                _request.UsesCustomProvider = false;
            }
            else
            {
                _request.UsesCustomProvider = true;
            }

            return _request;
        }

    }
}


text:
const html = require('choo/html')
const Component = require('choo/component')
const { input } = require('../form')
const { __ } = require('../../lib/locale')

module.exports = class Search extends Component {
  constructor (id, state) {
    super(id)
    this.state = state
    this.text = ''
  }

  update (cooperative) {
    return cooperative._id !== this.cooperative
  }

  load (element) {
    element.querySelector('#coop-search-input').focus()
  }

  unload () {
    this.text = ''
  }

  createElement (cooperative, onselect) {
    this.cooperative = cooperative._id

    const { cooperatives, consumptions: { type } } = this.state
    const pattern = new RegExp(this.text.replace(/\\/, '//'), 'i')
    const results = this.text ? cooperatives.filter(item => {
      if (item._id === cooperative._id) return false
      if (!item.meters.find(meter => meter.type === type && meter.valid)) return false
      return pattern.test(item.name)
    }) : []

    const oninput = event => {
      this.text = event.target.value
      this.rerender()
    }

    return html`
      <form class="Form">

${__('Find cooperative')}

        ${input({ label: __('Type here'), id: 'coop-search-input', type: 'search', name: 'search', oninput: oninput, value: this.text, autocomplete: 'off', autofocus: true, autocorrect: 'off' })}
        ${this.text ? html`

            ${results.length ? results.slice(0, 6).map(item => html`

                <button class="Button Button--link u-block u-sizeFull u-paddingAb" type="submit" name="compare" value="cooperative:${item._id}" onclick=${onselect}>
                  ${item.name}
                </button>

            `) : html`

                ${__('Sorry, we couldn\'t find any cooperative by that name')}

            `}

        ` : null}
      </form>
    `
  }
}


text:
package org.owasp.esapi.core.logging;

import org.owasp.esapi.core.SecurityComponent;
import org.owasp.esapi.core.event.SecurityEvent;

/**
 * The SecurityLogger interface replaces the Logger interface from ESAPI 2.x. The SecurityLogger is intended to be used
 * to log security specific events, and is generally intended to be logged into a dedicated repository intended for only
 * security events.
 *
 * There are several different levels that can be logged into, implementors are responsible for mapping the SecurityLogger
 * methdos to their Logging equivelant in an adaptor class.
 *
 * Each method expects a {@link org.owasp.esapi.core.event.SecurityEvent} to be supplied, this event will contain contextual information about the
 * logging event in addition to the event description which can be logged allowing filtering based off of Security Event
 * when parsing or reading Security logs.
 */
public interface SecurityLogger extends SecurityComponent {
    <T extends SecurityEvent> void audit(T event, String message, Object... parms);
    <T extends SecurityEvent> void audit(T event, Throwable t, String message, Object... parms);

    <T extends SecurityEvent> void always(T event, String message, Object... parms);
    <T extends SecurityEvent> void always(T event, Throwable t, String message, Object... parms);

    <T extends SecurityEvent> void debug(T event, String message, Object... parms);
    <T extends SecurityEvent> void debug(T event, Throwable t, String message, Object... parms);

    <T extends SecurityEvent> void info(T event, String message, Object... parms);
    <T extends SecurityEvent> void info(T event, Throwable t, String message, Object... parms);

    <T extends SecurityEvent> void warn(T event, String message, Object... parms);
    <T extends SecurityEvent> void warn(T event, Throwable t, String message, Object... parms);

    <T extends SecurityEvent> void error(T event, String message, Object... parms);
    <T extends SecurityEvent> void error(T event, Throwable t, String message, Object... parms);
}


text:
package org.apache.hadoop.hbase.ipc;

import java.net.InetSocketAddress;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testclassification.RPCTests;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.ManualEnvironmentEdge;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category({RPCTests.class, MediumTests.class})   // Can't be small, we're playing with the EnvironmentEdge
public class TestHBaseClient {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestHBaseClient.class);

  @Test
  public void testFailedServer(){
    ManualEnvironmentEdge ee = new ManualEnvironmentEdge();
    EnvironmentEdgeManager.injectEdge(  ee );
    FailedServers fs = new FailedServers(new Configuration());
    Throwable testThrowable = new Throwable();//throwable already tested in TestFailedServers.java

    InetSocketAddress ia = InetSocketAddress.createUnresolved("bad", 12);
    InetSocketAddress ia2 = InetSocketAddress.createUnresolved("bad", 12);  // same server as ia
    InetSocketAddress ia3 = InetSocketAddress.createUnresolved("badtoo", 12);
    InetSocketAddress ia4 = InetSocketAddress.createUnresolved("badtoo", 13);

    Assert.assertFalse( fs.isFailedServer(ia) );

    fs.addToFailedServers(ia,testThrowable);
    Assert.assertTrue( fs.isFailedServer(ia) );
    Assert.assertTrue( fs.isFailedServer(ia2) );

    ee.incValue( 1 );
    Assert.assertTrue( fs.isFailedServer(ia) );
    Assert.assertTrue( fs.isFailedServer(ia2) );

    ee.incValue( RpcClient.FAILED_SERVER_EXPIRY_DEFAULT + 1 );
    Assert.assertFalse( fs.isFailedServer(ia) );
    Assert.assertFalse( fs.isFailedServer(ia2) );

    fs.addToFailedServers(ia,testThrowable);
    fs.addToFailedServers(ia3,testThrowable);
    fs.addToFailedServers(ia4,testThrowable);

    Assert.assertTrue( fs.isFailedServer(ia) );
    Assert.assertTrue( fs.isFailedServer(ia2) );
    Assert.assertTrue( fs.isFailedServer(ia3) );
    Assert.assertTrue( fs.isFailedServer(ia4) );

    ee.incValue( RpcClient.FAILED_SERVER_EXPIRY_DEFAULT + 1 );
    Assert.assertFalse( fs.isFailedServer(ia) );
    Assert.assertFalse( fs.isFailedServer(ia2) );
    Assert.assertFalse( fs.isFailedServer(ia3) );
    Assert.assertFalse( fs.isFailedServer(ia4) );

    fs.addToFailedServers(ia3,testThrowable);
    Assert.assertFalse( fs.isFailedServer(ia4) );
  }
}