text:
package uk.co.amyboyd.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

/**
 * @author Unknown
 */
public class RssWriter {
    private static final XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    private RssFeed feed;

    private XMLEvent lineEnd;

    private XMLEvent tab;

    public RssWriter(final RssFeed feed) {
        this.feed = feed;
        setWhitespace(true);
    }

    public void setWhitespace(final boolean enable) {
        if (enable) {
            lineEnd = eventFactory.createDTD("\n");
            tab = eventFactory.createDTD("\t");
        } else {
            lineEnd = eventFactory.createDTD("");
            tab = eventFactory.createDTD("");
        }
    }

    public void setFeed(final RssFeed feed) {
        this.feed = feed;
    }

    public void write(final File outputFile) throws Exception {
        final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        final XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(outputFile));

        write(eventWriter);
    }

    public void write(final OutputStream stream) throws Exception {
        final XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
        final XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(stream);

        write(eventWriter);
    }

    private void write(final XMLEventWriter eventWriter) throws Exception {
        // Create and write Start Tag.
        final StartDocument startDocument = eventFactory.createStartDocument();
        eventWriter.add(startDocument);
        eventWriter.add(lineEnd);

        final StartElement rssStart = eventFactory.createStartElement("", "", "rss");
        eventWriter.add(rssStart);
        eventWriter.add(eventFactory.createAttribute("version", "2.0"));
        eventWriter.add(lineEnd);

        eventWriter.add(eventFactory.createStartElement("", "", "channel"));
        eventWriter.add(lineEnd);

        createNode(eventWriter, "title", feed.getTitle());
        createNode(eventWriter, "link", feed.getLink());
        createNode(eventWriter, "description", feed.getDescription());
        createNode(eventWriter, "language", feed.getLanguage());
        createNode(eventWriter, "copyright", feed.getCopyright());
        createNode(eventWriter, "pubdate", feed.getPubDate());

        for (final RssMessage message: feed.getMessages()) {
            eventWriter.add(eventFactory.createStartElement("", "", "item"));
            eventWriter.add(lineEnd);
            createNode(eventWriter, "title", message.getTitle());
            createNode(eventWriter, "description", message.getDescription());
            createNode(eventWriter, "link", message.getLink());
            createNode(eventWriter, "author", message.getAuthor());
            createNode(eventWriter, "guid", message.getGuid());
            eventWriter.add(lineEnd);
            eventWriter.add(eventFactory.createEndElement("", "", "item"));
            eventWriter.add(lineEnd);

        }

        eventWriter.add(lineEnd);
        eventWriter.add(eventFactory.createEndElement("", "", "channel"));
        eventWriter.add(lineEnd);
        eventWriter.add(eventFactory.createEndElement("", "", "rss"));
        eventWriter.add(lineEnd);
        eventWriter.add(eventFactory.createEndDocument());
        eventWriter.close();
    }

    private void createNode(final XMLEventWriter eventWriter, final String name, final String value)
            throws XMLStreamException {
        final StartElement sElement = eventFactory.createStartElement("", "", name);
        eventWriter.add(tab);
        eventWriter.add(sElement);

        final Characters characters = eventFactory.createCharacters(value);
        eventWriter.add(characters);

        final EndElement eElement = eventFactory.createEndElement("", "", name);
        eventWriter.add(eElement);
        eventWriter.add(lineEnd);
    }
}


text:
package com.gemstone.gemfire.internal.statistics;

import com.gemstone.gemfire.Statistics;

/**
 * Defines the minimal contract for a StatisticsSampler. This is used by
 * classes that need to interact with the sampler.
 *
 * @author Kirk Lund
 * @since 7.0
 */
public interface StatisticsSampler {

  /**
   * Returns the number of times a statistics resource has been add or deleted.
   */
  public int getStatisticsModCount();

  /**
   * Returns an array of all the current statistics resource instances.
   */
  public Statistics[] getStatistics();

  /**
   * Waits for the SampleCollector to be created and initialized.
   *
   * @param timeout maximum number of milliseconds to wait
   * @return the initialized SampleCollector or null if timed out
   * @throws InterruptedException if the current thread is interrupted while waiting
   */
  public SampleCollector waitForSampleCollector(long timeout) throws InterruptedException;

  /**
   * Waits for at least one statistics sample to occur before returning.
   *
   * @param timeout maximum number of milliseconds to wait
   * @return true if a statistics sample occurred; false if wait timed out
   * @throws InterruptedException if the current thread is interrupted while waiting
   */
  public boolean waitForSample(long timeout) throws InterruptedException;
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Cupella\ExplainPDO;

class Explain
{
    /** @var \PDO */
    private $pdo;
    /** @var string */
    private $queryString;
    /** @var array */
    private $parameters;

    /**
     * Explain constructor.
     * @param \PDO $pdo
     * @param string $queryString
     * @param array $parameters
     */
    public function __construct(\PDO $pdo, $queryString, array $parameters = array())
    {
        $this->pdo = $pdo;
        $this->queryString = $queryString;
        $this->parameters = $parameters;
    }

    /**
     * @return array|null
     */
    public function getResult()
    {
        if (preg_match('/^\s*(SELECT)\s+/i',$this->queryString)) {
            $sth = $this->pdo->prepare('EXPLAIN ' . $this->queryString);
            $sth->execute($this->parameters);
            return $sth->fetchAll(\PDO::FETCH_ASSOC);
        } else {
            return null;
        }
    }
}


text:
package gw.internal.gosu.ir.transform;

import gw.internal.gosu.parser.TypeVariableType;
import gw.internal.gosu.parser.ICompilableTypeInternal;
import gw.internal.gosu.parser.DynamicFunctionSymbol;
import gw.internal.gosu.parser.expressions.InitializerAssignment;
import gw.lang.ir.IRStatement;
import gw.lang.ir.IRExpression;
import gw.lang.ir.IRSymbol;
import gw.lang.ir.IRType;
import gw.lang.reflect.IType;
import gw.lang.reflect.IRelativeTypeInfo;
import gw.lang.parser.IStatement;
import gw.util.Stack;

import java.util.List;

public interface TopLevelTransformationContext {

  void maybeAssignOuterRef(List<IRStatement> statements);

  void maybePushSupersEnclosingThisRef( List<IRExpression> arguments );

  void pushEnumNameAndOrdinal( IType type, List<IRExpression> args );

  void initCapturedSymbolFields( List<IRStatement> statements );

  void initTypeVarFields( List<IRStatement> statements );

  void initializeInstanceFields( List<IRStatement> statements );

  void addAssertionsStaticField();

  ICompilableTypeInternal getGosuClass();

  boolean shouldUseReflection( IType declaringClass, IRelativeTypeInfo.Accessibility accessibility );

  String getOuterThisFieldName();

  String getOuterThisParamName();

  IType getSuperType();

  ICompilableTypeInternal getEnclosingType();

  String getSourceFileRef();

  String getSourceLine(int lineNumber);

  boolean isNonStaticInnerClass();

  boolean compilingEnhancement();

  boolean compilingEnum();

  boolean compilingBlock();

  boolean compilingProgram();

  IRType getIRTypeForCurrentClass();

  boolean isExternalSymbol( String name );

  // Calls that previously were on FunctionStatementTransformer

  IRSymbol makeAndIndexTempSymbol( IRType type );
  public IRSymbol makeAndIndexTempSymbol( String strNameSuffix, IRType type );

  IRSymbol getTypeParamIndex( TypeVariableType type );

  IRSymbol getSymbol(String symbolName);

  boolean hasSymbol( String strSymbol );

  void pushScope( boolean bInitialInstanceMethodScope );

  void popScope();

  void putSymbol(IRSymbol symbol);

  void putSymbols(List<IRSymbol> symbols);

  String makeTempSymbolName();

  boolean isBlockInvoke();

  boolean isFragmentEvaluation();

  IRStatement compile( IStatement stmt );

  IRSymbol createSymbol(String name, IRType type);

  boolean hasSuperBeenInvoked();

  void markSuperInvoked();

  void updateSuperInvokedAfterLastExpressionCompiles();

  Stack<IRScope> getScopes();

  String getCurrentFunctionName();

  boolean isCurrentFunctionStatic();

  IType getCurrentFunctionReturnType();

  IRStatement compileInitializerAssignment( InitializerAssignment stmt, IRExpression root );

  boolean currentlyCompilingBlock();

  DynamicFunctionSymbol getCurrentFunction();
}


text:
using System;
using System.IO;

using Microsoft.Scripting.Utils;

namespace Microsoft.Scripting {

    [Serializable]
    internal sealed class SourceStringContentProvider : TextContentProvider {
        private readonly string _code;

        internal SourceStringContentProvider(string code) {
            ContractUtils.RequiresNotNull(code, nameof(code));

            _code = code;
        }

