text:
extern crate lettre;

use lettre::transport::stub::StubEmailTransport;
use lettre::transport::EmailTransport;
use lettre::email::EmailBuilder;

#[test]
fn stub_transport() {
    let mut sender = StubEmailTransport;
    let email = EmailBuilder::new()
                    .to("root@localhost")
                    .from("user@localhost")
                    .body("Hello World!")
                    .subject("Hello")
                    .build()
                    .unwrap();
    let result = sender.send(email);
    assert!(result.is_ok());
}


text:
// Program: iamAlive.js
// Purpose: application heartbeat module to show the app is alive.
// Author:  Ray Lai
// Updated: Sep 12, 2016
// License: MIT license
//
module.exports = function(app) {
  console.log("/iamAlive.js - iamAlive is loaded.");

  /**
  * @api {get} /iamAlive system heartbeat
  * @apiVersion 0.1.0
  * @apiName iamAlive
  * @apiDescription application heartbeat module to show the app is alive.
  * @apiGroup System
  *
  * @apiSuccess {String} message system status about the platform
  *
  * @apiExample {curl} Example usage:
  * curl -X GET http://localhost:3000/iamAlive
  *
  * @apiSuccessExample Success-Response:
  *     HTTP/1.1 200 OK
  *     {
  *       "message": "IoT platform is alive"
  *     }
  *
  * @apiError (Error 500) {json} N/A Not applicable
  *
  * @apiErrorExample {json} Error-Response:
  *     HTTP/1.1 500 Not Found
  *     {
  *       "error": "Internal system error. Please check with system administrator to restart servers."
  *     }
  **/
	app.get('/verifyMe', function(req, res) {
		res.json({'message': 'IoT platform is alive'});
	});
};

redpajama_set_name: RedPajamaGithub


text:
package scalapb.proptest

import java.io.File
import dotty.tools.dotc.Main
import dotty.tools.dotc.reporting.Reporter

object CompilerInterface {
  def compile(files: Seq[File], classPath: Seq[String], outDir: File): Unit = {
    val args = files.map(_.toString()) ++
      Seq("-d", outDir.toString(), "-usejavacp", "-classpath", classPath.mkString(":"))
    val reporter: Reporter = Main.process(args.toArray)
    if (reporter.hasErrors) {
      throw RuntimeException("Scala sources had errors")
    }
  }
}


text:
package org.jboss.weld.tests.contexts.passivating.injection.broken;

import java.io.Serializable;

import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.enterprise.inject.TransientReference;
import javax.inject.Inject;

@SuppressWarnings("serial")
@Decorator
public class AnimalDecoratorBroken2 implements Animal, Serializable {

    @Inject
    @Delegate
    private Animal delegate;

    @Inject
    public AnimalDecoratorBroken2(Truck truck, @TransientReference Pasture pasture) {
    }

    @Inject
    public void init(Truck truck, Pasture pasture) {
    }

    public void run() {
        delegate.run();
    }

}


text:
package commands

import (
	"log"
	"os"
	"path/filepath"

	"github.com/pkg/errors"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"moul.io/assh/v2/pkg/config"
	loggerpkg "moul.io/assh/v2/pkg/logger"
	"moul.io/assh/v2/pkg/version"
)

var commands = []*cobra.Command{
	pingCommand,
	proxyCommand,
	infoCommand,
	configCommand,
	socketsCommand,
	wrapperCommand,
}

// RootCmd is the root cobra command containing all commands for assh.
var RootCmd = &cobra.Command{
	Use:              "assh",
	Short:            "assh - advanced ssh config",
	Version:          version.Version + " (" + version.VcsRef + ")",
	TraverseChildren: true,
}

// nolint:gochecknoinits
func init() {
	ex, err := os.Executable()
	if err != nil {
		log.Fatal(err)
	}
	abspath, err := filepath.Abs(ex)
	if err != nil {
		log.Fatal(err)
	}
	config.SetASSHBinaryPath(abspath)

	RootCmd.Flags().BoolP("help", "h", false, "print usage")
	RootCmd.Flags().StringP("config", "c", "~/.ssh/assh.yml", "Location of config file")
	RootCmd.Flags().BoolP("debug", "D", false, "Enable debug mode")
	RootCmd.Flags().BoolP("verbose", "V", false, "Enable verbose mode")

	_ = viper.BindEnv("debug", "ASSH_DEBUG")
	_ = viper.BindEnv("config", "ASSH_CONFIG")
	_ = viper.BindPFlags(RootCmd.Flags())

	RootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
		if viper.GetBool("debug") {
			if err := os.Setenv("ASSH_DEBUG", "1"); err != nil {
				return err
			}
		}
		if err := initLogging(viper.GetBool("debug"), viper.GetBool("verbose")); err != nil {
			return err
		}
		return nil
	}

	RootCmd.AddCommand(commands...)
}

func initLogging(debug bool, verbose bool) error {
	config := zap.NewDevelopmentConfig()
	config.Level.SetLevel(loggerpkg.MustLogLevel(debug, verbose))
	if !debug {
		config.DisableStacktrace = true
		config.DisableCaller = true
		config.EncoderConfig.TimeKey = ""
		config.EncoderConfig.NameKey = ""
	}
	config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
	l, err := config.Build()
	if err != nil {
		return errors.Wrap(err, "failed to initialize logger")
	}
	zap.ReplaceGlobals(l)
	return nil
}


text:
SwiftGoal
=========

This project showcases the Model-View-ViewModel (MVVM) architecture with [ReactiveCocoa 4][reactive-cocoa], while serving as a digital logbook of [FIFA matches][fifa-wikipedia]. It was inspired on a theoretical level by Justin Spahr-Summers' talk [Enemy of the State][enemy-of-the-state], and on a more practical one by Ash Furrow's [C-41][c-41] app.

[reactive-cocoa]: https://github.com/ReactiveCocoa/ReactiveCocoa
[fifa-wikipedia]: https://en.wikipedia.org/wiki/FIFA_(video_game_series)
[enemy-of-the-state]: https://github.com/jspahrsummers/enemy-of-the-state
[c-41]: https://github.com/ashfurrow/C-41

As the Swift language and the ecosystem around it [matured][reactive-cocoa-releases], porting the original [ObjectiveGoal][objective-goal] project became a natural next step, as Swift's type safety makes it a perfect fit for functional reactive programming.

[reactive-cocoa-releases]: https://github.com/ReactiveCocoa/ReactiveCocoa/releases
[objective-goal]: https://github.com/richeterre/ObjectiveGoal

Requirements
------------

SwiftGoal runs on iOS 9+ and requires Xcode 7.1 with Swift 2.1 to build.

Setup
-----

No separate backend is required to use the app, as it stores all its data locally in the `Documents` directory by default. Note that things might break in future releases, e.g. if some model fields change.

For serious use and if you want to share data across multiple devices, I recommend you use [Goalbase][goalbase] as a backend. It's easy to get started:

1. Follow the setup instructions in the [Goalbase documentation][goalbase-docs].
2. Enable the "Use Remote Store" switch under _Settings > SwiftGoal_.
3. Make sure the base URL is set correctly. The default value should be fine if you run `rails server` in your Goalbase directory, but for a remote setup (e.g. on Heroku) you'll need to update this setting.

[goalbase]: https://github.com/richeterre/goalbase
[goalbase-docs]: https://github.com/richeterre/goalbase/blob/master/README.md

Unit Tests
----------

SwiftGoal is thoroughly covered by unit tests, which are written with [Quick][quick] and [Nimble][nimble]. An advantage of such [BDD-style][bdd-wikipedia] frameworks is that they document the behavior of the tested code in plain English. To run the unit tests, simply hit `Cmd + U` in Xcode.

