text:
import copy
import datetime
import locale
import os
import pickle
import sys
from ._compat import PY2, string_types, pjoin, iteritems, to_bytes, exists
from ._load import portalocker
from .helpers.classes import SQLCustomType

class Migrator(object):
    def __init__(self, adapter):
        self.adapter = adapter

    @property
    def db(self):
        return self.adapter.db

    @property
    def dialect(self):
        return self.adapter.dialect

    @property
    def dbengine(self):
        return self.adapter.dbengine

    def create_table(self, table, migrate=True, fake_migrate=False,
                     polymodel=None):
        db = table._db
        fields = []
        # PostGIS geo fields are added after the table has been created
        postcreation_fields = []
        sql_fields = {}
        sql_fields_aux = {}
        TFK = {}
        tablename = table._tablename
        types = self.adapter.types
        for sortable, field in enumerate(table, start=1):
            field_name = field.name
            field_type = field.type
            if isinstance(field_type, SQLCustomType):
                ftype = field_type.native or field_type.type
            elif field_type.startswith(('reference', 'big-reference')):
                if field_type.startswith('reference'):
                    referenced = field_type[10:].strip()
                    type_name = 'reference'
                else:
                    referenced = field_type[14:].strip()
                    type_name = 'big-reference'

                if referenced == '.':
                    referenced = tablename
                constraint_name = self.dialect.constraint_name(
                    tablename, field_name)
                # if not '.' in referenced \
                #         and referenced != tablename \
                #         and hasattr(table,'_primarykey'):
                #     ftype = types['integer']
                #else:
                try:
                    rtable = db[referenced]
                    rfield = rtable._id
                    rfieldname = rfield.name
                    rtablename = referenced
                except (KeyError, ValueError, AttributeError) as e:
                    self.db.logger.debug('Error: %s' % e)
                    try:
                        rtablename, rfieldname = referenced.split('.')
                        rtable = db[rtablename]
                        rfield = rtable[rfieldname]
                    except Exception as e:
                        self.db.logger.debug('Error: %s' % e)
                        raise KeyError(
                            'Cannot resolve reference %s in %s definition' % (
                                referenced, table._tablename))

                # must be PK reference or unique
                if getattr(rtable, '_primarykey', None) and rfieldname in \
                   rtable._primarykey or rfield.unique:
                    ftype = types[rfield.type[:9]] % \
                        dict(length=rfield.length)
                    # multicolumn primary key reference?
                    if not rfield.unique and len(rtable._primarykey) > 1:
                        # then it has to be a table level FK
                        if rtablename not in TFK:
                            TFK[rtablename] = {}
                        TFK[rtablename][rfieldname] = field_name
                    else:
                        fk = rtable.sqlsafe + ' (' + rfield.sqlsafe_name + ')'
                        ftype = ftype + \
                            types['reference FK'] % dict(
                                # should be quoted
                                constraint_name=constraint_name,
                                foreign_key=fk,
                                table_name=table.sqlsafe,
                                field_name=field.sqlsafe_name,
                                on_delete_action=field.ondelete)
                else:
                    # make a guess here for circular references
                    if referenced in db:
                        id_fieldname = db[referenced]._id.sqlsafe_name
                    elif referenced == tablename:
                        id_fieldname = table._id.sqlsafe_name
                    else:  # make a guess
                        id_fieldname = self.dialect.quote('id')
                    #gotcha: the referenced table must be defined before
                    #the referencing one to be able to create the table
                    #Also if it's not recommended, we can still support
                    #references to tablenames without rname to make
                    #migrations and model relationship work also if tables
                    #are not defined in order
                    if referenced == tablename:
                        real_referenced = db[referenced].sqlsafe
                    else:
                        real_referenced = (
                            referenced in db and db[referenced].sqlsafe or
                            referenced)
                    rfield = db[referenced]._id
                    ftype_info = dict(
                        index_name=self.dialect.quote(field_name+'__idx'),
                        field_name=field.sqlsafe_name,
                        constraint_name=self.dialect.quote(constraint_name),
                        foreign_key='%s (%s)' % (
                            real_referenced, rfield.sqlsafe_name),
                        on_delete_action=field.ondelete)
                    ftype_info['null'] = ' NOT NULL' if field.notnull else \
                        self.dialect.allow_null
                    ftype_info['unique'] = ' UNIQUE' if field.unique else ''
                    ftype = types[type_name] % ftype_info
            elif field_type.startswith('list:reference'):
                ftype = types[field_type[:14]]
            elif field_type.startswith('decimal'):
                precision, scale = map(int, field_type[8:-1].split(','))
                ftype = types[field_type[:7]] % \
                    dict(precision=precision, scale=scale)
            elif field_type.startswith('geo'):
                if not hasattr(self.adapter, 'srid'):
                    raise RuntimeError('Adapter does not support geometry')
                srid = self.adapter.srid
                geotype, parms = field_type[:-1].split('(')
                if geotype not in types:
                    raise SyntaxError(
                        'Field: unknown field type: %s for %s' % (
                            field_type, field_name))
                ftype = types[geotype]
                if self.dbengine == 'postgres' and geotype == 'geometry':
                    if self.db._ignore_field_case is True:
                        field_name = field_name.lower()
                    # parameters: schema, srid, dimension
                    dimension = 2  # GIS.dimension ???
                    parms = parms.split(',')
                    if len(parms) == 3:
                        schema, srid, dimension = parms
                    elif len(parms) == 2:
                        schema, srid = parms
                    else:
                        schema = parms[0]
                    ftype = "SELECT AddGeometryColumn ('%%(schema)s', '%%(tablename)s', '%%(fieldname)s', %%(srid)s, '%s', %%(dimension)s);" % types[geotype]
                    ftype = ftype % dict(schema=schema,
                                         tablename=tablename,
                                         fieldname=field_name, srid=srid,
                                         dimension=dimension)
                    postcreation_fields.append(ftype)
            elif field_type not in types:
                raise SyntaxError('Field: unknown field type: %s for %s' % (
                    field_type, field_name))
            else:
                ftype = types[field_type] % {'length': field.length}

            if not field_type.startswith(('id', 'reference', 'big-reference')):
                if field.notnull:
                    ftype += ' NOT NULL'
                else:
                    ftype += self.dialect.allow_null
                if field.unique:
                    ftype += ' UNIQUE'
                if field.custom_qualifier:
                    ftype += ' %s' % field.custom_qualifier

            # add to list of fields
            sql_fields[field_name] = dict(
                length=field.length,
                unique=field.unique,
                notnull=field.notnull,
                sortable=sortable,
                type=str(field_type),
                sql=ftype)

            if field.notnull and field.default is not None:
                # Caveat: sql_fields and sql_fields_aux
                # differ for default values.
                # sql_fields is used to trigger migrations and sql_fields_aux
                # is used for create tables.
                # The reason is that we do not want to trigger
                # a migration simply because a default value changes.
                not_null = self.dialect.not_null(field.default, field_type)
                ftype = ftype.replace('NOT NULL', not_null)
            sql_fields_aux[field_name] = dict(sql=ftype)
            # Postgres - PostGIS:
            # geometry fields are added after the table has been created, not now
            if not (self.dbengine == 'postgres' and
               field_type.startswith('geom')):
                fields.append('%s %s' % (field.sqlsafe_name, ftype))
        other = ';'

        # backend-specific extensions to fields
        if self.dbengine == 'mysql':
            if not hasattr(table, "_primarykey"):
                fields.append('PRIMARY KEY (%s)' % (
                    self.dialect.quote(table._id.name)))
            engine = self.adapter.adapter_args.get('engine', 'InnoDB')
            other = ' ENGINE=%s CHARACTER SET utf8;' % engine

        fields = ',\n    '.join(fields)
        for rtablename in TFK:
            rfields = TFK[rtablename]
            pkeys = [
                self.dialect.quote(pk) for pk in db[rtablename]._primarykey]
            fkeys = [self.dialect.quote(rfields[k].name) for k in pkeys]
            fields = fields + ',\n    ' + \
                types['reference TFK'] % dict(
                    table_name=table.sqlsafe,
                    field_name=', '.join(fkeys),
                    foreign_table=table.sqlsafe,
                    foreign_key=', '.join(pkeys),
                    on_delete_action=field.ondelete)

        if getattr(table, '_primarykey', None):
            query = "CREATE TABLE %s(\n    %s,\n    %s) %s" % \
                (table.sqlsafe, fields,
                 self.dialect.primary_key(', '.join([
                    self.dialect.quote(pk)
                    for pk in table._primarykey])), other)
        else:
            query = "CREATE TABLE %s(\n    %s\n)%s" % \
                (table.sqlsafe, fields, other)

        uri = self.adapter.uri
        if uri.startswith('sqlite:///') \
                or uri.startswith('spatialite:///'):
            if PY2:
                path_encoding = sys.getfilesystemencoding() \
                    or locale.getdefaultlocale()[1] or 'utf8'
                dbpath = uri[9:uri.rfind('/')].decode(
                    'utf8').encode(path_encoding)
            else:
                dbpath = uri[9:uri.rfind('/')]
        else:
            dbpath = self.adapter.folder

        if not migrate:
            return query
        elif uri.startswith('sqlite:memory') or \
                uri.startswith('spatialite:memory'):
            table._dbt = None
        elif isinstance(migrate, string_types):
            table._dbt = pjoin(dbpath, migrate)
        else:
            table._dbt = pjoin(
                dbpath, '%s_%s.table' % (db._uri_hash, tablename))

        if not table._dbt or not self.file_exists(table._dbt):
            if table._dbt:
                self.log('timestamp: %s\n%s\n'
                         % (datetime.datetime.today().isoformat(),
                            query), table)
            if not fake_migrate:
                self.adapter.create_sequence_and_triggers(query, table)
                db.commit()
                # Postgres geom fields are added now,
                # after the table has been created
                for query in postcreation_fields:
                    self.adapter.execute(query)
                    db.commit()
            if table._dbt:
                tfile = self.file_open(table._dbt, 'wb')
                pickle.dump(sql_fields, tfile)
                self.file_close(tfile)
                if fake_migrate:
                    self.log('faked!\n', table)
                else:
                    self.log('success!\n', table)
        else:
            tfile = self.file_open(table._dbt, 'rb')
            try:
                sql_fields_old = pickle.load(tfile)
            except EOFError:
                self.file_close(tfile)
                raise RuntimeError('File %s appears corrupted' % table._dbt)
            self.file_close(tfile)
            if sql_fields != sql_fields_old:
                self.migrate_table(
                    table,
                    sql_fields, sql_fields_old,
                    sql_fields_aux, None,
                    fake_migrate=fake_migrate
                    )
        return query

    def _fix(self, item):
        k, v = item
        if not isinstance(v, dict):
            v = dict(type='unknown', sql=v)
        if self.db._ignore_field_case is not True:
            return k, v
        return k.lower(), v

    def migrate_table(self, table, sql_fields, sql_fields_old, sql_fields_aux,
                      logfile, fake_migrate=False):
        # logfile is deprecated (moved to adapter.log method)
        db = table._db
        db._migrated.append(table._tablename)
        tablename = table._tablename
        # make sure all field names are lower case to avoid
        # migrations because of case cahnge
        sql_fields = dict(map(self._fix, iteritems(sql_fields)))
        sql_fields_old = dict(map(self._fix, iteritems(sql_fields_old)))
        sql_fields_aux = dict(map(self._fix, iteritems(sql_fields_aux)))
        if db._debug:
            db.logger.debug('migrating %s to %s' % (
                sql_fields_old, sql_fields))

        keys = list(sql_fields.keys())
        for key in sql_fields_old:
            if key not in keys:
                keys.append(key)
        new_add = self.dialect.concat_add(tablename)

        metadata_change = False
        sql_fields_current = copy.copy(sql_fields_old)
        for key in keys:
            query = None
            if key not in sql_fields_old:
                sql_fields_current[key] = sql_fields[key]
                if self.dbengine in ('postgres',) and \
                   sql_fields[key]['type'].startswith('geometry'):
                    # 'sql' == ftype in sql
                    query = [sql_fields[key]['sql']]
                else:
                    query = ['ALTER TABLE %s ADD %s %s;' % (
                        table.sqlsafe, key,
                        sql_fields_aux[key]['sql'].replace(', ', new_add))]
                metadata_change = True
            elif self.dbengine in ('sqlite', 'spatialite'):
                if key in sql_fields:
                    sql_fields_current[key] = sql_fields[key]
                metadata_change = True
            elif key not in sql_fields:
                del sql_fields_current[key]
                ftype = sql_fields_old[key]['type']
                if self.dbengine == 'postgres' and \
                   ftype.startswith('geometry'):
                    geotype, parms = ftype[:-1].split('(')
                    schema = parms.split(',')[0]
                    query = ["SELECT DropGeometryColumn ('%(schema)s', \
                             '%(table)s', '%(field)s');" % dict(
                                schema=schema, table=tablename, field=key)]
                elif self.dbengine in ('firebird',):
                    query = ['ALTER TABLE %s DROP %s;' % (
                        self.dialect.quote(tablename),
                        self.dialect.quote(key))]
                else:
                    query = ['ALTER TABLE %s DROP COLUMN %s;' % (
                        self.dialect.quote(tablename),
                        self.dialect.quote(key))]
                metadata_change = True
            elif (
               sql_fields[key]['sql'] != sql_fields_old[key]['sql'] and not
               (key in table.fields and
                isinstance(table[key].type, SQLCustomType)) and not
               sql_fields[key]['type'].startswith('reference') and not
               sql_fields[key]['type'].startswith('double') and not
               sql_fields[key]['type'].startswith('id')):
                sql_fields_current[key] = sql_fields[key]
                t = tablename
                tt = sql_fields_aux[key]['sql'].replace(', ', new_add)
                if self.dbengine in ('firebird',):
                    drop_expr = 'ALTER TABLE %s DROP %s;'
                else:
                    drop_expr = 'ALTER TABLE %s DROP COLUMN %s;'
                key_tmp = key + '__tmp'
                query = [
                    'ALTER TABLE %s ADD %s %s;' % (
                        self.dialect.quote(t), self.dialect.quote(key_tmp),
                        tt),
                    'UPDATE %s SET %s=%s;' % (
                        self.dialect.quote(t), self.dialect.quote(key_tmp),
                        self.dialect.quote(key)),
                    drop_expr % (
                        self.dialect.quote(t), self.dialect.quote(key)),
                    'ALTER TABLE %s ADD %s %s;' % (
                        self.dialect.quote(t),
                        self.dialect.quote(key), tt),
                    'UPDATE %s SET %s=%s;' % (
                        self.dialect.quote(t), self.dialect.quote(key),
                        self.dialect.quote(key_tmp)),
                    drop_expr % (
                        self.dialect.quote(t), self.dialect.quote(key_tmp))
                ]
                metadata_change = True
            elif sql_fields[key]['type'] != sql_fields_old[key]['type']:
                sql_fields_current[key] = sql_fields[key]
                metadata_change = True

            if query:
                self.log(
                    'timestamp: %s\n' % datetime.datetime.today().isoformat(),
                    table)
                for sub_query in query:
                    self.log(sub_query + '\n', table)
                    if fake_migrate:
                        if db._adapter.commit_on_alter_table:
                            self.save_dbt(table, sql_fields_current)
                        self.log('faked!\n', table)
                    else:
                        self.adapter.execute(sub_query)
                        # Caveat: mysql, oracle and firebird
                        # do not allow multiple alter table
                        # in one transaction so we must commit
                        # partial transactions and
                        # update table._dbt after alter table.
                        if db._adapter.commit_on_alter_table:
                            db.commit()
                            self.save_dbt(table, sql_fields_current)
                            self.log('success!\n', table)

            elif metadata_change:
                self.save_dbt(table, sql_fields_current)

        if metadata_change and not (
           query and db._adapter.commit_on_alter_table):
            db.commit()
            self.save_dbt(table, sql_fields_current)
            self.log('success!\n', table)

    def save_dbt(self, table, sql_fields_current):
        tfile = self.file_open(table._dbt, 'wb')
        pickle.dump(sql_fields_current, tfile)
        self.file_close(tfile)

    def log(self, message, table=None):
        isabs = None
        logfilename = self.adapter.adapter_args.get('logfile', 'sql.log')
        writelog = bool(logfilename)
        if writelog:
            isabs = os.path.isabs(logfilename)
        if table and table._dbt and writelog and self.adapter.folder:
            if isabs:
                table._loggername = logfilename
            else:
                table._loggername = pjoin(self.adapter.folder, logfilename)
            logfile = self.file_open(table._loggername, 'ab')
            logfile.write(to_bytes(message))
            self.file_close(logfile)

    @staticmethod
    def file_open(filename, mode='rb', lock=True):
        #to be used ONLY for files that on GAE may not be on filesystem
        if lock:
            fileobj = portalocker.LockedFile(filename, mode)
        else:
            fileobj = open(filename, mode)
        return fileobj

    @staticmethod
    def file_close(fileobj):
        #to be used ONLY for files that on GAE may not be on filesystem
        if fileobj:
            fileobj.close()

    @staticmethod
    def file_delete(filename):
        os.unlink(filename)

    @staticmethod
    def file_exists(filename):
        #to be used ONLY for files that on GAE may not be on filesystem
        return exists(filename)


