text:
import pytest
from quokka import create_app

# def pytest_runtest_setup(item):
#     # called for running each test in 'a' directory
#     print ("setting up", item)

@pytest.fixture
def app():
    app = create_app(config='quokka.test_settings',
                     DEBUG=False,
                     test=True,
                     mode='test')
    return app

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "Spread Syntax"
date: 2022-03-04 08:23:00
category: javascript
tags: [javascript]
---

### Replace apply()
```javascript
function myFunction(x, y, z) { }
let args = [0, 1, 2];
myFunction.apply(null, args);
```
can be written as
```javascript
function myFunction(x, y, z) { }
let args = [1, 2, 2];
myFunction(...args);
```
can be used multiple time.
```javascript
function myFunction(v, w, x, y, z) { }
let args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);
```

### Apply for new operator
When calling a constructor with new it's not possible to directly use an array and apply() (apply() does a [[Call]] and not a [[Construct]]).
However, an array can be easily used with new thanks to spread syntax:
```javascript
let dataFields = [1970, 0, 1]; // 1 Jan 1970
let d = new Date(...dataFields);
```

### Copy an array
```javascript
let arr = [1,2,3];
let arr2 = [...arr]; // like arr.slice()
```

```javascript
arr2.push(4);
// arr2 becomes [1,2,3,4]
// arr remains unaffected
```

### Maybe Unsuitable for copying multimenstional arrays

Spread syntax effectively goes one level deep while copying an array.
(The same is true with `Object.assign()`.)

```javascript
let a = [[1], [2], [3]];
let b = [...a];

b.shift().shift();
// 1

// Oh no!  Now array 'a' is affected as well:
a
// [[], [2], [3]]
```

### A better way to concatenate arrays
```javascript
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];

// Append all items from arr2 onto arr1
arr1 = arr1.concat(arr2);

arr1 = [...arr1, ...arr2];
// Note: Not to use const otherwise, it will give TypeError (invalid assignment)
```

`Array.propotype.unshift()` is often used to insert an array of values at the start of an existing array.
```javascript
// Prepen all items from arr2 onto arr1
Array.prototype.unshift.apply(arr1, arr2);
// arr1 is now [3, 4, 5, 0, 1, 2]

arr1 = [...arr2, ...arr1]
```
**Unlike** `unshift()`, this creates a new `arr1`, and does not modify the original `arr1` array in-place.