[quick]: https://github.com/Quick/Quick
[nimble]: https://github.com/Quick/Nimble
[bdd-wikipedia]: https://en.wikipedia.org/wiki/Behavior-driven_development

User Features
-------------

* [x] Create players
* [x] Create matches with home/away players and score
* [x] View list of matches
* [x] Edit existing match information
* [x] Delete matches
* [x] Pull-to-refresh any list in the app
* [x] See animated list changes
* [x] Enjoy custom fonts and colors
* [x] Get alerts about network and server errors
* [x] View player rankings
* [ ] Switch between different ranking periods (last month, all time, …)
* [ ] See date and time of each match
* [ ] See matches grouped by date range (e.g. last week, last month, earlier)
* [ ] View more player statistics (e.g. won/drawn/lost count, nemesis player, …)
* [ ] Delete players alongside their dependent matches

Code Checklist
--------------

* [x] Validate player name before creating
* [x] Validate match player counts before creating
* [x] Move base URL to Settings for easy customization
* [ ] Cancel network requests when the associated view becomes inactive
* [ ] Retry network requests 1 or 2 times before giving up
* [x] Detect and animate match data changes
* [x] Write tests for models
* [x] Write tests for view models
* [ ] Write tests for helpers and store
* [ ] Deduplicate `isActiveSignal` code on view controllers (via a protocol extension?)
* [ ] Create watchOS 2 app for quick match entry
* [ ] Drop Auto Layout [library][snapkit] in favor of `UIStackView` and `NSLayoutAnchor`

[snapkit]: https://github.com/SnapKit/SnapKit

Benefits of MVVM
----------------

__High testability:__ The basic premise of testing is to verify correct output for a given input. As a consequence, any class that minimizes the amount of dependencies affecting its output becomes a good candidate for testing. MVVM's separation of logic (the view model layer) from presentation (the view layer) means that the view model can be tested with minimal setup. For instance, injecting a mock `Store` that provides a known amount of `Match` instances is enough to verify that the `MatchesViewModel` reports the correct amount of matches. The view layer becomes trivial, as it simply binds to those outputs.

__Better separation of concerns:__ `UIViewController` and its friends have been rightfully [scorned][mvc-tweet] for handling far too many things, from interface rotation to networking to providing table data. MVVM solves this by making a clear cut between UI and business logic. While a view controller would still acts as its table view's data source, it forwards the actual data queries to its own view model. Presentation details, such as animating new rows into the table view, will be handled in the view layer.

__Encapsulation of state:__ As suggested by Gary Bernhardt in his famous talk ["Boundaries"][boundaries-talk], view models offer a stateful shell around the stateless core of the app, the model layer. If need be, the app's state can be persisted and restored simply by storing the view model. While the view may be extremely stateful too, its state is ultimately derived from that of the view model, and thus does not require to be stored.

[mvc-tweet]: https://twitter.com/colin_campbell/status/293167951132098560
[boundaries-talk]: https://www.destroyallsoftware.com/talks/boundaries

Acknowledgements
----------------

This project is kindly sponsored by [Futurice][futurice] as part of their fantastic [open-source program][spice-program]. Kiitos!

The icons within the app are courtesy of [Icons8][icons8] – a resource well worth checking out.

[futurice]: http://futurice.com/
[spice-program]: http://www.spiceprogram.org/
[icons8]: https://icons8.com/


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

namespace DataObjects.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute(@"Data Source=(LocalDb)\v11.0;AttachDbFilename=""C:\Users\Jacob\Documents\_Projects\DoFramework 4.5\Upgrade 4.0 to 4.5\Patterns in Action 4.5\Mvc\App_Data\action.mdf"";Initial Catalog=Action;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework")]
        public string ActionConnectionString {
            get {
                return ((string)(this["ActionConnectionString"]));
            }
        }
    }
}


text:
<?php

namespace backend\modules\funding\controllers;

use Yii;
use common\models\FundingAllocation;
use common\models\FundingAllocationSearch;
use common\models\Appointment;
use common\models\OnAccount;
use common\models\AppointmentSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * FundingAllocationController implements the CRUD actions for FundingAllocation model.
 */
class FundingAllocationController extends Controller {

        /**
         * @inheritdoc
         */
        public function behaviors() {
                return [
                    'verbs' => [
                        'class' => VerbFilter::className(),
                        'actions' => [
                            'delete' => ['POST'],
                        ],
                    ],
                ];
        }

        /**
         * Lists all FundingAllocation models.
         * @return mixed
         */
        public function actionIndex() {
                $searchModel = new AppointmentSearch();
                $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

                return $this->render('index', [
                            'searchModel' => $searchModel,
                            'dataProvider' => $dataProvider,
                ]);
        }

        /**
         * Displays a single FundingAllocation model.
         * @param integer $id
         * @return mixed
         */
        public function actionView($id) {
                return $this->render('view', [
                            'model' => $this->findModel($id),
                ]);
        }

        /**
         * Creates a new FundingAllocation model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         * @return mixed
         */
        public function actionCreate() {
                $model = new FundingAllocation();

                if ($model->load(Yii::$app->request->post()) && $model->save()) {
                        return $this->redirect(['view', 'id' => $model->id]);
                } else {
                        return $this->render('create', [
                                    'model' => $model,
                        ]);
                }
        }

        /**
         * Updates an existing FundingAllocation model.
         * If update is successful, the browser will be redirected to the 'view' page.
         * @param integer $id
         * @return mixed
         */
        public function actionUpdate($id) {
                $model = $this->findModel($id);

                if ($model->load(Yii::$app->request->post()) && $model->save()) {
                        return $this->redirect(['view', 'id' => $model->id]);
                } else {
                        return $this->render('update', [
                                    'model' => $model,
                        ]);
                }
        }

        public function actionAdd($id, $fund_id = NULL) {
                $fundings = FundingAllocation::findAll(['appointment_id' => $id]);
                $appointment = Appointment::findOne($id);
                if (!isset($fund_id)) {
                        $model = new FundingAllocation;
                } else {
                        $model = $this->findModel($fund_id);
                        $model->fund_date = Yii::$app->ChangeDateFormate->SingleDateFormat($model->fund_date);
                }
                if ($model->load(Yii::$app->request->post()) && Yii::$app->SetValues->Attributes($model)) {
                        $check = $_POST['check'];
                        $model->appointment_id = $id;
                        $model->type = 1;
                        $model->fund_date = Yii::$app->ChangeDateFormate->SingleDateFormat($model->fund_date);
                        if ($check == 1) {
                                $onaccount = OnAccount::find()->orderBy(['id' => SORT_DESC])->where(['debtor_id' => $model->principal_id])->one();
                                if (!empty($onaccount)) {
                                        if ($onaccount->balance >= $model->amount) {
                                                $model->save(false);
                                                $this->UpdateOnAccount($model, $onaccount);
                                        } else {
                                                Yii::$app->getSession()->setFlash('error', 'On Account amount is Lower');
                                                return $this->redirect(['add', 'id' => $id]);
                                        }
                                }
                        } else {
                                $model->save(false);
                        }
                        return $this->redirect(['add', 'id' => $id]);
                }
                return $this->render('add', [
                            'model' => $model,
                            'fundings' => $fundings,
                            'appointment' => $appointment,
                            'id' => $id,
                ]);
        }

        public function UpdateOnAccount($model_fund, $onaccount) {
                $model = new OnAccount;
                $model->debtor_id = $model_fund->principal_id;
                $model->transaction_type = 2;
                $model->payment_type = $model_fund->principal_id;
                $model->check_no = $model_fund->check_no;
                $model->amount = $model_fund->amount;
                $model->date = $model_fund->fund_date;
                $model->appointment_id = $model_fund->appointment_id;
                $model->balance = $onaccount->balance - $model_fund->amount;
                $model->comment = $model_fund->description;
                $model->date = Yii::$app->ChangeDateFormate->SingleDateFormat($model->date);
                Yii::$app->SetValues->Attributes($model);
                $model->save();
        }