text:
package javax.mail.search;

import javax.mail.Message;
import javax.mail.MessagingException;

/**
 * @version $Rev$ $Date$
 */
public final class SizeTerm extends IntegerComparisonTerm {

	private static final long serialVersionUID = -2556219451005103709L;

    public SizeTerm(int comparison, int size) {
        super(comparison, size);
    }

    public boolean match(Message message) {
        try {
            return match(message.getSize());
        } catch (MessagingException e) {
            return false;
        }
    }

    public boolean equals(Object other) {
        if (this == other) return true;
        if (other instanceof SizeTerm == false) return false;
        return super.equals(other);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

// include_paths.php @generated by Composer

$vendorDir = dirname( dirname( __FILE__ ) );
$baseDir = dirname( $vendorDir );

return array(
    $baseDir.'/phpseclib',
    $vendorDir.'/phing/phing/classes',
);


text:
const tilebelt = require('tilebelt');

function polygonToBbox(polygon) {
  const ring = polygon.coordinates[0];

  const minX = ring[0][0];
  const minY = ring[0][1];
  const maxX = ring[2][0];
  const maxY = ring[2][1];

  return [minX, minY, maxX, maxY].join(',');
}

class TileifyAGS {
  constructor(url, urlParamConfig, pixelRatio) {
    this.url = url;

    this.urlParameters = {
      bboxSR: '4326',
      imageSR: '3857',
      f: 'image',
    };

    let tileSize = 256;

    if (pixelRatio) {
      tileSize *= pixelRatio;
    }

    this.urlParameters.size = encodeURIComponent(`${tileSize},${tileSize}`);

    if (urlParamConfig != null) {
      Object.entries(urlParamConfig).forEach(([key, value]) => {
        this.urlParameters[key] = value;
      });
    }
  }

  getTileUrl(x, y, z) {
    const tile = [x, y, z];
    const tileGeojson = tilebelt.tileToGeoJSON(tile);
    const polygon = tileGeojson.geometry;
    const bbox = polygonToBbox(polygon);

    let fullUrl = this.url;
    if (this.url.endsWith('ImageServer')) {
      fullUrl += "/exportImage?";
    } else {
      fullUrl += "/export?";
    }
    fullUrl += `&bbox=${encodeURIComponent(bbox)}`;

    Object.entries(this.urlParameters).forEach(([key, value]) => {
      fullUrl += `&${key}=${value}`;
    });

    return fullUrl;
  }
}

module.exports = TileifyAGS;


text:
// Copyright (c) 2014, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb;

/**
 * Config for rate limiter, which is used to control write rate of flush and
 * compaction.
 *
 * @see RateLimiterConfig
 */
public class GenericRateLimiterConfig extends RateLimiterConfig {
  private static final long DEFAULT_REFILL_PERIOD_MICROS = (100 * 1000);
  private static final int DEFAULT_FAIRNESS = 10;

  /**
   * GenericRateLimiterConfig constructor
   *
   * @param rateBytesPerSecond this is the only parameter you want to set
   *     most of the time. It controls the total write rate of compaction
   *     and flush in bytes per second. Currently, RocksDB does not enforce
   *     rate limit for anything other than flush and compaction, e.g. write to WAL.
   * @param refillPeriodMicros this controls how often tokens are refilled. For example,
   *     when rate_bytes_per_sec is set to 10MB/s and refill_period_us is set to
   *     100ms, then 1MB is refilled every 100ms internally. Larger value can lead to
   *     burstier writes while smaller value introduces more CPU overhead.
   *     The default should work for most cases.
   * @param fairness RateLimiter accepts high-pri requests and low-pri requests.
   *     A low-pri request is usually blocked in favor of hi-pri request. Currently,
   *     RocksDB assigns low-pri to request from compaction and high-pri to request
   *     from flush. Low-pri requests can get blocked if flush requests come in
   *     continuously. This fairness parameter grants low-pri requests permission by
   *     fairness chance even though high-pri requests exist to avoid starvation.
   *     You should be good by leaving it at default 10.
   */
  public GenericRateLimiterConfig(final long rateBytesPerSecond,
      final long refillPeriodMicros, final int fairness) {
    rateBytesPerSecond_ = rateBytesPerSecond;
    refillPeriodMicros_ = refillPeriodMicros;
    fairness_ = fairness;
  }

  /**
   * GenericRateLimiterConfig constructor
   *
   * @param rateBytesPerSecond this is the only parameter you want to set
   *     most of the time. It controls the total write rate of compaction
   *     and flush in bytes per second. Currently, RocksDB does not enforce
   *     rate limit for anything other than flush and compaction, e.g. write to WAL.
   */
  public GenericRateLimiterConfig(final long rateBytesPerSecond) {
    this(rateBytesPerSecond, DEFAULT_REFILL_PERIOD_MICROS, DEFAULT_FAIRNESS);
  }

  @Override protected long newRateLimiterHandle() {
    return newRateLimiterHandle(rateBytesPerSecond_, refillPeriodMicros_,
        fairness_);
  }

  private native long newRateLimiterHandle(long rateBytesPerSecond,
      long refillPeriodMicros, int fairness);
  private final long rateBytesPerSecond_;
  private final long refillPeriodMicros_;
  private final int fairness_;
}


text:
package calzone;

import calzone.model.CalzoneFinishedBuild;
import calzone.model.FinishedBuildStatus;
import jetbrains.buildServer.messages.Status;
import jetbrains.buildServer.serverSide.SBuild;
import jetbrains.buildServer.serverSide.SBuildServer;
import jetbrains.buildServer.serverSide.SBuildType;
import jetbrains.buildServer.serverSide.SFinishedBuild;

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

public class FinishedBuildMaker {
    private final SBuildServer buildServer;
    private final TimeFormatter timeFormatter;

    public FinishedBuildMaker(SBuildServer buildServer, TimeFormatter timeFormatter) {
        this.buildServer = buildServer;
        this.timeFormatter = timeFormatter;
    }

    public CalzoneFinishedBuild lastFinishedBuild(SBuildType sBuildType) {
        SBuild lastFinished = sBuildType.getLastChangesFinished();
        if (lastFinished == null) {
            return new CalzoneFinishedBuild(FinishedBuildStatus.none, formattedTimeSinceFirstFailure(sBuildType));
        }

        if (lastFinished.getBuildStatus().equals(Status.UNKNOWN)) {
            // need to dig deeper for last build status - most recent build probably cancelled
            Date latestCompletedStatusDate = null;
            List<SFinishedBuild> buildHistory = sBuildType.getHistory(null, false, false);
            for (SFinishedBuild finishedBuild : buildHistory) {
                Status status = finishedBuild.getBuildStatus();
                if (!status.equals(Status.UNKNOWN) && (latestCompletedStatusDate == null || finishedBuild.getStartDate().compareTo(latestCompletedStatusDate) > 0)) {
                    lastFinished = finishedBuild;
                    latestCompletedStatusDate = finishedBuild.getStartDate();
                }
            }
        }
        return new CalzoneFinishedBuild(FinishedBuildStatus.from(lastFinished.getStatusDescriptor()), formattedTimeSinceFirstFailure(sBuildType));
    }

    private String formattedTimeSinceFirstFailure(SBuildType sBuildType) {
        if (!sBuildType.getStatus().isFailed()) {
            return null;
        }

        SBuild lastGoodBuild = sBuildType.getLastChangesSuccessfullyFinished();

        if (lastGoodBuild == null) {
            return null;
        }

        List<SBuild> entriesSince = buildServer.getEntriesSince(lastGoodBuild, sBuildType);
        if (entriesSince.isEmpty()) {
            return null;
        }

        return timeFormatter.formatDateSince(entriesSince.get(entriesSince.size() - 2).getStartDate());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@android:id/background">
        <shape android:shape="rectangle" >
            <corners android:radius="5dp" />

            <gradient
                android:angle="270"
                android:endColor="@color/caldroid_white"
                android:startColor="@color/caldroid_black" />
        </shape>
    </item>
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape android:shape="rectangle" >
                <corners android:radius="5dp" />

                <gradient
                    android:angle="270"
                    android:endColor="@color/caldroid_white"
                    android:startColor="@color/caldroid_black" />
            </shape>
        </clip>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape android:shape="rectangle" >
                <corners android:radius="5dp" />

                <gradient
                    android:angle="0"
                    android:endColor="@color/green_light"
                    android:startColor="@color/caldroid_white" />
            </shape>
        </clip>
    </item>

</layer-list>


text:
namespace sfui
{

  class Popup : public Widget
  {
  public:
    WIDGET_DERIVED(Popup, Widget);
    Popup(WidgetWindow *TopWindow, optional<Theme*> theme = optional<Theme*>());
    virtual ~Popup() override;

    static shared_ptr Create(WidgetWindow *TopWindow, optional<Theme*> theme = optional<Theme*>());

    void Add(Widget::shared_ptr widget);
    virtual void Open();
    virtual void Close();

    virtual void InitDropShadow();

    virtual void Update() override;
    virtual void Render(sf::RenderTarget &Target) override;
    void SetStealsFocus(bool steals);

    virtual void SetPosition(const Vec2i &Position) override;
    virtual void SetSize(const Vec2i &Size) override;

    virtual bool HandleEvent(const sf::Event &event) override;

  protected:
    //virtual void MouseMoved() override;
    //virtual void MouseEntered() override;
    //virtual void MouseLeft() override;
    //virtual void MousePressed(bool left, bool right) override;
    //virtual void MouseReleased(bool left, bool right) override;

    DropShadow m_DropShadow;

    sf::RectangleShape DropShadowRect;
    sf::Texture dropShadowTexture;
    bool m_StealFocus = false;
    bool m_MoveToFront = true;
    bool m_IsOpen = false;
    Panel::shared_ptr m_Panel = nullptr;
    WidgetWindow *m_StealFocusFrom = nullptr;
  };

}

#endif // SFUI_POPUP_H


text:
package main

const sshGithubFormat string = "git@github.com:.+/%s.git"
const httpsGithubFormat string = "https://github.com/.+/%s.git"
const projectURLFormat string = "https://intranet.hbtn.io/projects/%d.json"
const myCurrentProjectsURL string = "https://intranet.hbtn.io/dashboards/my_current_projects.json"


text:
exports.notFound = function(req, res, next){
	res.status(404);
	res.render('not-found');
};

exports.serverError = function(error, req, res, next){
	res.status(500);
	res.render('server-erro', {error : error});
};


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Tests\Translator;

use PHPUnit\Framework\TestCase;
use Spiral\Translator\Config\TranslatorConfig;
use Symfony\Component\Translation\Dumper\DumperInterface;
use Symfony\Component\Translation\Dumper\PoFileDumper;
use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Translation\Loader\PhpFileLoader;

class ConfigTest extends TestCase
{
    public function testDefaultLocale(): void
    {
        $config = new TranslatorConfig([
            'locale' => 'ru'
        ]);

        $this->assertSame('ru', $config->getDefaultLocale());
    }

    public function testDefaultDomain(): void
    {
        $config = new TranslatorConfig([
            'locale' => 'ru'
        ]);

        $this->assertSame('messages', $config->getDefaultDomain());
    }

    public function testFallbackLocale(): void
    {
        $config = new TranslatorConfig([
            'fallbackLocale' => 'ru'
        ]);

        $this->assertSame('ru', $config->getFallbackLocale());
    }

    public function testRegisterMessages(): void
    {
        $config = new TranslatorConfig(['autoRegister' => true]);
        $this->assertTrue($config->isAutoRegisterMessages());

        $config = new TranslatorConfig(['autoRegister' => false]);
        $this->assertFalse($config->isAutoRegisterMessages());

        //Legacy
        $config = new TranslatorConfig(['registerMessages' => true]);
        $this->assertTrue($config->isAutoRegisterMessages());
    }

    public function testLocalesDirectory(): void
    {
        $config = new TranslatorConfig([
            'localesDirectory' => 'directory/'
        ]);

        $this->assertSame('directory/', $config->getLocalesDirectory());
    }

    public function testLocaleDirectory(): void
    {
        $config = new TranslatorConfig([
            'localesDirectory' => 'directory/'
        ]);

        $this->assertSame('directory/ru/', $config->getLocaleDirectory('ru'));
    }

    public function testLocaleDirectoryShort(): void
    {
        $config = new TranslatorConfig([
            'directory' => 'directory/'
        ]);

        $this->assertSame('directory/ru/', $config->getLocaleDirectory('ru'));
    }

    public function testDomains(): void
    {
        $config = new TranslatorConfig([
            'domains' => [
                'spiral'   => [
                    'spiral-*'
                ],
                'messages' => ['*']
            ]
        ]);

        $this->assertSame('spiral', $config->resolveDomain('spiral-views'));
        $this->assertSame('messages', $config->resolveDomain('vendor-views'));
    }

    public function testDomainsFallback(): void
    {
        $config = new TranslatorConfig([
            'domains' => [
                'spiral' => [
                    'spiral-*'
                ]
            ]
        ]);

        $this->assertSame('external', $config->resolveDomain('external'));
    }

    public function testHasLoader(): void
    {
        $config = new TranslatorConfig([
            'loaders' => ['php' => PhpFileLoader::class]
        ]);

        $this->assertTrue($config->hasLoader('php'));
        $this->assertFalse($config->hasLoader('txt'));
    }

    public function testGetLoader(): void
    {
        $config = new TranslatorConfig([
            'loaders' => ['php' => PhpFileLoader::class]
        ]);

        $this->assertInstanceOf(LoaderInterface::class, $config->getLoader('php'));
    }

    public function testHasDumper(): void
    {
        $config = new TranslatorConfig([
            'dumpers' => ['po' => PoFileDumper::class]
        ]);

        $this->assertTrue($config->hasDumper('po'));
        $this->assertFalse($config->hasDumper('xml'));
    }

    public function testGetDumper(): void
    {
        $config = new TranslatorConfig([
            'dumpers' => ['po' => PoFileDumper::class]
        ]);

        $this->assertInstanceOf(DumperInterface::class, $config->getDumper('po'));
    }
}


text:
#pragma once
#include <aws/ram/RAM_EXPORTS.h>
#include <aws/ram/RAMRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ram/model/ResourceRegionScopeFilter.h>
#include <utility>

namespace Aws
{
namespace RAM
{
namespace Model
{

  /**
   */
  class AWS_RAM_API ListPendingInvitationResourcesRequest : public RAMRequest
  {
  public:
    ListPendingInvitationResourcesRequest();

    // 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 "ListPendingInvitationResources"; }

    Aws::String SerializePayload() const override;

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation. You can use
     * GetResourceShareInvitations to find the ARN of the invitation.

     */
    inline const Aws::String& GetResourceShareInvitationArn() const{ return m_resourceShareInvitationArn; }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation. You can use
     * GetResourceShareInvitations to find the ARN of the invitation.

     */
    inline bool ResourceShareInvitationArnHasBeenSet() const { return m_resourceShareInvitationArnHasBeenSet; }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation. You can use
     * GetResourceShareInvitations to find the ARN of the invitation.

     */
    inline void SetResourceShareInvitationArn(const Aws::String& value) { m_resourceShareInvitationArnHasBeenSet = true; m_resourceShareInvitationArn = value; }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation. You can use
     * GetResourceShareInvitations to find the ARN of the invitation.

     */
    inline void SetResourceShareInvitationArn(Aws::String&& value) { m_resourceShareInvitationArnHasBeenSet = true; m_resourceShareInvitationArn = std::move(value); }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation. You can use
     * GetResourceShareInvitations to find the ARN of the invitation.

     */
    inline void SetResourceShareInvitationArn(const char* value) { m_resourceShareInvitationArnHasBeenSet = true; m_resourceShareInvitationArn.assign(value); }

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation. You can use
     * GetResourceShareInvitations to find the ARN of the invitation.

     */
    inline ListPendingInvitationResourcesRequest& WithResourceShareInvitationArn(const Aws::String& value) { SetResourceShareInvitationArn(value); return *this;}

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation. You can use
     * GetResourceShareInvitations to find the ARN of the invitation.

     */
    inline ListPendingInvitationResourcesRequest& WithResourceShareInvitationArn(Aws::String&& value) { SetResourceShareInvitationArn(std::move(value)); return *this;}

    /**
     *
Specifies the Amazon
     * Resoure Name (ARN) of the invitation. You can use
     * GetResourceShareInvitations to find the ARN of the invitation.

     */
    inline ListPendingInvitationResourcesRequest& WithResourceShareInvitationArn(const char* value) { SetResourceShareInvitationArn(value); return *this;}

    /**
     *
Specifies that you want to receive the next page of results. Valid only if
     * you received a NextToken response in the previous request. If you
     * did, it indicates that more output is available. Set this parameter to the value
     * provided by the previous call's NextToken response to request the
     * next page of results.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
Specifies that you want to receive the next page of results. Valid only if
     * you received a NextToken response in the previous request. If you
     * did, it indicates that more output is available. Set this parameter to the value
     * provided by the previous call's NextToken response to request the
     * next page of results.

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
Specifies that you want to receive the next page of results. Valid only if
     * you received a NextToken response in the previous request. If you
     * did, it indicates that more output is available. Set this parameter to the value
     * provided by the previous call's NextToken response to request the
     * next page of results.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
Specifies that you want to receive the next page of results. Valid only if
     * you received a NextToken response in the previous request. If you
     * did, it indicates that more output is available. Set this parameter to the value
     * provided by the previous call's NextToken response to request the
     * next page of results.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
Specifies that you want to receive the next page of results. Valid only if
     * you received a NextToken response in the previous request. If you
     * did, it indicates that more output is available. Set this parameter to the value
     * provided by the previous call's NextToken response to request the
     * next page of results.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
Specifies that you want to receive the next page of results. Valid only if
     * you received a NextToken response in the previous request. If you
     * did, it indicates that more output is available. Set this parameter to the value
     * provided by the previous call's NextToken response to request the
     * next page of results.

     */
    inline ListPendingInvitationResourcesRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
Specifies that you want to receive the next page of results. Valid only if
     * you received a NextToken response in the previous request. If you
     * did, it indicates that more output is available. Set this parameter to the value
     * provided by the previous call's NextToken response to request the
     * next page of results.

     */
    inline ListPendingInvitationResourcesRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
Specifies that you want to receive the next page of results. Valid only if
     * you received a NextToken response in the previous request. If you
     * did, it indicates that more output is available. Set this parameter to the value
     * provided by the previous call's NextToken response to request the
     * next page of results.

     */
    inline ListPendingInvitationResourcesRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

    /**
     *
Specifies the total number of results that you want included on each page of
     * the response. If you do not include this parameter, it defaults to a value that
     * is specific to the operation. If additional items exist beyond the number you
     * specify, the NextToken response element is returned with a value
     * (not null). Include the specified value as the NextToken request
     * parameter in the next call to the operation to get the next part of the results.
     * Note that the service might return fewer results than the maximum even when
     * there are more results available. You should check NextToken after
     * every operation to ensure that you receive all of the results.

     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     *
Specifies the total number of results that you want included on each page of
     * the response. If you do not include this parameter, it defaults to a value that
     * is specific to the operation. If additional items exist beyond the number you
     * specify, the NextToken response element is returned with a value
     * (not null). Include the specified value as the NextToken request
     * parameter in the next call to the operation to get the next part of the results.
     * Note that the service might return fewer results than the maximum even when
     * there are more results available. You should check NextToken after
     * every operation to ensure that you receive all of the results.

     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     *
Specifies the total number of results that you want included on each page of
     * the response. If you do not include this parameter, it defaults to a value that
     * is specific to the operation. If additional items exist beyond the number you
     * specify, the NextToken response element is returned with a value
     * (not null). Include the specified value as the NextToken request
     * parameter in the next call to the operation to get the next part of the results.
     * Note that the service might return fewer results than the maximum even when
     * there are more results available. You should check NextToken after
     * every operation to ensure that you receive all of the results.

     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     *
Specifies the total number of results that you want included on each page of
     * the response. If you do not include this parameter, it defaults to a value that
     * is specific to the operation. If additional items exist beyond the number you
     * specify, the NextToken response element is returned with a value
     * (not null). Include the specified value as the NextToken request
     * parameter in the next call to the operation to get the next part of the results.
     * Note that the service might return fewer results than the maximum even when
     * there are more results available. You should check NextToken after
     * every operation to ensure that you receive all of the results.

     */
    inline ListPendingInvitationResourcesRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    /**
     *
Specifies that you want the results to include only resources that have the
     * specified scope.

 ALL – the results include both
     * global and regional resources or resource types.

     * GLOBAL – the results include only global resources or resource
     * types.

 REGIONAL – the results include only
     * regional resources or resource types.

The default value is
     * ALL.

     */
    inline const ResourceRegionScopeFilter& GetResourceRegionScope() const{ return m_resourceRegionScope; }

    /**
     *
Specifies that you want the results to include only resources that have the
     * specified scope.

 ALL – the results include both
     * global and regional resources or resource types.

     * GLOBAL – the results include only global resources or resource
     * types.

 REGIONAL – the results include only
     * regional resources or resource types.

The default value is
     * ALL.

     */
    inline bool ResourceRegionScopeHasBeenSet() const { return m_resourceRegionScopeHasBeenSet; }

    /**
     *
Specifies that you want the results to include only resources that have the
     * specified scope.

 ALL – the results include both
     * global and regional resources or resource types.

     * GLOBAL – the results include only global resources or resource
     * types.

 REGIONAL – the results include only
     * regional resources or resource types.

The default value is
     * ALL.

     */
    inline void SetResourceRegionScope(const ResourceRegionScopeFilter& value) { m_resourceRegionScopeHasBeenSet = true; m_resourceRegionScope = value; }

    /**
     *
Specifies that you want the results to include only resources that have the
     * specified scope.

 ALL – the results include both
     * global and regional resources or resource types.

     * GLOBAL – the results include only global resources or resource
     * types.

 REGIONAL – the results include only
     * regional resources or resource types.

The default value is
     * ALL.

     */
    inline void SetResourceRegionScope(ResourceRegionScopeFilter&& value) { m_resourceRegionScopeHasBeenSet = true; m_resourceRegionScope = std::move(value); }

    /**
     *
Specifies that you want the results to include only resources that have the
     * specified scope.

 ALL – the results include both
     * global and regional resources or resource types.

     * GLOBAL – the results include only global resources or resource
     * types.

 REGIONAL – the results include only
     * regional resources or resource types.

The default value is
     * ALL.

     */
    inline ListPendingInvitationResourcesRequest& WithResourceRegionScope(const ResourceRegionScopeFilter& value) { SetResourceRegionScope(value); return *this;}

    /**
     *
Specifies that you want the results to include only resources that have the
     * specified scope.

 ALL – the results include both
     * global and regional resources or resource types.

     * GLOBAL – the results include only global resources or resource
     * types.

 REGIONAL – the results include only
     * regional resources or resource types.

The default value is
     * ALL.

     */
    inline ListPendingInvitationResourcesRequest& WithResourceRegionScope(ResourceRegionScopeFilter&& value) { SetResourceRegionScope(std::move(value)); return *this;}

  private:

    Aws::String m_resourceShareInvitationArn;
    bool m_resourceShareInvitationArnHasBeenSet = false;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet = false;

    int m_maxResults;
    bool m_maxResultsHasBeenSet = false;

    ResourceRegionScopeFilter m_resourceRegionScope;
    bool m_resourceRegionScopeHasBeenSet = false;
  };

} // namespace Model
} // namespace RAM
} // namespace Aws


text:
SeaBattle is a two player game. The objective of SeaBattle is to sink all your oppenent's ships.
The game begins by selecting your player(1/2), and selecting the player to move first.
Once done, your primary and tracking board will be generated.
After, enter the targetted coordinates from you and your oppenent.
The grid will automatically update itself.
Do until all of one player's ships are sunk.

## Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.

### Prerequisites

For PC users:
None

For Mac or Linux:

```
[GNU Compiler](https://gcc.gnu.org/)
```

### Installing

For PC Users:

Simply download "SeaBattle.exe" and run

For Mac or Linux:

1)Download entire "SEABATTLE" folder

2a)Open SeaBattle.dev and compile in DevC++ (see 'Built With' for more information)

2b)Compile via command line or terminal

For information on compiling on a Linux system
```
https://www.cyberciti.biz/faq/howto-compile-and-run-c-cplusplus-code-in-linux/
```

For information on compiling on a MacOS
```
https://www.cs.drexel.edu/~mcs171/Sp14/extras/g++/index.html
```

### Coding style

Indentation

```
if (hours < 24 && minutes < 60 && seconds < 60) {
    return true;
} else {
    return false;
}
```
Spacing

```
int i;
for (i=0; i<10; ++i) {
    printf("%d", i*i+i);
}
```
Vertical Allignment

```
$search = array('a', 'b', 'c', 'd', 'e');
$replacement = array('foo', 'bar', 'baz', 'quux');
```

## Built With

* [Dev C+++](http://www.bloodshed.net/devcpp.html)  The IDE used

## Authors

* **Caden Garrett** - *Initial work* - [CadenMG](https://github.com/CadenMG/)

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

## Acknowledgments

* Jay Snellen


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Test LocatiePercelen</title>
  <link rel="stylesheet" href="../../resources/css/localTest.css" />

Test dummy Widget

test placeholder


text:
package example.staticinitializer;

public class Foo {
	static {
		if (true) {
			throw new FooBarException();
		}
	}
}


text:
[![Build Status](https://travis-ci.org/rakyll/boom.png?branch=master)](https://travis-ci.org/rakyll/boom)

Boom is a tiny program that sends some load to a web application. It's similar to Apache Bench ([ab](http://httpd.apache.org/docs/2.2/programs/ab.html)), but with better availability across different platforms and a less troubling installation experience.

Boom is originally written by Tarek Ziade in Python and is available on [tarekziade/boom](https://github.com/tarekziade/boom). But, due to its dependency requirements and my personal annoyance of maintaining concurrent programs in Python, I decided to rewrite it in Go.

## Installation

Simple as it takes to type the following command:

    go get github.com/rakyll/boom

## Usage

Boom supports custom headers, request body and basic authentication. It runs provided number of requests in the provided concurrency level, and prints stats.
~~~
Usage: boom [options...] <url>

Options:
  -n  Number of requests to run.
  -c  Number of requests to run concurrently. Total number of requests cannot
      be smaller than the concurency level.
  -q  Rate limit, in seconds (QPS).
  -o  Output type. If none provided, a summary is printed.
      "csv" is the only supported alternative. Dumps the response
      metrics in comma-seperated values format.

  -m  HTTP method, one of GET, POST, PUT, DELETE, HEAD, OPTIONS.
  -h  Custom HTTP headers, name1:value1;name2:value2.
  -t  Timeout in ms.
  -A  HTTP Accept header.
  -d  HTTP request body.
  -T  Content-type, defaults to "text/html".
  -a  Basic authentication, username:password.
  -x  HTTP Proxy address as host:port.

  -readall              Consumes the entire request body.
  -allow-insecure       Allow bad/expired TLS/SSL certificates.
  -disable-compression  Disable compression.
  -disable-keepalive    Disable keep-alive, prevents re-use of TCP
                        connections between different HTTP requests.
  -cpus                 Number of used cpu cores.
                        (default for current machine is 1 cores)
~~~

This is what happens when you run Boom:

	% boom -n 1000 -c 100 https://google.com
	1000 / 1000 ∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎ 100.00 %

	Summary:
	  Total:        21.1307 secs.
	  Slowest:      2.9959 secs.
	  Fastest:      0.9868 secs.
	  Average:      2.0827 secs.
	  Requests/sec: 47.3246
	  Speed index:  Hahahaha

	Response time histogram:
      0.987 [1]     |
      1.188 [2]     |
      1.389 [3]     |
      1.590 [18]    |∎∎
      1.790 [85]    |∎∎∎∎∎∎∎∎∎∎∎
      1.991 [244]   |∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎
      2.192 [284]   |∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎
      2.393 [304]   |∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎∎
      2.594 [50]    |∎∎∎∎∎∎
      2.795 [5]     |
      2.996 [4]     |

	Latency distribution:
	  10% in 1.7607 secs.
	  25% in 1.9770 secs.
	  50% in 2.0961 secs.
	  75% in 2.2385 secs.
	  90% in 2.3681 secs.
	  95% in 2.4451 secs.
	  99% in 2.5393 secs.

	Status code distribution:
	  [200]	1000 responses

## License

Copyright 2014 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. ![Analytics](https://ga-beacon.appspot.com/UA-46881978-1/boom?pixel)


text:
from __future__ import unicode_literals

import json
import warnings
from unittest import skipUnless

from django.test import SimpleTestCase, ignore_warnings
from django.test.utils import reset_warning_registry
from django.utils import six, text
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding import force_text
from django.utils.functional import lazy
from django.utils.translation import override

lazystr = lazy(force_text, six.text_type)

IS_WIDE_BUILD = (len('\U0001F4A9') == 1)

class TestUtilsText(SimpleTestCase):

    def test_get_text_list(self):
        self.assertEqual(text.get_text_list(['a', 'b', 'c', 'd']), 'a, b, c or d')
        self.assertEqual(text.get_text_list(['a', 'b', 'c'], 'and'), 'a, b and c')
        self.assertEqual(text.get_text_list(['a', 'b'], 'and'), 'a and b')
        self.assertEqual(text.get_text_list(['a']), 'a')
        self.assertEqual(text.get_text_list([]), '')
        with override('ar'):
            self.assertEqual(text.get_text_list(['a', 'b', 'c']), "a، b أو c")

    def test_smart_split(self):
        testdata = [
            ('This is "a person" test.',
                ['This', 'is', '"a person"', 'test.']),
            ('This is "a person\'s" test.',
                ['This', 'is', '"a person\'s"', 'test.']),
            ('This is "a person\\"s" test.',
                ['This', 'is', '"a person\\"s"', 'test.']),
            ('"a \'one',
                ['"a', "'one"]),
            ('all friends\' tests',
                ['all', 'friends\'', 'tests']),
            ('url search_page words="something else"',
                ['url', 'search_page', 'words="something else"']),
            ("url search_page words='something else'",
                ['url', 'search_page', "words='something else'"]),
            ('url search_page words "something else"',
                ['url', 'search_page', 'words', '"something else"']),
            ('url search_page words-"something else"',
                ['url', 'search_page', 'words-"something else"']),
            ('url search_page words=hello',
                ['url', 'search_page', 'words=hello']),
            ('url search_page words="something else',
                ['url', 'search_page', 'words="something', 'else']),
            ("cut:','|cut:' '",
                ["cut:','|cut:' '"]),
            (lazystr("a b c d"),  # Test for #20231
                ['a', 'b', 'c', 'd']),
        ]
        for test, expected in testdata:
            self.assertEqual(list(text.smart_split(test)), expected)

    def test_truncate_chars(self):
        truncator = text.Truncator(
            'The quick brown fox jumped over the lazy dog.'
        )
        self.assertEqual('The quick brown fox jumped over the lazy dog.',
            truncator.chars(100)),
        self.assertEqual('The quick brown fox ...',
            truncator.chars(23)),
        self.assertEqual('The quick brown fo.....',
            truncator.chars(23, '.....')),

        # Ensure that we normalize our unicode data first
        nfc = text.Truncator('o\xfco\xfco\xfco\xfc')
        nfd = text.Truncator('ou\u0308ou\u0308ou\u0308ou\u0308')
        self.assertEqual('oüoüoüoü', nfc.chars(8))
        self.assertEqual('oüoüoüoü', nfd.chars(8))
        self.assertEqual('oü...', nfc.chars(5))
        self.assertEqual('oü...', nfd.chars(5))

        # Ensure the final length is calculated correctly when there are
        # combining characters with no precomposed form, and that combining
        # characters are not split up.
        truncator = text.Truncator('-B\u030AB\u030A----8')
        self.assertEqual('-B\u030A...', truncator.chars(5))
        self.assertEqual('-B\u030AB\u030A-...', truncator.chars(7))
        self.assertEqual('-B\u030AB\u030A----8', truncator.chars(8))

        # Ensure the length of the end text is correctly calculated when it
        # contains combining characters with no precomposed form.
        truncator = text.Truncator('-----')
        self.assertEqual('---B\u030A', truncator.chars(4, 'B\u030A'))
        self.assertEqual('-----', truncator.chars(5, 'B\u030A'))

        # Make a best effort to shorten to the desired length, but requesting
        # a length shorter than the ellipsis shouldn't break
        self.assertEqual('...', text.Truncator('asdf').chars(1))

    def test_truncate_words(self):
        truncator = text.Truncator('The quick brown fox jumped over the lazy '
            'dog.')
        self.assertEqual('The quick brown fox jumped over the lazy dog.',
            truncator.words(10))
        self.assertEqual('The quick brown fox...', truncator.words(4))
        self.assertEqual('The quick brown fox[snip]',
            truncator.words(4, '[snip]'))

    def test_truncate_html_words(self):
        truncator = text.Truncator('
The quick brown fox'
            ' jumped over the lazy dog.
')
        self.assertEqual('
The quick brown fox jumped over'
            ' the lazy dog.
', truncator.words(10, html=True))
        self.assertEqual('
The quick brown fox...'
            '
', truncator.words(4, html=True))
        self.assertEqual('
The quick brown fox....'
            '
', truncator.words(4, '....', html=True))
        self.assertEqual('
The quick brown fox'
            '
', truncator.words(4, '', html=True))

        # Test with new line inside tag
        truncator = text.Truncator('
The quick brown fox jumped over the lazy dog.
')
        self.assertEqual('
The quick brown...
', truncator.words(3, '...', html=True))

        # Test self-closing tags
        truncator = text.Truncator('
The
quick brown fox jumped over'
            ' the lazy dog.')
        self.assertEqual('
The
quick brown...',
            truncator.words(3, '...', html=True))
        truncator = text.Truncator('
The
quick brown fox '
            'jumped over the lazy dog.')
        self.assertEqual('
The
quick brown...',
            truncator.words(3, '...', html=True))

        # Test html entities
        truncator = text.Truncator('Buenos días!'
            ' ¿Cómo está?')
        self.assertEqual('Buenos días! ¿Cómo...',
            truncator.words(3, '...', html=True))
        truncator = text.Truncator('
I <3 python, what about you?
')
        self.assertEqual('
I <3 python...
',
            truncator.words(3, '...', html=True))

    def test_wrap(self):
        digits = '1234 67 9'
        self.assertEqual(text.wrap(digits, 100), '1234 67 9')
        self.assertEqual(text.wrap(digits, 9), '1234 67 9')
        self.assertEqual(text.wrap(digits, 8), '1234 67\n9')

        self.assertEqual(text.wrap('short\na long line', 7),
                         'short\na long\nline')

        self.assertEqual(text.wrap('do-not-break-long-words please? ok', 8),
                         'do-not-break-long-words\nplease?\nok')

        long_word = 'l%sng' % ('o' * 20)
        self.assertEqual(text.wrap(long_word, 20), long_word)
        self.assertEqual(text.wrap('a %s word' % long_word, 10),
                         'a\n%s\nword' % long_word)

    def test_normalize_newlines(self):
        self.assertEqual(text.normalize_newlines("abc\ndef\rghi\r\n"),
                         "abc\ndef\nghi\n")
        self.assertEqual(text.normalize_newlines("\n\r\r\n\r"), "\n\n\n\n")
        self.assertEqual(text.normalize_newlines("abcdefghi"), "abcdefghi")
        self.assertEqual(text.normalize_newlines(""), "")

    def test_normalize_newlines_bytes(self):
        """normalize_newlines should be able to handle bytes too"""
        normalized = text.normalize_newlines(b"abc\ndef\rghi\r\n")
        self.assertEqual(normalized, "abc\ndef\nghi\n")
        self.assertIsInstance(normalized, six.text_type)

    def test_slugify(self):
        items = (
            ('Hello, World!', 'hello-world'),
            ('spam & eggs', 'spam-eggs'),
        )
        for value, output in items:
            self.assertEqual(text.slugify(value), output)

    def test_unescape_entities(self):
        items = [
            ('', ''),
            ('foo', 'foo'),
            ('&', '&'),
            ('&', '&'),
            ('&', '&'),
            ('foo & bar', 'foo & bar'),
            ('foo & bar', 'foo & bar'),
        ]
        for value, output in items:
            self.assertEqual(text.unescape_entities(value), output)

    def test_get_valid_filename(self):
        filename = "^&'@{}[],$=!-#()%+~_123.txt"
        self.assertEqual(text.get_valid_filename(filename), "-_123.txt")

    def test_compress_sequence(self):
        data = [{'key': i} for i in range(10)]
        seq = list(json.JSONEncoder().iterencode(data))
        seq = [s.encode('utf-8') for s in seq]
        actual_length = len(b''.join(seq))
        out = text.compress_sequence(seq)
        compressed_length = len(b''.join(out))
        self.assertTrue(compressed_length < actual_length)

    @ignore_warnings(category=RemovedInDjango19Warning)
    def test_javascript_quote(self):
        input = ""
        output = r""
        output = r"


text:
package com.heneryh.aquanotes.ui.livestock;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple layout that fits and centers each child view, maintaining aspect ratio.
 */
public class FitCenterFrameLayout extends ViewGroup {
    public FitCenterFrameLayout(Context context) {
        super(context);
    }

    public FitCenterFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // We purposely disregard child measurements.
        final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
        setMeasuredDimension(width, height);

        int childWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.UNSPECIFIED);
        int childHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED);

        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            getChildAt(i).measure(childWidthSpec, childHeightSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int childCount = getChildCount();

        final int parentLeft = getPaddingLeft();
        final int parentTop = getPaddingTop();
        final int parentRight = r - l - getPaddingRight();
        final int parentBottom = b - t - getPaddingBottom();

        final int parentWidth = parentRight - parentLeft;
        final int parentHeight = parentBottom - parentTop;

        int unpaddedWidth, unpaddedHeight, parentUnpaddedWidth, parentUnpaddedHeight;
        int childPaddingLeft, childPaddingTop, childPaddingRight, childPaddingBottom;

        for (int i = 0; i < childCount; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() == GONE) {
                continue;
            }

            // Fit and center the child within the parent. Make sure not to consider padding
            // as part of the child's aspect ratio.

            childPaddingLeft = child.getPaddingLeft();
            childPaddingTop = child.getPaddingTop();
            childPaddingRight = child.getPaddingRight();
            childPaddingBottom = child.getPaddingBottom();

            unpaddedWidth = child.getMeasuredWidth() - childPaddingLeft - childPaddingRight;
            unpaddedHeight = child.getMeasuredHeight() - childPaddingTop - childPaddingBottom;

            parentUnpaddedWidth = parentWidth - childPaddingLeft - childPaddingRight;
            parentUnpaddedHeight = parentHeight - childPaddingTop - childPaddingBottom;

            if (parentUnpaddedWidth * unpaddedHeight > parentUnpaddedHeight * unpaddedWidth) {
                // The child view should be left/right letterboxed.
                final int scaledChildWidth = unpaddedWidth * parentUnpaddedHeight
                        / unpaddedHeight + childPaddingLeft + childPaddingRight;
                child.layout(
                        parentLeft + (parentWidth - scaledChildWidth) / 2,
                        parentTop,
                        parentRight - (parentWidth - scaledChildWidth) / 2,
                        parentBottom);
            } else {
                // The child view should be top/bottom letterboxed.
                final int scaledChildHeight = unpaddedHeight * parentUnpaddedWidth
                        / unpaddedWidth + childPaddingTop + childPaddingBottom;
                child.layout(
                        parentLeft,
                        parentTop + (parentHeight - scaledChildHeight) / 2,
                        parentRight,
                        parentTop + (parentHeight + scaledChildHeight) / 2);
            }
        }
    }
}


text:
namespace LibGit2Sharp.Core
{
    internal enum GitErrorCode
    {
        Ok = 0,
        Error = -1,

        /// <summary>
        ///   Input does not exist in the scope searched.
        /// </summary>
        NotFound = -3,

        /// <summary>
        ///   Input already exists in the processed scope.
        /// </summary>
        Exists = -4,

        /// <summary>
        ///   The given short oid is ambiguous.
        /// </summary>
        Ambiguous = -5,

        /// <summary>
        ///   Buffer related issue.
        /// </summary>
        Buffer = -6,

        /// <summary>
        ///   Callback error.
        /// </summary>
        User = -7,

        /// <summary>
        ///   Operation cannot be performed against a bare repository.
        /// </summary>
        BareRepo = -8,

        /// <summary>
        ///   Operation cannot be performed against an orphaned HEAD.
        /// </summary>
        OrphanedHead = -9,

        /// <summary>
        ///   Operation cannot be performed against a not fully merged index.
        /// </summary>
        UnmergedEntries = -10,

        /// <summary>
        ///   Push cannot be performed against the remote without losing commits.
        /// </summary>
        NonFastForward = -11,

        /// <summary>
        ///   Input is not a valid specification.
        /// </summary>
        InvalidSpecification = -12,

        /// <summary>
        ///   A conflicting change has been detected.
        /// </summary>
        MergeConflict = -13,

        /// <summary>
        ///   Skip and passthrough the given ODB backend.
        /// </summary>
        PassThrough = -30,

        /// <summary>
        ///   There are no more entries left to iterate.
        /// </summary>
        IterOver = -31,
    }
}


text:
title: Unit Testing Angular Views
date: "2015-03-07"
---

In this blog post I will be focusing on how to replace integrated tests with unit tests in client-side Angular.JS applications. I originally wrote this post for my employer at the time [Trōv](https://trov.com).

### How to test an Angular view?

For example, here is a simple dropdown box with a controller that supplies the currently logged-in user.

```language-markup
<li class="dropdown">
  <a id="email" href="#" data-toggle="dropdown" class="dropdown-toggle">
    {{ user.email || user.name || "Anon" }}
  </a>
  <ul class="dropdown-menu">
    <li>
      <a id="logout" data-ng-click="logout()">
        Logout
      </a>
    </li>
  </ul>
</li>
```

What are the key scenarios to be tested here? I will cover the following:

* It should display the user email when the user has an email.
* It should display the user name when the user has no email.
* It should display a default user name when the user has no email or name.
* It should logout when the logout button is clicked in the dropdown menu.

What is the best way to write a test for each of these scenarios? The common answer is to write an integrated test, typically using [Protractor](http://www.protractortest.org/).

However, integrated tests have the following drawbacks associated with them:

* They force unrelated systems into the test, thereby creating room for test failures unrelated to the system under test.
* They are unopinionated about the design of the view, so there is no pressure for it to be broken up into smaller views, controllers, or directives.
* Over time, integrated tests can become slow and hard to maintain.
* They are fragile when changes occur in the application.

The above four integrated tests involve the real implementation of the controller for the corresponding view, thereby leaving it exposed to bugs in that system. The fourth scenario includes the logout interaction, which could involve page transitions, database calls, updating localStorage user models, and triggering analytics events. The basic correctness of the view should not require brittle tests.

### Unit Testing a View

Unit testing views can be done in Angular.js and avoids the integrated test problems mentioned earlier. These tests validate the view independent of other systems, and can be run both in parallel and in memory without spinning up the server or database. Pressure is put on the design of the view by the tests, which encourages the creation of new views and directives.

An interactive example with all four scenarios is on [plunkr](http://plnkr.co/edit/k9kjPQJ644fxjcEYqeNC?p=preview); however, the approach can be explained by the following snippets:

```language-javascript
// Get html template from cache
beforeEach(inject(function($templateCache) {
  viewHtml = $templateCache.get("some/valid/templateUrl");
}));
```

```language-javascript
// Setup stubbed scope and create dropdownElement.
var $rootScope;
var $scope;
var $compile;
var dropdownElement;

beforeEach(inject(function(_$compile_, _$rootScope_){
  $compile = _$compile_;
  $rootScope = _$rootScope_;

  $scope = $rootScope.$new();
  $scope.user = {};
  $scope.logout = sinon.stub();
  dropdownElement = angular.element(viewHtml);
}));
```

```language-javascript
// Compile element, digest cycle for stubbed scope, verify expectations
it("should display the user email when the user has an email.", function () {
  $scope.user.email = "cody@trov.com";
  compileElement();

  var email = dropdownElement.find("#email");

  expect(email.text().trim()).toBe($scope.user.email);
});

function compileElement() {
  $compile(dropdownElement)($scope);
  $rootScope.$digest();
}
```

### Further Reading

* [Zealake's similar approach to unit testing Angular.js views](http://www.zealake.com/2014/01/01/unit-test-your-angularjs-views/)
* [23tux's similar approach to unit testing Angular.js views](http://stackoverflow.com/questions/23083645/unit-test-views-best-practice)
* [Unit testing Angular.JS directives](https://robots.thoughtbot.com/angular-testing-directives)


text:
'use strict';

const ApplicationError = require('../../libs/application-error.js');
const MongoModel = require('./common/mongoModel.js');

const has = Object.prototype.hasOwnProperty;

class Cards extends MongoModel {
  constructor(config) {
    const modelName = 'Card';
    super(Object.assign(config, { modelName }));
    this.log = this.log.child({ modelName });
  }

  /**
   * Добавляет карту
   * @param {Object} card - описание карты
   * @param {String} card.cardNumber - номер карты
   * @param {Number} card.balance - баланс карты
   */
  async create(card) {
    const log = this.log.child({
      function: 'create',
    });

    const isDataValid = card
      && has.call(card, 'cardNumber')
      && has.call(card, 'balance')
      && has.call(card, 'userId');

    if (!isDataValid) {
      throw new ApplicationError('Card data is invalid', 400);
    }

    const isCardExist = await this.findOne({
      cardNumber: card.cardNumber,
      userId: card.userId,
    });

    if (isCardExist) {
      throw new ApplicationError('Card already exist', 400);
    }

    const id = await this._generateId();
    const newCard = Object.assign({}, card, { id });

    await this._insert(newCard);

    log.trace('New card added', newCard);

    return newCard;
  }

  /**
   * Списание средств с карты
   * @param {Number} id идентификатор карты
   * @param {Number} sum сумма
   */
  async withdraw(id, sum) {
    const card = await this.getById(id);
    const newBalance = Number(card.balance) - Number(sum);

    if (newBalance < 0) {
      throw new ApplicationError('No money');
    }

    await this._update({ id }, { balance: newBalance });
  }

  /**
   * Пополнение карты
   * @param {Number} id идентификатор карты
   * @param {Number} sum сумма
   */
  async refill(id, sum) {
    const card = await this.getById(id);
    const newBalance = Number(card.balance) + Number(sum);

    await this._update({ id }, { balance: newBalance });
  }

  /**
   * Удаляет карту
   * @param {Number} id - идентификатор карты
   */
  async remove(id) {
    const log = this.log.child({
      function: 'remove',
    });

    const card = await this.getById(id);

    if (!card) {
      throw new ApplicationError(`Card with ID=${id} not found`, 404);
    }

    const result = await this._remove({ id });

    log.trace(`Card #${id} removed successfully`);

    return result;
  }
}

module.exports = Cards;


text:
layout: post
microblog: true
audio:
photo:
date: 2011-11-03 22:32:43 -0600
guid: http://craigmcclellan.micro.blog/2011/11/04/t132314306942468096.html
---
Got Lion on my laptop and I'm in love. I wish I could update my work computer too. #imlookingatyouavid


text:
/**
 * Inports
 */
@import url(parts/fonts.css);
@import url(parts/base.css);
@import url(parts/parallax.css);
@import url(parts/countdown.css);
@import url(parts/map.css);
@import url(parts/ribbon.css);

.meetup {
    display: inline-block;
    padding: 0 .2em 0 0;
    text-align: center;
    margin:0;
    line-height: 30px;
}
.meetup:before {
    font-family: zocial;
    font-size:1.6em;
    content: "\f13a";
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../">
  <title data-ice="title">TrelloConnector | API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home

  Reference
  Source
  Test
  Repository

    <input class="search-input">

CTrelloConnector

Fpoll

import TrelloConnector from 'hoist-connector-trello/src/connector.js'

  public
  class

  | source

TrelloConnector

Extends:

@hoist/oauth-connector~OAuthConnectorBase → TrelloConnector

Constructor Summary

Public Constructor

      public

           constructor(configuration: object)

create a new TrelloConnector

Method Summary

Public Methods

      public

           delete(path: *): *

      public

           get(path: *, urlArguments: *): *

      public

           post(path: *, body: *): *

      public

           put(path: *, body: *): *

Public Constructors

    public

    constructor(configuration: object)

      source

create a new TrelloConnector

Params:

Name	Type	Attribute	Description

      configuration
      object

the configuration details for this connector

      configuration.apiKey
      string

the trello API Key

      configuration.apiSecret
      string

the trello API secret

      configuration.appName
      string

the application name as it should show up to the user in Trello

Public Methods

    public

    delete(path: *): *

      source

Params:

Name	Type	Attribute	Description

      path
      *

Return:

        *

    public

    get(path: *, urlArguments: *): *

      source

Params:

Name	Type	Attribute	Description

      path
      *

      urlArguments
      *

Return:

        *

    public

    post(path: *, body: *): *

      source

Params:

Name	Type	Attribute	Description

      path
      *

      body
      *

Return:

        *

    public

    put(path: *, body: *): *

      source

Params:

Name	Type	Attribute	Description

      path
      *

      body
      *

Return:

        *

  Generated by ESDoc(0.4.6)


text:
require "omniauth/medium/version"
require "omniauth/strategies/medium"


text:
package edu.emory.cci.aiw.cvrg.eureka.common.comm;

/**
 *
 * @author Andrew Post
 */
public class EtlTableColumn {

    private String tableName;
    private String columnName;
    private String path;
    private String format;

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getColumnName() {
        return columnName;
    }

    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

}


text:
static exception_mask_t FIRCLSMachExceptionMask(void);
static void* FIRCLSMachExceptionServer(void* argument);
static bool FIRCLSMachExceptionThreadStart(FIRCLSMachExceptionReadContext* context);
static bool FIRCLSMachExceptionReadMessage(FIRCLSMachExceptionReadContext* context,
                                           MachExceptionMessage* message);
static kern_return_t FIRCLSMachExceptionDispatchMessage(FIRCLSMachExceptionReadContext* context,
                                                        MachExceptionMessage* message);
static bool FIRCLSMachExceptionReply(FIRCLSMachExceptionReadContext* context,
                                     MachExceptionMessage* message,
                                     kern_return_t result);
static bool FIRCLSMachExceptionRegister(FIRCLSMachExceptionReadContext* context,
                                        exception_mask_t ignoreMask);
static bool FIRCLSMachExceptionUnregister(FIRCLSMachExceptionOriginalPorts* originalPorts,
                                          exception_mask_t mask);
static bool FIRCLSMachExceptionRecord(FIRCLSMachExceptionReadContext* context,
                                      MachExceptionMessage* message);

#pragma mark - Initialization
void FIRCLSMachExceptionInit(FIRCLSMachExceptionReadContext* context, exception_mask_t ignoreMask) {
  if (!FIRCLSUnlinkIfExists(context->path)) {
    FIRCLSSDKLog("Unable to reset the mach exception file %s\n", strerror(errno));
  }

  if (!FIRCLSMachExceptionRegister(context, ignoreMask)) {
    FIRCLSSDKLog("Unable to register mach exception handler\n");
    return;
  }

  if (!FIRCLSMachExceptionThreadStart(context)) {
    FIRCLSSDKLog("Unable to start thread\n");
    FIRCLSMachExceptionUnregister(&context->originalPorts, context->mask);
  }
}

void FIRCLSMachExceptionCheckHandlers(void) {
  if (_firclsContext.readonly->debuggerAttached) {
    return;
  }

  // It isn't really critical that this be done, as its extremely uncommon to run into
  // preexisting handlers.
  // Can use task_get_exception_ports for this.
}

static exception_mask_t FIRCLSMachExceptionMask(void) {
  exception_mask_t mask;

  // EXC_BAD_ACCESS
  // EXC_BAD_INSTRUCTION
  // EXC_ARITHMETIC
  // EXC_EMULATION - non-failure
  // EXC_SOFTWARE - non-failure
  // EXC_BREAKPOINT - trap instructions, from the debugger and code. Needs special treatment.
  // EXC_SYSCALL - non-failure
  // EXC_MACH_SYSCALL - non-failure
  // EXC_RPC_ALERT - non-failure
  // EXC_CRASH - see below
  // EXC_RESOURCE - non-failure, happens when a process exceeds a resource limit
  // EXC_GUARD - see below
  //
  // EXC_CRASH is a special kind of exception.  It is handled by launchd, and treated special by
  // the kernel.  Seems that we cannot safely catch it - our handler will never be called.  This
  // is a confirmed kernel bug.  Lacking access to EXC_CRASH means we must use signal handlers to
  // cover all types of crashes.
  // EXC_GUARD is relatively new, and isn't available on all OS versions. You have to be careful,
  // becuase you cannot succesfully register hanlders if there are any unrecognized masks. We've
  // dropped support for old OS versions that didn't have EXC_GUARD (iOS 5 and below, macOS 10.6 and
  // below) so we always add it now

  mask = EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION | EXC_MASK_ARITHMETIC |
         EXC_MASK_BREAKPOINT | EXC_MASK_GUARD;

  return mask;
}

static bool FIRCLSMachExceptionThreadStart(FIRCLSMachExceptionReadContext* context) {
  pthread_attr_t attr;

  if (pthread_attr_init(&attr) != 0) {
    FIRCLSSDKLog("pthread_attr_init %s\n", strerror(errno));
    return false;
  }

  if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) {
    FIRCLSSDKLog("pthread_attr_setdetachstate %s\n", strerror(errno));
    return false;
  }

  // Use to pre-allocate a stack for this thread
  // The stack must be page-aligned
  if (pthread_attr_setstack(&attr, _firclsContext.readonly->machStack,
                            CLS_MACH_EXCEPTION_HANDLER_STACK_SIZE) != 0) {
    FIRCLSSDKLog("pthread_attr_setstack %s\n", strerror(errno));
    return false;
  }

  if (pthread_create(&context->thread, &attr, FIRCLSMachExceptionServer, context) != 0) {
    FIRCLSSDKLog("pthread_create %s\n", strerror(errno));
    return false;
  }

  pthread_attr_destroy(&attr);

  return true;
}

exception_mask_t FIRCLSMachExceptionMaskForSignal(int signal) {
  switch (signal) {
    case SIGTRAP:
      return EXC_MASK_BREAKPOINT;
    case SIGSEGV:
      return EXC_MASK_BAD_ACCESS;
    case SIGBUS:
      return EXC_MASK_BAD_ACCESS;
    case SIGILL:
      return EXC_MASK_BAD_INSTRUCTION;
    case SIGABRT:
      return EXC_MASK_CRASH;
    case SIGSYS:
      return EXC_MASK_CRASH;
    case SIGFPE:
      return EXC_MASK_ARITHMETIC;
  }

  return 0;
}

#pragma mark - Message Handling
static void* FIRCLSMachExceptionServer(void* argument) {
  FIRCLSMachExceptionReadContext* context = argument;

  pthread_setname_np("com.google.firebase.crashlytics.MachExceptionServer");

  while (1) {
    MachExceptionMessage message;

    // read the exception message
    if (!FIRCLSMachExceptionReadMessage(context, &message)) {
      break;
    }

    // handle it, and possibly forward
    kern_return_t result = FIRCLSMachExceptionDispatchMessage(context, &message);

    // and now, reply
    if (!FIRCLSMachExceptionReply(context, &message, result)) {
      break;
    }
  }

  FIRCLSSDKLog("Mach exception server thread exiting\n");

  return NULL;
}

static bool FIRCLSMachExceptionReadMessage(FIRCLSMachExceptionReadContext* context,
                                           MachExceptionMessage* message) {
  mach_msg_return_t r;

  memset(message, 0, sizeof(MachExceptionMessage));

  r = mach_msg(&message->head, MACH_RCV_MSG | MACH_RCV_LARGE, 0, sizeof(MachExceptionMessage),
               context->port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
  if (r != MACH_MSG_SUCCESS) {
    FIRCLSSDKLog("Error receving mach_msg (%d)\n", r);
    return false;
  }

  FIRCLSSDKLog("Accepted mach exception message\n");

  return true;
}

static kern_return_t FIRCLSMachExceptionDispatchMessage(FIRCLSMachExceptionReadContext* context,
                                                        MachExceptionMessage* message) {
  FIRCLSSDKLog("Mach exception: 0x%x, count: %d, code: 0x%llx 0x%llx\n", message->exception,
               message->codeCnt, message->codeCnt > 0 ? message->code[0] : -1,
               message->codeCnt > 1 ? message->code[1] : -1);

  // This will happen if a child process raises an exception, as the exception ports are
  // inherited.
  if (message->task.name != mach_task_self()) {
    FIRCLSSDKLog("Mach exception task mis-match, returning failure\n");
    return KERN_FAILURE;
  }

  FIRCLSSDKLog("Unregistering handler\n");
  if (!FIRCLSMachExceptionUnregister(&context->originalPorts, context->mask)) {
    FIRCLSSDKLog("Failed to unregister\n");
    return KERN_FAILURE;
  }

  FIRCLSSDKLog("Restoring original signal handlers\n");
  if (!FIRCLSSignalSafeInstallPreexistingHandlers(&_firclsContext.readonly->signal)) {
    FIRCLSSDKLog("Failed to restore signal handlers\n");
    return KERN_FAILURE;
  }

  FIRCLSSDKLog("Recording mach exception\n");
  if (!FIRCLSMachExceptionRecord(context, message)) {
    FIRCLSSDKLog("Failed to record mach exception\n");
    return KERN_FAILURE;
  }

  return KERN_SUCCESS;
}

static bool FIRCLSMachExceptionReply(FIRCLSMachExceptionReadContext* context,
                                     MachExceptionMessage* message,
                                     kern_return_t result) {
  MachExceptionReply reply;
  mach_msg_return_t r;

  // prepare the reply
  reply.head.msgh_bits = MACH_MSGH_BITS(MACH_MSGH_BITS_REMOTE(message->head.msgh_bits), 0);
  reply.head.msgh_remote_port = message->head.msgh_remote_port;
  reply.head.msgh_size = (mach_msg_size_t)sizeof(MachExceptionReply);
  reply.head.msgh_local_port = MACH_PORT_NULL;
  reply.head.msgh_id = message->head.msgh_id + 100;

  reply.NDR = NDR_record;

  reply.retCode = result;

  FIRCLSSDKLog("Sending exception reply\n");

  // send it
  r = mach_msg(&reply.head, MACH_SEND_MSG, reply.head.msgh_size, 0, MACH_PORT_NULL,
               MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL);
  if (r != MACH_MSG_SUCCESS) {
    FIRCLSSDKLog("mach_msg reply failed (%d)\n", r);
    return false;
  }

  FIRCLSSDKLog("Exception reply delivered\n");

  return true;
}

#pragma mark - Registration
static bool FIRCLSMachExceptionRegister(FIRCLSMachExceptionReadContext* context,
                                        exception_mask_t ignoreMask) {
  mach_port_t task = mach_task_self();

  kern_return_t kr = mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &context->port);
  if (kr != KERN_SUCCESS) {
    FIRCLSSDKLog("Error: mach_port_allocate failed %d\n", kr);
    return false;
  }

  kr = mach_port_insert_right(task, context->port, context->port, MACH_MSG_TYPE_MAKE_SEND);
  if (kr != KERN_SUCCESS) {
    FIRCLSSDKLog("Error: mach_port_insert_right failed %d\n", kr);
    mach_port_deallocate(task, context->port);
    return false;
  }

  // Get the desired mask, which covers all the mach exceptions we are capable of handling,
  // but clear out any that are in our ignore list.  We do this by ANDing with the bitwise
  // negation.  Because we are only clearing bits, there's no way to set an incorrect mask
  // using ignoreMask.
  context->mask = FIRCLSMachExceptionMask() & ~ignoreMask;

  // ORing with MACH_EXCEPTION_CODES will produce 64-bit exception data
  kr = task_swap_exception_ports(task, context->mask, context->port,
                                 EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE,
                                 context->originalPorts.masks, &context->originalPorts.count,
                                 context->originalPorts.ports, context->originalPorts.behaviors,
                                 context->originalPorts.flavors);
  if (kr != KERN_SUCCESS) {
    FIRCLSSDKLog("Error: task_swap_exception_ports %d\n", kr);
    return false;
  }

  for (int i = 0; i < context->originalPorts.count; ++i) {
    FIRCLSSDKLog("original 0x%x 0x%x 0x%x 0x%x\n", context->originalPorts.ports[i],
                 context->originalPorts.masks[i], context->originalPorts.behaviors[i],
                 context->originalPorts.flavors[i]);
  }

  return true;
}

static bool FIRCLSMachExceptionUnregister(FIRCLSMachExceptionOriginalPorts* originalPorts,
                                          exception_mask_t mask) {
  kern_return_t kr;

  // Re-register all the old ports.
  for (mach_msg_type_number_t i = 0; i < originalPorts->count; ++i) {
    // clear the bits from this original mask
    mask &= ~originalPorts->masks[i];

    kr =
        task_set_exception_ports(mach_task_self(), originalPorts->masks[i], originalPorts->ports[i],
                                 originalPorts->behaviors[i], originalPorts->flavors[i]);
    if (kr != KERN_SUCCESS) {
      FIRCLSSDKLog("unable to restore original port: %d", originalPorts->ports[i]);
    }
  }

  // Finally, mark any masks we registered for that do not have an original port as unused.
  kr = task_set_exception_ports(mach_task_self(), mask, MACH_PORT_NULL,
                                EXCEPTION_DEFAULT | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
  if (kr != KERN_SUCCESS) {
    FIRCLSSDKLog("unable to unset unregistered mask: 0x%x", mask);
    return false;
  }

  return true;
}

#pragma mark - Recording
static void FIRCLSMachExceptionNameLookup(exception_type_t number,
                                          mach_exception_data_type_t code,
                                          const char** name,
                                          const char** codeName) {
  if (!name || !codeName) {
    return;
  }

  *name = NULL;
  *codeName = NULL;

  switch (number) {
    case EXC_BAD_ACCESS:
      *name = "EXC_BAD_ACCESS";
      switch (code) {
        case KERN_INVALID_ADDRESS:
          *codeName = "KERN_INVALID_ADDRESS";
          break;
        case KERN_PROTECTION_FAILURE:
          *codeName = "KERN_PROTECTION_FAILURE";
          break;
      }

      break;
    case EXC_BAD_INSTRUCTION:
      *name = "EXC_BAD_INSTRUCTION";
#if CLS_CPU_X86
      *codeName = "EXC_I386_INVOP";
#endif
      break;
    case EXC_ARITHMETIC:
      *name = "EXC_ARITHMETIC";
#if CLS_CPU_X86
      switch (code) {
        case EXC_I386_DIV:
          *codeName = "EXC_I386_DIV";
          break;
        case EXC_I386_INTO:
          *codeName = "EXC_I386_INTO";
          break;
        case EXC_I386_NOEXT:
          *codeName = "EXC_I386_NOEXT";
          break;
        case EXC_I386_EXTOVR:
          *codeName = "EXC_I386_EXTOVR";
          break;
        case EXC_I386_EXTERR:
          *codeName = "EXC_I386_EXTERR";
          break;
        case EXC_I386_EMERR:
          *codeName = "EXC_I386_EMERR";
          break;
        case EXC_I386_BOUND:
          *codeName = "EXC_I386_BOUND";
          break;
        case EXC_I386_SSEEXTERR:
          *codeName = "EXC_I386_SSEEXTERR";
          break;
      }
#endif
      break;
    case EXC_BREAKPOINT:
      *name = "EXC_BREAKPOINT";
#if CLS_CPU_X86
      switch (code) {
        case EXC_I386_DIVERR:
          *codeName = "EXC_I386_DIVERR";
          break;
        case EXC_I386_SGLSTP:
          *codeName = "EXC_I386_SGLSTP";
          break;
        case EXC_I386_NMIFLT:
          *codeName = "EXC_I386_NMIFLT";
          break;
        case EXC_I386_BPTFLT:
          *codeName = "EXC_I386_BPTFLT";
          break;
        case EXC_I386_INTOFLT:
          *codeName = "EXC_I386_INTOFLT";
          break;
        case EXC_I386_BOUNDFLT:
          *codeName = "EXC_I386_BOUNDFLT";
          break;
        case EXC_I386_INVOPFLT:
          *codeName = "EXC_I386_INVOPFLT";
          break;
        case EXC_I386_NOEXTFLT:
          *codeName = "EXC_I386_NOEXTFLT";
          break;
        case EXC_I386_EXTOVRFLT:
          *codeName = "EXC_I386_EXTOVRFLT";
          break;
        case EXC_I386_INVTSSFLT:
          *codeName = "EXC_I386_INVTSSFLT";
          break;
        case EXC_I386_SEGNPFLT:
          *codeName = "EXC_I386_SEGNPFLT";
          break;
        case EXC_I386_STKFLT:
          *codeName = "EXC_I386_STKFLT";
          break;
        case EXC_I386_GPFLT:
          *codeName = "EXC_I386_GPFLT";
          break;
        case EXC_I386_PGFLT:
          *codeName = "EXC_I386_PGFLT";
          break;
        case EXC_I386_EXTERRFLT:
          *codeName = "EXC_I386_EXTERRFLT";
          break;
        case EXC_I386_ALIGNFLT:
          *codeName = "EXC_I386_ALIGNFLT";
          break;
        case EXC_I386_ENDPERR:
          *codeName = "EXC_I386_ENDPERR";
          break;
        case EXC_I386_ENOEXTFLT:
          *codeName = "EXC_I386_ENOEXTFLT";
          break;
      }
#endif
      break;
    case EXC_GUARD:
      *name = "EXC_GUARD";
      break;
  }
}

static bool FIRCLSMachExceptionRecord(FIRCLSMachExceptionReadContext* context,
                                      MachExceptionMessage* message) {
  if (!context || !message) {
    return false;
  }

  if (FIRCLSContextMarkAndCheckIfCrashed()) {
    FIRCLSSDKLog("Error: aborting mach exception handler because crash has already occurred\n");
    exit(1);
    return false;
  }

  FIRCLSFile file;

  if (!FIRCLSFileInitWithPath(&file, context->path, false)) {
    FIRCLSSDKLog("Unable to open mach exception file\n");
    return false;
  }

  FIRCLSFileWriteSectionStart(&file, "mach_exception");

  FIRCLSFileWriteHashStart(&file);

  FIRCLSFileWriteHashEntryUint64(&file, "exception", message->exception);

  // record the codes
  FIRCLSFileWriteHashKey(&file, "codes");
  FIRCLSFileWriteArrayStart(&file);
  for (mach_msg_type_number_t i = 0; i < message->codeCnt; ++i) {
    FIRCLSFileWriteArrayEntryUint64(&file, message->code[i]);
  }
  FIRCLSFileWriteArrayEnd(&file);

  const char* name = NULL;
  const char* codeName = NULL;

  FIRCLSMachExceptionNameLookup(message->exception, message->codeCnt > 0 ? message->code[0] : 0,
                                &name, &codeName);

  FIRCLSFileWriteHashEntryString(&file, "name", name);
  FIRCLSFileWriteHashEntryString(&file, "code_name", codeName);

  FIRCLSFileWriteHashEntryUint64(&file, "original_ports", context->originalPorts.count);
  FIRCLSFileWriteHashEntryUint64(&file, "time", time(NULL));

  FIRCLSFileWriteHashEnd(&file);

  FIRCLSFileWriteSectionEnd(&file);

  FIRCLSHandler(&file, message->thread.name, NULL);

  FIRCLSFileClose(&file);

  return true;
}

#else

INJECT_STRIP_SYMBOL(cls_mach_exception)

#endif