### Spread in object literals
> The [Rest/Spread Properties for ECMAScript](https://github.com/tc39/proposal-object-rest-spread) proposal (ES2018) added spread properties to [object literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#1). It copies own enumerable properties from a provided object onto a new object.
> Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

```javascript
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };

let cloneObj = { ...obj1 };
// Object { foo: "bar", x: 42 }

let cloneObj = { ...obj1, ...obj2 };
// Object { foo: "baz", x: 42, y: 13 }
```

Note that Object.assign() triggers setters, whereas spread syntax doesn't.

> Note that you cannot replace or mimic the `Object.assign()` function:

```javascript
let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
const merge = ( ...objects ) => ( { ...objects } );

let mergeObj1 = merge (obj1, obj2);
// Object { 0: { foo: 'bar', x: 42}, 1: { foo: 'baz', y: 13 } }
```

## Only for iterables
> Spread syntax (other than in the case of spread properties) can only be applied to iterable objects like Array,
> or with iterating functions such as `map()`, `reduce()`, and `assign()`.
> Many objects are not iterable, including `Object`:
```javascript
let obj = {'key1': 'value1'};
let array = [...obj]; // TypeError: obj is not iterable
```
> To use spread syntax with these objects, you will need to provide an iterator function.

[jekyll]: http://jekyllrb.com
[jekyll-gh]: https://github.com/jekyll/jekyll
[jekyll-help]: https://github.com/jekyll/jekyll-help


text:
package edu.jhu.hlt.parma.types

trait HasLocation {
    def location: Mention
	override def equals(other: Any): Boolean = {
		if(other.isInstanceOf[HasLocation])
			location == other.asInstanceOf[HasLocation].location
		else false
	}
	override def hashCode: Int = location.hashCode
}


text:
package org.intellij.idea.lang.javascript.intention.constant;

import javax.annotation.Nonnull;

import org.intellij.idea.lang.javascript.intention.JSElementPredicate;
import org.intellij.idea.lang.javascript.intention.JSIntention;
import org.intellij.idea.lang.javascript.psiutil.ErrorUtil;
import org.intellij.idea.lang.javascript.psiutil.ExpressionUtil;
import org.intellij.idea.lang.javascript.psiutil.JSElementFactory;

import com.intellij.lang.javascript.psi.JSExpression;
import com.intellij.lang.javascript.psi.JSLiteralExpression;
import com.intellij.lang.javascript.psi.JSReferenceExpression;
import com.intellij.lang.javascript.psi.JSCallExpression;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.util.IncorrectOperationException;

public class JSConstantExpressionIntention extends JSIntention {
    @Override
	@Nonnull
    protected JSElementPredicate getElementPredicate() {
        return new ConstantExpressionPredicate();
    }

    @Override
	public void processIntention(@Nonnull PsiElement element) throws IncorrectOperationException {
        final JSExpression  expression = (JSExpression) element;
        final Object        value      = ExpressionUtil.computeConstantExpression(expression);
        final String        newExpression;

        if (value instanceof String) {
            newExpression = '"' + StringUtil.escapeStringCharacters((String) value) + '"';
        } else {
            newExpression = String.valueOf(value);
        }
        JSElementFactory.replaceExpression(expression, newExpression);
    }

    private static class ConstantExpressionPredicate implements JSElementPredicate {
        @Override
		public boolean satisfiedBy(@Nonnull PsiElement element) {
            if (!(element instanceof JSExpression)) {
                return false;
            }
            if (ErrorUtil.containsError(element)) {
                return false;
            }
            final JSExpression expression = (JSExpression) element;

            if (element instanceof JSLiteralExpression ||
                ( element instanceof JSReferenceExpression &&
                  ((JSReferenceExpression)element).getQualifier() != null
                ) ||
                expression instanceof JSCallExpression
               ) {
                return false;
            }
            if (!ExpressionUtil.isConstantExpression(expression)) {
                return false;
            }

            if (ExpressionUtil.computeConstantExpression(expression) == null) {
                return false;
            }

            final PsiElement parent = element.getParent();

            if (!(parent instanceof JSExpression)) {
                return true;
            }
            return (!ExpressionUtil.isConstantExpression((JSExpression) parent));
        }
    }
}


text:
require 'rubygems'
require 'lib/easy_nils'


text:
class BasePanel(object):
    """Returns a panel instance.

    This class should be subclassed to define a local panel configuration.

    To build a panel, do the following in the __init__() method of your local
        subclass:

    1. add instances of the necessary interfaces to the 'interfaces' dict
        attribute:
        >>> self.interfaces['comedi'] = comedi.ComediInterface(device_name='/dev/comedi0')

    2. add inputs and outputs to the 'inputs' and 'outputs' list attributes:
        >>> for in_chan in range(4):
                self.inputs.append(hwio.BooleanInput(interface=self.interfaces['comedi'],
                                                 params = {'subdevice': 2,
                                                           'channel': in_chan
                                                           },
                                                 )
    3. add components constructed from your inputs and outputs:
        >>> self.hopper = components.Hopper(IR=self.inputs[3],solenoid=self.outputs[4])

    4. assign panel methods needed for operant behavior, such as 'reward':
        >>> self.reward = self.hopper.reward

    5. finally, define a reset() method that will set the entire panel to a
        neutral state:

        >>> def reset(self):
        >>>     for output in self.outputs:
        >>>         output.set(False)
        >>>     self.house_light.write(True)
        >>>     return True

    """
    def __init__(self, *args,**kwargs):

        self.interfaces = {}

        self.inputs = []
        self.outputs = []

    def reset(self):
         raise NotImplementedError


text:
import xmpp
import feedparser
from models import *
import time,re
import urllib

login = '<Your feeder bot>'
pwd   = '<your feeder bot password>'

# Lets login
jid=xmpp.JID(login)
user, server = jid.getNode(), jid.getDomain()
cnx = xmpp.Client(server,debug=[])
conres = cnx.connect(server=('talk.google.com',5223))
authres = cnx.auth(user,pwd, 'Home')

def send_feed():
    kwds = Keyword.get()
    temp_url = "http://search.twitter.com/search.atom?q=%s"
    for k in kwds:
        feed_url = temp_url % (urllib.quote(k.data),)
        d = False
        try:
            d = feedparser.parse(feed_url)
        except UnicodeDecodeError,e:
            pass
        if d:
            fdate = k.updated_at
            entries = d.entries
            entries.reverse()
            for entry in entries:
                try:
                    dtuple = entry.updated_parsed
                    pdate = datetime.datetime(dtuple[0],dtuple[1],dtuple[2],dtuple[3],dtuple[4],dtuple[5])
                    fdate = pdate
                except AttributeError:
                    fdate = datetime.datetime.now()
                if pdate>k.updated_at:
                    content = entry.title
                    try:
                        content = entry.summary_detail.value
                    except AttributeError:
                        content = entry.content[0].value
                    content = re.sub('<([^!>]([^>]|\n)*)>', '', content)
                    cnx.send(xmpp.Message("<your primary>","***"+str(k.id)+"***"+content))
            k.updated_at = fdate
            k.save()

cnx.sendInitPresence()

while cnx.Process(1):
    send_feed()
    time.sleep(100)


text:
@getter(GetterType.Option, "id", null)
@setter(SetterType.Option)
class VersionSelectField extends Select2Field {
    private releasedFirst: boolean;

    constructor(id: string, field: JiraMetaField, config: { releasedFirst: boolean, multiSelect: boolean }) {
        let options = {
            data: []
        };
        super(id, field, options, config.multiSelect);
        this.releasedFirst = config.releasedFirst;
        this.init();
    }

    init() {
        let allowedValues: JiraVersion[] = <JiraVersion[]>this.fieldMeta.allowedValues;

        let releasedVersions = allowedValues
            .filter(option => { return option.released && !option.archived })
            .map(this.convertToSelect2);

        let unreleasedVersions = allowedValues
            .filter(option => { return !option.released && !option.archived })
            .map(this.convertToSelect2);

        let releasedOptGroup: Select2Element = {
            id: 'releasedVersions',
            text: yasoon.i18n('dialog.releasedVersions'),
            children: releasedVersions
        };

        let unreleasedOptGroup: Select2Element = {
            id: 'unreleasedVersions',
            text: yasoon.i18n('dialog.unreleasedVersions'),
            children: unreleasedVersions
        };

        this.options.data = [];
        if (this.releasedFirst) {
            if (releasedOptGroup.children.length > 0)
                this.options.data.push(releasedOptGroup);
            if (unreleasedOptGroup.children.length > 0)
                this.options.data.push(unreleasedOptGroup);
        } else {
            if (unreleasedOptGroup.children.length > 0)
                this.options.data.push(unreleasedOptGroup);
            if (releasedOptGroup.children.length > 0)
                this.options.data.push(releasedOptGroup);
        }
    }

    convertToSelect2(version: JiraValue): Select2Element {
        let result: Select2Element = {
            id: version.id,
            text: version.name || version.value,
            data: version
        };

        if (version.iconUrl) {
            result.icon = jira.icons.mapIconUrl(version.iconUrl);
        }

        return result;
    }
}


text:
@interface StaffManage : NSObject

//查看所有员工
- (void)showALlStaffInfo;

//根据手机号查看指定员工信息
- (void)showStaffInfoByTelNum:(NSString*)telNum;

//创建单例员工管理对象
+ (instancetype)defaultStaffManage;

@end


text:
package at.forsyte.apalache.tla.bmcmt.rules.deprecated

import at.forsyte.apalache.tla.bmcmt._
import at.forsyte.apalache.tla.bmcmt.rewriter.ConstSimplifierForSmt
import at.forsyte.apalache.tla.bmcmt.rules.SubstRule
import at.forsyte.apalache.tla.bmcmt.types.BoolT
import at.forsyte.apalache.tla.lir.convenience.tla
import at.forsyte.apalache.tla.lir.oper.TlaBoolOper
import at.forsyte.apalache.tla.lir.{NameEx, OperEx}

/**
  * Implements an equivalence A <=> B by rewriting it to A = B.
  *
  * @author Igor Konnov
  */
@deprecated("Normalizer takes care of it")
class EquivRule(rewriter: SymbStateRewriter) extends RewritingRule {
  private val substRule = new SubstRule(rewriter)
  private val simplifier = new ConstSimplifierForSmt()

  override def isApplicable(symbState: SymbState): Boolean = {
    symbState.ex match {
      case OperEx(TlaBoolOper.equiv, _, _) => true
      case _ => false
    }
  }

  override def apply(state: SymbState): SymbState = {
    state.ex match {
      case OperEx(TlaBoolOper.equiv, left, right) =>
        var leftState = rewriter.rewriteUntilDone(state.setRex(left))
        val rightState = rewriter.rewriteUntilDone(leftState.setRex(right))
        var nextState = rightState.updateArena(_.appendCell(BoolT()))
        val pred = nextState.arena.topCell
        rewriter.solverContext.assertGroundExpr(tla.eql(pred.toNameEx, tla.equiv(leftState.ex, rightState.ex)))
        nextState.setRex(pred.toNameEx)

      case _ =>
        throw new RewriterException("%s is not applicable".format(getClass.getSimpleName), state.ex)
    }
  }
}


text:
/**
 * Chapter 2. OOP.
 * Lesson 10. Exceptions.
 *
 * The package include some kinds of request classes.
 * package contains solution of task 789.
 *
 * @author Pavel Zubaha (mailto:Apximar@gmail.com)
 * @since 06.09.17
 * @version 1
 */
package pzubaha.observer;


text:
import discord
import asyncio

from typing import List
from discord.ext.commands import Context

EMOJI_MAP = {"back": "⬅", "forward": "➡"}

async def paginate(ctx: Context, msg: discord.Message, embeds: List[discord.Embed], timeout=30.0) -> None:
    emojis = EMOJI_MAP.values()
    for emoji in emojis:
        await msg.add_reaction(emoji)

    current_index = 0
    while True:
        try:
            reaction, _ = await ctx.bot.wait_for(
                "reaction_add",
                timeout=timeout,
                check=lambda reaction, user: (
                    user == ctx.author and reaction.emoji in emojis and reaction.message.id == msg.id
                ),
            )
        except asyncio.TimeoutError:
            return await msg.clear_reactions()

        if reaction.emoji == EMOJI_MAP["back"]:
            current_index = current_index - 1 if current_index > 0 else 0
        if reaction.emoji == EMOJI_MAP["forward"]:
            current_index = current_index + 1 if current_index < len(embeds) - 1 else len(embeds) - 1

        await msg.edit(embed=embeds[current_index])
        await msg.remove_reaction(reaction.emoji, ctx.author)


text:
SET(MODULE_CUSTOM_TESTS
  mitkFiberBundleXReaderWriterTest.cpp
  mitkGibbsTrackingTest.cpp
  mitkStreamlineTrackingTest.cpp
  mitkPeakExtractionTest.cpp
  mitkLocalFiberPlausibilityTest.cpp
  mitkFiberTransformationTest.cpp
  mitkFiberExtractionTest.cpp
  mitkFiberGenerationTest.cpp
)


text:
from __future__ import unicode_literals

from django.db import models, migrations
import datetime
from django.utils.timezone import utc

class Migration(migrations.Migration):

    dependencies = [
        ('billing', '0010_auto_20160517_2017'),
    ]

    operations = [
        migrations.AlterField(
            model_name='membership',
            name='date_end',
            field=models.DateTimeField(default=datetime.datetime(2016, 5, 17, 20, 18, 24, 477018, tzinfo=utc), verbose_name=b'End Date'),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='membership',
            name='date_start',
            field=models.DateTimeField(default=datetime.datetime(2016, 5, 17, 20, 18, 24, 477078, tzinfo=utc), verbose_name=b'Start Date'),
            preserve_default=True,
        ),
    ]


text:
from django.contrib.auth.models import User
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from .models import ImagerProfile

@receiver(post_save, sender=User)
def create_profile_for_user(sender, **kwargs):
    """Add a related profile to user if needed."""
    instance = kwargs.get('instance')
    if not instance or kwargs.get('raw', False):
        return
    try:
        instance.profile
    except ImagerProfile.DoesNotExist:
        instance.profile = ImagerProfile()
        instance.profile.save()

@receiver(post_delete, sender=ImagerProfile)
def delete_user_for_profile(sender, **kwargs):
    """Delete a related photos when user is deleted."""
    instance = kwargs.get('instance')
    if not instance:
        return
    try:
        instance.user.delete()
    except User.DoesNotExist:
        pass


text:
'use strict';

var JSONSelect = require('jsonselect');
/* global -Promise */
var Promise = global.Promise || require('es6-promise').Promise;

var DATABASEURL = 'database.json';
var database = null;

/**
 * Retrieves the data of the presentations
 *
 * @returns {Promise}
 */
function getConference() {
   return new Promise(function(resolve, reject) {
      if (database) {
         resolve(database.conference);
         return;
      }

      var request = new XMLHttpRequest();
      request.open('GET', DATABASEURL);
      request.onload = function() {
         if (request.status >= 200 && request.status < 400) {
            database = JSON.parse(request.responseText);
            resolve(database.conference);
         } else {
            reject(Error('Data not found'));
         }
      };
      request.onerror = function() {
         reject(Error('Network error'));
      };
      request.send();
   });
}

/**
 * Tests if a given date string exists in the dates of the conference
 *
 * @param {string} date
 * @returns {Promise|!Promise.<RESULT>|*}
 */
function dateExists(date) {
   return getConference().then(function(conference) {
      var datesFound = Object.keys(conference).filter(function(currentDate) {
         return currentDate === date;
      });

      return datesFound.length > 0;
   });
}

/**
 * Retrieves the data about the conference
 *
 * @returns {Promise}
 */
function getAbout() {
   return new Promise(function(resolve, reject) {
      if (database) {
         resolve(database.about);
         return;
      }

      var request = new XMLHttpRequest();
      request.open('GET', DATABASEURL);
      request.onload = function() {
         if (request.status >= 200 && request.status < 400) {
            database = JSON.parse(request.responseText);
            resolve(database.about);
         } else {
            reject(Error('Data not found'));
         }
      };
      request.onerror = function() {
         reject(Error('Network error'));
      };
      request.send();
   });
}

/**
 * Searches a speaker based on the twitter handle provided
 *
 * @param {string} twitterHandle
 * @returns {Promise|!Promise.<RESULT>|*}
 */
function searchSpeaker(twitterHandle) {
   if (typeof twitterHandle !== 'string') {
      throw Error('The twitterHandle parameter must be a string');
   }

   return getConference().then(function(data) {
      try {
         return data ?
            JSONSelect.match('.speaker :has(.twitter:val("' + twitterHandle + '"))', database.conference)[0] :
            null;
      } catch(ex) {
         return null;
      }
   });
}

/**
 * Searches a talk based on the title provided
 *
 * @param {string} title
 * @returns {Promise|!Promise.<RESULT>|*}
 */
function searchTalk(title) {
   if (typeof title !== 'string') {
      throw Error('The title parameter must be a string');
   }

   return getConference().then(function(data) {
      try {
         return data ?
            JSONSelect.match(':has(.title:val("' + title + '"))', database.conference)[0] :
            null;
      } catch(ex) {
         return null;
      }
   });
}

/**
 * Converts a string representing a date into a string
 * more suitable to be used as a part of a URL
 *
 * @param {string} date
 * @returns {string}
 */
function dateStringToUrlDate(date) {
   return date === '' ? date : date.split('/').join('-');
}

/**
 * Converts a string containing a date in a format suitable
 * to be used as a part of a URL into a string containing a date
 *
 * @param {string} date
 * @returns {string}
 */
function urlDateToDateString(date) {
   return date === '' ? date : date.split('-').join('/');
}

var Utility = {
   getConference: getConference,
   dateExists: dateExists,
   getAbout: getAbout,
   searchSpeaker: searchSpeaker,
   searchTalk: searchTalk,
   dateStringToUrlDate: dateStringToUrlDate,
   urlDateToDateString: urlDateToDateString
};

module.exports = Utility;


text:
<form model="ecom2.settings">
    <field name="delivery_slot_discount"/>
    <newline/>
    <field name="delivery_max_days"/>
    <newline/>
    <field name="delivery_min_hours"/>
    <newline/>
    <field name="ecom_num_lots"/>
    <newline/>
    <field name="sale_lead_time_nostock"/>
    <newline/>
    <field name="work_time_start"/>
    <field name="work_time_end"/>
    <newline/>
    <field name="ecom_return_url"/>
    <related>
        <field name="extra_ship_addresses"/>
    </related>
</form>


text:
@implementation CGSkillMeleeZhuRen

- (instancetype)init
{
    self = [super initWithSID:CGSkillIdMeleeQiankun];
    if (self) {
        self.targetAvailable = CGSkillTargetAvailableEnemy;
        self.menualTargetAvailable = CGSkillTargetAvailableEnemy | CGSkillTargetAvailableFriend;
        self.effArea = CGSkillEffect1;
        self.name = @"诸刃";

        CGSkillBuffParam *p1 = [[CGSkillBuffParam alloc] init];
        p1.t = CGSkillBuffAtk;
        p1.a = 0;
        p1.k = 1.5;
        p1.duration = 1;
        p1.tarType = CGSkillBuffTargetScr;

        CGSkillBuffParam *p2 = [[CGSkillBuffParam alloc] init];
        p2.t = CGSkillBuffMeleeHitRat;
        p2.a = 0;
        p2.k = 0.5;
        p2.duration = 1;
        p1.tarType = CGSkillBuffSpr;

        self.buffParams = [NSMutableArray arrayWithObjects:p1, p2, nil];

    }
    return self;
}

- (float)damageK
{
    return (CGRandom(20) + 90) / 100.f;
}

- (BOOL)isHitSrc:(CGUnit *)src
             des:(CGUnit *)des
{
    return [self isHitSrc:src des:des];
}

@end


text:
#pragma once
#include <aws/appconfigdata/AppConfigData_EXPORTS.h>
#include <aws/appconfigdata/AppConfigDataRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace AppConfigData
{
namespace Model
{

  /**
   */
  class AWS_APPCONFIGDATA_API StartConfigurationSessionRequest : public AppConfigDataRequest
  {
  public:
    StartConfigurationSessionRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "StartConfigurationSession"; }

    Aws::String SerializePayload() const override;

    /**
     *
The application ID or the application name.

     */
    inline const Aws::String& GetApplicationIdentifier() const{ return m_applicationIdentifier; }

    /**
     *
The application ID or the application name.

     */
    inline bool ApplicationIdentifierHasBeenSet() const { return m_applicationIdentifierHasBeenSet; }

    /**
     *
The application ID or the application name.

     */
    inline void SetApplicationIdentifier(const Aws::String& value) { m_applicationIdentifierHasBeenSet = true; m_applicationIdentifier = value; }

    /**
     *
The application ID or the application name.

     */
    inline void SetApplicationIdentifier(Aws::String&& value) { m_applicationIdentifierHasBeenSet = true; m_applicationIdentifier = std::move(value); }

    /**
     *
The application ID or the application name.

     */
    inline void SetApplicationIdentifier(const char* value) { m_applicationIdentifierHasBeenSet = true; m_applicationIdentifier.assign(value); }

    /**
     *
The application ID or the application name.

     */
    inline StartConfigurationSessionRequest& WithApplicationIdentifier(const Aws::String& value) { SetApplicationIdentifier(value); return *this;}

    /**
     *
The application ID or the application name.

     */
    inline StartConfigurationSessionRequest& WithApplicationIdentifier(Aws::String&& value) { SetApplicationIdentifier(std::move(value)); return *this;}

    /**
     *
The application ID or the application name.

     */
    inline StartConfigurationSessionRequest& WithApplicationIdentifier(const char* value) { SetApplicationIdentifier(value); return *this;}

    /**
     *
The environment ID or the environment name.

     */
    inline const Aws::String& GetEnvironmentIdentifier() const{ return m_environmentIdentifier; }

    /**
     *
The environment ID or the environment name.

     */
    inline bool EnvironmentIdentifierHasBeenSet() const { return m_environmentIdentifierHasBeenSet; }

    /**
     *
The environment ID or the environment name.

     */
    inline void SetEnvironmentIdentifier(const Aws::String& value) { m_environmentIdentifierHasBeenSet = true; m_environmentIdentifier = value; }

    /**
     *
The environment ID or the environment name.

     */
    inline void SetEnvironmentIdentifier(Aws::String&& value) { m_environmentIdentifierHasBeenSet = true; m_environmentIdentifier = std::move(value); }

    /**
     *
The environment ID or the environment name.

     */
    inline void SetEnvironmentIdentifier(const char* value) { m_environmentIdentifierHasBeenSet = true; m_environmentIdentifier.assign(value); }

    /**
     *
The environment ID or the environment name.

     */
    inline StartConfigurationSessionRequest& WithEnvironmentIdentifier(const Aws::String& value) { SetEnvironmentIdentifier(value); return *this;}

    /**
     *
The environment ID or the environment name.

     */
    inline StartConfigurationSessionRequest& WithEnvironmentIdentifier(Aws::String&& value) { SetEnvironmentIdentifier(std::move(value)); return *this;}

    /**
     *
The environment ID or the environment name.

     */
    inline StartConfigurationSessionRequest& WithEnvironmentIdentifier(const char* value) { SetEnvironmentIdentifier(value); return *this;}

    /**
     *
The configuration profile ID or the configuration profile name.

     */
    inline const Aws::String& GetConfigurationProfileIdentifier() const{ return m_configurationProfileIdentifier; }

    /**
     *
The configuration profile ID or the configuration profile name.

     */
    inline bool ConfigurationProfileIdentifierHasBeenSet() const { return m_configurationProfileIdentifierHasBeenSet; }

    /**
     *
The configuration profile ID or the configuration profile name.

     */
    inline void SetConfigurationProfileIdentifier(const Aws::String& value) { m_configurationProfileIdentifierHasBeenSet = true; m_configurationProfileIdentifier = value; }

    /**
     *
The configuration profile ID or the configuration profile name.

     */
    inline void SetConfigurationProfileIdentifier(Aws::String&& value) { m_configurationProfileIdentifierHasBeenSet = true; m_configurationProfileIdentifier = std::move(value); }

    /**
     *
The configuration profile ID or the configuration profile name.

     */
    inline void SetConfigurationProfileIdentifier(const char* value) { m_configurationProfileIdentifierHasBeenSet = true; m_configurationProfileIdentifier.assign(value); }

    /**
     *
The configuration profile ID or the configuration profile name.

     */
    inline StartConfigurationSessionRequest& WithConfigurationProfileIdentifier(const Aws::String& value) { SetConfigurationProfileIdentifier(value); return *this;}

    /**
     *
The configuration profile ID or the configuration profile name.

     */
    inline StartConfigurationSessionRequest& WithConfigurationProfileIdentifier(Aws::String&& value) { SetConfigurationProfileIdentifier(std::move(value)); return *this;}

    /**
     *
The configuration profile ID or the configuration profile name.

     */
    inline StartConfigurationSessionRequest& WithConfigurationProfileIdentifier(const char* value) { SetConfigurationProfileIdentifier(value); return *this;}

    /**
     *
Sets a constraint on a session. If you specify a value of, for example, 60
     * seconds, then the client that established the session can't call
     * GetLatestConfiguration more frequently then every 60 seconds.

     */
    inline int GetRequiredMinimumPollIntervalInSeconds() const{ return m_requiredMinimumPollIntervalInSeconds; }

    /**
     *
Sets a constraint on a session. If you specify a value of, for example, 60
     * seconds, then the client that established the session can't call
     * GetLatestConfiguration more frequently then every 60 seconds.

     */
    inline bool RequiredMinimumPollIntervalInSecondsHasBeenSet() const { return m_requiredMinimumPollIntervalInSecondsHasBeenSet; }

    /**
     *
Sets a constraint on a session. If you specify a value of, for example, 60
     * seconds, then the client that established the session can't call
     * GetLatestConfiguration more frequently then every 60 seconds.

     */
    inline void SetRequiredMinimumPollIntervalInSeconds(int value) { m_requiredMinimumPollIntervalInSecondsHasBeenSet = true; m_requiredMinimumPollIntervalInSeconds = value; }

    /**
     *
Sets a constraint on a session. If you specify a value of, for example, 60
     * seconds, then the client that established the session can't call
     * GetLatestConfiguration more frequently then every 60 seconds.

     */
    inline StartConfigurationSessionRequest& WithRequiredMinimumPollIntervalInSeconds(int value) { SetRequiredMinimumPollIntervalInSeconds(value); return *this;}

  private:

    Aws::String m_applicationIdentifier;
    bool m_applicationIdentifierHasBeenSet = false;

    Aws::String m_environmentIdentifier;
    bool m_environmentIdentifierHasBeenSet = false;

    Aws::String m_configurationProfileIdentifier;
    bool m_configurationProfileIdentifierHasBeenSet = false;

    int m_requiredMinimumPollIntervalInSeconds;
    bool m_requiredMinimumPollIntervalInSecondsHasBeenSet = false;
  };

} // namespace Model
} // namespace AppConfigData
} // namespace Aws