        public function actionDeleteFund($id) {

                $this->findModel($id)->delete();
                return $this->redirect(Yii::$app->request->referrer);
        }

        /**
         * Deletes an existing FundingAllocation model.
         * If deletion is successful, the browser will be redirected to the 'index' page.
         * @param integer $id
         * @return mixed
         */
        public function actionDelete($id) {
                $this->findModel($id)->delete();

                return $this->redirect(['index']);
        }

        /**
         * Finds the FundingAllocation model based on its primary key value.
         * If the model is not found, a 404 HTTP exception will be thrown.
         * @param integer $id
         * @return FundingAllocation the loaded model
         * @throws NotFoundHttpException if the model cannot be found
         */
        protected function findModel($id) {
                if (($model = FundingAllocation::findOne($id)) !== null) {
                        return $model;
                } else {
                        throw new NotFoundHttpException('The requested page does not exist.');
                }
        }

}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;

namespace Nerven.Taskuler
{
    [PublicAPI]
    public interface ITaskulerWorker
    {
        bool IsRunning { get; }

        IObservable<TaskulerNotification> NotificationsSource { get; }

        IEnumerable<ITaskulerScheduleHandle> GetSchedules();

        ITaskulerScheduleHandle AddSchedule(string scheduleName, ITaskulerSchedule schedule);

        Task StartAsync(CancellationToken cancellationToken = default(CancellationToken));

        Task RunAsync(CancellationToken cancellationToken);

        Task StopAsync();

        Task WaitAsync(CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
<?php

namespace Bab\RabbitMq\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class VhostResetCommand extends BaseCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure(): void
    {
        parent::configure();

        $this
            ->setName('vhost:reset')
            ->setDescription('Reset a vhost')
            ->addArgument('vhost', InputArgument::REQUIRED, 'Which vhost should be cleaned ?')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $vhostManager = $this->getVhostManager($input, $output, $input->getArgument('vhost'));
        $vhostManager->resetVhost();

        return 0;
    }
}


text:
===============================
xlpo
===============================

.. image:: https://img.shields.io/travis/fabiocorneti/xlpo.svg
        :target: https://travis-ci.org/fabiocorneti/xlpo

.. image:: https://coveralls.io/repos/fabiocorneti/xlpo/badge.svg
         :target: https://coveralls.io/r/fabiocorneti/xlpo
..
  .. image:: https://img.shields.io/pypi/v/xlpo.svg
          :target: https://pypi.python.org/pypi/xlpo

Description
-----------

Simple command line utilities to convert xls/xlsx files to gettext PO files and back.

Features
--------

* TODO


text:
<?php

declare(strict_types=1);

namespace Gitter\Resources;

use Gitter\Route;

/**
 * User schema
 *  - id:               Gitter User ID.
 *  - username:         Gitter/GitHub username.
 *  - displayName:      Gitter/GitHub user real name.
 *  - url:              Path to the user on Gitter.
 *  - avatarUrlSmall:   User avatar URI (small).
 *  - avatarUrlMedium:  User avatar URI (medium).
 *
 * @package Gitter\Resources
 */
class Users extends AbstractResource
{
    /**
     * @var array|null
     */
    private $currentUser;

    /**
     * Returns the current user logged in.
     *
     * @return array
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     * @throws \Throwable
     * @throws \Exception
     */
    public function current(): array
    {
        if ($this->currentUser === null) {
            $users = $this->fetch(Route::get('user'));

            if (isset($users[0])) {
                $this->currentUser = $users[0];
            } else {
                throw new \RuntimeException('Can not fetch current user');
            }
        }

        return $this->currentUser;
    }

    /**
     * @return string
     * @throws \Throwable
     * @throws \RuntimeException
     * @throws \Exception
     * @throws \InvalidArgumentException
     */
    public function currentUserId(): string
    {
        return (string)($this->current()['id'] ?? null);
    }

    /**
     * List of Rooms the user is part of.
     *
     * @param string|null $userId User id
     * @return array
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     * @throws \Throwable
     * @throws \Exception
     */
    public function rooms(string $userId = null): array
    {
        return $this->fetch(
            Route::get('user/{userId}/rooms')
                ->with('userId', $userId ?? $this->currentUserId())
        );
    }

    /**
     * You can retrieve unread items and mentions using the following endpoint.
     *
     * @param string $roomId
     * @param string|null $userId
     * @return array
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     * @throws \Throwable
     * @throws \Exception
     */
    public function unreadItems(string $roomId, string $userId = null): array
    {
        return $this->fetch(
            Route::get('user/{userId}/rooms/{roomId}/unreadItems')
                ->withMany(['userId' => $userId ?? $this->currentUserId(), 'roomId' => $roomId])
        );
    }

    /**
     * There is an additional endpoint nested under rooms that you can use to mark chat messages as read
     *
     * @param string $roomId
     * @param array $messageIds
     * @param string|null $userId
     * @return array
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     * @throws \Throwable
     * @throws \Exception
     */
    public function markAsRead(string $roomId, array $messageIds, string $userId = null): array
    {
        return $this->fetch(
            Route::post('user/{userId}/rooms/{roomId}/unreadItems')
                ->withMany(['userId' => $userId ?? $this->currentUserId(), 'roomId' => $roomId])
                ->withBody('chat', $messageIds)
        );
    }

    /**
     * List of the user's GitHub Organisations and their respective Room if available.
     *
     * @param string|null $userId
     * @return array
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     * @throws \Throwable
     * @throws \Exception
     */
    public function orgs(string $userId = null): array
    {
        return $this->fetch(
            Route::get('user/{userId}/orgs')
                ->with('userId', $userId ?? $this->currentUserId())
        );
    }

    /**
     * List of the user's GitHub Repositories and their respective Room if available.
     *
     * Note: It'll return private repositories if the current user has granted Gitter privileges to access them.
     *
     * @param string|null $userId
     * @return array
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     * @throws \Throwable
     * @throws \Exception
     */
    public function repos(string $userId = null): array
    {
        return $this->fetch(
            Route::get('user/{userId}/repos')
                ->with('userId', $userId ?? $this->currentUserId())
        );
    }

    /**
     * List of Gitter channels nested under the current user.
     *
     * @param string|null $userId
     * @return array
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     * @throws \Throwable
     * @throws \Exception
     */
    public function channels(string $userId = null): array
    {
        return $this->fetch(
            Route::get('user/{userId}/channels')
                ->with('userId', $userId ?? $this->currentUserId())
        );
    }
}


text:
package com.olegych.scastie.client.components

import com.olegych.scastie.api.ConsoleOutput
import com.olegych.scastie.client.ConsoleState
import com.olegych.scastie.client.HTMLFormatter
import japgolly.scalajs.react._
import org.scalajs.dom.raw.HTMLDivElement

import vdom.all._

final case class Console(isOpen: Boolean,
                         isRunning: Boolean,
                         consoleOutputs: Vector[ConsoleOutput],
                         close: Reusable[Callback],
                         open: Reusable[Callback]) {
  @inline def render: VdomElement = Console.component(this)
}

object Console {

  implicit val reusability: Reusability[Console] =
    Reusability.derive[Console]

  private val consoleElement = Ref[HTMLDivElement]