        public override SourceCodeReader GetReader() {
            return new SourceCodeReader(new StringReader(_code), null);
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Tapesia corni f. corni

### Remarks
null


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package com.ebay.trading.api;

import java.io.Serializable;
import com.leansoft.nano.annotation.*;
import java.util.List;
import java.util.Date;

/**
 *
 * Details about a specific site.
 *
 */
public class SiteDetailsType implements Serializable {

    private static final long serialVersionUID = -1L;

	@Element(name = "Site")
	@Order(value=0)
	public SiteCodeType site;

	@Element(name = "SiteID")
	@Order(value=1)
	public Integer siteID;

	@Element(name = "DetailVersion")
	@Order(value=2)
	public String detailVersion;

	@Element(name = "UpdateTime")
	@Order(value=3)
	public Date updateTime;

	@AnyElement
	@Order(value=4)
	public List<Object> any;

}


text:
"""This file defines the Concrete Array --- a leaf node in the expression graph

A concrete array is constructed from a Data Descriptor Object which handles the
 indexing and basic interpretation of bytes
"""

from __future__ import absolute_import, division, print_function

import datashape

from ..compute.ops import ufuncs
from .. import compute

from ..datadescriptor import (DDesc, Deferred_DDesc, Stream_DDesc, ddesc_as_py)
from ..io import _printing

class Array(object):
    """An Array contains:

        DDesc
        Sequence of Bytes (where are the bytes)
        Index Object (how do I get to them)
        Data Shape Object (what are the bytes? how do I interpret them)
        axis and dimension labels
        user-defined meta-data (whatever are needed --- provenance propagation)
    """
    def __init__(self, data, axes=None, labels=None, user={}):
        if not isinstance(data, DDesc):
            raise TypeError(('Constructing a blaze array directly '
                            'requires a data descriptor, not type '
                            '%r') % (type(data)))
        self.ddesc = data
        self.axes = axes or [''] * (len(self.ddesc.dshape) - 1)
        self.labels = labels or [None] * (len(self.ddesc.dshape) - 1)
        self.user = user
        self.expr = None

        if isinstance(data, Deferred_DDesc):
            # NOTE: we need 'expr' on the Array to perform dynamic programming:
            #       Two concrete arrays should have a single Op! We cannot
            #       store this in the data descriptor, since there are many
            self.expr = data.expr  # hurgh

        # Inject the record attributes.
        injected_props = {}
        # This is a hack to help get the blaze-web server onto blaze arrays.
        ds = data.dshape
        ms = ds[-1] if isinstance(ds, datashape.DataShape) else ds
        if isinstance(ms, datashape.Record):
            for name in ms.names:
                injected_props[name] = _named_property(name)

        # Need to inject attributes on the Array depending on dshape
        # attributes, in cases other than Record
        if data.dshape in [datashape.dshape('int32'),
                           datashape.dshape('int64')]:
            def __int__(self):
                # Evaluate to memory
                e = compute.eval.eval(self)
                return int(e.ddesc.dynd_arr())
            injected_props['__int__'] = __int__
        elif data.dshape in [datashape.dshape('float32'),
                             datashape.dshape('float64')]:
            def __float__(self):
                # Evaluate to memory
                e = compute.eval.eval(self)
                return float(e.ddesc.dynd_arr())
            injected_props['__float__'] = __float__
        elif ms in [datashape.complex_float32, datashape.complex_float64]:
            if len(data.dshape) == 1:
                def __complex__(self):
                    # Evaluate to memory
                    e = compute.eval.eval(self)
                    return complex(e.ddesc.dynd_arr())
                injected_props['__complex__'] = __complex__
            injected_props['real'] = _ufunc_to_property(ufuncs.real)
            injected_props['imag'] = _ufunc_to_property(ufuncs.imag)
        elif ms == datashape.date_:
            injected_props['year'] = _ufunc_to_property(ufuncs.year)
            injected_props['month'] = _ufunc_to_property(ufuncs.month)
            injected_props['day'] = _ufunc_to_property(ufuncs.day)
        elif ms == datashape.time_:
            injected_props['hour'] = _ufunc_to_property(ufuncs.hour)
            injected_props['minute'] = _ufunc_to_property(ufuncs.minute)
            injected_props['second'] = _ufunc_to_property(ufuncs.second)
            injected_props['microsecond'] = _ufunc_to_property(ufuncs.microsecond)
        elif ms == datashape.datetime_:
            injected_props['date'] = _ufunc_to_property(ufuncs.date)
            injected_props['time'] = _ufunc_to_property(ufuncs.time)
            injected_props['year'] = _ufunc_to_property(ufuncs.year)
            injected_props['month'] = _ufunc_to_property(ufuncs.month)
            injected_props['day'] = _ufunc_to_property(ufuncs.day)
            injected_props['hour'] = _ufunc_to_property(ufuncs.hour)
            injected_props['minute'] = _ufunc_to_property(ufuncs.minute)
            injected_props['second'] = _ufunc_to_property(ufuncs.second)
            injected_props['microsecond'] = _ufunc_to_property(ufuncs.microsecond)

        if injected_props:
            self.__class__ = type('Array', (Array,), injected_props)

    @property
    def dshape(self):
        return self.ddesc.dshape

    @property
    def deferred(self):
        return self.ddesc.capabilities.deferred

    def __array__(self):
        import numpy as np

        # TODO: Expose PEP-3118 buffer interface

        if hasattr(self.ddesc, "__array__"):
            return np.array(self.ddesc)

        return np.array(self.ddesc.dynd_arr())

    def __iter__(self):
        if len(self.dshape.shape) == 1:
            return (ddesc_as_py(dd) for dd in self.ddesc)
        return (Array(dd) for dd in self.ddesc)

    def __getitem__(self, key):
        dd = self.ddesc.__getitem__(key)

        # Single element?
        if not self.deferred and not dd.dshape.shape:
            return ddesc_as_py(dd)
        else:
            return Array(dd)

    def __setitem__(self, key, val):
        self.ddesc.__setitem__(key, val)

    def __len__(self):
        shape = self.dshape.shape
        if shape:
            return shape[0]
        raise IndexError('Scalar blaze arrays have no length')

    def __nonzero__(self):
        # For Python 2
        if len(self.dshape.shape) == 0:
            # Evaluate to memory
            e = compute.eval.eval(self)
            return bool(e.ddesc.dynd_arr())
        else:
            raise ValueError("The truth value of an array with more than one "
                             "element is ambiguous. Use a.any() or a.all()")

    def __bool__(self):
        # For Python 3
        if len(self.dshape.shape) == 0:
            # Evaluate to memory
            e = compute.eval.eval(self)
            return bool(e.ddesc.dynd_arr())
        else:
            raise ValueError("The truth value of an array with more than one "
                             "element is ambiguous. Use a.any() or a.all()")

    def __str__(self):
        if hasattr(self.ddesc, '_printer'):
            return self.ddesc._printer()
        return _printing.array_str(self)

    def __repr__(self):
        if hasattr(self.ddesc, "_printer_repr"):
            return self.ddesc._printer_repr()
        return _printing.array_repr(self)

    def where(self, condition):
        """Iterate over values fulfilling a condition."""
        if self.ddesc.capabilities.queryable:
            iterator = self.ddesc.where(condition)
            ddesc = Stream_DDesc(iterator, self.dshape, condition)
            return Array(ddesc)
        else:
            raise ValueError(
                'Data descriptor do not support efficient queries')

def _named_property(name):
    @property
    def getprop(self):
        return Array(self.ddesc.getattr(name))
    return getprop

def _ufunc_to_property(uf):
    @property
    def getprop(self):
        return uf(self)
    return getprop

def binding(f):
    def binder(self, *args):
        return f(self, *args)
    return binder

def __rufunc__(f):
    def __rop__(self, other):
        return f(other, self)
    return __rop__

def _inject_special_binary(names):
    for ufunc_name, special_name in names:
        ufunc = getattr(ufuncs, ufunc_name)
        setattr(Array, '__%s__' % special_name, binding(ufunc))
        setattr(Array, '__r%s__' % special_name, binding(__rufunc__(ufunc)))

def _inject_special(names):
    for ufunc_name, special_name in names:
        ufunc = getattr(ufuncs, ufunc_name)
        setattr(Array, '__%s__' % special_name, binding(ufunc))

_inject_special_binary([
    ('add', 'add'),
    ('subtract', 'sub'),
    ('multiply', 'mul'),
    ('true_divide', 'truediv'),
    ('mod', 'mod'),
    ('floor_divide', 'floordiv'),
    ('equal', 'eq'),
    ('not_equal', 'ne'),
    ('greater', 'gt'),
    ('greater_equal', 'ge'),
    ('less_equal', 'le'),
    ('less', 'lt'),
    ('divide', 'div'),
    ('bitwise_and', 'and'),
    ('bitwise_or', 'or'),
    ('bitwise_xor', 'xor'),
    ('power', 'pow'),
    ])
_inject_special([
    ('bitwise_not', 'invert'),
    ('negative', 'neg'),
    ])

"""
These should be functions

    @staticmethod
    def fromfiles(list_of_files, converters):
        raise NotImplementedError

    @staticmethod
    def fromfile(file, converter):
        raise NotImplementedError

    @staticmethod
    def frombuffers(list_of_buffers, converters):
        raise NotImplementedError

    @staticmethod
    def frombuffer(buffer, converter):
        raise NotImplementedError

    @staticmethod
    def fromobjects():
        raise NotImplementedError

    @staticmethod
    def fromiterator(buffer):
        raise NotImplementedError

"""


text:
import { storiesOf } from "@storybook/react"
import React from "react"

import SelectableLink from "../SelectableLink"

storiesOf("Onboarding", module).add("SelectableLink", () => {
  return (
    <div style={{ width: "400px" }}>
      <SelectableLink text="Buy Art & Design" onSelect={selected => selected} />
    </div>
  )
})


text:
package commenttemplate.expressions.function;

import java.lang.reflect.Array;
import java.util.Collection;
import commenttemplate.expressions.tree.Exp;
import commenttemplate.context.Context;

/**
 *
 * @author thiago
 */
public class Length extends Function {

	protected int length(Object sizeable) {
		if (sizeable instanceof Collection) {
			return ((Collection)sizeable).size();
		}

		if (sizeable instanceof String) {
			return ((String)sizeable).length();
		}

		if (sizeable.getClass().isArray()) {
			return Array.getLength(sizeable);
		}

		return 0;
	}

	@Override
	public Object eval(Context context) {
		Exp []args = getArgs();
		int length = 0;

		for (Exp arg : args) {
			Object evaluated = arg.eval(context);
			length += length(evaluated);
		}

		return length;
	}
}


text:
@implementation WMHubWindow

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.windowLevel = UIWindowLevelAlert - 1;
    }
    return self;
}

@end


text:
discover
===================

[![License](http://img.shields.io/:license-mit-blue.svg)](http://doge.mit-license.org)

#### Table of Contents

1. [Overview](#overview)
2. [Module Description - What the module does and why it is useful](#module-description)
3. [Setup - The basics of getting started with discover](#setup)
    * [Setup requirements](#setup-requirements)
    * [Beginning with discover](#beginning-with-discover)
4. [Usage - Configuration options and additional functionality](#usage)
5. [Limitations - OS compatibility, etc.](#limitations)
6. [Development - Guide for contributing to the module](#development)

## Overview

Used to install the Discover tool on Kali.

## Module Description

This module will install Discover on a Kali machine. This may be useful for Systems Administrators or
Penetration Testers.

## Setup

### Setup Requirements

The git puppet module is required for this module to work
properly. Please add it to your Puppetfile like so:

```
mod 'puppetlabs/git'
```

### Beginning with discover

Simply specify the directory you wish Discover to be installed to as a parameter and run the module as you would any other.

## Usage
Install the discover tool to /opt/discover:
```
class { 'discover':
  install_location => '/opt/discover',
}
```

## Limitations

This has been built to work with Kali only.

## Development

Feel free to fork this up and issue a pull request if you want to improve on the
work that has already been done.

## Release Notes/Contributors/Etc

Jayson Grace (l50) <jayson.e.grace@gmail.com>


text:
<?php

require_once('linode.php');

$sizes = $provider->listSizes(); // list linode plans
print_r($sizes);

$locations = $provider->listLocations(); // list linode datacenters
print_r($locations);


text:
class HitsJS : public Nan::ObjectWrap {
public:
  static NAN_MODULE_INIT(Init);
  static v8::Local<v8::Object> NewObject(lucy_Hits* new_hit_doc);

private:
  explicit HitsJS() {}
  virtual ~HitsJS() {
    CFISH_DECREF(lucy_hits);
  }
  static NAN_GETTER(Total_Hits);
  static NAN_METHOD(Hits_Next);
  static NAN_METHOD(New);

  static Nan::Persistent<v8::Function> constructor;
  lucy_Hits *lucy_hits;

};
#endif


text:
package kata.test;

import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
import org.eclipse.collections.impl.test.Verify;
import kata.domain.Task;
import kata.domain.TaskFinder;
import kata.domain.TaskList;
import org.junit.Assert;
import org.junit.Test;

import java.sql.Timestamp;
import java.util.Date;

public class ExercisesAuditOnly
        extends AbstractMithraTest
{
    @Override
    protected String[] getTestDataFilenames()
    {
        return new String[]{"testdata/data_Tasks.txt"}; // Look into this file to see the test data being used
    }

// **** NOTES ****
// (1)
// Different applications can have different conventions to represent the business dates and processing dates.
// In this exercise, we are using:
// * IN_Z<@processingDate, OUT_Z> = @processingDate (see toIsInclusive() in processingDate attribute
// * Infinity date = "9999-12-01 23:59:00.0", a.k.a. kata.util.TimestampProvider.getInfinityDate().
// Look at the definition of the processingDate attribute in Task.xml to see how this is defined/used.
//
// (2)
// Are you completely unfamiliar with chaining?
// See the Reladomo documentation

//------------------------ Question 1 --------------------------------------------------------
// Get all Tasks

    public TaskList getActiveTasks()
    {
        Assert.fail("Implement this functionality to make the test pass");
        return null;
    }

    @Test
    public void testQ1()
    {
        TaskList tasks = this.getActiveTasks();

        Verify.assertSetsEqual(UnifiedSet.newSetWith("Colonize Moon", "Dam River"),
                tasks.asEcList().collect(TaskFinder.name()).toSet());
        Verify.assertSetsEqual(UnifiedSet.newSetWith("In Design", "Restarted"),
                tasks.asEcList().collect(TaskFinder.status()).toSet());
    }

//------------------------ Question 2 --------------------------------------------------------
// Get all tasks for a given date

    public TaskList getTasksAsOf(Date date)
    {
        Assert.fail("Implement this functionality to make the test pass");
        return null;
    }

    @Test
    public void testQ2()
    {
        Timestamp processingDate = Timestamp.valueOf("1991-08-15 18:30:00.0");

        TaskList tasks = this.getTasksAsOf(processingDate);

        Verify.assertSetsEqual(UnifiedSet.newSetWith("Build Bridge", "Dam River"),
                tasks.asEcList().collect(TaskFinder.name()).toSet());
        Verify.assertSetsEqual(UnifiedSet.newSetWith("Restarted", "Damming"),
                tasks.asEcList().collect(TaskFinder.status()).toSet());
    }

//------------------------ Question 3 --------------------------------------------------------
// Get history for a specific taskId, across all time

    public TaskList getTaskHistory(int taskId)
    {
        Assert.fail("Implement this functionality to make the test pass");
        return null;
    }

    @Test
    public void testQ3()
    {
        TaskList tasks = this.getTaskHistory(1);

        Verify.assertAllSatisfy(tasks, Predicates.attributeEqual(TaskFinder.name(), "Build Bridge"));

        Verify.assertSetsEqual(UnifiedSet.newSetWith(
                Timestamp.valueOf("1965-01-01 06:00:00.0"),
                Timestamp.valueOf("1967-01-01 11:30:22.0"),
                Timestamp.valueOf("1990-01-01 06:00:00.0")),
                tasks.asEcList().collect(TaskFinder.processingDateFrom()).toSet());
    }

//------------------------ Question 4 --------------------------------------------------------
// End a task.  The task should no longer show up in current query results.

    public void endTask(final String name)
    {
        Assert.fail("Implement this functionality to make the test pass");
    }

    @Test
    public void testQ4()
    {
        int tasksBefore = new TaskList(TaskFinder.all()).count();

        Task damRiver = TaskFinder.findOne(TaskFinder.name().eq("Dam River"));

        this.endTask(damRiver.getName());

        Assert.assertTrue(damRiver.isDeletedOrMarkForDeletion());

        int tasksAfter = new TaskList(TaskFinder.all()).count();

        Assert.assertEquals(tasksBefore - 1, tasksAfter);
    }

//------------------------ Question 5 --------------------------------------------------------
// Modify the status of an existing task.
// Return the modified task.

    public Task updateTaskStatus(final int taskId, final String newStatus)
    {
        Assert.fail("Implement this functionality to make the test pass");
        return null;
    }

    @Test
    public void testQ5()
    {
        Task colonizeMoon = this.updateTaskStatus(3, "Designing Moonbuggy");

        Assert.assertEquals(3, colonizeMoon.getTaskId());
        Assert.assertEquals("Colonize Moon", colonizeMoon.getName());
        Assert.assertEquals("Designing Moonbuggy", colonizeMoon.getStatus());
        Assert.assertTrue(colonizeMoon.getProcessingDateFrom().after(Timestamp.valueOf("2010-01-01 06:00:00.0")));
    }
}


text:
/*
 * onionrouting.cc
 *
 *  Created on: Feb 5, 2014
 *      Author: diarraa
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <time.h>

#include <peerreview/tools/parameters.h>
#include <peerreview/transport/id/simple.h>
#include "onionrouting.h"

#define SUBSYSTEM "onionrouting"

OnionRouting::OnionRouting(IdentityTransport *transport, Parameters *params,
        int nbRelais, bool logEvents) {
    this->transport = transport;
    this->app = NULL;
    this->logEvents = logEvents;
    this->numMembers = 0;
    this->memberInfo = NULL;
    this->commandTime = -1;
    this->params = params;
    this->command = (char*)malloc(200*sizeof(char));
    memset(&state, 0, sizeof(state));
    init();

    if (params && params->existsSetting("onionroutingMisbehavior")) {
        char valuebuf[200];
        params->getAsString("onionroutingMisbehavior", valuebuf, sizeof(valuebuf));
        char *sti = strtok(valuebuf, ",");
        char *scmd = sti ? strtok(NULL, "\r\n") : NULL;
        if (!scmd)
            panic("Syntax: onionroutingMisbehavior=timeMicros,command");

        commandTime = atoll(sti);
        strcpy(command, scmd);
    }
    //this->nodes = (char**)malloc(10*sizeof(char*));
    //this->nbFwd = 0;
    //this->nbRcvd = 0;
    this->nbRelais = nbRelais;

    this->nbEVT_BOOTSTRAP = 0;
    this->nbEVT_TRANSMIT = 0;
    this->nbEVT_SEND_O = 0;
    this->nbEVT_RECV_O = 0;
    this->nbEVT_STATUS = 0;

    /*Read parameters from the configuration file*/
    if (params)
        readMemberInfo(params);
}

OnionRouting::~OnionRouting() {
    init();

    if (memberInfo) {
        for (int i = 0; i < numMembers; i++)
            delete memberInfo[i].subject;
        free(memberInfo);
    }

    if (app)
        delete app;
}

void OnionRouting::init() {
    for (int i = 0; i < state.numPeers; i++)
        delete state.peer[i].handle;

    memset(&state, 0, sizeof(state));
    state.numPeers = 0;
    state.numExpectedMessages = 0;
    state.lastExpectedMessage = 5;
}

void OnionRouting::readMemberInfo(Parameters *params) {
    /* The mapping between nodes and their witnesses is static;
       each node reads it from the configuration file and
       stores it in memory. */

    numMembers = params->numSections();
    memberInfo = (struct memberInfo*) malloc(
            sizeof(struct memberInfo) * numMembers);
    nodes = (char**) malloc(sizeof(char*) * numMembers);
    if (!memberInfo)
        panic("OR: Out of memory when allocating memberInfo");

    for (int i = 0; i < numMembers; i++) {
        const char *name = params->getSectionByIndex(i);
        params->selectSection(name);
        memberInfo[i].subject = transport->readNodeHandleFromString(name);
        memberInfo[i].numWitnesses = params->getAsInt("witnesses");
    }

}

/*peeledOnion *OnionRouting::peelOnion(char *onion) {
  peeledOnion *po = (peeledOnion*) malloc(10 * sizeof(peeledOnion));
  char *tmp1 = strtok(onion, "|");
  char *tmp2 = strtok(NULL, "|");
  char *tmp3 = strtok(NULL, "");
  printf("**********\n");
  printf("tmp1 = %s\n",tmp1);
  printf("tmp2 = %s\n",tmp2);
  printf("tmp3 = %s\n",tmp3);
  if (tmp2) {
  char *peerID = strtok(tmp2, "/");
  char *peerIP = peerID ? strtok(NULL, "/") : NULL;
  printf("peerID = %s\n",peerID);
  printf("peerIP = %s\n",peerIP);
  printf("**********\n");
  po->node = new SimpleNodeHandle(
  SimpleIdentifier::readFromString(peerID, 160),
  inet_addr(peerIP));
  if (tmp3) {
  char *tmp = strcat(tmp1, "|");
  po->msg = strcat(tmp, tmp3);
  } else
  po->msg = tmp1;

  } else {
  if (tmp3) {
  char *peerID = strtok(tmp3, "/");
  char *peerIP = peerID ? strtok(NULL, "/") : NULL;
  po->node = new SimpleNodeHandle(
  SimpleIdentifier::readFromString(peerID, 160),
  inet_addr(peerIP));
  } else {
  po->node = NULL;
  }
  po->msg = tmp1;

  }

  return po;
  }*/

void OnionRouting::setCallback(OnionRoutingApp *app) {
    this->app = app;
}

void OnionRouting::bootstrap(NodeHandle **initialPeers, int numInitialPeers) {
    assert(state.numPeers == 0);
    char buf1[256];

    /* This is called once after startup to initialize the node.
       We record an entry in the secure history, so we can repeat
       the call during replay. */

    unsigned char event[1 + MAX_HANDLE_SIZE * numInitialPeers];
    unsigned int eventLen = 0;

    Basics::writeByte(event, &eventLen, numInitialPeers);
    for (int i = 0; i < numInitialPeers; i++) {

            //Jeremie//plog(2, "Adding peer %s [%d]", initialPeers[i]->render(buf1),state.numPeers);
        initialPeers[i]->write(event, &eventLen, sizeof(event));
        assert(state.numPeers < MAX_PEERS);
        state.peer[state.numPeers].handle = initialPeers[i]->clone();
        state.peer[state.numPeers].active = true;
        state.numPeers++;
    }

    if (logEvents) {
        nbEVT_BOOTSTRAP++;

        //Jeremie//plog(3,"EVT_BOOTSTRAP : EntrySize = %lld nbEVT_BOOTSTRAP = %d", eventLen, nbEVT_BOOTSTRAP);
        transport->logEvent(EVT_BOOTSTRAP, event, eventLen);
    }
}

void OnionRouting::send(unsigned int seq, char *msg, int len, NodeHandle* dest) {
    if (logEvents) {
        unsigned char entry[sizeof(seq) + 20];
        *(unsigned int*)&entry[0] = seq;
        transport->hash(&entry[sizeof(seq)], (unsigned char*) msg, len);
        nbEVT_TRANSMIT++;

        //Jeremie//plog(3,"EVT_TRANSMIT : EntrySize = %lld nbEVT_TRANSMIT = %d", sizeof(entry), nbEVT_TRANSMIT);
        transport->logEvent(EVT_TRANSMIT, entry, sizeof(entry));
        nbEVT_SEND_O++;

        //Jeremie//plog(3,"EVT_SEND_O : EntrySize = %lld nbEVT_SEND_O = %d", len, nbEVT_SEND_O);
        transport->logEvent(EVT_SEND_O, msg, len);
    }

    //Jeremie//plog(3, "Transmitting message #%d (%d bytes)", seq, len);

    /* Next, we peel onion and create a message to send */
    unsigned char *message = (unsigned char*) malloc(6 + len);
    message[0] = MSG_DATA;
    message[1] = 50; /* TTL */
    *(unsigned int*) &message[2] = seq;
    memcpy(message + 6, msg, len);

    char buf[200];
    //printf("Sending onion to %s\n", dest->render(buf));
    transport->send(dest, false, message, len + 6, 6);
    //transport->send(dest, false, message, len + 6, -1);
    free(message);
}

void OnionRouting::receive(NodeHandle *source, bool datagram,
        unsigned char *msg, int msglen) {
    char buf1[256];

    /* Respond to incoming messages. The first byte is the message type. */
    switch (msg[0]) {
        case MSG_DATA: {
                           int seq = *(unsigned int*) &msg[2];

                           //Jeremie//plog(3, "Received DATA #%d from %s (%d bytes, TTL %d)", seq, source->render(buf1), msglen - 6, msg[1]);

                           /* We got a data block. Give it to the application. */
                           if (app) {
                               app->receive(seq, (char*) &msg[6], msglen - 6);
                               if(logEvents)
                                   nbEVT_RECV_O++;
                               //Jeremie//plog(3,"EVT_RECV_O : EntrySize = %lld nbEVT_RECV_O = %d", msglen-6, nbEVT_RECV_O);
                               transport->logEvent(EVT_RECV_O,(char*) &msg[6],msglen-6);
                               //nbRcvd++;
                               ////Jeremie//plog(4, "nbRcvd = %d", nbRcvd);
                           }

                           /* If we're a bad node, eat the block */
                           /*if ((commandTime>=0) && (transport->getTime()>=commandTime) && !strcasecmp(command, "silent")) {
                             //Jeremie//plog(4, "Mischief: Silent");
                           //printf("totooo\n"); //par moi
                           msg[1] = 1;
                           }

                           if ((--msg[1]) > 0) {
                           //pour l'injection de fautes
                           } else {
                           warning("Message TTL has expired; dropping message");
                           }*/
                           break;
                       }
        case MSG_CHECK: {

                            //Jeremie//plog(3, "Received CHECK from %s", source->render(buf1));
                            break;
                        }
        default: {
                     warning("Unknown message type %d; ignoring", msg[0]);
                     break;
                 }
    }

}

/////////////////////// PeerReview //////////////////////////
void OnionRouting::statusChange(Identifier *id, int status) {
    char buf1[256];

    //Jeremie//plog(2, "Update: %s becomes %d", id->render(buf1), status);

    /* This is called when the state of another node changes (that is,
       it becomes trusted, suspected or exposed). Again, we record
       an entry in the secure history so we can reproduce the call
       during replay. We also reconfigure the topology to exclude
       suspected or exposed nodes. */

    if (logEvents) {
        unsigned char event[1+MAX_ID_SIZE];
        unsigned int eventLen = 0;

        Basics::writeByteSafe(status, event, &eventLen, sizeof(event));
        id->write(event, &eventLen, sizeof(event));
        nbEVT_STATUS++;

        //Jeremie//plog(3,"EVT_STATUS : EntrySize = %lld nbEVT_STATUS = %d", eventLen, nbEVT_STATUS);
        transport->logEvent(EVT_STATUS, event, eventLen);
    }

    for (int i=0; i<state.numPeers; i++) {
        if (state.peer[i].handle->getIdentifier()->equals(id)) {
            state.peer[i].active = (status == STATUS_TRUSTED);
            if (status == STATUS_SUSPECTED) {
                unsigned char msg[1] = { MSG_CHECK };
                transport->send(state.peer[i].handle, false, msg, sizeof(msg));
            }
        }
    }
}

void OnionRouting::timerExpired(int timerID) {

}

int OnionRouting::storeCheckpoint(unsigned char *buffer, unsigned int maxlen) {
    return 0;
}

bool OnionRouting::loadCheckpoint(unsigned char *buffer, unsigned int len) {
    return false;
}

void OnionRouting::getWitnesses(Identifier *subject, WitnessListener *callback){
    assert(memberInfo);
    char buf1[256];

    /* This determines a list of witnesses for a given node. Since the mapping
       in this application is static, we just have to look up this information
       in memory (it was read from the config file earlier) */

    int idx = -1;
    for (int i=0; i<numMembers; i++) {
        if (subject->equals(memberInfo[i].subject->getIdentifier()))
            idx = i;
    }

    if (idx<0)
        panic("Cannot answer getWitnesses(%s) request", subject->render(buf1));

    NodeHandle **witnesses = (NodeHandle**) malloc(memberInfo[idx].numWitnesses * sizeof(NodeHandle*));
    for (int i=0; i<memberInfo[idx].numWitnesses; i++)
        witnesses[i] = memberInfo[(idx+numMembers-(1+i))%numMembers].subject;

    callback->notifyWitnessSet(subject, memberInfo[idx].numWitnesses, witnesses);

    free(witnesses);

}

int OnionRouting::getMyWitnessedNodes(NodeHandle **nodes, int maxResults){
    assert(memberInfo);

    /* Find out which nodes are witnessed by the local node. Again, the
       mapping is static, so we just have to look it up in memory. */

    NodeHandle *myself = transport->getLocalHandle();
    int myIndex = -1;
    for (int i=0; (myIndex<0) && (i<numMembers); i++)
        if (memberInfo[i].subject->equals(myself))
            myIndex = i;

    assert(myIndex >= 0);

    int numResults = 0;
    for (int i=1; (i<numMembers) && (numResults<maxResults); i++) {
        if (memberInfo[(myIndex+i)%numMembers].numWitnesses >= i)
            nodes[numResults++] = memberInfo[(myIndex+i)%numMembers].subject;
    }

    return numResults;
}

PeerReviewCallback *OnionRouting::getReplayInstance(ReplayWrapper *replayWrapper){
    /* Get another instance of the state machine for replay... */

    //OnionRouting *instance = new OnionRouting(replayWrapper, NULL, false);
    //OnionRoutingReplayHelper *helper = new OnionRoutingReplayHelper(instance, replayWrapper);

    /* ... and register all the event types we've been writing to the
       secure history, so we can reproduce the corresponding events */
    /*replayWrapper->registerCallback(helper);
      replayWrapper->registerEvent(helper, EVT_BOOTSTRAP);
      replayWrapper->registerEvent(helper, EVT_TRANSMIT);
      replayWrapper->registerEvent(helper, EVT_STATUS);
      return instance;*/
    return NULL;
}

void OnionRouting::OnionRoutingReplayHelper::replayEvent(unsigned char type, unsigned char *entry, int entrySize)
{
    /*switch (type) {
      case EVT_BOOTSTRAP:
      {
      Replay a bootstrap event

      unsigned int pos = 0;
      int numHandles = Basics::readByte(entry, &pos);
      NodeHandle **handles = (NodeHandle**) malloc(numHandles * sizeof(NodeHandle*));
      for (int i=0; i<numHandles; i++)
      handles[i] = transport->readNodeHandle(entry, &pos, entrySize);
      onionrouting->bootstrap(handles, numHandles);
      for (int i=0; i<numHandles; i++)
      delete handles[i];
      free(handles);
      break;

      }
      case EVT_STATUS:
      {
      Replay a status change event

      unsigned int pos = 0;
      int status = Basics::readByte(entry, &pos);
      Identifier *id = transport->readIdentifier(entry, &pos, entrySize);
      onionrouting->statusChange(id, status);
      delete id;
      break;

      }
      case EVT_TRANSMIT:
      Replay a transmission event

      transport->logText(SUBSYSTEM, 2, "Transmitting %d bytes, seq #%d", entrySize-4, *(unsigned int*)&entry[0]);
    //onionrouting->send(*(unsigned int*)&entry[0], (char*)&entry[4], entrySize-4);
    NodeHandle *dest;  //à donner une valeur
    onionrouting->send(*(unsigned int*)&entry[0], (char*)&entry[4], entrySize-4,dest);

    break;
    default:
    panic("Replay helper cannot replay events of type #%d", type);
    }*/

}


text:
namespace Csla.Core
{
  /// <summary>
  /// Defines the methods required to participate
  /// in n-level undo within the CSLA .NET framework.
  /// </summary>
  /// <remarks>
  /// This interface is used by Csla.Core.UndoableBase
  /// to initiate begin, cancel and apply edit operations.
  /// </remarks>
  public interface IUndoableObject
  {
    /// <summary>
    /// Gets the current edit level of the object.
    /// </summary>
    int EditLevel { get; }
    /// <summary>
    /// Copies the state of the object and places the copy
    /// onto the state stack.
    /// </summary>
    /// <param name="parentEditLevel">
    /// Parent object's edit level.
    /// </param>
    /// <param name="parentBindingEdit">
    /// Indicates whether parent is in edit mode due to data binding.
    /// </param>
    void CopyState(int parentEditLevel, bool parentBindingEdit);
    /// <summary>
    /// Restores the object's state to the most recently
    /// copied values from the state stack.
    /// </summary>
    /// <remarks>
    /// Restores the state of the object to its
    /// previous value by taking the data out of
    /// the stack and restoring it into the fields
    /// of the object.
    /// </remarks>
    /// <param name="parentEditLevel">
    /// Parent object's edit level.
    /// </param>
    /// <param name="parentBindingEdit">
    /// Indicates whether parent is in edit mode due to data binding.
    /// </param>
    void UndoChanges(int parentEditLevel, bool parentBindingEdit);
    /// <summary>
    /// Accepts any changes made to the object since the last
    /// state copy was made.
    /// </summary>
    /// <remarks>
    /// The most recent state copy is removed from the state
    /// stack and discarded, thus committing any changes made
    /// to the object's state.
    /// </remarks>
    /// <param name="parentEditLevel">
    /// Parent object's edit level.
    /// </param>
    /// <param name="parentBindingEdit">
    /// Indicates whether parent is in edit mode due to data binding.
    /// </param>
    void AcceptChanges(int parentEditLevel, bool parentBindingEdit);
  }
}


text:
module FFaker
  module Tweet
    extend ModuleUtils
    extend self

    # Options
    # num_hashtags:   How many hashtags (default: (skewed (40%) 1-4))
    # num_mentions:   How many mentions (default: (skewed (20% 1-2))
    # reply:          Add reply? (default: (random 10%)
    # body_length:    Target length (rand(20..140)) (will be <= target)
    def tweet(args = {})
      options = {
        num_hashtags: [0, rand(-5..4)].max,
        num_mentions: [0, rand(-7..2)].max,
        reply: (rand(1..10) == 1),
        body_length: rand(20..140)
      }.merge(args)

      my_reply = options[:reply] ? "#{mention} " : ''
      my_mentions = (options[:num_mentions]).positive? ? "#{mentions(options[:num_mentions])} " : ''
      my_tags = tags(options[:num_hashtags])

      remaining = [
        options[:body_length],
        140 - (my_reply.size + my_mentions.size + my_tags.size)
      ].min

      "#{my_reply}#{body(remaining)}#{my_mentions}#{my_tags}"
    end

    def mention
      "@#{FFaker::Internet.user_name}"
    end

    def mentions(num = 2)
      mention_names = []
      num.times { mention_names << mention }
      mention_names.join(' ')
    end

    def body(required_length = 140)
      required_length = [required_length, 20].max
      body = ''
      prefix = ''
      until body.size > required_length
        body += "#{prefix}#{FFaker::Lorem.sentence}"
        prefix = ' '
      end
      body[required_length - 1] = '#'
      body.gsub(/\s\S*\#.*$/, '.')
    end

    def tags(num_tags = 2)
      fetch_sample(HASHTAG, count: num_tags).join(' ')
    end
  end
end


text:
package com.inepex.inei18n.shared;

import java.util.TreeMap;

public class I18nStoreBase {

    protected TreeMap<String, I18nModule> modulesByName = new TreeMap<String, I18nModule>();

    public void registerModule(I18nModule module) {
        modulesByName.put(module.getModuleName(), module);
    }

}


text:
package org.eclipse.php.internal.core;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.dltk.core.ICallHierarchyFactory;
import org.eclipse.dltk.core.ICallProcessor;
import org.eclipse.dltk.core.ICalleeProcessor;
import org.eclipse.dltk.core.IMethod;
import org.eclipse.dltk.core.search.IDLTKSearchScope;
import org.eclipse.php.internal.core.search.PHPCallProcessor;
import org.eclipse.php.internal.core.search.PHPCalleeProcessor;

public class PHPCallHierarchyFactory implements ICallHierarchyFactory {

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.dltk.core.ICallHierarchyFactory#createCalleeProcessor(org
	 * .eclipse.dltk.core.IMethod, org.eclipse.core.runtime.IProgressMonitor,
	 * org.eclipse.dltk.core.search.IDLTKSearchScope)
	 */
	@Override
	public ICalleeProcessor createCalleeProcessor(IMethod method, IProgressMonitor monitor, IDLTKSearchScope scope) {
		return new PHPCalleeProcessor(method, monitor, scope);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.eclipse.dltk.core.ICallHierarchyFactory#createCallProcessor()
	 */
	@Override
	public ICallProcessor createCallProcessor() {
		return new PHPCallProcessor();
	}

}


text:
namespace content {
class NavigationHandle;
}  // namespace content

namespace safe_browsing {
class PasswordProtectionRequestContent;

// PasswordProtectionCommitDeferringCondition defers navigations under the
// following conditions:
// (1) The navigation starts while there is a on-going sync password
//     reuse ping. When the verdict comes back, if the verdict results in
//     showing a modal warning dialog, the navigation continues to be deferred;
//     otherwise, the deferred navigation will be resumed.
// (2) The navigation starts while there is a modal warning showing.
//
// If a modal warning is showing, the navigation will continue to be deferred
// until the user takes an action and dismisses the dialog, at which point the
// navigation will resume.
class PasswordProtectionCommitDeferringCondition
    : public content::CommitDeferringCondition {
 public:
  PasswordProtectionCommitDeferringCondition(
      content::NavigationHandle& navigation_handle,
      PasswordProtectionRequestContent& request);

  PasswordProtectionCommitDeferringCondition(
      const PasswordProtectionCommitDeferringCondition&) = delete;
  PasswordProtectionCommitDeferringCondition& operator=(
      const PasswordProtectionCommitDeferringCondition&) = delete;

  ~PasswordProtectionCommitDeferringCondition() override;

  // Overrides content::CommitDeferringCondition
  //
  // Called from a NavigationHandle when a navigation is ready and about to
  // commit. Unless ResumeNavigation() was already called, this will return
  // kDefer which will defer the navigation from committing until `resume` is
  // invoked (via `ResumeNavigation()`).
  Result WillCommitNavigation(base::OnceClosure resume) override;

  // Called by the PasswordProtectionService when it decides this navigation no
  // longer needs to be deferred (e.g. because a ping resulted in not showing a
  // modal, or a shown modal was dismissed by the user). If called after this
  // navigation tried to commit, this invokes the `resume` closure passed to
  // WillCommitNavigation. If called before WillCommitNavigation,
  // WillCommitNavigation will not defer the commit.
  void ResumeNavigation();

  // For testing only. Registers a callback that will be invoked when
  // WillCommitNavigatoin is called by the navigation. This is useful for
  // yielding in a test when this condition is invoked.
  void register_invoke_callback_for_testing(base::OnceClosure callback) {
    invoke_callback_for_testing_ = std::move(callback);
  }

 private:
  // A pointer to the PasswordProtectionRequestContent on whose behalf this
  // condition is deferring navigations.
  base::WeakPtr<PasswordProtectionRequestContent> request_;

  // The resume closure used to resume the navigation past this
  // CommitDeferringCondition.
  base::OnceClosure resume_;

  base::OnceClosure invoke_callback_for_testing_;

  // Set to true to indicate the request has asked to resume the navigation,
  // i.e. the request result didn't result in a modal being shown, or the user
  // has dismissed the modal.
  bool navigation_was_resumed_ = false;
};

}  // namespace safe_browsing

#endif  // COMPONENTS_SAFE_BROWSING_CONTENT_BROWSER_PASSWORD_PROTECTION_PASSWORD_PROTECTION_COMMIT_DEFERRING_CONDITION_H_


text:
/*****************************************************************************/
//	File:			RadioSubTitle.cpp
//	Author:			Retro
//	Date:			Dec2003
//
//	Description:	This class enables subtitles for radio messages. Radio messages
//					are created in voicefilter.cpp in the soundthread and are displyed
//					in otwloop.cpp in the graphics thread.
//					One problem is that the order of created messages is not necessarily
//					the order in which they should be played, eg is the 'Tower, inbound'
//					reply from the Tower scheduled to play about 7 secs after the call,
//					the messages are howver generated simultaneously. Thus, a simple
//					FIFO like buffer is out of the question.
//					So this class implements a linked list (derived from AList.cpp out
//					of falclib) and inserts/removes messages according to their scheduled
//					playtime.
//					Works like this: on constucting the class a csv file with all the typed-up
//					radiomessiges is read in and placed in a big table. When a messages is
//					created (in voicefilter.cpp) it constructs the string out of the chunks
//					read from that csv file and a new node, containing this string, its
//					scheduled playtime and a colour representing the channel it originated from,
//					is placed into the linked list at the correct place (time-sorted, 'earliest'
//					message first).
//					The graphics loop then requests a sorted list of all inputstrings+the associated
//					colours - while doing this I also clean the linked list of messages that already
//					have been displayed long enough - 'old messages fall out of the front of the
//					linked list'
//
//	Issues:			I don´t have completely examined the multithreading problem, eg what happens
//					if the graphics loop requests a list of strings while the sound loop at the
//					same time adds a new message.. I guess I can´t use mutex thingies or such,
//					since delaying a thread is a big nono... hrmm
//					However I´ve never had a problem with this as of yet, and I´ve flown quite a
//					few heavy-duty ('radio-call-wise') mission.. of course, that doesn´t prove anything..
/*****************************************************************************/
#include "stdhdr.h"
#include "radiosubtitle.h"
#include "falcsnd\voicefilter.h"
#include <string.h>
#include <stdio.h>

#include <comdef.h>	// Retro 23May2004

#pragma warning (push,4)

CRITICAL_SECTION  RadioSubTitle::cs_radiosubtitle;

// default channel colours
#define TOFROM_FLIGHT_COLOUR		0xff00ff00	// green
#define TO_PACKAGE_COLOUR			0xff0000ff	// red
#define TOFROM_PACKAGE_COLOUR		0xff00ffff	// yellow
#define TO_TEAM_COLOUR				0xffff0000	// blue	- this is the guard channel, actually..
#define IN_PROXIMITY_COLOUR			0xffffff00	// cyan
#define TO_WORLD_COLOUR				0xff808080	// no idea, kinda dark grey :p
#define TOFROM_TOWER_COLOUR			0xff000000	// black
#define STANDARD_COLOUR				0xffffffff	// white

#define THE_INPUT_FILE_NAME			"F4Talk95v1-0-0.csv"

#define MAX_READ_LEN 2048	//	max size of a single line in the csv line. since that whole file is 300k,
							//	2MB should be enough I guess
#define SEPARATOR ','
#define SEP ","
#define QUOTAS '"'

//	#define WRITE_BACK_STRING_FILE
//	#define SHOW_FRAG_AND_TALKER___BUT_MEM_LEAK
//	#define DISPLAY_CHANNEL_NAME

/*****************************************************************************/
//
/*****************************************************************************/
RadioSubTitle::RadioSubTitle(const int MaximumMessageNum, const unsigned long TTL)
{

	if (MaximumMessageNum != 0)
		MaxMessageNum = MaximumMessageNum;
	else
		MaxMessageNum = 20;

	if (TTL != 0)
		messageTTL = TTL;
	else
		messageTTL = MESSAGE_TTL;

	theRadioChatterList = new AList();
	currentlyEditedNode = (SubTitleNode*)0;
	LinkedListCount = 0;

#ifndef DYNAMIC_LINE_NUM	// Retro 11Jan2004
	for (int i = 0; i < MAX_FRAG_NUM; i++)
	{
		theStrings[i] = 0;
	}
#endif	// DYNAMIC_LINE_NUM

	colour_Flight		= TOFROM_FLIGHT_COLOUR;
	colour_ToPackage	= TO_PACKAGE_COLOUR;
	colour_ToFromPackage= TOFROM_PACKAGE_COLOUR;
	colour_Team			= TO_TEAM_COLOUR;		// this is the guard channel
	colour_Proximity	= IN_PROXIMITY_COLOUR;
	colour_World		= TO_WORLD_COLOUR;
	colour_Tower		= TOFROM_TOWER_COLOUR;
	colour_Standard		= STANDARD_COLOUR;	// only used in default cases which (shouldn´t happen actually)

#ifdef DYNAMIC_LINE_NUM	// Retro 11Jan2004
	FragCount = CountLinesInFile(THE_INPUT_FILE_NAME);
	if (FragCount == 0)
	{
		throw Init_Error("No frag lines in subtitles input file");
	}
	else
	{
//		theStrings = (csvLine**)calloc(sizeof(csvLine*),FragCount+100); // Retro 11Jan2004 - accounting for count-errors :p
		theStrings = (csvLine**)calloc(sizeof(csvLine*),FragCount);
		if (theStrings == (csvLine**)0)
		{
			throw Init_Error("Could not create strings");
		}
	}
#endif	// DYNAMIC_LINE_NUM

	if (!ReadNewFile(THE_INPUT_FILE_NAME))
	{
		throw Init_Error("Error reading the subtitles input file");
	}

#ifdef WRITE_BACK_STRING_FILE
	WriteOut();
#endif

	InitializeCriticalSection(&cs_radiosubtitle);
}

/*****************************************************************************/
//
/*****************************************************************************/
RadioSubTitle::~RadioSubTitle(void)
{
	int i = 0;

	SubTitleNode* node = 0;
	do
	{
		delete(theRadioChatterList->RemHead());
		node = (SubTitleNode*)theRadioChatterList->GetHead();
	} while (node);

	delete(theRadioChatterList);
	theRadioChatterList = 0;

#ifndef DYNAMIC_LINE_NUM	// Retro 11Jan2004
	for (i = 0; i < MAX_FRAG_NUM; i++)
	{
		if (theStrings[i])
		{
			delete(theStrings[i]);
		}
	}
#else	// DYNAMIC_LINE_NUM
	if (theStrings)
	{
		while (theStrings[i])
		{
			delete(theStrings[i]);
			theStrings[i] = 0;
			i++;
		}
		free(theStrings);
		theStrings = 0;
	}
#endif	// DYNAMIC_LINE_NUM

	DeleteCriticalSection(&cs_radiosubtitle);
}

/*****************************************************************************/
//
/*****************************************************************************/
void RadioSubTitle::SetTTLAndMessageNum(const int MessageNum, const unsigned long TTL)
{
	if (MessageNum != 0)
		MaxMessageNum = MessageNum;
	else
		MaxMessageNum = 20;

	if (TTL != 0)
		messageTTL = TTL;
	else
		messageTTL = MESSAGE_TTL;
}

/*****************************************************************************/
//	wipes nodes in the list but not the list itself.
/*****************************************************************************/
void RadioSubTitle::ResetAll()
{
	SubTitleNode* node = 0;
	do
	{
		delete(theRadioChatterList->RemHead());
		node = (SubTitleNode*)theRadioChatterList->GetHead();
	} while (node);
	LinkedListCount = 0;
}

/*****************************************************************************/
//	creates a new message-node, marks this node as 'editable' to enable appending
//	of other bits
//	the messages are kept in a time-sorted linked list, starting with the oldest
//	this linked list gets cleaned of outdated messages in the getTimeSortedMessages()
//	function
/*****************************************************************************/
void RadioSubTitle::NewMessage(const int theTalker, const int theFrag, const unsigned long thePlayTime, const char theFilter)
{
	EnterCriticalSection(&cs_radiosubtitle);	// locking out the graphicsthread..

	currentlyEditedNode = new SubTitleNode();
	if (!currentlyEditedNode)
	{
#pragma warning(disable:4127)
		ShiAssert(false);
#pragma warning(default:4127)
		LeaveCriticalSection(&cs_radiosubtitle);
		return;
	}

	LinkedListCount++;
	currentlyEditedNode->messageStartTime = thePlayTime;
	currentlyEditedNode->associatedChannel = FindChannelColour(theFilter);

#ifndef DISPLAY_CHANNEL_NAME
	char* rchunk = GetRadioChunk(theTalker, theFrag);
	if (rchunk)
	{
		OverWriteString(&currentlyEditedNode->theSpokenLine, rchunk);
	}
#else
	char* chan = FindChannelName(theFilter);
	char* rchunk = GetRadioChunk(theTalker, theFrag);
	if (rchunk)
	{
		char* sum = (char*)malloc(strlen(chan)+strlen(rchunk)+1);
		if (sum)
		{
			strcpy(sum,chan);
			strcat(sum,rchunk);

			OverWriteString(&currentlyEditedNode->theSpokenLine, sum);
			free(sum);
		}
	}
#endif

	SubTitleNode* index = (SubTitleNode*)theRadioChatterList->GetHead();
	while ((index)&&(index->messageStartTime < thePlayTime))
	{
		index = (SubTitleNode*)index->GetSucc();
	}
	if (index)
		currentlyEditedNode->InsertAfter(index);
	else
		theRadioChatterList->AddTail(currentlyEditedNode);

	LeaveCriticalSection(&cs_radiosubtitle);
}

/*****************************************************************************/
//	Appends a string chunk to an already existing message
/*****************************************************************************/
void RadioSubTitle::AddToMessage(const int theTalker, const int theFrag)
{
	EnterCriticalSection(&cs_radiosubtitle);	// locking out the graphicsthread..

	char* rchunk = GetRadioChunk(theTalker, theFrag);
	if ((rchunk)&&(currentlyEditedNode))
	{
		AppendToString(&currentlyEditedNode->theSpokenLine," ");
		AppendToString(&currentlyEditedNode->theSpokenLine,rchunk);
	}

	LeaveCriticalSection(&cs_radiosubtitle);

}

/*****************************************************************************/
//	should eventually look up the current string in the talkview csv file..
/*****************************************************************************/
char* RadioSubTitle::GetRadioChunk(const int theTalker, const int theFrag)
{
#ifdef SHOW_FRAG_AND_TALKER___BUT_MEM_LEAK
	if ((theStrings[theFrag])&&(theTalker < MAX_VOICE_NUM))
	{
		char* bla = (char*)malloc(strlen(theStrings[theFrag]->Voices[theTalker])+30);	// mem leak but it´s only for test anyway
		if (bla)
		{
			char tmp[30];
			sprintf(tmp,"-> %i %i ",theTalker, theFrag);
			strcpy(bla,theStrings[theFrag]->Voices[theTalker]);
			strcat(bla,tmp);
			return bla;
		}
		else
		{
			return "bla";
		}
	}
	else
		return 0;
#else
#ifdef NDEBUG
	if ((theFrag < FragCount)&&(theStrings[theFrag])&&(theTalker < MAX_VOICE_NUM)&&!F4IsBadReadPtr(theStrings[theFrag], sizeof(csvLine)))
	{
		return theStrings[theFrag]->Voices[theTalker];
	}
#else
	if ((theFrag < FragCount)&&(theStrings[theFrag])&&(theTalker < MAX_VOICE_NUM))
	{
		if (F4IsBadReadPtr(theStrings[theFrag], sizeof(csvLine)))
		{
#pragma warning(disable:4127)
			ShiAssert(false);
#pragma warning(default:4127)
			return 0;
		}
		else
			return theStrings[theFrag]->Voices[theTalker];
	}
#endif
	else
		return 0;
#endif
}

/*****************************************************************************/
//	Returns an array of structures containing a radiomessage and a colour
//	representing the channel it was sent on..
//	Also does housekeeping on the linked list (throws out outdated messages..)
/*****************************************************************************/
ColouredSubTitle** RadioSubTitle::GetTimeSortedMessages(const unsigned long theTime)
{

	EnterCriticalSection(&cs_radiosubtitle);	// locking out the soundthread

	// Get the oldest message in the list..
	SubTitleNode* node = (SubTitleNode*)theRadioChatterList->GetHead();
	if (!node)
	{
		LeaveCriticalSection(&cs_radiosubtitle);
		return 0;	// no messages to play..
	}

	// walking back in the list
	// we are not going to draw messages that have already outlived their TTL..
	// if they weren´t displayed by now, well, tough luck (and I betcha your FPS suck hairy donkey balls too)
	// these messages are going to be removed actually..
	// this is done for every message (node) till I find one that is still to be drawn - and as the list is
	// sorted by time, all following ones have also to be drawn so I break from the loop
	while ((node)&&(node->messageStartTime  + messageTTL < theTime))
	{
		SubTitleNode* nodeToDelete = (SubTitleNode*)theRadioChatterList->RemHead();
		if (nodeToDelete)
		{
			delete(nodeToDelete);
			LinkedListCount--;
		}
		node = (SubTitleNode*)theRadioChatterList->GetHead();
	}

	if (!node)
	{
		LeaveCriticalSection(&cs_radiosubtitle);
		 return 0;	// no messages to play.. (all messages were outdated)
	}

	// the calling routine has to delete that array..
	ColouredSubTitle** theMessages = (ColouredSubTitle**)calloc(sizeof(ColouredSubTitle*),LinkedListCount+1);
	if (!theMessages)
	{
		LeaveCriticalSection(&cs_radiosubtitle);
		return 0;
	}

	int i = 0;

	while (node)
	{
		// also do NOT draw are messages (nodes) that are scheduled to be played in da future
		// since the list is sorted I can actually break once this condition is met
		if (node->messageStartTime > theTime)
		{
			break;
		}
		if ((node->messageStartTime < theTime)&&(theTime < node->messageStartTime + messageTTL))
		{
#if 0	// Retro 23May2004
			theMessages[i] = (ColouredSubTitle*)malloc(sizeof(ColouredSubTitle));
			if (theMessages[i])
			{
				if (node->theSpokenLine)	// Retro 28Feb2004
				{
					theMessages[i]->theString = (char*)malloc(strlen(node->theSpokenLine)+1);
					strcpy(theMessages[i]->theString,node->theSpokenLine);
					theMessages[i]->theColour = node->associatedChannel;
					i++;
				}
				else
				{
#pragma warning(disable:4127)
					ShiAssert(false);
#pragma warning(default:4127)
				}
			}
#else	// Retro 23May2004
			if (node->theSpokenLine)	// Retro 28Feb2004
			{
				theMessages[i] = (ColouredSubTitle*)malloc(sizeof(ColouredSubTitle));
				if (theMessages[i])
				{
					theMessages[i]->theString = (char*)malloc(strlen(node->theSpokenLine)+1);
					strcpy(theMessages[i]->theString,node->theSpokenLine);
					theMessages[i]->theColour = node->associatedChannel;
					i++;
				}
				else
				{
					throw _com_error(E_OUTOFMEMORY);
				}
			}
			else
			{
#pragma warning(disable:4127)
				ShiAssert(false);
#pragma warning(default:4127)
			}
#endif	// Retro 23May2004
		}
		node = (SubTitleNode*)node->GetSucc();

		// there´s a (user-set) limit on how many messages my be displayed, so we break out here
		// (even if there may be messages that still should be played)
		if (i > MaxMessageNum)
			break;
	}

	LeaveCriticalSection(&cs_radiosubtitle);

	return theMessages;
}

#ifdef WRITE_BACK_STRING_FILE
/*****************************************************************************/
//
/*****************************************************************************/
void RadioSubTitle::WriteOut(void)
{
	FILE* fp = fopen("Talk_output.csv","wt");
	if (fp)
	{
#ifndef DYNAMIC_LINE_NUM	// Retro 11Jan2004
		for (int j = 0; j < MAX_FRAG_NUM; j++)
		{
			if (theStrings[j])
			{
				for (int i = 0; i < MAX_VOICE_NUM; i++)
				{
					if (theStrings[j]->Voices[i])
					{
						fprintf(fp,"%s",theStrings[j]->Voices[i]);
					}
					fprintf(fp,SEP);
				}
				fprintf(fp,"\n");
			}
		}
#else
		if (theStrings)
		{
			while(theStrings[i])
			{
				for (int i = 0; i < MAX_VOICE_NUM; i++)
				{
					if (theStrings[j]->Voices[i])
					{
						fprintf(fp,"%s",theStrings[j]->Voices[i]);
					}
					fprintf(fp,SEP);
				}
				fprintf(fp,"\n");
			}
		}
#endif	// DYNAMIC_LINE_NUM
		fclose(fp);
	}
}
#endif	// WRITE_BACK_STRING_FILE

/*****************************************************************************/
//	hmm.. actually ranking is not important ? indeed it is :/
/*****************************************************************************/
unsigned long RadioSubTitle::FindChannelColour(const char theChannel)
{
	if (theChannel & TOFROM_TOWER)
		return colour_Tower;
	else if (theChannel & TOFROM_FLIGHT)
		return colour_Flight;
	else if (theChannel & TO_PACKAGE)
		return colour_ToPackage;
	else if (theChannel & TOFROM_PACKAGE)
		return colour_ToFromPackage;
	else if (theChannel & TO_TEAM)
		return colour_Team;
	else if (theChannel & IN_PROXIMITY)
		return colour_Proximity;
	else if (theChannel & TO_WORLD)
		return colour_World;
	else
		return colour_Standard;
}

/*****************************************************************************/
//
/*****************************************************************************/
char* RadioSubTitle::FindChannelName(const char theChannel)
{
	if (theChannel & TOFROM_TOWER)
		return "[Tower] ";
	else if (theChannel & TOFROM_FLIGHT)
		return "[Flight] ";
	else if (theChannel & TO_PACKAGE)
		return "[To Package] ";
	else if (theChannel & TOFROM_PACKAGE)
		return "[To/From Package] ";
	else if (theChannel & TO_TEAM)
		return "[Guard] ";
	else if (theChannel & IN_PROXIMITY)
		return "[Proximity] ";
	else if (theChannel & TO_WORLD)
		return "[Broadcast] ";
	else
		return "[Unknown] ";
}

/*****************************************************************************/
//
/*****************************************************************************/
void RadioSubTitle::SetChannelColours(	unsigned long flight, unsigned long toPackage, unsigned long ToFromPackage,
										unsigned long Team, unsigned long Proximity, unsigned long World,
										unsigned long Tower, unsigned long Standard)
{
	if (flight != 0)		colour_Flight		= flight;
	if (toPackage != 0)		colour_ToPackage	= toPackage;
	if (ToFromPackage != 0)	colour_ToFromPackage= ToFromPackage;
	// 'Team' is the guard channel
	if (Team != 0)			colour_Team			= Team;
	if (Proximity != 0)		colour_Proximity	= Proximity;
	if (World != 0)			colour_World		= World;
	if (Tower != 0)			colour_Tower		= Tower;
	if (Standard != 0)		colour_Standard		= Standard;
}

/*****************************************************************************/
//	Inputs should be null-terminated strings that can be read as hex-number
//	eg "0xFF00FF00"
/*****************************************************************************/
void RadioSubTitle::SetChannelColours(	char* flight, char* toPackage, char* ToFromPackage,
										char* Team, char* Proximity, char* World,
										char* Tower, char* Standard)
{
	unsigned long flightCol = 0;
	unsigned long toPackageCol = 0;
	unsigned long ToFromPackageCol = 0;
	unsigned long TeamCol = 0;
	unsigned long ProximityCol = 0;
	unsigned long WorldCol = 0;
	unsigned long TowerCol = 0;
	unsigned long StandardCol = 0;

	unsigned long temp = 0;

	if (flight)
		if (sscanf(flight,"%x",&temp) == 1)
			flightCol = temp;
	if (toPackage)
		if (sscanf(toPackage,"%x",&temp) == 1)
			toPackageCol = temp;
	if (ToFromPackage)
		if (sscanf(ToFromPackage,"%x",&temp) == 1)
			ToFromPackageCol = temp;
	if (Team)
		if (sscanf(Team,"%x",&temp) == 1)
			TeamCol = temp;
	if (Proximity)
		if (sscanf(Proximity,"%x",&temp) == 1)
			ProximityCol = temp;
	if (World)
		if (sscanf(World,"%x",&temp) == 1)
			WorldCol = temp;
	if (Tower)
		if (sscanf(Tower,"%x",&temp) == 1)
			TowerCol = temp;
	if (Standard)
		if (sscanf(Standard,"%x",&temp) == 1)
			StandardCol = temp;

	SetChannelColours(	flightCol,toPackageCol,ToFromPackageCol,
						TeamCol,ProximityCol,WorldCol,
						TowerCol,StandardCol);
}

/*****************************************************************************/
//
/*****************************************************************************/
inline void RadioSubTitle::AppendToString(char** theOldOne, const char* theNewOne)
{
	if ((!theOldOne)||(!*theOldOne)||(!theNewOne))
	{
		assert(false);
		return;
	}

	int oldLen = strlen(*theOldOne);
	int newLen = strlen(theNewOne);

	char* temp = (char*)malloc(oldLen+newLen+1);
	if (temp)
	{
		strcpy(temp,*theOldOne);
		strcat(temp,theNewOne);

		free(*theOldOne);
		*theOldOne = temp;
	}
}

/*****************************************************************************/
//
/*****************************************************************************/
inline void RadioSubTitle::OverWriteString(char** theOldOne, const char* theNewOne)
{
	if (!theNewOne)
	{
		assert(false);
		return;
	}

	if (theOldOne)
	{
		if (*theOldOne)
		{
		free(*theOldOne);
		*theOldOne = 0;
		}
	}

	*theOldOne = (char*)malloc(strlen(theNewOne)+1);
	if (*theOldOne)
	{
		strcpy(*theOldOne,theNewOne);
	}
}

/*****************************************************************************/
//
/*****************************************************************************/
void RadioSubTitle::HandleChunk(csvLine_t* theTextString, char* theChunk, int* ChunkCount)
{
	assert(theTextString);
	assert(ChunkCount);

	// 'theChunk' is often NULL, happens when the csv reads ',,'

	int ChunkIndex = *ChunkCount;

	switch (ChunkIndex)
	{
	case 0:	// frag #
		if (theChunk)
		{
			theTextString->Fragment = atoi(theChunk);
			free(theChunk);		// Retro 3Jan2004 - gotta close that mem leak.. oops
			theChunk = 0;
		}
		break;
	case 1:	// maxvoice #
		if (theChunk)
		{
			theTextString->VoiceCount = atoi(theChunk);
			free(theChunk);		// Retro 3Jan2004 - gotta close that mem leak.. oops
			theChunk = 0;
		}
		break;
	case 2: // the actual voices
	case 3: case 4: case 5:case 6: case 7: case 8: case 9:
	case 10: case 11: case 12: case 13: case 14: case 15:
		theTextString->Voices[ChunkIndex-2] = theChunk;
		break;
	case 16:	// summary
		theTextString->Summary = theChunk;
		break;
	case 17:	// eval
		if (theChunk)
		{
			theTextString->Eval = atoi(theChunk);
			free(theChunk);		// Retro 3Jan2004 - gotta close that mem leak.. oops
			theChunk = 0;
		}
		break;
	default:	// shoudn´t happen
		assert(false);
		break;
	}

	ChunkIndex++;
	*ChunkCount = ChunkIndex;
}

/*****************************************************************************/
// set start pointer

// check for "
// if yes, look for next "

// look for SEPERATOR
// set end pointer

// copy chunk, hand it to handleroutiner

// advance pointer
/*****************************************************************************/
void RadioSubTitle::breakDownLine(csvLine_t* theTextString, char* theLine, const int theLength)
{
	assert(theTextString);
	assert(theLine);

	// set start pointer
	char* start = theLine;
	char* end = theLine;
	int len = 0;
	int i = 0;
	bool inDoubleQuotes = false;

	int ChunkCount = 0;

	do
	{
		if (end == 0)
		{
			assert(false);
			break;
		}

		// check for "
		// if yes, look for next "
		if (*end == QUOTAS/*'"'*/)
		{
			do
			{
				end++;
			} while (*end != QUOTAS/*'"'*/);
			inDoubleQuotes = true;
		}

		// look for SEPERATOR
		// set end pointer
		if ((*end == SEPARATOR/*','*/)||(*end == '\0'))
		{
			if (end > start)
			{
				if (!inDoubleQuotes)
				{
					len = end - start + 1;
					char* tmp = (char*)malloc(len);
					if (tmp)
					{
						strncpy(tmp,start,len-1);
						tmp[len-1] = '\0';
						// copy chunk, hand it to handleroutiner
						HandleChunk(theTextString,tmp,&ChunkCount);
					}
					start = end+1;
				}
				else
				{
					len = end - start - 2 + 1;
					char* tmp = (char*)malloc(len);
					if (tmp)
					{
						strncpy(tmp,start+1,len-1);
						tmp[len-1] = '\0';
						// copy chunk, hand it to handleroutiner
						HandleChunk(theTextString,tmp,&ChunkCount);
					}
					start = end+1;
					inDoubleQuotes = false;
				}
			}
			else if (start == end)
			{
				// copy chunk, hand it to handleroutiner
				HandleChunk(theTextString,0,&ChunkCount);
				start = end+1;
			}
			else
			{
				assert(false);
			}

			if (*end == '\0')
			{
				break;
			}
		}
		i++;
		// advance pointer
		end++;
	} while (i < theLength);

//	assert(ChunkCount-1 == theTextString->VoiceCount);
}

/*****************************************************************************/
//
/*****************************************************************************/
bool RadioSubTitle::ReadNewFile(const char* theFileName)
{

	FILE* fp = fopen(theFileName,"rt");
	if (fp)
	{
		char tmp[MAX_READ_LEN];
		int j = 0;

		while (fgets(&tmp[0],MAX_READ_LEN,fp) != NULL)
		{
			if (j == 0)
			{
				j++;
				continue;	// ignoring the first line
			}

			tmp[strlen(tmp)-1] = 0;	// getting rid of that damn newline

			theStrings[j-1] = new csvLine_t;
			breakDownLine(theStrings[j-1],tmp,strlen(tmp));
			j++;
		}
		fclose(fp);
		return true;
	}
	else
	{
	 	return false;
	}
}

#ifdef DYNAMIC_LINE_NUM		// Retro 11Jan2004
/*****************************************************************************/
//	bwhahaaha.. counts lines in a file.. lol I guess this isn´t very elegant
/*****************************************************************************/
int RadioSubTitle::CountLinesInFile(const char* theFileName)
{
	FILE* fp = fopen(theFileName,"rt");
	if (fp)
	{
		char tmp[MAX_READ_LEN];
		int linecount = 0;

		while (fgets(&tmp[0],MAX_READ_LEN,fp) != NULL)
		{
			linecount++;
		}
		fclose(fp);
		return linecount;
	}
	return 0;
}
#endif	// DYNAMIC_LINE_NUM
#pragma warning (pop)


text:
ENV["RAILS_ENV"] = "test"

require "rails_app/config/environment"
require "rails/test_help"


text:
package edu.mtu.citizenscience.thunderbay;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MapFragmentTab extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.mapfragmenttab, container, false);
        return rootView;
    }

}


text:
<?php

namespace Bhaktaraz\RSSGenerator;

use SimpleXMLElement as XMLElement;

class SimpleXMLElement extends XMLElement
{

    /**
     * @param string $name
     * @param string $value
     * @param string $namespace
     * @return XMLElement
     */
    public function addChild($name, $value = null, $namespace = null)
    {
        if ($value !== null and is_string($value) === true) {
            $value = str_replace('&', '&', $value);
        }

        return parent::addChild($name, $value, $namespace);
    }

    /**
     * Create a child with CDATA value
     * @param string $name The name of the child element to add.
     * @param string $cdata_text The CDATA value of the child element.
     */
    public function addChildCData($name, $cdata_text)
    {
        $child = $this->addChild($name);
        $child->addCData($cdata_text);
    }

    /**
     * Add CDATA text in a node
     * @param string $cdata_text The CDATA value  to add
     */
    private function addCData($cdata_text)
    {
        $node = dom_import_simplexml($this);
        $no = $node->ownerDocument;
        $node->appendChild($no->createCDATASection($cdata_text));
    }
}


text:
Masters
=======

Overview of the Masters including bi-temporal versioning  + Links to more detailed docs in corresponding doc modules

.. toctree::
   :maxdepth: 2
   :glob:

   *


text:
<!DOCTYPE html>
<html>
    <head>
        <title>bayes</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <script src="release/bayes.js" type="text/javascript"></script>
    </body>
</html>


text:
#include "test.h"
__FBSDID("$FreeBSD: head/lib/libarchive/test/read_open_memory.c 191183 2009-04-17 01:06:31Z kientzle $");

#include <errno.h>
#include <stdlib.h>
#include <string.h>

/*
 * Read an archive from a block of memory.
 *
 * This is identical to archive_read_open_memory(), except
 * that it goes out of its way to be a little bit unpleasant,
 * in order to better test the libarchive internals.
 */

struct read_memory_data {
	unsigned char	*buffer;
	unsigned char	*end;
	size_t	 read_size;
	size_t copy_buff_size;
	size_t copy_buff_offset;
	char *copy_buff;
};

static int	memory_read_close(struct archive *, void *);
static int	memory_read_open(struct archive *, void *);
static off_t	memory_read_skip(struct archive *, void *, off_t request);
static ssize_t	memory_read(struct archive *, void *, const void **buff);
static int	read_open_memory_internal(struct archive *a, void *buff,
    size_t size, size_t read_size, int fullapi);

int
read_open_memory(struct archive *a, void *buff, size_t size, size_t read_size)
{
	return read_open_memory_internal(a, buff, size, read_size, 1);
}

/*
 * As above, but don't register any optional part of the API, to verify
 * that internals work correctly with just the minimal entry points.
 */
int
read_open_memory2(struct archive *a, void *buff, size_t size, size_t read_size)
{
	return read_open_memory_internal(a, buff, size, read_size, 0);
}

static int
read_open_memory_internal(struct archive *a, void *buff,
    size_t size, size_t read_size, int fullapi)
{
	struct read_memory_data *mine;

	mine = (struct read_memory_data *)malloc(sizeof(*mine));
	if (mine == NULL) {
		archive_set_error(a, ENOMEM, "No memory");
		return (ARCHIVE_FATAL);
	}
	memset(mine, 0, sizeof(*mine));
	mine->buffer = (unsigned char *)buff;
	mine->end = mine->buffer + size;
	mine->read_size = read_size;
	mine->copy_buff_offset = 32;
	mine->copy_buff_size = read_size + mine->copy_buff_offset * 2;
	mine->copy_buff = malloc(mine->copy_buff_size);
	memset(mine->copy_buff, 0xA5, mine->copy_buff_size);
	if (fullapi)
		return (archive_read_open2(a, mine, memory_read_open,
			    memory_read, memory_read_skip, memory_read_close));
	else
		return (archive_read_open2(a, mine, NULL,
			    memory_read, NULL, memory_read_close));
}

/*
 * There's nothing to open.
 */
static int
memory_read_open(struct archive *a, void *client_data)
{
	(void)a; /* UNUSED */
	(void)client_data; /* UNUSED */
	return (ARCHIVE_OK);
}

/*
 * In order to exercise libarchive's internal read-combining logic,
 * we deliberately copy data for each read to a separate buffer.
 * That way, code that runs off the end of the provided data
 * will screw up.
 */
static ssize_t
memory_read(struct archive *a, void *client_data, const void **buff)
{
	struct read_memory_data *mine = (struct read_memory_data *)client_data;
	size_t size;

	(void)a; /* UNUSED */
	size = mine->end - mine->buffer;
	if (size > mine->read_size)
		size = mine->read_size;
	else
		memset(mine->copy_buff, 0xA5, mine->copy_buff_size);
	memcpy(mine->copy_buff + mine->copy_buff_offset, mine->buffer, size);
	*buff = mine->copy_buff + mine->copy_buff_offset;

        mine->buffer += size;
	return ((ssize_t)size);
}

/*
 * How mean can a skip() routine be?  Let's try to find out.
 */
static off_t
memory_read_skip(struct archive *a, void *client_data, off_t skip)
{
	struct read_memory_data *mine = (struct read_memory_data *)client_data;

	(void)a; /* UNUSED */
	/* We can't skip by more than is available. */
	if ((off_t)skip > (off_t)(mine->end - mine->buffer))
		skip = mine->end - mine->buffer;
	/* Always do small skips by prime amounts. */
	if (skip > 71)
		skip = 71;
	mine->buffer += skip;
	return (skip);
}

/*
 * Close is just cleaning up our one small bit of data.
 */
static int
memory_read_close(struct archive *a, void *client_data)
{
	struct read_memory_data *mine = (struct read_memory_data *)client_data;
	(void)a; /* UNUSED */
	free(mine->copy_buff);
	free(mine);
	return (ARCHIVE_OK);
}


text:
using OPSIVRSystem.Config;
using OPSIVRSystem.IVRMenus;

namespace OPSIVRSystem.CommonViewModel
{
    public class VmIVRMenuElementInfoReader : VmIVRMenuElementBase
    {

        public VmIVRMenuElementInfoReader()
        {
            Icon = "/OPSIVRSystem;component/Resources/texttospeech.png";
            Introduction = "This is the info reader menu";
            Name = "Info reader menu element";
            TypeText = "Info reader menu";

        }

        private VmIVRMenuElementInfoReader(VmIVRMenuElementInfoReader original)
            : base(original)
        {

        }

        public VmIVRMenuElementInfoReader(IVRMenuElementInfoReader model)
            : base(model)
        {
            Icon = "/OPSIVRSystem;component/Resources/texttospeech.png";
        }

        public VmIVRMenuElementInfoReader(IVRMenuInfoReaderConfig model)
            : base(model)
        {
            Icon = "/OPSIVRSystem;component/Resources/texttospeech.png";
        }

        public override VmIVRMenuElementBase GetAClone()
        {
            return new VmIVRMenuElementInfoReader(this);
        }

        public override IVRMenuElementBase GetModel()
        {
            var res = new IVRMenuElementInfoReader();
            InitModelCommonFields(res);
            return res;
        }
    }
}


text:
;(function (CodeMirror, Pos) {

  var ldKeywords = [];

  var previousHint;

  function getToken(e, cur){ return e.getTokenAt(cur); }

  function accum(arr, fn, result){
    result = result || [];
    var len = arr.length,
      _ = function(val){ result.push(val); };
    for(var i=0; i < len; i++){
      fn(_, arr[i], i);
    }
    return result;
  }

  function keywordsLike(str){
    str = str ? String(str).trim() : "";
    var result = accum(ldKeywords, function(_, kw){
      !str || ~kw.key.indexOf(str) ? _(kw.key) : null;
    });

    if(str){ result.sort(relevanceComparator(str)); }

    return accum(result, function(_, kw){
      _({
        text: kw,
        className: "cm-meta"
      });
    });
  }

  function contextLike(str, doc){
    var ctx, key,
      result = [];

    str = str ? String(str).trim() : "";

    if(doc && (ctx = doc["@context"])){
      for(key in ctx){
        if(!ctx.hasOwnProperty(key)){ return; }
        !str || ~key.indexOf(str) ? result.push({text: key}) : null;
      }
    }
    return result;
  }

  function relevanceComparator(str){
    return function(a, b){
      var result = a.indexOf(str) - b.indexOf(str);
      if(!result){
        return a.localeCompare(b);
      }
      return result;
    };
  }

  function hidePopover(){
    previousHint && previousHint.popover("destroy");
    previousHint = null;
  }

  function showPopover(doc){
    return function(hint){

      hidePopover();

      // sigh.
      previousHint = $(".CodeMirror-hint-active");

      var ctx,
        hintObj,
        prefixed,
        val,
        content = "",
        i;

      for(i = 0; i < ldKeywords.length; i++){
        if(ldKeywords[i].key === hint.text){
          hintObj = ldKeywords[i];
        }
      }

      if(!hintObj && doc && (ctx = doc["@context"])){
        prefixed = hint.text.split(":");

        if(ctx.hasOwnProperty(hint.text)){
          val = ctx[hint.text];
          if(prefixed.length === 2){
            // some kind of prefix?
            hintObj = {
              type: val["@type"] ? [val["@type"]] : undefined,
              description: (ctx[prefixed[0]] || "") + prefixed[1]
            };
          }else if(typeof val === "object"){
            // some complex thing?
            hintObj = {
              type: val["@type"] ? [val["@type"]] : undefined,
              description: val["@id"]
            };
          }else{
            // some kind of naked value?
            hintObj = {
              description: val
            };
          }
        }else if(ctx.hasOwnProperty(prefixed[0])){
          hintObj = {
            description: (ctx[prefixed[0]] || "") + prefixed[1]
          };
        }
      }

      if(!hintObj){ return; }

      if(hintObj.description){
        content += '
' +
          hintObj.description.replace(/<.*>/g, '') +
          '
';
      }

      if(hintObj.type && hintObj.type.length){
        content += "
Expects ";
        for(i = 0; i < hintObj.type.length; i++){
          content += label(hintObj.type[i]);
        }
        content += "
";
      }

      if(hintObj.enum && hintObj.enum.length){
        content += "
Can be ";
        for(i = 0; i < hintObj.enum.length; i++){
          content += label(hintObj.enum[i]);
        }
        content += "
";
      }

      if(hintObj.format){
        content += "
Format " + label(hintObj.format) + "
";
      }

      previousHint.popover({
        content: content,
        container: "body",
        html: true
      });
      previousHint.popover("show");
    };
  }

  function label(value, cls){
    return '' +
      value.replace(/<.*>/g, '') +
      '';
  }

  function findLdKeywords(schemata){
    var i,
      def_key,
      def,
      prop_key,
      prop;
    // pull out the @ keywords
    for(i = 0; i < schemata.length; i++){
      var schema = schemata[0];
      for(def_key in schema.definitions){
        def = schema.definitions[def_key];
        for(prop_key in def.properties){
          prop = def.properties[prop_key];
          if(prop_key.indexOf("@") === 0){
            ldKeywords.push({
              key: prop_key,
              description: prop.description,
              type: typeof prop.type === "string" ?
                [prop.type] : (prop.type || []),
              format: prop.format,
              enum: prop.enum || []
            });
          }
        }
      }
    }
  }

  CodeMirror.registerHelper("hint", "jsonld", function(editor, options){

     // Find the token at the cursor
    var cur = editor.getCursor(),
      token = getToken(editor, cur),
      tprop = token,

      // was this started by pressing "@"
      isAt = options.isAt,
      lastParsed = options.lastParsed,

      schemata = typeof options.schemata === "function" ?
        options.schemata() :
        options.schemata,

      word = token.string,
      start = token.start,
      end = token.end + -1 * (word.slice(-1) === '"'),

      match,
      stripped = false,

      result;

    if(!ldKeywords.length && schemata.length){
      findLdKeywords(schemata);
    }

    function suggest(suggestions){
      var hints = {
        list: suggestions,
        from: Pos(cur.line, start + 1),
        to: Pos(cur.line, end)
      };

      // various hint events
      CodeMirror.on(hints, "select", showPopover(lastParsed));
      CodeMirror.on(hints, "close", hidePopover);

      return hints;
    }

    token.state = CodeMirror.innerMode(editor.getMode(), token.state).state;

    function finish(word){
      // clean up words, move pointers
      if(word.match(/^[\{\[]/)){
        // i just made an empty list and typed "@"...
        word = "";
        start++;
        stripped = true;
      }else if(word.match(/^"/)){
        // i just started a quoted string...
        word = word.replace(/(^"|"$)/g, "");
        stripped = true;
      }

      if(isAt){
        // this was started by pressing @..
        if(!~word.indexOf("@")){
          // and the user is expecting a @
          editor.replaceSelection("@", "end", "+input");
        }else if(!stripped){
          start--;
        }
        return suggest(keywordsLike(word.replace("@", "")));
      }else if(match = word.match(/^"?@(.*)/)){
        return suggest(keywordsLike(match[1]));
      }

      return suggest(contextLike(word, lastParsed).concat(keywordsLike(word)));
    }

    result = finish(word);
    if(!result.list.length && word.indexOf(":") !== -1 && word.indexOf("://") === -1){
      // try again with the prefix
      result = finish(word.split(":")[0]);
      result.list.unshift({text: word.replace(/"/g, "")});
    }
    return result;
  });
}).call(this, CodeMirror, CodeMirror.Pos, $);


text:
CREATE TABLE IF NOT EXISTS `analytics_keywords` (
 `id` int(11) NOT NULL auto_increment,
 `keyword` varchar(255) NOT NULL,
 `entrances` int(11) NOT NULL,
 `date` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `analytics_landing_pages` (
 `id` int(11) NOT NULL auto_increment,
 `page_path` varchar(255) NOT NULL,
 `entrances` int(11) NOT NULL,
 `bounces` int(11) NOT NULL,
 `bounce_rate` varchar(255) NOT NULL,
 `start_date` datetime NOT NULL,
 `end_date` datetime NOT NULL,
 `updated_on` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `analytics_pages` (
 `id` int(11) NOT NULL auto_increment,
 `page` varchar(255) NOT NULL,
 `date_viewed` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `analytics_referrers` (
 `id` int(11) NOT NULL auto_increment,
 `referrer` varchar(255) NOT NULL,
 `entrances` int(11) NOT NULL,
 `date` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;


text:
var KnCode = /** @class */ (function () {
    function KnCode() {
    }
    KnCode.prototype.render = function () {
        return (this.block
            ? h("pre", { "c": { "code-container": true, "block": true } },
                h(0, 0))
            : h("code", { "c": { "code-container": true } },
                h(0, 0)));
    };
    KnCode.prototype.componentWillLoad = function () {
        this._html = this.element.innerHTML;
        if (this.block) {
            var spaceLength = this._html.match(/^\s*/)[0].length - 1;
            if (spaceLength >= 0) {
                var reg = new RegExp("\\n\\s{" + spaceLength + "}", 'g');
                this._html = this._html.replace(reg, '\n');
            }
        }
        this._html = this._html.trim();
    };
    KnCode.prototype.componentDidLoad = function () {
        var container = this.element.getElementsByClassName('code-container')[0];
        container.innerText = this._html;
    };
    return KnCode;
}());
export { KnCode };


text:
{-# OPTIONS_GHC -fno-warn-tabs #-}

module AES
( encryptECB
, decryptECB
, encryptCBC
, decryptCBC
, genCTRKeyStream
, encryptCTR
, decryptCTR
) where

import Common
import Xor

import qualified Crypto.Cipher.AES as A
import Data.Bits
import qualified Data.Vector.Generic as V
import Data.Vector.Storable.ByteString
import Data.Word

import Control.Exception.Base

encryptECB :: ByteVector -> ByteVector -> ByteVector
encryptECB key bytes
	| V.length key /= 16 = error "key must be 128 bits"
	| V.length bytes `rem` 16 /= 0 = error "bytes must be a multiple of 128 bits"
	| otherwise = byteStringToVector $ A.encryptECB keyProcessed bytesUnpacked
		where
		keyProcessed = A.initAES $ vectorToByteString key
		bytesUnpacked = vectorToByteString bytes

decryptECB :: ByteVector -> ByteVector -> ByteVector
decryptECB key bytes
	| V.length key /= 16 = error "key must be 128 bits"
	| V.length bytes `rem` 16 /= 0 = error "bytes must be a multiple of 128 bits"
	| otherwise = byteStringToVector $ A.decryptECB keyProcessed bytesUnpacked
		where
		keyProcessed = A.initAES $ vectorToByteString key
		bytesUnpacked = vectorToByteString bytes

encryptCBC :: ByteVector -> ByteVector -> ByteVector -> ByteVector
encryptCBC key iv bytes
	| V.length key /= 16 = error "key must be 128 bits"
	| V.length iv /= 16 = error "iv must be 128 bits"
	| V.length bytes `rem` 16 /= 0 = error "bytes must be a multiple of 128 bits"
	| otherwise = go iv bytes
		where
		go prev bs
			| V.length bs == 0 = V.empty
			| otherwise = enc V.++ go enc (V.drop 16 bs)
				where
				enc = byteStringToVector $ A.encryptECB keyProcessed curr
				curr = vectorToByteString $ xorBytes (V.take 16 bs) prev
		keyProcessed = A.initAES $ vectorToByteString key

decryptCBC :: ByteVector -> ByteVector -> ByteVector -> ByteVector
decryptCBC key iv bytes
	| V.length key /= 16 = error "key must be 128 bits"
	| V.length iv /= 16 = error "iv must be 128 bits"
	| V.length bytes `rem` 16 /= 0 = error "bytes must be a multiple of 128 bits"
	| otherwise = xorBytes dec prevs
		where
		dec = decryptECB key bytes
		prevs = V.take (V.length bytes) $ iv V.++ bytes

genCTRKeyStream :: (Int, Int) -> ByteVector -> ByteVector -> ByteVector
genCTRKeyStream (start, end) key nonce
	| V.length key /= 16 = error "key must be 128 bits"
	| V.length nonce /= 8 = error "nonce must be 64 bits"
	| otherwise = chop $ V.concat $ map keyStreamBlock [startBlock..endBlock]
	where
	startBlock = start `quot` 16
	endBlock = end `quot` 16
	startDrop = start - startBlock * 16
	endDrop = (endBlock * 16 + 15) - end
	chop = dropFromTail endDrop . V.drop startDrop
		where
		dropFromTail len bytes = V.take (V.length bytes - len) bytes
	keyStreamBlock ind = encryptECB key ctr
		where
		ctr = nonce V.++ word64ToBytes (fromIntegral ind)
			where
			word64ToBytes :: Word64 -> ByteVector
			word64ToBytes = V.fromList . splitBitsAt [0, 8..63]

encryptCTR :: ByteVector -> ByteVector -> ByteVector -> ByteVector
encryptCTR key nonce bytes = xorBytes bytes keyStreamBytes
	where
	keyStreamBytes = genCTRKeyStream (0, V.length bytes - 1) key nonce

decryptCTR :: ByteVector -> ByteVector -> ByteVector -> ByteVector
decryptCTR = encryptCTR


text:
Custom product page plugin for wordpress.

  - Image
  - Price
  - Description
  - Details
  - Table details

### Version
1.0.0

### Tech

* [Wordpress] - web software you can use to create a beautiful website, blog, or app.
* [PHP] - a popular general-purpose scripting language that is especially suited to web development.
* [jQuery] - the Write Less, Do More, JavaScript Library.
* [jQuery-UI] - a curated set of user interface interactions, effects, widgets, and themes.

### Installation
Upload custom-product-page folder in your /wp-content/plugins folder in your wordpress installation

### License

MIT [LICENSE]

[LICENSE]:https://github.com/ToniChaz/custom-product-page/blob/master/LICENSE
[Wordpress]:https://www.wordpress.com/
[PHP]:http://php.net/
[jQuery]:http://jquery.com
[jQuery-UI]:https://jqueryui.com/


text:
package API

type Passenger struct {
	message
	mID         int
	mState      int
	mType       string
	mFloor      int
	mX          float64
	mY          float64
	mElevator   int
	mFromFloor  int
	mDestFloor  int
	mTimeToAway int
	mWeight     float64
}

func (p *Passenger) ID() int {
	return p.mID
}

func (p *Passenger) State() int {
	return p.mState
}

func (p *Passenger) Type() string {
	return p.mType
}

func (p *Passenger) Floor() int {
	return p.mFloor
}

func (p *Passenger) X() float64 {
	return p.mX
}

func (p *Passenger) Y() float64 {
	return p.mY
}

func (p *Passenger) HasElevator() bool {
	return p.mElevator != -1
}

func (p *Passenger) FromFloor() int {
	return p.mFromFloor
}

func (p *Passenger) DestFloor() int {
	return p.mDestFloor
}

func (p *Passenger) TimeToAway() int {
	return p.mTimeToAway
}

func (p *Passenger) Weight() float64 {
	return p.mWeight
}

func (p *Passenger) SetElevator(elevator *Elevator) {
	p.mElevator = elevator.ID()

	cmd := make(map[string]interface{})
	cmd["passenger_id"] = p.ID()
	cmd["elevator_id"] = elevator.ID()

	message := make(map[string]interface{})
	message["command"] = "set_elevator_to_passenger"
	message["args"] = cmd

	p.mMessages = append(p.mMessages, message)
}

func NewPassenger(JSONObj map[string]interface{}) *Passenger {
	p := &Passenger{}

	id, _ := JSONObj["id"]
	p.mID = int(id.(float64))

	state, _ := JSONObj["state"]
	p.mState = int(state.(float64))

	t, _ := JSONObj["type"]
	p.mType = t.(string)

	floor, _ := JSONObj["floor"]
	p.mFloor = int(floor.(float64))

	x, _ := JSONObj["x"]
	p.mX = x.(float64)

	y, _ := JSONObj["y"]
	p.mY = y.(float64)

	elevator, ok := JSONObj["elevator"]
	if !ok || elevator == nil {
		p.mElevator = -1
	} else {
		p.mElevator = int(elevator.(float64))
	}

	fromFloor, _ := JSONObj["from_floor"]
	p.mFromFloor = int(fromFloor.(float64))

	destFloor, _ := JSONObj["dest_floor"]
	p.mDestFloor = int(destFloor.(float64))

	timeToAway, _ := JSONObj["time_to_away"]
	p.mTimeToAway = int(timeToAway.(float64))

	weight, _ := JSONObj["weight"]
	p.mWeight = weight.(float64)

	return p
}


text:
class A
class B extends A

val a: Product2[Int, B] = (23, new A)
//False


text:
const assert = require('assert');
const adminHelper = require('../../common/admin-helper')();
const environment = require('../../fixtures/cli/environment');
const namespace = 'express-gateway:users:info';
const idGen = require('uuid-base62');

describe('eg users info', () => {
  let program, env, userId, username;

  before(() => {
    ({ program, env } = environment.bootstrap());
    return adminHelper.start();
  });
  after(() => adminHelper.stop());

  beforeEach(() => {
    env.prepareHijack();
    username = idGen.v4();

    return adminHelper.admin.users.create({
      username: username,
      firstname: 'La',
      lastname: 'Deeda'
    })
    .then(user => {
      userId = user.id;
    });
  });

  afterEach(() => {
    env.resetHijack();
  });

  it('returns user info', done => {
    env.hijack(namespace, generator => {
      let output = null;
      let error = null;

      generator.once('run', () => {
        generator.log.error = message => {
          error = message;
        };
        generator.stdout = message => {
          output = message;
        };
      });

      generator.once('end', () => {
        const user = JSON.parse(output);

        assert.equal(user.firstname, 'La');
        assert.equal(user.lastname, 'Deeda');
        assert(user.isActive);

        assert.equal(error, null);

        done();
      });
    });

    env.argv = program.parse('users info ' + username);
  });

  it('prints only the user id when using the --quiet flag', done => {
    env.hijack(namespace, generator => {
      let output = null;
      let error = null;

      generator.once('run', () => {
        generator.log.error = message => {
          error = message;
        };
        generator.stdout = message => {
          output = message;
        };
      });

      generator.once('end', () => {
        assert.equal(output, userId);
        assert.equal(error, null);

        done();
      });
    });

    env.argv = program.parse('users info ' + username + ' -q');
  });
});