text:
using System.Configuration;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Affecto.AuthenticationServer.Configuration.Tests
{
    [TestClass]
    public class IncompleteScopeConfigurationTests : ConfigurationTestsBase
    {
        [TestMethod]
        [ExpectedException(typeof(ConfigurationErrorsException))]
        public void ScopeNameCanNotBeEmpty()
        {
            SetupAuthenticationServerConfiguration("ScopeNameEmpty.config");
        }

        [TestMethod]
        [ExpectedException(typeof(ConfigurationErrorsException))]
        public void ScopeNameCanNotBeMissing()
        {
            SetupAuthenticationServerConfiguration("ScopeNameMissing.config");
        }

        [TestMethod]
        [ExpectedException(typeof(ConfigurationErrorsException))]
        public void ScopeDisplayNameCanNotBeEmpty()
        {
            SetupAuthenticationServerConfiguration("ScopeDisplayNameEmpty.config");
        }

        [TestMethod]
        [ExpectedException(typeof(ConfigurationErrorsException))]
        public void ScopeDisplayNameCanNotBeMissing()
        {
            SetupAuthenticationServerConfiguration("ScopeDisplayNameMissing.config");
        }

        [TestMethod]
        public void ScopeDoesNotIncludeAllClaimsForUserByDefault()
        {
            SetupAuthenticationServerConfiguration("ScopeDoesNotIncludeAllClaimsForUserByDefault.config");
            Assert.IsFalse(authenticationServerConfiguration.Scopes.Single().IncludeAllClaimsForUser);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

    <sectioninfo>
      <title>Empty document</title>
    </sectioninfo>
    <para>Just some text.</para>


text:
// WARNING: this file is generated and will be overwritten
// Generated on Mon May 12 2014 10:36:47 GMT-0700 (PDT)

// if you're checking out this file, you should check us out too.
// http://jobs.appcelerator.com

/**
 * JSC implementation for UIKit/UINavigationController
 */
@import JavaScriptCore;
@import UIKit;
#import <hyperloop.h>
#import <ti_coremotion_converters.h>
@import Foundation;
@import UIKit;

// export typdefs we use
typedef id (*Function_id__P__id__SEL______)(id,SEL,...);

// export methods we use
extern Class HyperloopJSValueRefToClass(JSContextRef,JSValueRef,JSValueRef*,bool*);
extern JSValueRef HyperloopClassToJSValueRef(JSContextRef,Class);
extern JSValueRef HyperloopNSArrayToJSValueRef(JSContextRef,NSArray *);
extern JSValueRef HyperloopNSMethodSignatureToJSValueRef(JSContextRef,NSMethodSignature *);
extern JSValueRef HyperloopNSSetToJSValueRef(JSContextRef,NSSet *);
extern JSValueRef HyperloopNSStringToJSValueRef(JSContextRef,NSString *);
extern JSValueRef HyperloopUIGestureRecognizerToJSValueRef(JSContextRef,UIGestureRecognizer *);
extern JSValueRef HyperloopUINavigationBarToJSValueRef(JSContextRef,UINavigationBar *);
extern JSValueRef HyperloopUINavigationControllerToJSValueRef(JSContextRef,UINavigationController *);
extern JSValueRef HyperloopUIToolbarToJSValueRef(JSContextRef,UIToolbar *);
extern JSValueRef HyperloopUIViewControllerToJSValueRef(JSContextRef,UIViewController *);
extern JSValueRef HyperloopboolToJSValueRef(JSContextRef,bool);
extern JSValueRef Hyperloopid_UINavigationControllerDelegate_ToJSValueRef(JSContextRef,id<UINavigationControllerDelegate>);
extern JSValueRef Hyperloopid__P__id__SEL______ToJSValueRef(JSContextRef,Function_id__P__id__SEL______);
extern JSValueRef HyperloopintToJSValueRef(JSContextRef,int);
extern NSArray * HyperloopJSValueRefToNSArray(JSContextRef,JSValueRef,JSValueRef*,bool*);
extern NSString * HyperloopJSValueRefToNSString(JSContextRef,JSValueRef,JSValueRef*,bool*);
extern SEL HyperloopJSValueRefToSEL(JSContextRef,JSValueRef,JSValueRef*,bool*);
extern UIViewController * HyperloopJSValueRefToUIViewController(JSContextRef,JSValueRef,JSValueRef*,bool*);
extern bool HyperloopJSValueRefTobool(JSContextRef,JSValueRef,JSValueRef*,bool*);
extern id HyperloopJSValueRefToid(JSContextRef,JSValueRef,JSValueRef*,bool*);
extern id<UINavigationControllerDelegate> HyperloopJSValueRefToid_UINavigationControllerDelegate_(JSContextRef,JSValueRef,JSValueRef*,bool*);
extern int HyperloopJSValueRefToint(JSContextRef,JSValueRef,JSValueRef*,bool*);
extern struct _NSZone * HyperloopJSValueRefTostruct__NSZone_P(JSContextRef,JSValueRef,JSValueRef*,bool*);


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;

namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
    internal abstract class AbstractVsTextViewFilter<TPackage, TLanguageService> : AbstractVsTextViewFilter, IVsTextViewFilter, IVsReadOnlyViewNotification
        where TPackage : AbstractPackage<TPackage, TLanguageService>
        where TLanguageService : AbstractLanguageService<TPackage, TLanguageService>
    {
        private readonly AbstractLanguageService<TPackage, TLanguageService> _languageService;

        protected AbstractVsTextViewFilter(
            AbstractLanguageService<TPackage, TLanguageService> languageService,
            IWpfTextView wpfTextView,
            IVsEditorAdaptersFactoryService editorAdaptersFactoryService,
            ICommandHandlerServiceFactory commandHandlerServiceFactory)
            : base(wpfTextView, commandHandlerServiceFactory, editorAdaptersFactoryService, languageService.SystemServiceProvider)
        {
            _languageService = languageService;
        }

        int IVsTextViewFilter.GetDataTipText(TextSpan[] pSpan, out string pbstrText)
        {
            try
            {
                return GetDataTipTextImpl(pSpan, out pbstrText);
            }
            catch (Exception e) when (FatalError.ReportWithoutCrash(e) && false)
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        protected virtual int GetDataTipTextImpl(TextSpan[] pSpan, out string pbstrText)
        {
            pbstrText = null;

            var debugInfo = _languageService.LanguageDebugInfo;
            if (debugInfo != null)
            {
                var subjectBuffer = WpfTextView.GetBufferContainingCaret();
                if (subjectBuffer == null)
                {
                    return VSConstants.E_FAIL;
                }

                var vsBuffer = EditorAdaptersFactory.GetBufferAdapter(subjectBuffer);

                // TODO: broken in REPL
                if (vsBuffer == null)
                {
                    return VSConstants.E_FAIL;
                }

                return debugInfo.GetDataTipText(vsBuffer, pSpan, pbstrText);
            }

            return VSConstants.E_FAIL;
        }

        int IVsTextViewFilter.GetPairExtents(int iLine, int iIndex, TextSpan[] pSpan)
        {
            try
            {
                int result = VSConstants.S_OK;
                _languageService.Package.ComponentModel.GetService<IWaitIndicator>().Wait(
                    "Intellisense",
                    allowCancel: true,
                    action: c => result = GetPairExtentsWorker(iLine, iIndex, pSpan, c.CancellationToken));

                return result;
            }
            catch (Exception e) when (FatalError.ReportWithoutCrash(e) && false)
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        private int GetPairExtentsWorker(int iLine, int iIndex, TextSpan[] pSpan, CancellationToken cancellationToken)
        {
            var braceMatcher = _languageService.Package.ComponentModel.GetService<IBraceMatchingService>();
            return GetPairExtentsWorker(
                WpfTextView,
                _languageService.Workspace,
                braceMatcher,
                iLine,
                iIndex,
                pSpan,
                (VSConstants.VSStd2KCmdID)this.CurrentlyExecutingCommand == VSConstants.VSStd2KCmdID.GOTOBRACE_EXT,
                cancellationToken);
        }

        int IVsTextViewFilter.GetWordExtent(int iLine, int iIndex, uint dwFlags, TextSpan[] pSpan)
            => VSConstants.E_NOTIMPL;

        #region Edit and Continue

        int IVsReadOnlyViewNotification.OnDisabledEditingCommand(ref Guid pguidCmdGuid, uint dwCmdId)
        {
            var container = GetSubjectBufferContainingCaret().AsTextContainer();
            if (!CodeAnalysis.Workspace.TryGetWorkspace(container, out var workspace))
            {
                return VSConstants.S_OK;
            }

            var vsWorkspace = workspace as VisualStudioWorkspaceImpl;
            if (vsWorkspace == null)
            {
                return VSConstants.S_OK;
            }

            foreach (var documentId in vsWorkspace.GetRelatedDocumentIds(container))
            {
                var hostProject = vsWorkspace.GetHostProject(documentId.ProjectId) as AbstractProject;
                if (hostProject?.EditAndContinueImplOpt != null)
                {
                    if (hostProject.EditAndContinueImplOpt.OnEdit(documentId))
                    {
                        break;
                    }
                }
            }

            return VSConstants.S_OK;
        }

        #endregion
    }
}


text:
class Business:
    def __init__(self, name, address, rating, rating_count, location):
        self.name = name
        self.address = address
        self.rating = rating
        self.rating_count = rating_count
        self.bayesian = 0.0
        self.source_count = 1
        self.location = location


text: module.exports = require('./bundle').pluginSyntaxJsx()


text:
#ifndef ZBE_JSON_GRAPHICS_JSONGRAPHICSLOADERS_H_
#define ZBE_JSON_GRAPHICS_JSONGRAPHICSLOADERS_H_

#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>

#include <nlohmann/json.hpp>

#include "ZBE/core/tools/containers/RsrcDictionary.h"
#include "ZBE/core/tools/containers/RsrcStore.h"
#include "ZBE/core/tools/graphics/SpriteSheet.h"
#include "ZBE/core/system/SysError.h"
#include "ZBE/core/system/SysIdGenerator.h"

#include "ZBE/graphics/MultiSpriteSheet.h"
#include "ZBE/resources/contextnames.h"
#include "ZBE/resources/definitions.h"

#include "ZBE/core/system/system.h"

#include "ZBE/SDL/OGL/SDLOGLWindow.h"
#include "ZBE/OGL/graphics/OGLGraphics.h"
#include "ZBE/OGL/graphics/OGLModelSheet.h"
#include "ZBE/OGL/graphics/implementations/SimpleOGLModelSheet.h"

namespace zbe {
namespace JSONGraphicsLoaders{

//class ZBEAPI JSONGraphicsLoaders {
//public:
//  using json = nlohmann::json;
//
//  static JSONGraphicsLoaders& getInstance() {
//    static JSONGraphicsLoaders instance;
//    return instance;
//  }

  ZBEAPI ImgDef JSONImgDefLoad(nlohmann::json j, uint64_t graphicsId);

  ZBEAPI void JSONImgDefFileLoad(std::istream& is, uint64_t graphicsId, RsrcStore<ImgDef>& rsrcImgDef, NameRsrcDictionary& nrd);

  ZBEAPI SprtDef JSONSprtDefLoad(nlohmann::json j, RsrcStore<ImgDef>& rsrcImgDef, NameRsrcDictionary& nrd);

  ZBEAPI void JSONMultiSpriteSheetFileLoad(std::istream& is, RsrcStore<zbe::SpriteSheet<uint64_t, int64_t, double, Vector2D, Vector2D> >& rsrcAnimSprt, NameRsrcDictionary& nrd, RsrcStore<zbe::OGLModelSheet<uint64_t, double, double, Vector3D, Vector3D> >& rsrcModelSheet, RsrcStore<ImgDef>& rsrcImgDef);

  ZBEAPI void JSONSimpleModelSheetFileLoad(std::istream& is, std::shared_ptr<SDLOGLWindow> window, RsrcStore<zbe::SpriteSheet<uint64_t, int64_t, double, Vector2D, Vector2D> >& rsrcAnimSprt, NameRsrcDictionary& nrd, RsrcStore<zbe::OGLModelSheet<uint64_t, double, double, Vector3D, Vector3D> >& rsrcModelSheet, RsrcStore<OGLGraphics> &graphicsStore);

  ZBEAPI void JSONSpriteOGLModelSheetFileLoad(std::istream& is, std::shared_ptr<SDLOGLWindow> window, RsrcStore<OGLModelSheet<uint64_t, Vector2D, Vector2D>>& rsrcModelSheet, NameRsrcDictionary& nrd, RsrcStore<ImgDef>& rsrcImgDef);

  ZBEAPI void JSONGLSLProgramFileLoad(std::istream& is, std::shared_ptr<SDLOGLWindow> window, RsrcDictionary<uint64_t>& uintStore);

// private:
//  JSONGraphicsLoaders() {}

//  RsrcStore<zbe::SpriteSheet<uint64_t, int64_t, double, Vector2D, Vector2D> >& rsrcAnimSprt = RsrcStore<zbe::SpriteSheet<uint64_t, int64_t, double, Vector2D, Vector2D> >::getInstance();
//  RsrcStore<ImgDef>& rsrcImgDef = RsrcStore<ImgDef>::getInstance();
//  NameRsrcDictionary& nrd = NameRsrcDictionary::getInstance();
//  RsrcDictionary<uint64_t>& uintStore = RsrcDictionary<uint64_t>::getInstance();
//  RsrcStore<int>& rsrcModelSheet = RsrcStore<int>::getInstance();
  //RsrcStore<zbe::OGLModelSheet<uint64_t, double, double, Vector3D, Vector3D> >& rsrcModelSheet = RsrcStore<zbe::OGLModelSheet<uint64_t, double, double, Vector3D, Vector3D> >::getInstance();
//};
}  // namespace JSONGraphicsLoaders
}  // namespace zbe

#endif  // ZBE_JSON_GRAPHICS_JSONGRAPHICSLOADERS_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@color/materialize_primary_dark"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:srcCompat="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Flight Duty Tracker"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline" />

</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Dapper.FluentMap.Utils;

namespace Dapper.FluentMap.Mapping
{
    /// <summary>
    /// Represents a non-typed mapping of an entity.
    /// </summary>
    public interface IEntityMap
    {
        /// <summary>
        /// Gets the collection of mapped properties.
        /// </summary>
        IList<IPropertyMap> PropertyMaps { get; }
    }

    /// <summary>
    /// Represents a typed mapping of an entity.
    /// This serves as a marker interface for generic type inference.
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity to configure the mapping for.</typeparam>
    public interface IEntityMap<TEntity> : IEntityMap
    {
    }

    /// <summary>
    /// Serves as the base class for all entity mapping implementations.
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <typeparam name="TPropertyMap">The type of the property mapping.</typeparam>
    public abstract class EntityMapBase<TEntity, TPropertyMap> : IEntityMap<TEntity>
        where TPropertyMap : IPropertyMap
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Dapper.FluentMap.Mapping.EntityMapBase"/> class.
        /// </summary>
        protected EntityMapBase()
        {
            PropertyMaps = new List<IPropertyMap>();
        }

        /// <summary>
        /// Gets the collection of mapped properties.
        /// </summary>
        public IList<IPropertyMap> PropertyMaps { get; private set; }

        /// <summary>
        /// Returns an instance of <typeparamref name="TPropertyMap"/> which can perform custom mapping
        /// for the specified property on <typeparamref name="TEntity"/>.
        /// </summary>
        /// <param name="expression">Expression to the property on <typeparamref name="TEntity"/>.</param>
        /// <returns>The created <see cref="T:Dapper.FluentMap.Mapping.PropertyMap"/> instance. This enables a fluent API.</returns>
        /// <exception cref="T:System.Exception">when a duplicate mapping is provided.</exception>
        protected TPropertyMap Map(Expression<Func<TEntity, object>> expression)
        {
            var info = (PropertyInfo)ReflectionHelper.GetMemberInfo(expression);
            var propertyMap = GetPropertyMap(info);
            ThrowIfDuplicateMapping(propertyMap);
            PropertyMaps.Add(propertyMap);
            return propertyMap;
        }

        /// <summary>
        /// When overridden in a derived class, gets the property mapping for the specified property.
        /// </summary>
        /// <param name="info">The <see cref="PropertyInfo"/> for the property.</param>
        /// <returns>An instance of <typeparamref name="TPropertyMap"/>.</returns>
        protected abstract TPropertyMap GetPropertyMap(PropertyInfo info);

        private void ThrowIfDuplicateMapping(IPropertyMap map)
        {
            if (PropertyMaps.Any(p => p.PropertyInfo.Name == map.PropertyInfo.Name))
            {
                throw new Exception(string.Format("Duplicate mapping detected. Property '{0}' is already mapped to column '{1}'.", map.PropertyInfo.Name, map.ColumnName));
            }
        }
    }

    /// <summary>
    /// Represents a typed mapping of an entity.
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity to configure the mapping for.</typeparam>
    public abstract class EntityMap<TEntity> : EntityMapBase<TEntity, PropertyMap>
        where TEntity : class
    {
        protected override PropertyMap GetPropertyMap(PropertyInfo info)
        {
            return new PropertyMap(info);
        }
    }
}


text:
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;

namespace Newtonsoft.Json.Converters
{
  /// <summary>
  /// Converts an ExpandoObject to and from JSON.
  /// </summary>
  public class ExpandoObjectConverter : JsonConverter
  {
    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
      // can write is set to false
    }

    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
    /// <param name="objectType">Type of the object.</param>
    /// <param name="existingValue">The existing value of object being read.</param>
    /// <param name="serializer">The calling serializer.</param>
    /// <returns>The object value.</returns>
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
      return ReadValue(reader);
    }

    private object ReadValue(JsonReader reader)
    {
      while (reader.TokenType == JsonToken.Comment)
      {
        if (!reader.Read())
          throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
      }

      switch (reader.TokenType)
      {
        case JsonToken.StartObject:
          return ReadObject(reader);
        case JsonToken.StartArray:
          return ReadList(reader);
        default:
          if (JsonReader.IsPrimitiveToken(reader.TokenType))
            return reader.Value;

          throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
      }
    }

    private object ReadList(JsonReader reader)
    {
      IList<object> list = new List<object>();

      while (reader.Read())
      {
        switch (reader.TokenType)
        {
          case JsonToken.Comment:
            break;
          default:
            object v = ReadValue(reader);

            list.Add(v);
            break;
          case JsonToken.EndArray:
            return list;
        }
      }

      throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
    }

    private object ReadObject(JsonReader reader)
    {
      IDictionary<string, object> expandoObject = new ExpandoObject();

      while (reader.Read())
      {
        switch (reader.TokenType)
        {
          case JsonToken.PropertyName:
            string propertyName = reader.Value.ToString();

            if (!reader.Read())
              throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");

            object v = ReadValue(reader);

            expandoObject[propertyName] = v;
            break;
          case JsonToken.Comment:
            break;
          case JsonToken.EndObject:
            return expandoObject;
        }
      }

      throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
    }

    /// <summary>
    /// Determines whether this instance can convert the specified object type.
    /// </summary>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>
    /// 	<c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
    /// </returns>
    public override bool CanConvert(Type objectType)
    {
      return (objectType == typeof (ExpandoObject));
    }

    /// <summary>
    /// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
    /// </summary>
    /// <value>
    /// 	<c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
    /// </value>
    public override bool CanWrite
    {
      get { return false; }
    }
  }
}

#endif


text:
package org.oep.core.dossiermgt.model.impl;

import com.liferay.portal.kernel.bean.AutoEscapeBeanHandler;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSON;
import com.liferay.portal.kernel.lar.StagedModelType;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ProxyUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.impl.BaseModelImpl;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.util.PortalUtil;

import com.liferay.portlet.expando.model.ExpandoBridge;
import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil;

import org.oep.core.dossiermgt.model.DocFile;
import org.oep.core.dossiermgt.model.DocFileModel;
import org.oep.core.dossiermgt.model.DocFileSoap;

import java.io.Serializable;

import java.sql.Types;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * The base model implementation for the DocFile service. Represents a row in the "oep_dossiermgt_docfile" database table, with each column mapped to a property of this class.
 *
 * <p>
 * This implementation and its corresponding interface {@link org.oep.core.dossiermgt.model.DocFileModel} exist only as a container for the default property accessors generated by ServiceBuilder. Helper methods and all application logic should be put in {@link DocFileImpl}.
 * </p>
 *
 * @author trungdk
 * @see DocFileImpl
 * @see org.oep.core.dossiermgt.model.DocFile
 * @see org.oep.core.dossiermgt.model.DocFileModel
 * @generated
 */
@JSON(strict = true)
public class DocFileModelImpl extends BaseModelImpl<DocFile>
	implements DocFileModel {
	/*
	 * NOTE FOR DEVELOPERS:
	 *
	 * Never modify or reference this class directly. All methods that expect a doc file model instance should use the {@link org.oep.core.dossiermgt.model.DocFile} interface instead.
	 */
	public static final String TABLE_NAME = "oep_dossiermgt_docfile";
	public static final Object[][] TABLE_COLUMNS = {
			{ "uuid_", Types.VARCHAR },
			{ "docFileId", Types.BIGINT },
			{ "userId", Types.BIGINT },
			{ "groupId", Types.BIGINT },
			{ "companyId", Types.BIGINT },
			{ "createDate", Types.TIMESTAMP },
			{ "modifiedDate", Types.TIMESTAMP },
			{ "dossierId", Types.BIGINT },
			{ "dossierDocId", Types.BIGINT },
			{ "docTemplateId", Types.BIGINT },
			{ "docFileVersionId", Types.BIGINT },
			{ "docFileName", Types.VARCHAR },
			{ "docFileType", Types.BIGINT },
			{ "verifyStatus", Types.INTEGER },
			{ "note", Types.VARCHAR },
			{ "approveBy", Types.VARCHAR },
			{ "approveDate", Types.TIMESTAMP },
			{ "premier", Types.INTEGER }
		};
	public static final String TABLE_SQL_CREATE = "create table oep_dossiermgt_docfile (uuid_ VARCHAR(75) null,docFileId LONG not null primary key,userId LONG,groupId LONG,companyId LONG,createDate DATE null,modifiedDate DATE null,dossierId LONG,dossierDocId LONG,docTemplateId LONG,docFileVersionId LONG,docFileName VARCHAR(100) null,docFileType LONG,verifyStatus INTEGER,note VARCHAR(200) null,approveBy VARCHAR(100) null,approveDate DATE null,premier INTEGER)";
	public static final String TABLE_SQL_DROP = "drop table oep_dossiermgt_docfile";
	public static final String ORDER_BY_JPQL = " ORDER BY docFile.docFileId ASC";
	public static final String ORDER_BY_SQL = " ORDER BY oep_dossiermgt_docfile.docFileId ASC";
	public static final String DATA_SOURCE = "liferayDataSource";
	public static final String SESSION_FACTORY = "liferaySessionFactory";
	public static final String TX_MANAGER = "liferayTransactionManager";
	public static final boolean ENTITY_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
				"value.object.entity.cache.enabled.org.oep.core.dossiermgt.model.DocFile"),
			true);
	public static final boolean FINDER_CACHE_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
				"value.object.finder.cache.enabled.org.oep.core.dossiermgt.model.DocFile"),
			true);
	public static final boolean COLUMN_BITMASK_ENABLED = GetterUtil.getBoolean(com.liferay.util.service.ServiceProps.get(
				"value.object.column.bitmask.enabled.org.oep.core.dossiermgt.model.DocFile"),
			true);
	public static long COMPANYID_COLUMN_BITMASK = 1L;
	public static long GROUPID_COLUMN_BITMASK = 2L;
	public static long UUID_COLUMN_BITMASK = 4L;
	public static long DOCFILEID_COLUMN_BITMASK = 8L;

	/**
	 * Converts the soap model instance into a normal model instance.
	 *
	 * @param soapModel the soap model instance to convert
	 * @return the normal model instance
	 */
	public static DocFile toModel(DocFileSoap soapModel) {
		if (soapModel == null) {
			return null;
		}

		DocFile model = new DocFileImpl();

		model.setUuid(soapModel.getUuid());
		model.setDocFileId(soapModel.getDocFileId());
		model.setUserId(soapModel.getUserId());
		model.setGroupId(soapModel.getGroupId());
		model.setCompanyId(soapModel.getCompanyId());
		model.setCreateDate(soapModel.getCreateDate());
		model.setModifiedDate(soapModel.getModifiedDate());
		model.setDossierId(soapModel.getDossierId());
		model.setDossierDocId(soapModel.getDossierDocId());
		model.setDocTemplateId(soapModel.getDocTemplateId());
		model.setDocFileVersionId(soapModel.getDocFileVersionId());
		model.setDocFileName(soapModel.getDocFileName());
		model.setDocFileType(soapModel.getDocFileType());
		model.setVerifyStatus(soapModel.getVerifyStatus());
		model.setNote(soapModel.getNote());
		model.setApproveBy(soapModel.getApproveBy());
		model.setApproveDate(soapModel.getApproveDate());
		model.setPremier(soapModel.getPremier());

		return model;
	}

	/**
	 * Converts the soap model instances into normal model instances.
	 *
	 * @param soapModels the soap model instances to convert
	 * @return the normal model instances
	 */
	public static List<DocFile> toModels(DocFileSoap[] soapModels) {
		if (soapModels == null) {
			return null;
		}

		List<DocFile> models = new ArrayList<DocFile>(soapModels.length);

		for (DocFileSoap soapModel : soapModels) {
			models.add(toModel(soapModel));
		}

		return models;
	}

	public static final long LOCK_EXPIRATION_TIME = GetterUtil.getLong(com.liferay.util.service.ServiceProps.get(
				"lock.expiration.time.org.oep.core.dossiermgt.model.DocFile"));

	public DocFileModelImpl() {
	}

	@Override
	public long getPrimaryKey() {
		return _docFileId;
	}

	@Override
	public void setPrimaryKey(long primaryKey) {
		setDocFileId(primaryKey);
	}

	@Override
	public Serializable getPrimaryKeyObj() {
		return _docFileId;
	}

	@Override
	public void setPrimaryKeyObj(Serializable primaryKeyObj) {
		setPrimaryKey(((Long)primaryKeyObj).longValue());
	}

	@Override
	public Class<?> getModelClass() {
		return DocFile.class;
	}

	@Override
	public String getModelClassName() {
		return DocFile.class.getName();
	}

	@Override
	public Map<String, Object> getModelAttributes() {
		Map<String, Object> attributes = new HashMap<String, Object>();

		attributes.put("uuid", getUuid());
		attributes.put("docFileId", getDocFileId());
		attributes.put("userId", getUserId());
		attributes.put("groupId", getGroupId());
		attributes.put("companyId", getCompanyId());
		attributes.put("createDate", getCreateDate());
		attributes.put("modifiedDate", getModifiedDate());
		attributes.put("dossierId", getDossierId());
		attributes.put("dossierDocId", getDossierDocId());
		attributes.put("docTemplateId", getDocTemplateId());
		attributes.put("docFileVersionId", getDocFileVersionId());
		attributes.put("docFileName", getDocFileName());
		attributes.put("docFileType", getDocFileType());
		attributes.put("verifyStatus", getVerifyStatus());
		attributes.put("note", getNote());
		attributes.put("approveBy", getApproveBy());
		attributes.put("approveDate", getApproveDate());
		attributes.put("premier", getPremier());

		return attributes;
	}

	@Override
	public void setModelAttributes(Map<String, Object> attributes) {
		String uuid = (String)attributes.get("uuid");

		if (uuid != null) {
			setUuid(uuid);
		}

		Long docFileId = (Long)attributes.get("docFileId");

		if (docFileId != null) {
			setDocFileId(docFileId);
		}

		Long userId = (Long)attributes.get("userId");

		if (userId != null) {
			setUserId(userId);
		}

		Long groupId = (Long)attributes.get("groupId");

		if (groupId != null) {
			setGroupId(groupId);
		}

		Long companyId = (Long)attributes.get("companyId");

		if (companyId != null) {
			setCompanyId(companyId);
		}

		Date createDate = (Date)attributes.get("createDate");

		if (createDate != null) {
			setCreateDate(createDate);
		}

		Date modifiedDate = (Date)attributes.get("modifiedDate");

		if (modifiedDate != null) {
			setModifiedDate(modifiedDate);
		}

		Long dossierId = (Long)attributes.get("dossierId");

		if (dossierId != null) {
			setDossierId(dossierId);
		}

		Long dossierDocId = (Long)attributes.get("dossierDocId");

		if (dossierDocId != null) {
			setDossierDocId(dossierDocId);
		}

		Long docTemplateId = (Long)attributes.get("docTemplateId");

		if (docTemplateId != null) {
			setDocTemplateId(docTemplateId);
		}

		Long docFileVersionId = (Long)attributes.get("docFileVersionId");

		if (docFileVersionId != null) {
			setDocFileVersionId(docFileVersionId);
		}

		String docFileName = (String)attributes.get("docFileName");

		if (docFileName != null) {
			setDocFileName(docFileName);
		}

		Long docFileType = (Long)attributes.get("docFileType");

		if (docFileType != null) {
			setDocFileType(docFileType);
		}

		Integer verifyStatus = (Integer)attributes.get("verifyStatus");

		if (verifyStatus != null) {
			setVerifyStatus(verifyStatus);
		}

		String note = (String)attributes.get("note");

		if (note != null) {
			setNote(note);
		}

		String approveBy = (String)attributes.get("approveBy");

		if (approveBy != null) {
			setApproveBy(approveBy);
		}

		Date approveDate = (Date)attributes.get("approveDate");

		if (approveDate != null) {
			setApproveDate(approveDate);
		}

		Integer premier = (Integer)attributes.get("premier");

		if (premier != null) {
			setPremier(premier);
		}
	}

	@JSON
	@Override
	public String getUuid() {
		if (_uuid == null) {
			return StringPool.BLANK;
		}
		else {
			return _uuid;
		}
	}

	@Override
	public void setUuid(String uuid) {
		if (_originalUuid == null) {
			_originalUuid = _uuid;
		}

		_uuid = uuid;
	}

	public String getOriginalUuid() {
		return GetterUtil.getString(_originalUuid);
	}

	@JSON
	@Override
	public long getDocFileId() {
		return _docFileId;
	}

	@Override
	public void setDocFileId(long docFileId) {
		_docFileId = docFileId;
	}

	@JSON
	@Override
	public long getUserId() {
		return _userId;
	}

	@Override
	public void setUserId(long userId) {
		_userId = userId;
	}

	@Override
	public String getUserUuid() throws SystemException {
		return PortalUtil.getUserValue(getUserId(), "uuid", _userUuid);
	}

	@Override
	public void setUserUuid(String userUuid) {
		_userUuid = userUuid;
	}

	@JSON
	@Override
	public long getGroupId() {
		return _groupId;
	}

	@Override
	public void setGroupId(long groupId) {
		_columnBitmask |= GROUPID_COLUMN_BITMASK;

		if (!_setOriginalGroupId) {
			_setOriginalGroupId = true;

			_originalGroupId = _groupId;
		}

		_groupId = groupId;
	}

	public long getOriginalGroupId() {
		return _originalGroupId;
	}

	@JSON
	@Override
	public long getCompanyId() {
		return _companyId;
	}

	@Override
	public void setCompanyId(long companyId) {
		_columnBitmask |= COMPANYID_COLUMN_BITMASK;

		if (!_setOriginalCompanyId) {
			_setOriginalCompanyId = true;

			_originalCompanyId = _companyId;
		}

		_companyId = companyId;
	}

	public long getOriginalCompanyId() {
		return _originalCompanyId;
	}

	@JSON
	@Override
	public Date getCreateDate() {
		return _createDate;
	}

	@Override
	public void setCreateDate(Date createDate) {
		_createDate = createDate;
	}

	@JSON
	@Override
	public Date getModifiedDate() {
		return _modifiedDate;
	}

	@Override
	public void setModifiedDate(Date modifiedDate) {
		_modifiedDate = modifiedDate;
	}

	@JSON
	@Override
	public long getDossierId() {
		return _dossierId;
	}

	@Override
	public void setDossierId(long dossierId) {
		_dossierId = dossierId;
	}

	@JSON
	@Override
	public long getDossierDocId() {
		return _dossierDocId;
	}

	@Override
	public void setDossierDocId(long dossierDocId) {
		_dossierDocId = dossierDocId;
	}

	@JSON
	@Override
	public long getDocTemplateId() {
		return _docTemplateId;
	}

	@Override
	public void setDocTemplateId(long docTemplateId) {
		_docTemplateId = docTemplateId;
	}

	@JSON
	@Override
	public long getDocFileVersionId() {
		return _docFileVersionId;
	}

	@Override
	public void setDocFileVersionId(long docFileVersionId) {
		_docFileVersionId = docFileVersionId;
	}

	@JSON
	@Override
	public String getDocFileName() {
		if (_docFileName == null) {
			return StringPool.BLANK;
		}
		else {
			return _docFileName;
		}
	}

	@Override
	public void setDocFileName(String docFileName) {
		_docFileName = docFileName;
	}

	@JSON
	@Override
	public long getDocFileType() {
		return _docFileType;
	}

	@Override
	public void setDocFileType(long docFileType) {
		_docFileType = docFileType;
	}

	@JSON
	@Override
	public int getVerifyStatus() {
		return _verifyStatus;
	}

	@Override
	public void setVerifyStatus(int verifyStatus) {
		_verifyStatus = verifyStatus;
	}

	@JSON
	@Override
	public String getNote() {
		if (_note == null) {
			return StringPool.BLANK;
		}
		else {
			return _note;
		}
	}

	@Override
	public void setNote(String note) {
		_note = note;
	}

	@JSON
	@Override
	public String getApproveBy() {
		if (_approveBy == null) {
			return StringPool.BLANK;
		}
		else {
			return _approveBy;
		}
	}

	@Override
	public void setApproveBy(String approveBy) {
		_approveBy = approveBy;
	}

	@JSON
	@Override
	public Date getApproveDate() {
		return _approveDate;
	}

	@Override
	public void setApproveDate(Date approveDate) {
		_approveDate = approveDate;
	}

	@JSON
	@Override
	public int getPremier() {
		return _premier;
	}

	@Override
	public void setPremier(int premier) {
		_premier = premier;
	}

	@Override
	public StagedModelType getStagedModelType() {
		return new StagedModelType(PortalUtil.getClassNameId(
				DocFile.class.getName()));
	}

	public long getColumnBitmask() {
		return _columnBitmask;
	}

	@Override
	public ExpandoBridge getExpandoBridge() {
		return ExpandoBridgeFactoryUtil.getExpandoBridge(getCompanyId(),
			DocFile.class.getName(), getPrimaryKey());
	}

	@Override
	public void setExpandoBridgeAttributes(ServiceContext serviceContext) {
		ExpandoBridge expandoBridge = getExpandoBridge();

		expandoBridge.setAttributes(serviceContext);
	}

	@Override
	public DocFile toEscapedModel() {
		if (_escapedModel == null) {
			_escapedModel = (DocFile)ProxyUtil.newProxyInstance(_classLoader,
					_escapedModelInterfaces, new AutoEscapeBeanHandler(this));
		}

		return _escapedModel;
	}

	@Override
	public Object clone() {
		DocFileImpl docFileImpl = new DocFileImpl();

		docFileImpl.setUuid(getUuid());
		docFileImpl.setDocFileId(getDocFileId());
		docFileImpl.setUserId(getUserId());
		docFileImpl.setGroupId(getGroupId());
		docFileImpl.setCompanyId(getCompanyId());
		docFileImpl.setCreateDate(getCreateDate());
		docFileImpl.setModifiedDate(getModifiedDate());
		docFileImpl.setDossierId(getDossierId());
		docFileImpl.setDossierDocId(getDossierDocId());
		docFileImpl.setDocTemplateId(getDocTemplateId());
		docFileImpl.setDocFileVersionId(getDocFileVersionId());
		docFileImpl.setDocFileName(getDocFileName());
		docFileImpl.setDocFileType(getDocFileType());
		docFileImpl.setVerifyStatus(getVerifyStatus());
		docFileImpl.setNote(getNote());
		docFileImpl.setApproveBy(getApproveBy());
		docFileImpl.setApproveDate(getApproveDate());
		docFileImpl.setPremier(getPremier());

		docFileImpl.resetOriginalValues();

		return docFileImpl;
	}

	@Override
	public int compareTo(DocFile docFile) {
		long primaryKey = docFile.getPrimaryKey();

		if (getPrimaryKey() < primaryKey) {
			return -1;
		}
		else if (getPrimaryKey() > primaryKey) {
			return 1;
		}
		else {
			return 0;
		}
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}

		if (!(obj instanceof DocFile)) {
			return false;
		}

		DocFile docFile = (DocFile)obj;

		long primaryKey = docFile.getPrimaryKey();

		if (getPrimaryKey() == primaryKey) {
			return true;
		}
		else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		return (int)getPrimaryKey();
	}

	@Override
	public void resetOriginalValues() {
		DocFileModelImpl docFileModelImpl = this;

		docFileModelImpl._originalUuid = docFileModelImpl._uuid;

		docFileModelImpl._originalGroupId = docFileModelImpl._groupId;

		docFileModelImpl._setOriginalGroupId = false;

		docFileModelImpl._originalCompanyId = docFileModelImpl._companyId;

		docFileModelImpl._setOriginalCompanyId = false;

		docFileModelImpl._columnBitmask = 0;
	}

	@Override
	public CacheModel<DocFile> toCacheModel() {
		DocFileCacheModel docFileCacheModel = new DocFileCacheModel();

		docFileCacheModel.uuid = getUuid();

		String uuid = docFileCacheModel.uuid;

		if ((uuid != null) && (uuid.length() == 0)) {
			docFileCacheModel.uuid = null;
		}

		docFileCacheModel.docFileId = getDocFileId();

		docFileCacheModel.userId = getUserId();

		docFileCacheModel.groupId = getGroupId();

		docFileCacheModel.companyId = getCompanyId();

		Date createDate = getCreateDate();

		if (createDate != null) {
			docFileCacheModel.createDate = createDate.getTime();
		}
		else {
			docFileCacheModel.createDate = Long.MIN_VALUE;
		}

		Date modifiedDate = getModifiedDate();

		if (modifiedDate != null) {
			docFileCacheModel.modifiedDate = modifiedDate.getTime();
		}
		else {
			docFileCacheModel.modifiedDate = Long.MIN_VALUE;
		}

		docFileCacheModel.dossierId = getDossierId();

		docFileCacheModel.dossierDocId = getDossierDocId();

		docFileCacheModel.docTemplateId = getDocTemplateId();

		docFileCacheModel.docFileVersionId = getDocFileVersionId();

		docFileCacheModel.docFileName = getDocFileName();

		String docFileName = docFileCacheModel.docFileName;

		if ((docFileName != null) && (docFileName.length() == 0)) {
			docFileCacheModel.docFileName = null;
		}

		docFileCacheModel.docFileType = getDocFileType();

		docFileCacheModel.verifyStatus = getVerifyStatus();

		docFileCacheModel.note = getNote();

		String note = docFileCacheModel.note;

		if ((note != null) && (note.length() == 0)) {
			docFileCacheModel.note = null;
		}

		docFileCacheModel.approveBy = getApproveBy();

		String approveBy = docFileCacheModel.approveBy;

		if ((approveBy != null) && (approveBy.length() == 0)) {
			docFileCacheModel.approveBy = null;
		}

		Date approveDate = getApproveDate();

		if (approveDate != null) {
			docFileCacheModel.approveDate = approveDate.getTime();
		}
		else {
			docFileCacheModel.approveDate = Long.MIN_VALUE;
		}

		docFileCacheModel.premier = getPremier();

		return docFileCacheModel;
	}

	@Override
	public String toString() {
		StringBundler sb = new StringBundler(37);

		sb.append("{uuid=");
		sb.append(getUuid());
		sb.append(", docFileId=");
		sb.append(getDocFileId());
		sb.append(", userId=");
		sb.append(getUserId());
		sb.append(", groupId=");
		sb.append(getGroupId());
		sb.append(", companyId=");
		sb.append(getCompanyId());
		sb.append(", createDate=");
		sb.append(getCreateDate());
		sb.append(", modifiedDate=");
		sb.append(getModifiedDate());
		sb.append(", dossierId=");
		sb.append(getDossierId());
		sb.append(", dossierDocId=");
		sb.append(getDossierDocId());
		sb.append(", docTemplateId=");
		sb.append(getDocTemplateId());
		sb.append(", docFileVersionId=");
		sb.append(getDocFileVersionId());
		sb.append(", docFileName=");
		sb.append(getDocFileName());
		sb.append(", docFileType=");
		sb.append(getDocFileType());
		sb.append(", verifyStatus=");
		sb.append(getVerifyStatus());
		sb.append(", note=");
		sb.append(getNote());
		sb.append(", approveBy=");
		sb.append(getApproveBy());
		sb.append(", approveDate=");
		sb.append(getApproveDate());
		sb.append(", premier=");
		sb.append(getPremier());
		sb.append("}");

		return sb.toString();
	}

	@Override
	public String toXmlString() {
		StringBundler sb = new StringBundler(58);

		sb.append("<model><model-name>");
		sb.append("org.oep.core.dossiermgt.model.DocFile");
		sb.append("</model-name>");

		sb.append(
			"<column><column-name>uuid</column-name><column-value><![CDATA[");
		sb.append(getUuid());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>docFileId</column-name><column-value><![CDATA[");
		sb.append(getDocFileId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>userId</column-name><column-value><![CDATA[");
		sb.append(getUserId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>groupId</column-name><column-value><![CDATA[");
		sb.append(getGroupId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>companyId</column-name><column-value><![CDATA[");
		sb.append(getCompanyId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>createDate</column-name><column-value><![CDATA[");
		sb.append(getCreateDate());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>modifiedDate</column-name><column-value><![CDATA[");
		sb.append(getModifiedDate());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>dossierId</column-name><column-value><![CDATA[");
		sb.append(getDossierId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>dossierDocId</column-name><column-value><![CDATA[");
		sb.append(getDossierDocId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>docTemplateId</column-name><column-value><![CDATA[");
		sb.append(getDocTemplateId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>docFileVersionId</column-name><column-value><![CDATA[");
		sb.append(getDocFileVersionId());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>docFileName</column-name><column-value><![CDATA[");
		sb.append(getDocFileName());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>docFileType</column-name><column-value><![CDATA[");
		sb.append(getDocFileType());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>verifyStatus</column-name><column-value><![CDATA[");
		sb.append(getVerifyStatus());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>note</column-name><column-value><![CDATA[");
		sb.append(getNote());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>approveBy</column-name><column-value><![CDATA[");
		sb.append(getApproveBy());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>approveDate</column-name><column-value><![CDATA[");
		sb.append(getApproveDate());
		sb.append("]]></column-value></column>");
		sb.append(
			"<column><column-name>premier</column-name><column-value><![CDATA[");
		sb.append(getPremier());
		sb.append("]]></column-value></column>");

		sb.append("</model>");

		return sb.toString();
	}

	private static ClassLoader _classLoader = DocFile.class.getClassLoader();
	private static Class<?>[] _escapedModelInterfaces = new Class[] {
			DocFile.class
		};
	private String _uuid;
	private String _originalUuid;
	private long _docFileId;
	private long _userId;
	private String _userUuid;
	private long _groupId;
	private long _originalGroupId;
	private boolean _setOriginalGroupId;
	private long _companyId;
	private long _originalCompanyId;
	private boolean _setOriginalCompanyId;
	private Date _createDate;
	private Date _modifiedDate;
	private long _dossierId;
	private long _dossierDocId;
	private long _docTemplateId;
	private long _docFileVersionId;
	private String _docFileName;
	private long _docFileType;
	private int _verifyStatus;
	private String _note;
	private String _approveBy;
	private Date _approveDate;
	private int _premier;
	private long _columnBitmask;
	private DocFile _escapedModel;
}


text: <!-- Builtin view javascript is in the main index.html -->


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lucene.Net.Store.Azure
{
    internal class AzureLockFactory : LockFactory
    {
        private AzureDirectory _directory;
        private Directory _cacheDirectory;
        private string _rootFolder;
        private Dictionary<string, AzureLock> _locks = new Dictionary<string, AzureLock>();

        public AzureLockFactory(AzureDirectory directory, Directory cacheDirectory, string rootFolder)
        {
            _directory = directory;
            _cacheDirectory = cacheDirectory;
            _rootFolder = rootFolder;
        }

        public override void ClearLock(string name)
        {
            lock (_locks)
            {
                if (_locks.ContainsKey(name))
                {
                    _locks[name].BreakLock();
                }
            }
            _cacheDirectory.ClearLock(name);

        }

        public override Lock MakeLock(string name)
        {
            lock (_locks)
            {
                if (!_locks.ContainsKey(name))
                {
                    _locks.Add(name, new AzureLock(_rootFolder + name, _directory));
                }
                return _locks[name];
            }
        }
    }
}


text:
package peerhandoutpolicy

import (
	"fmt"
	"sort"

	"github.com/uber-go/tally"

	"github.com/uber/kraken/core"
)

type peerPriorityInfo struct {
	peer     *core.PeerInfo
	priority int
	label    string
}

// assignmentPolicy defines the policy for assigning priority to peers.
type assignmentPolicy interface {
	assignPriority(peer *core.PeerInfo) (priority int, label string)
}

// PriorityPolicy wraps an assignmentPolicy and uses it to sort lists of peers.
type PriorityPolicy struct {
	stats  tally.Scope
	policy assignmentPolicy
}

// NewPriorityPolicy returns a PriorityPolicy that assigns priorities using the given priority policy.
func NewPriorityPolicy(stats tally.Scope, priorityPolicy string) (*PriorityPolicy, error) {
	p := &PriorityPolicy{
		stats: stats.Tagged(map[string]string{
			"module":   "peerhandoutpolicy",
			"priority": priorityPolicy,
		}),
	}

	switch priorityPolicy {
	case _defaultPolicy:
		p.policy = newDefaultAssignmentPolicy()
	case _completenessPolicy:
		p.policy = newCompletenessAssignmentPolicy()
	default:
		return nil, fmt.Errorf("priority policy %q not found", priorityPolicy)
	}

	return p, nil
}

// SortPeers returns the given list of peers sorted by the priority assigned to them
// by the priorityPolicy. Excludes the source peer from the list.
func (p *PriorityPolicy) SortPeers(source *core.PeerInfo, peers []*core.PeerInfo) []*core.PeerInfo {

	peerPriorities := make([]*peerPriorityInfo, 0, len(peers))
	for k := 0; k < len(peers); k++ {
		if peers[k] != source {
			priority, label := p.policy.assignPriority(peers[k])
			peerPriorities = append(peerPriorities,
				&peerPriorityInfo{peers[k], priority, label})
		}
	}

	sort.Slice(peerPriorities, func(i, j int) bool {
		return peerPriorities[i].priority < peerPriorities[j].priority
	})

	priorityCounts := make(map[string]int)
	for k := 0; k < len(peerPriorities); k++ {
		p := peerPriorities[k]
		peers[k] = p.peer
		if _, ok := priorityCounts[p.label]; ok {
			priorityCounts[p.label]++
		} else {
			priorityCounts[p.label] = 1
		}
	}
	peers = peers[:len(peerPriorities)]

	for label, count := range priorityCounts {
		p.stats.Tagged(map[string]string{
			"label": label,
		}).Gauge("count").Update(float64(count))
	}

	return peers
}


text:
FactoryGirl.define do
  factory :user_feedback do

  end
end


text:
package org.apache.deltaspike.jsf.impl.listener.request;

import org.apache.deltaspike.core.spi.activation.Deactivatable;
import org.apache.deltaspike.jsf.impl.util.JsfUtils;

import javax.faces.context.ExternalContext;
import javax.faces.context.ExternalContextWrapper;
import java.io.IOException;
import javax.faces.context.FacesContext;
import org.apache.deltaspike.jsf.impl.util.ClientWindowHelper;
import org.apache.deltaspike.jsf.spi.scope.window.ClientWindow;

public class DeltaSpikeExternalContextWrapper extends ExternalContextWrapper implements Deactivatable
{
    private final ExternalContext wrapped;
    private final ClientWindow clientWindow;

    DeltaSpikeExternalContextWrapper(ExternalContext wrapped, ClientWindow clientWindow)
    {
        this.wrapped = wrapped;
        this.clientWindow = clientWindow;
    }

    @Override
    public void redirect(String url) throws IOException
    {
        FacesContext facesContext = FacesContext.getCurrentInstance();

        // skip if we are in initialRedirect mode because
        // save messages via flash scope will fail because the JSF lifecycle isn't initialized
        if (!ClientWindowHelper.isInitialRedirect(facesContext))
        {
            JsfUtils.saveFacesMessages(this.wrapped);
        }

        String targetURL = ClientWindowHelper.appendWindowId(facesContext, url, this.clientWindow);

        this.wrapped.redirect(targetURL);
    }

    @Override
    public ExternalContext getWrapped()
    {
        return wrapped;
    }
}


text:
import os

from keystone.openstack.common.db.sqlalchemy import migration

def _repo_path():
    return os.path.join(os.path.abspath(os.path.dirname(__file__)),
                        'migrate_repo')

def db_version_control(version=None):
    return migration.db_version_control(_repo_path(), version=version)

def db_sync(version=None):
    return migration.db_sync(_repo_path(), version=version)

def db_version(version=None):
    return migration.db_version(_repo_path(), version)


text:
FROM debian:jessie

MAINTAINER wencan <i@wencan.org>

RUN printf "deb http://httpredir.debian.org/debian jessie main contrib" > /etc/apt/sources.list
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        wget java-package build-essential libgl1-mesa-glx libgtk2.0-0 libxslt1.1 libxtst6 libxxf86vm1 \
    && rm -rf /var/lib/apt/lists/*

RUN groupadd java && useradd -r -g java java

ENV JAVA_VERSION 8u101

WORKDIR /tmp
RUN wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" \
        -O jdk-${JAVA_VERSION}-linux-x64.tar.gz \
        http://download.oracle.com/otn-pub/java/jdk/${JAVA_VERSION}-b13/jdk-${JAVA_VERSION}-linux-x64.tar.gz \
    && chmod +r jdk-${JAVA_VERSION}-linux-x64.tar.gz \
    && su java -c 'yes | fakeroot make-jpkg jdk-${JAVA_VERSION}-linux-x64.tar.gz' \
    && dpkg --install oracle-java8-jdk_${JAVA_VERSION}_amd64.deb \
    && rm jdk-${JAVA_VERSION}-linux-x64.tar.gz oracle-java8-jdk_${JAVA_VERSION}_amd64.deb

WORKDIR /

RUN ln -s /usr/lib/jvm/jdk-8-oracle-x64 /usr/lib/jvm/default-java
ENV JAVA_HOME /usr/lib/jvm/default-java

CMD ["java"]


text:
package org.apache.camel.impl.converter;

import org.apache.camel.spi.FactoryFinder;
import org.apache.camel.spi.Injector;
import org.apache.camel.spi.PackageScanClassResolver;

/**
 * Default implementation of a type converter registry used for
 * type converters in Camel.
 *

 * This implementation will load type converters up-front on startup.
 *
 * @version
 */
public class DefaultTypeConverter extends BaseTypeConverterRegistry {

    public DefaultTypeConverter(PackageScanClassResolver resolver, Injector injector, FactoryFinder factoryFinder) {
        super(resolver, injector, factoryFinder);
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();
        // load type converters up front
        loadTypeConverters();
    }

}


text:
use std::fmt::Write;
use syntax::ast;
use syntax::abi;
use syntax::parse::ParseSess;
use syntax::attr::AttrMetaMethods;

use ::Program;

pub fn translate(sess: &ParseSess, out: &mut String, prog: &mut Program, stages: &[&str], item: &ast::Item) {
    let diag = &sess.span_diagnostic;

    match item.vis {
        ast::Visibility::Inherited => (),
        _ => diag.span_err(item.span, "`pub` visibility has no meaning"),
    }

    match item.node {
        ast::ItemStatic(ref ty, muta, ref expr) => {
            match muta {
                ast::MutImmutable => (),
                _ => diag.span_err(item.span, "variables are implicitly mutable"),
            }

            ::var::translate(sess, out, &item.attrs[..], item.ident,
                             &**ty, Some(&**expr), false);
        }

        ast::ItemConst(ref ty, ref expr) => {
            write!(out, "const ").unwrap();
            ::var::translate(sess, out, &item.attrs[..], item.ident,
                             &**ty, Some(&**expr), false);
        }

        ast::ItemFn(ref decl, unsafety, abi, ref generics, ref block) => {
            let ast::FnDecl { ref inputs, ref output, variadic }
                = **decl;

            if variadic {
                diag.span_err(item.span, "can't translate variadic functions");
            }

            match unsafety {
                ast::Unsafety::Normal => (),
                _ => diag.span_err(item.span, "can't translate unsafe functions"),
            }

            match abi {
                abi::Abi::Rust => (),
                _ => diag.span_err(item.span, "can't translate non-default ABI"),
            }

            if generics.is_parameterized() {
                diag.span_err(item.span, "can't translate generic functions");
            }

            let output = match *output {
                ast::NoReturn(..) => {
                    diag.span_err(item.span, "function doesn't return");
                    return;
                }
                ast::DefaultReturn(..) => None,
                ast::Return(ref t) => Some(&**t),
            };

            for attr in item.attrs.iter() {
                let name = &*attr.name();
                match name {
                    "vertex" => {
                        if prog.vertex.is_none() {
                            prog.vertex = Some(String::new());
                        }
                        let vert: &mut String = prog.vertex.as_mut().unwrap();
                        ::shaders::translate(sess, vert, item.ident, "vertex", stages, &inputs[..], output, &**block);
                        return;
                    },
                    "fragment" => {
                        if prog.fragment.is_none() {
                            prog.fragment = Some(String::new());
                        }
                        let vert: &mut String = prog.fragment.as_mut().unwrap();
                        ::shaders::translate(sess, vert, item.ident, "fragment", stages, &inputs[..], output, &**block);
                        return;
                    },
                    "geometry" => {
                        if prog.geometry.is_none() {
                            prog.geometry = Some(String::new());
                        }
                        let sh: &mut String = prog.geometry.as_mut().unwrap();

                        if let Some(args) = attr.meta_item_list() {
                            for (i, arg) in args.iter().enumerate() {
                                match arg.node {
                                    ast::MetaWord(ref name) if i == 0 =>
                                        write!(sh, "layout({}) in;\n", name).unwrap(),
                                    ast::MetaNameValue(ref name, ref val) if i == 1 => {
                                        match val.node {
                                            ast::LitStr(ref val, _) =>
                                                write!(sh, "layout({}, max_vertices = {}) out;\n", name, val.parse::<u32>().unwrap()).unwrap(),
                                            _ => (),
                                        }
                                    },
                                    _ => (),
                                }
                            }
                        }

                        ::shaders::translate(sess, sh, item.ident, "geometry", stages, &inputs[..], output, &**block);
                        return;
                    },
                    _ => ()
                }
                //diag.span_err(attr.span, "no function attributes are supported");
            }

            ::fun::translate(sess, out, item.ident, &inputs[..], output, &**block);
        }

        ast::ItemMac(_) => {
            diag.span_bug(item.span, "macros should be gone by now");
        }

        ast::ItemStruct(ref def, ref generics) => {
            if generics.is_parameterized() {
                diag.span_err(item.span, "can't translate generic functions");
            }

            ::data::translate(sess, out, &item.attrs[..], item.ident, &def.fields[..]);
        }

        _ => {
            diag.span_err(item.span, "can't translate this sort of item");
        }
    }
}