  def render(props: Console): VdomElement = {
    val (displayConsole, displaySwitcher) =
      if (props.isOpen) (display.block, display.none)
      else (display.none, display.block)

    val consoleCss =
      if (props.isOpen)
        TagMod(cls := "console-open")
      else EmptyVdom

    val (users, systems) = props.consoleOutputs.partition {
      case u: ConsoleOutput.UserOutput => true
      case _                           => false
    }

    val toShow =
      if (users.isEmpty) props.consoleOutputs
      else users

    def renderConsoleOutputs: String = {
      s"<pre>${HTMLFormatter.format(toShow.map(_.show).mkString("\n"))}</pre>"
    }

    div(cls := "console-container", consoleCss)(
      div(cls := "console", displayConsole)(
        div(cls := "handler"),
        div(cls := "switcher-hide", displayConsole, role := "button", onClick --> props.close)(
          i(cls := "fa fa-terminal"),
          "Console (F3)",
          i(cls := "fa fa-caret-down")
        ),
        div.withRef(consoleElement)(
          cls := "output-console",
          dangerouslySetInnerHtml := renderConsoleOutputs
        )
      ),
      div(cls := "switcher-show", role := "button", onClick --> props.open)(
        displaySwitcher,
        i(cls := "fa fa-terminal"),
        "Console (F3)",
        i(cls := "fa fa-caret-up")
      )
    )
  }

  private val component =
    ScalaComponent
      .builder[Console]("Console")
      .initialState(ConsoleState.default)
      .render_P(render)
      .componentDidUpdate(
        scope =>
          Callback {
            consoleElement.unsafeGet().scrollTop = consoleElement.unsafeGet().scrollHeight.toDouble
          }.when_(scope.prevProps.isRunning)
      )
      .configure(Reusability.shouldComponentUpdate)
      .build
}


text:
function C=find_quantile(G,W,C)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%     Copyright 2014 University of Memphis
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%%
i=0;
for now=1:size(W.window,2)
    if isempty(W.window(now).sensor{G.SENSOR.R_ECGID}), continue;end;
    if W.window(now).sensor{G.SENSOR.R_ECGID}.quality~=G.QUALITY.GOOD,continue;end;
    if isempty(W.window(now).sensor{G.SENSOR.R_ECGID}.rr), continue;end;
    ind=find(W.window(now).sensor{G.SENSOR.R_ECGID}.rr.quality==G.QUALITY.GOOD);
    v=W.window(now).sensor{G.SENSOR.R_ECGID}.rr.sample(ind);
    if isempty(v),continue;end
    i=i+1;
%    C.Q95(i)=quantile(v,0.95);
%    v=winsorize(v);
    C.Q9(i)=quantile(v,0.9);
    C.timestamp(i)=W.window(now).endtimestamp;
    C.matlab_timestamp(i)=W.window(now).end_matlabtime;

end
end


text:
package org.apache.taverna.tavlang;

public class TavernaCommandline {

	public static void main(String args[]){
		CommandLineTool tool = new CommandLineTool();
		tool.parse(args);

	}
}


text:
package com.jalotsav.aalayam;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.crashlytics.android.Crashlytics;
import com.jalotsav.aalayam.common.AalayamConstants;
import com.jalotsav.aalayam.common.General_Fnctns;
import com.jalotsav.aalayam.common.UserSessionManager;
import com.jalotsav.aalayam.navgndrwer.doctor.NavgnDrawer_Main_Doctor;
import com.jalotsav.aalayam.navgndrwer.doctor.NavgnDrwrDoctor;
import com.jalotsav.aalayam.navgndrwer.patient.NavgnDrawer_Main_Patient;
import com.jalotsav.aalayam.service.InternetService;

import io.fabric.sdk.android.Fabric;

public class Aalayam extends Activity implements AalayamConstants {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fabric.with(this, new Crashlytics());
        setContentView(R.layout.lo_aalayam);

        final int openFrgmntPostn = getIntent().getIntExtra(OPEN_FRGMNT_BY_POSTN, NAVDRWER_FRGMNT_DASHBOARD);

        Handler mhandlr = new Handler();
        mhandlr.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                finish();

                // Check Internet check service is running or not, If not then Start Service
                if (General_Fnctns.isServiceRunning(InternetService.class, Aalayam.this))
                    Log.i(TAG, "InternetCheck Service already Running");
                else {

                    Log.e(TAG, "InternetCheck Service NOT Running, Start Service");
                    startService(new Intent(Aalayam.this, InternetService.class));
                }

//                Intent intntNvgnDrwrDoctr = new Intent(Aalayam.this, NavgnDrawer_Main_Doctor.class);
                Intent intntNvgnDrwrDoctr = new Intent(Aalayam.this, NavgnDrwrDoctor.class);
                intntNvgnDrwrDoctr.putExtra(OPEN_FRGMNT_BY_POSTN, openFrgmntPostn);
                startActivity(intntNvgnDrwrDoctr);
            }
        }, 3000);
    }
}


text:
 /*global window, module*/
(function($){
	'use strict';
	var Helper = $.Util = {
	    StateLoopRemover : {
		removeLoop : function(stack, index) {
		    stack.splice(index, Helper.StateLoopRemover.findLastOccurence(stack,index) - index);

		    return stack;
		},

		findLastOccurence : function(stack, index) {
		    var find = stack[index];
		    var foundAt = index;

		    stack.forEach(function(el, i) {
			if(find.state.x === el.state.x && find.state.y === el.state.y) {
			    foundAt = i;
			}
		    });
		    return foundAt;
		}
	    }
	};

})(window || module.exports);


text:
var get = Ember.get, set = Ember.set, map = Ember.ArrayPolyfills.map, isNone = Ember.isNone;

function mustImplement(name) {
  return function() {
    throw new Ember.Error("Your serializer " + this.toString() + " does not implement the required method " + name);
  };
}

/**
  A serializer is responsible for serializing and deserializing a group of
  records.

  `DS.Serializer` is an abstract base class designed to help you build a
  serializer that can read to and write from any serialized form.  While most
  applications will use `DS.JSONSerializer`, which reads and writes JSON, the
  serializer architecture allows your adapter to transmit things like XML,
  strings, or custom binary data.

  Typically, your application's `DS.Adapter` is responsible for both creating a
  serializer as well as calling the appropriate methods when it needs to
  materialize data or serialize a record.

  The serializer API is designed as a series of layered hooks that you can
  override to customize any of the individual steps of serialization and
  deserialization.

  The hooks are organized by the three responsibilities of the serializer:

  1. Determining naming conventions
  2. Serializing records into a serialized form
  3. Deserializing records from a serialized form

  Because Ember Data lazily materializes records, the deserialization
  step, and therefore the hooks you implement, are split into two phases:

  1. Extraction, where the serialized forms for multiple records are
     extracted from a single payload. The IDs of each record are also
     extracted for indexing.
  2. Materialization, where a newly-created record has its attributes
     and relationships initialized based on the serialized form loaded
     by the adapter.

  Additionally, a serializer can convert values from their JavaScript
  versions into their serialized versions via a declarative API.

  ## Naming Conventions

  One of the most common uses of the serializer is to map attribute names
  from the serialized form to your `DS.Model`. For example, in your model,
  you may have an attribute called `firstName`:

  ```javascript
  App.Person = DS.Model.extend({
    firstName: DS.attr('string')
  });
  ```

  However, because the web API your adapter is communicating with is
  legacy, it calls this attribute `FIRST_NAME`.

  You can determine the attribute name used in the serialized form
  by implementing `keyForAttributeName`:

  ```javascript
    keyForAttributeName: function(type, name) {
      return name.underscore.toUpperCase();
    }
  ```

  If your attribute names are not predictable, you can re-map them
  one-by-one using the `map` API:

  ```javascript
  App.Person.map('App.Person', {
    firstName: { key: '*API_USER_FIRST_NAME*' }
  });
  ```

  ## Serialization

  During the serialization process, a record or records are converted
  from Ember.js objects into their serialized form.

  These methods are designed in layers, like a delicious 7-layer
  cake (but with fewer layers).

  The main entry point for serialization is the `serialize`
  method, which takes the record and options.

  The `serialize` method is responsible for:

  * turning the record's attributes (`DS.attr`) into
    attributes on the JSON object.
  * optionally adding the record's ID onto the hash
  * adding relationships (`DS.hasMany` and `DS.belongsTo`)
    to the JSON object.

  Depending on the backend, the serializer can choose
  whether to include the `hasMany` or `belongsTo`
  relationships on the JSON hash.

  For very custom serialization, you can implement your
  own `serialize` method. In general, however, you will want
  to override the hooks described below.

  ### Adding the ID

  The default `serialize` will optionally call your serializer's
  `addId` method with the JSON hash it is creating, the
  record's type, and the record's ID. The `serialize` method
  will not call `addId` if the record's ID is undefined.

  Your adapter must specifically request ID inclusion by
  passing `{ includeId: true }` as an option to `serialize`.

  NOTE: You may not want to include the ID when updating an
  existing record, because your server will likely disallow
  changing an ID after it is created, and the PUT request
  itself will include the record's identification.

  By default, `addId` will:

  1. Get the primary key name for the record by calling
     the serializer's `primaryKey` with the record's type.
     Unless you override the `primaryKey` method, this
     will be `'id'`.
  2. Assign the record's ID to the primary key in the
     JSON hash being built.

  If your backend expects a JSON object with the primary
  key at the root, you can just override the `primaryKey`
  method on your serializer subclass.

  Otherwise, you can override the `addId` method for
  more specialized handling.

  ### Adding Attributes

  By default, the serializer's `serialize` method will call
  `addAttributes` with the JSON object it is creating
  and the record to serialize.

  The `addAttributes` method will then call `addAttribute`
  in turn, with the JSON object, the record to serialize,
  the attribute's name and its type.

  Finally, the `addAttribute` method will serialize the
  attribute:

  1. It will call `keyForAttributeName` to determine
     the key to use in the JSON hash.
  2. It will get the value from the record.
  3. It will call `serializeValue` with the attribute's
     value and attribute type to convert it into a
     JSON-compatible value. For example, it will convert a
     Date into a String.

  If your backend expects a JSON object with attributes as
  keys at the root, you can just override the `serializeValue`
  and `keyForAttributeName` methods in your serializer
  subclass and let the base class do the heavy lifting.

  If you need something more specialized, you can probably
  override `addAttribute` and let the default `addAttributes`
  handle the nitty gritty.

  ### Adding Relationships

  By default, `serialize` will call your serializer's
  `addRelationships` method with the JSON object that is
  being built and the record being serialized. The default
  implementation of this method is to loop over all of the
  relationships defined on your record type and:

  * If the relationship is a `DS.hasMany` relationship,
    call `addHasMany` with the JSON object, the record
    and a description of the relationship.
  * If the relationship is a `DS.belongsTo` relationship,
    call `addBelongsTo` with the JSON object, the record
    and a description of the relationship.

  The relationship description has the following keys:

  * `type`: the class of the associated information (the
    first parameter to `DS.hasMany` or `DS.belongsTo`)
  * `kind`: either `hasMany` or `belongsTo`

  The relationship description may get additional
  information in the future if more capabilities or
  relationship types are added. However, it will
  remain backwards-compatible, so the mere existence
  of new features should not break existing adapters.
*/
DS.Serializer = Ember.Object.extend({
  init: function() {
    this.mappings = Ember.Map.create();
    this.configurations = Ember.Map.create();
    this.globalConfigurations = {};
  },

  extract: mustImplement('extract'),
  extractMany: mustImplement('extractMany'),

  extractRecordRepresentation: function(loader, type, json, shouldSideload) {
    var mapping = this.mappingForType(type);
    var embeddedData, prematerialized = {}, reference;

    if (shouldSideload) {
      reference = loader.sideload(type, json);
    } else {
      reference = loader.load(type, json);
    }

    this.eachEmbeddedHasMany(type, function(name, relationship) {
      var embeddedData = json[this.keyFor(relationship)];
      if (!isNone(embeddedData)) {
        this.extractEmbeddedHasMany(loader, relationship, embeddedData, reference, prematerialized);
      }
    }, this);

    this.eachEmbeddedBelongsTo(type, function(name, relationship) {
      var embeddedData = json[this.keyFor(relationship)];
      if (!isNone(embeddedData)) {
        this.extractEmbeddedBelongsTo(loader, relationship, embeddedData, reference, prematerialized);
      }
    }, this);

    loader.prematerialize(reference, prematerialized);

    return reference;
  },

  extractEmbeddedHasMany: function(loader, relationship, array, parent, prematerialized) {
    var references = map.call(array, function(item) {
      if (!item) { return; }

      var reference = this.extractRecordRepresentation(loader, relationship.type, item, true);

      // If the embedded record should also be saved back when serializing the parent,
      // make sure we set its parent since it will not have an ID.
      var embeddedType = this.embeddedType(parent.type, relationship.key);
      if (embeddedType === 'always') {
        reference.parent = parent;
      }

      return reference;
    }, this);

    prematerialized[relationship.key] = references;
  },

  extractEmbeddedBelongsTo: function(loader, relationship, data, parent, prematerialized) {
    var reference = this.extractRecordRepresentation(loader, relationship.type, data, true);
    prematerialized[relationship.key] = reference;

    // If the embedded record should also be saved back when serializing the parent,
    // make sure we set its parent since it will not have an ID.
    var embeddedType = this.embeddedType(parent.type, relationship.key);
    if (embeddedType === 'always') {
      reference.parent = parent;
    }
  },

  //.......................
  //. SERIALIZATION HOOKS
  //.......................

  /**
    The main entry point for serializing a record. While you can consider this
    a hook that can be overridden in your serializer, you will have to manually
    handle serialization. For most cases, there are more granular hooks that you
    can override.

    If overriding this method, these are the responsibilities that you will need
    to implement yourself:

    * If the option hash contains `includeId`, add the record's ID to the serialized form.
      By default, `serialize` calls `addId` if appropriate.
    * Add the record's attributes to the serialized form. By default, `serialize` calls
      `addAttributes`.
    * Add the record's relationships to the serialized form. By default, `serialize` calls
      `addRelationships`.

    @param {DS.Model} record the record to serialize
    @param {Object} [options] a hash of options
    @returns {any} the serialized form of the record
  */
  serialize: function(record, options) {
    options = options || {};

    var serialized = this.createSerializedForm(), id;

    if (options.includeId) {
      if (id = get(record, 'id')) {
        this._addId(serialized, record.constructor, id);
      }
    }

    this.addAttributes(serialized, record);
    this.addRelationships(serialized, record);

    return serialized;
  },

  /**
    @private

    Given an attribute type and value, convert the value into the
    serialized form using the transform registered for that type.

    @param {any} value the value to convert to the serialized form
    @param {String} attributeType the registered type (e.g. `string`
      or `boolean`)
    @returns {any} the serialized form of the value
  */
  serializeValue: function(value, attributeType) {
    var transform = this.transforms ? this.transforms[attributeType] : null;

    Ember.assert("You tried to use an attribute type (" + attributeType + ") that has not been registered", transform);
    return transform.serialize(value);
  },

  /**
    A hook you can use to normalize IDs before adding them to the
    serialized representation.

    Because the store coerces all IDs to strings for consistency,
    this is the opportunity for the serializer to, for example,
    convert numerical IDs back into number form.

    @param {String} id the id from the record
    @returns {any} the serialized representation of the id
  */
  serializeId: function(id) {
    if (isNaN(id)) { return id; }
    return +id;
  },

  /**
    A hook you can use to change how attributes are added to the serialized
    representation of a record.

    By default, `addAttributes` simply loops over all of the attributes of the
    passed record, maps the attribute name to the key for the serialized form,
    and invokes any registered transforms on the value. It then invokes the
    more granular `addAttribute` with the key and transformed value.

    Since you can override `keyForAttributeName`, `addAttribute`, and register
    custom tranforms, you should rarely need to override this hook.

    @param {any} data the serialized representation that is being built
    @param {DS.Model} record the record to serialize
  */
  addAttributes: function(data, record) {
    record.eachAttribute(function(name, attribute) {
      this._addAttribute(data, record, name, attribute.type);
    }, this);
  },

  /**
    A hook you can use to customize how the key/value pair is added to
    the serialized data.

    @param {any} serialized the serialized form being built
    @param {String} key the key to add to the serialized data
    @param {any} value the value to add to the serialized data
  */
  addAttribute: Ember.K,

  /**
    A hook you can use to customize how the record's id is added to
    the serialized data.

    The `addId` hook is called with:

    * the serialized representation being built
    * the resolved primary key (taking configurations and the
      `primaryKey` hook into consideration)
    * the serialized id (after calling the `serializeId` hook)

    @param {any} data the serialized representation that is being built
    @param {String} key the resolved primary key
    @param {id} id the serialized id
  */
  addId: Ember.K,

  /**
    A hook you can use to change how relationships are added to the serialized
    representation of a record.

    By default, `addAttributes` loops over all of the relationships of the
    passed record, maps the relationship names to the key for the serialized form,
    and then invokes the public `addBelongsTo` and `addHasMany` hooks.

    Since you can override `keyForBelongsTo`, `keyForHasMany`, `addBelongsTo`,
    `addHasMany`, and register mappings, you should rarely need to override this
    hook.

    @param {any} data the serialized representation that is being built
    @param {DS.Model} record the record to serialize
  */
  addRelationships: function(data, record) {
    record.eachRelationship(function(name, relationship) {
      if (relationship.kind === 'belongsTo') {
        this._addBelongsTo(data, record, name, relationship);
      } else if (relationship.kind === 'hasMany') {
        this._addHasMany(data, record, name, relationship);
      }
    }, this);
  },

  /**
    A hook you can use to add a `belongsTo` relationship to the
    serialized representation.

    The specifics of this hook are very adapter-specific, so there
    is no default implementation. You can see `DS.JSONSerializer`
    for an example of an implementation of the `addBelongsTo` hook.

    The `belongsTo` relationship object has the following properties:

    * **type** a subclass of DS.Model that is the type of the
      relationship. This is the first parameter to DS.belongsTo
    * **options** the options passed to the call to DS.belongsTo
    * **kind** always `belongsTo`

    Additional properties may be added in the future.

    @param {any} data the serialized representation that is being built
    @param {DS.Model} record the record to serialize
    @param {String} key the key for the serialized object
    @param {Object} relationship an object representing the relationship
  */
  addBelongsTo: Ember.K,

  /**
    A hook you can use to add a `hasMany` relationship to the
    serialized representation.

    The specifics of this hook are very adapter-specific, so there
    is no default implementation. You may not need to implement this,
    for example, if your backend only expects relationships on the
    child of a one to many relationship.

    The `hasMany` relationship object has the following properties:

    * **type** a subclass of DS.Model that is the type of the
      relationship. This is the first parameter to DS.hasMany
    * **options** the options passed to the call to DS.hasMany
    * **kind** always `hasMany`

    Additional properties may be added in the future.

    @param {any} data the serialized representation that is being built
    @param {DS.Model} record the record to serialize
    @param {String} key the key for the serialized object
    @param {Object} relationship an object representing the relationship
  */
  addHasMany: Ember.K,

  /**
    NAMING CONVENTIONS

    The most commonly overridden APIs of the serializer are
    the naming convention methods:

    * `keyForAttributeName`: converts a camelized attribute name
      into a key in the adapter-provided data hash. For example,
      if the model's attribute name was `firstName`, and the
      server used underscored names, you would return `first_name`.
    * `primaryKey`: returns the key that should be used to
      extract the id from the adapter-provided data hash. It is
      also used when serializing a record.
  */

  /**
    A hook you can use in your serializer subclass to customize
    how an unmapped attribute name is converted into a key.

    By default, this method returns the `name` parameter.

    For example, if the attribute names in your JSON are underscored,
    you will want to convert them into JavaScript conventional
    camelcase:

    ```javascript
    App.MySerializer = DS.Serializer.extend({
      // ...

      keyForAttributeName: function(type, name) {
        return name.camelize();
      }
    });
    ```

    @param {DS.Model subclass} type the type of the record with
      the attribute name `name`
    @param {String} name the attribute name to convert into a key

    @returns {String} the key
  */
  keyForAttributeName: function(type, name) {
    return name;
  },

  /**
    A hook you can use in your serializer to specify a conventional
    primary key.

    By default, this method will return the string `id`.

    In general, you should not override this hook to specify a special
    primary key for an individual type; use `configure` instead.

    For example, if your primary key is always `__id__`:

    ```javascript
    App.MySerializer = DS.Serializer.extend({
      // ...
      primaryKey: function(type) {
        return '__id__';
      }
    });
    ```

    In another example, if the primary key always includes the
    underscored version of the type before the string `id`:

    ```javascript
    App.MySerializer = DS.Serializer.extend({
      // ...
      primaryKey: function(type) {
        // If the type is `BlogPost`, this will return
        // `blog_post_id`.
        var typeString = type.toString.split(".")[1].underscore();
        return typeString + "_id";
      }
    });
    ```

    @param {DS.Model subclass} type
    @returns {String} the primary key for the type
  */
  primaryKey: function(type) {
    return "id";
  },

  /**
    A hook you can use in your serializer subclass to customize
    how an unmapped `belongsTo` relationship is converted into
    a key.

    By default, this method calls `keyForAttributeName`, so if
    your naming convention is uniform across attributes and
    relationships, you can use the default here and override
    just `keyForAttributeName` as needed.

    For example, if the `belongsTo` names in your JSON always
    begin with `BT_` (e.g. `BT_posts`), you can strip out the
    `BT_` prefix:"

    ```javascript
    App.MySerializer = DS.Serializer.extend({
      // ...
      keyForBelongsTo: function(type, name) {
        return name.match(/^BT_(.*)$/)[1].camelize();
      }
    });
    ```

    @param {DS.Model subclass} type the type of the record with
      the `belongsTo` relationship.
    @param {String} name the relationship name to convert into a key

    @returns {String} the key
  */
  keyForBelongsTo: function(type, name) {
    return this.keyForAttributeName(type, name);
  },

  /**
    A hook you can use in your serializer subclass to customize
    how an unmapped `hasMany` relationship is converted into
    a key.

    By default, this method calls `keyForAttributeName`, so if
    your naming convention is uniform across attributes and
    relationships, you can use the default here and override
    just `keyForAttributeName` as needed.

    For example, if the `hasMany` names in your JSON always
    begin with the "table name" for the current type (e.g.
    `post_comments`), you can strip out the prefix:"

    ```javascript
    App.MySerializer = DS.Serializer.extend({
      // ...
      keyForHasMany: function(type, name) {
        // if your App.BlogPost has many App.BlogComment, the key from
        // the server would look like: `blog_post_blog_comments`
        //
        // 1. Convert the type into a string and underscore the
        //    second part (App.BlogPost -> blog_post)
        // 2. Extract the part after `blog_post_` (`blog_comments`)
        // 3. Underscore it, to become `blogComments`
        var typeString = type.toString().split(".")[1].underscore();
        return name.match(new RegExp("^" + typeString + "_(.*)$"))[1].camelize();
      }
    });
    ```

    @param {DS.Model subclass} type the type of the record with
      the `belongsTo` relationship.
    @param {String} name the relationship name to convert into a key

    @returns {String} the key
  */
  keyForHasMany: function(type, name) {
    return this.keyForAttributeName(type, name);
  },

  //.........................
  //. MATERIALIZATION HOOKS
  //.........................

  materialize: function(record, serialized, prematerialized) {
    var id;
    if (Ember.isNone(get(record, 'id'))) {
      if (prematerialized && prematerialized.hasOwnProperty('id')) {
        id = prematerialized.id;
      } else {
        id = this.extractId(record.constructor, serialized);
      }
      record.materializeId(id);
    }

    this.materializeAttributes(record, serialized, prematerialized);
    this.materializeRelationships(record, serialized, prematerialized);
  },

  deserializeValue: function(value, attributeType) {
    var transform = this.transforms ? this.transforms[attributeType] : null;

    Ember.assert("You tried to use a attribute type (" + attributeType + ") that has not been registered", transform);
    return transform.deserialize(value);
  },

  materializeAttributes: function(record, serialized, prematerialized) {
    record.eachAttribute(function(name, attribute) {
      if (prematerialized && prematerialized.hasOwnProperty(name)) {
        record.materializeAttribute(name, prematerialized[name]);
      } else {
        this.materializeAttribute(record, serialized, name, attribute.type);
      }
    }, this);
  },

  materializeAttribute: function(record, serialized, attributeName, attributeType) {
    var value = this.extractAttribute(record.constructor, serialized, attributeName);
    value = this.deserializeValue(value, attributeType);

    record.materializeAttribute(attributeName, value);
  },

  materializeRelationships: function(record, hash, prematerialized) {
    record.eachRelationship(function(name, relationship) {
      if (relationship.kind === 'hasMany') {
        if (prematerialized && prematerialized.hasOwnProperty(name)) {
          record.materializeHasMany(name, prematerialized[name]);
        } else {
          this.materializeHasMany(name, record, hash, relationship, prematerialized);
        }
      } else if (relationship.kind === 'belongsTo') {
        if (prematerialized && prematerialized.hasOwnProperty(name)) {
          record.materializeBelongsTo(name, prematerialized[name]);
        } else {
          this.materializeBelongsTo(name, record, hash, relationship, prematerialized);
        }
      }
    }, this);
  },

  materializeHasMany: function(name, record, hash, relationship) {
    var key = this._keyForHasMany(record.constructor, relationship.key);
    record.materializeHasMany(name, this.extractHasMany(record.constructor, hash, key));
  },

  materializeBelongsTo: function(name, record, hash, relationship) {
    var key = this._keyForBelongsTo(record.constructor, relationship.key);
    record.materializeBelongsTo(name, this.extractBelongsTo(record.constructor, hash, key));
  },

  _extractEmbeddedRelationship: function(type, hash, name, relationshipType) {
    var key = this['_keyFor' + relationshipType](type, name);

    if (this.embeddedType(type, name)) {
      return this['extractEmbedded' + relationshipType](type, hash, key);
    }
  },

  _extractEmbeddedBelongsTo: function(type, hash, name) {
    return this._extractEmbeddedRelationship(type, hash, name, 'BelongsTo');
  },

  _extractEmbeddedHasMany: function(type, hash, name) {
    return this._extractEmbeddedRelationship(type, hash, name, 'HasMany');
  },

  /**
    @private

    This method is called to get the primary key for a given
    type.

    If a primary key configuration exists for this type, this
    method will return the configured value. Otherwise, it will
    call the public `primaryKey` hook.

    @param {DS.Model subclass} type
    @returns {String} the primary key for the type
  */
  _primaryKey: function(type) {
    var config = this.configurationForType(type),
        primaryKey = config && config.primaryKey;

    if (primaryKey) {
      return primaryKey;
    } else {
      return this.primaryKey(type);
    }
  },

  /**
    @private

    This method looks up the key for the attribute name and transforms the
    attribute's value using registered transforms.

    Specifically:

    1. Look up the key for the attribute name. If available, this will use
       any registered mappings. Otherwise, it will invoke the public
       `keyForAttributeName` hook.
    2. Get the value from the record using the `attributeName`.
    3. Transform the value using registered transforms for the `attributeType`.
    4. Invoke the public `addAttribute` hook with the hash, key, and
       transformed value.

    @param {any} data the serialized representation being built
    @param {DS.Model} record the record to serialize
    @param {String} attributeName the name of the attribute on the record
    @param {String} attributeType the type of the attribute (e.g. `string`
      or `boolean`)
  */
  _addAttribute: function(data, record, attributeName, attributeType) {
    var key = this._keyForAttributeName(record.constructor, attributeName);
    var value = get(record, attributeName);

    this.addAttribute(data, key, this.serializeValue(value, attributeType));
  },

  /**
    @private

    This method looks up the primary key for the `type` and invokes
    `serializeId` on the `id`.

    It then invokes the public `addId` hook with the primary key and
    the serialized id.

    @param {any} data the serialized representation that is being built
    @param {Ember.Model subclass} type
    @param {any} id the materialized id from the record
  */
  _addId: function(hash, type, id) {
    var primaryKey = this._primaryKey(type);

    this.addId(hash, primaryKey, this.serializeId(id));
  },

  /**
    @private

    This method is called to get a key used in the data from
    an attribute name. It first checks for any mappings before
    calling the public hook `keyForAttributeName`.

    @param {DS.Model subclass} type the type of the record with
      the attribute name `name`
    @param {String} name the attribute name to convert into a key

    @returns {String} the key
  */
  _keyForAttributeName: function(type, name) {
    return this._keyFromMappingOrHook('keyForAttributeName', type, name);
  },

  /**
    @private

    This method is called to get a key used in the data from
    a belongsTo relationship. It first checks for any mappings before
    calling the public hook `keyForBelongsTo`.

    @param {DS.Model subclass} type the type of the record with
      the `belongsTo` relationship.
    @param {String} name the relationship name to convert into a key

    @returns {String} the key
  */
  _keyForBelongsTo: function(type, name) {
    return this._keyFromMappingOrHook('keyForBelongsTo', type, name);
  },

  keyFor: function(description) {
    var type = description.parentType,
        name = description.key;

    switch (description.kind) {
      case 'belongsTo':
        return this._keyForBelongsTo(type, name);
      case 'hasMany':
        return this._keyForHasMany(type, name);
    }
  },

  /**
    @private

    This method is called to get a key used in the data from
    a hasMany relationship. It first checks for any mappings before
    calling the public hook `keyForHasMany`.

    @param {DS.Model subclass} type the type of the record with
      the `hasMany` relationship.
    @param {String} name the relationship name to convert into a key

    @returns {String} the key
  */
  _keyForHasMany: function(type, name) {
    return this._keyFromMappingOrHook('keyForHasMany', type, name);
  },
  /**
    @private

    This method converts the relationship name to a key for serialization,
    and then invokes the public `addBelongsTo` hook.

    @param {any} data the serialized representation that is being built
    @param {DS.Model} record the record to serialize
    @param {String} name the relationship name
    @param {Object} relationship an object representing the relationship
  */
  _addBelongsTo: function(data, record, name, relationship) {
    var key = this._keyForBelongsTo(record.constructor, name);
    this.addBelongsTo(data, record, key, relationship);
  },

  /**
    @private

    This method converts the relationship name to a key for serialization,
    and then invokes the public `addHasMany` hook.

    @param {any} data the serialized representation that is being built
    @param {DS.Model} record the record to serialize
    @param {String} name the relationship name
    @param {Object} relationship an object representing the relationship
  */
  _addHasMany: function(data, record, name, relationship) {
    var key = this._keyForHasMany(record.constructor, name);
    this.addHasMany(data, record, key, relationship);
  },

  /**
    @private

    An internal method that handles checking whether a mapping
    exists for a particular attribute or relationship name before
    calling the public hooks.

    If a mapping is found, and the mapping has a key defined,
    use that instead of invoking the hook.

    @param {String} publicMethod the public hook to invoke if
      a mapping is not found (e.g. `keyForAttributeName`)
    @param {DS.Model subclass} type the type of the record with
      the attribute or relationship name.
    @param {String} name the attribute or relationship name to
      convert into a key
  */
  _keyFromMappingOrHook: function(publicMethod, type, name) {
    var key = this.mappingOption(type, name, 'key');

    if (key) {
      return key;
    } else {
      return this[publicMethod](type, name);
    }
  },

  /**
    TRANSFORMS
  */

  registerTransform: function(type, transform) {
    this.transforms[type] = transform;
  },

  registerEnumTransform: function(type, objects) {
    var transform = {
      deserialize: function(deserialized) {
        return Ember.A(objects).objectAt(deserialized);
      },
      serialize: function(serialized) {
        return Ember.EnumerableUtils.indexOf(objects, serialized);
      },
      values: objects
    };
    this.registerTransform(type, transform);
  },

  /**
    MAPPING CONVENIENCE
  */

  map: function(type, mappings) {
    this.mappings.set(type, mappings);
  },

  configure: function(type, configuration) {
    if (type && !configuration) {
      Ember.merge(this.globalConfigurations, type);
      return;
    }

    var config = Ember.create(this.globalConfigurations);
    Ember.merge(config, configuration);

    this.configurations.set(type, config);
  },

  mappingForType: function(type) {
    this._reifyMappings();
    return this.mappings.get(type) || {};
  },

  configurationForType: function(type) {
    this._reifyConfigurations();
    return this.configurations.get(type) || this.globalConfigurations;
  },

  _reifyMappings: function() {
    if (this._didReifyMappings) { return; }

    var mappings = this.mappings,
        reifiedMappings = Ember.Map.create();

    mappings.forEach(function(key, mapping) {
      if (typeof key === 'string') {
        var type = Ember.get(Ember.lookup, key);
        Ember.assert("Could not find model at path " + key, type);

        reifiedMappings.set(type, mapping);
      } else {
        reifiedMappings.set(key, mapping);
      }
    });

    this.mappings = reifiedMappings;

    this._didReifyMappings = true;
  },

  _reifyConfigurations: function() {
    if (this._didReifyConfigurations) { return; }

    var configurations = this.configurations,
        reifiedConfigurations = Ember.Map.create();

    configurations.forEach(function(key, mapping) {
      if (typeof key === 'string' && key !== 'plurals') {
        var type = Ember.get(Ember.lookup, key);
        Ember.assert("Could not find model at path " + key, type);

        reifiedConfigurations.set(type, mapping);
      } else {
        reifiedConfigurations.set(key, mapping);
      }
    });

    this.configurations = reifiedConfigurations;

    this._didReifyConfigurations = true;
  },

  mappingOption: function(type, name, option) {
    var mapping = this.mappingForType(type)[name];

    return mapping && mapping[option];
  },

  configOption: function(type, option) {
    var config = this.configurationForType(type);

    return config[option];
  },

  // EMBEDDED HELPERS

  embeddedType: function(type, name) {
    return this.mappingOption(type, name, 'embedded');
  },

  eachEmbeddedRecord: function(record, callback, binding) {
    this.eachEmbeddedBelongsToRecord(record, callback, binding);
    this.eachEmbeddedHasManyRecord(record, callback, binding);
  },

  eachEmbeddedBelongsToRecord: function(record, callback, binding) {
    var type = record.constructor;

    this.eachEmbeddedBelongsTo(record.constructor, function(name, relationship, embeddedType) {
      var embeddedRecord = get(record, name);
      if (embeddedRecord) { callback.call(binding, embeddedRecord, embeddedType); }
    });
  },

  eachEmbeddedHasManyRecord: function(record, callback, binding) {
    var type = record.constructor;

    this.eachEmbeddedHasMany(record.constructor, function(name, relationship, embeddedType) {
      var array = get(record, name);
      for (var i=0, l=get(array, 'length'); i<l; i++) {
        callback.call(binding, array.objectAt(i), embeddedType);
      }
    });
  },

  eachEmbeddedHasMany: function(type, callback, binding) {
    this.eachEmbeddedRelationship(type, 'hasMany', callback, binding);
  },

  eachEmbeddedBelongsTo: function(type, callback, binding) {
    this.eachEmbeddedRelationship(type, 'belongsTo', callback, binding);
  },

  eachEmbeddedRelationship: function(type, kind, callback, binding) {
    type.eachRelationship(function(name, relationship) {
      var embeddedType = this.embeddedType(type, name);

      if (embeddedType) {
        if (relationship.kind === kind) {
          callback.call(binding, name, relationship, embeddedType);
        }
      }
    }, this);
  }
});


text:
import * as Globalize from "../globalize";

declare module "../globalize" {
	interface NumberFormatterOptions extends CommonNumberFormatterOptions, NumberParserOptions { }
	interface NumberParserOptions {
		/**
		 * decimal (default), or percent.
		 */
		style?: "decimal" | "percent";
	}
	interface Shared {
		/**
		 * Return a function that formats a number according to the given options or locale's defaults.
		 * @param {NumberFormatterOptions} options A JSON object including none or any of the following options.
		 * style Optional String decimal (default), or percent.
		 * minimumIntegerDigits Optional Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary.
		 * minimumFractionDigits and maximumFractionDigits Optional Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns.
		 * minimumSignificantDigits and maximumSignificantDigits Optional Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits.
		 * round Optional String with rounding method ceil, floor, round (default), or truncate.
		 * useGrouping Optional Boolean (default is true) value indicating whether a grouping separator should be used.
		 * @returns {Function} Return a function that formats a number according to the given options.
		 */
		numberFormatter(options?: NumberFormatterOptions): (value: number) => string;
		/**
		 * Return a function that parses a string representing a number according to the given options or locale's defaults.
		 * @param {NumberParserOptions} options A JSON object including none or any of the following options.
		 * style Optional String decimal (default), or percent.
		 * @returns {Function} Return a function that parses a String representing a number according to the given options. If value is invalid, NaN is returned.
		 */
		numberParser(options?: NumberParserOptions): (value: string) => number
		/**
		 * Return a number formatted according to the given options or locale's defaults.
		 * @param {number} value The number to format
		 * @param {NumberFormatterOptions} options A JSON object including none or any of the following options.
		 * style Optional String decimal (default), or percent.
		 * minimumIntegerDigits Optional Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary.
		 * minimumFractionDigits and maximumFractionDigits Optional Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns.
		 * minimumSignificantDigits and maximumSignificantDigits Optional Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits.
		 * round Optional String with rounding method ceil, floor, round (default), or truncate.
		 * useGrouping Optional Boolean (default is true) value indicating whether a grouping separator should be used.
		 * @returns {string} Return the number formatted
		 */
		formatNumber(value: number, options?: NumberFormatterOptions): string;

		/**
		 * A function that parses a string representing a number according to the given options or locale's defaults.
		 * @param {string} value The number as string to parse
		 * @param {NumberParserOptions} options A JSON object including none or any of the following options.
		 * style Optional String decimal (default), or percent.
		 * @returns {number} Return a number according to the given options. If value is invalid, NaN is returned.
		 */
		parseNumber(value: string, options?: NumberParserOptions): number;
	}
}

export = Globalize;


text:
/// <reference path="fourslash.ts" />

////import j = N./**/ [|q|];
////namespace N { [|export const [|{| "isWriteAccess": true, "isDefinition": true, "contextRangeIndex": 1 |}q|] = 0;|] }

goTo.marker();
verify.referenceGroups("", [{ definition: "const N.q: 0", ranges: test.rangesByText().get("q") }]);


text:
@interface UIColor (Brand)

+ (UIColor *)yahooPurple;

@end