text:
#ifndef _NDNS_TINY_FSM_H
#define _NDNS_TINY_FSM_H

#include "wimax_osal_primitives.h"

#define MAX_STATES_COUNT	20
///////////////////////////////////
// types declarations
#pragma pack( push, 1 )
typedef struct _TinyFSM_t
{
	OSAL_critical_section csLock;
	OSAL_event_t hWaitingStateEvent;

	BOOL isInitialized;
	int state;
	int previousState;
	long waitingStates[MAX_STATES_COUNT];
} TinyFSM_t, *pTinyFSM_t;
#pragma pack( pop )

//////////////////////////////////
// funcations declarations

BOOL FSM_Init(pTinyFSM_t fsm);
void FSM_Finalize(pTinyFSM_t fsm);

// [Oran] This is a patch for fast reconnect.
// It should be removed once the Act no longer restarts the ND&S during device error
BOOL FSM_InitNoReset(pTinyFSM_t fsm);

// get the current state
int FSM_GetState(pTinyFSM_t fsm);
// get the previous state
int FSM_GetPreviousState(pTinyFSM_t fsm);
// move to a new state
void FSM_SetState(pTinyFSM_t fsm, int state);
// move to a new state ONLY if the current state is equal to the source state parameter
BOOL FSM_SetStateIfEqual(pTinyFSM_t fsm, int sourcState, int targetState);
// move to a new state ONLY if the current state is NOT equal to the source state parameter
BOOL FSM_SetStateIfNotEqual(pTinyFSM_t fsm, int sourcState, int targetState);
// wait until a certain state is reached
BOOL FSM_WaitForState(pTinyFSM_t fsm, int state, UINT32 timeout);
// wait until one of the specified states is reached
BOOL FSM_WaitForMultipleStates(pTinyFSM_t fsm, int* states, int statesCount, UINT32 timeout);

#endif // _NDNS_TINY_FSM_H


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#70636363">

    <ListView android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:drawSelectorOnTop="false"/>

    <ImageView
        android:id="@+id/wearpic"
        android:layout_marginTop="0dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:src="@drawable/wearpic" />

    <Button
        android:id="@+id/button_enter"
        android:layout_width="350dp"
        android:layout_height="70dp"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:text="Start"
        android:onClick="button_Enter"
        android:layout_marginTop="420dp"
        android:background="#50ffffff"
        android:textColor="#FFFFFF"/>

    <CheckBox
        android:id="@+id/checkbox1"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_gravity="center_horizontal"
        android:text="show next time"
        android:layout_marginTop="480dp"
        android:onClick="checkbox"
        android:textColor="#FFFFFF"/>

</FrameLayout>

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package kr;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 *
 * @author figgefred
 */
public class Tunnel {

    private BoardState StartingState;
    private LinkedList<BoardPosition> Positions;
    private Set<BoardPosition> LookUpSet;
    private boolean ContainsGoal = false;
    private boolean IsOneWay = true;
    private Direction lastAddedDirection = Direction.NONE;

    private Path Path;
    private Path RevPath;

    public Tunnel(BoardState startingState)
    {
        Positions = new LinkedList<>();
        LookUpSet = new HashSet<>();
        StartingState = startingState;
    }

    public boolean add(BoardPosition p) {

        if(Positions.isEmpty())
        {
            ContainsGoal = StartingState.get(p).isGoalNode();
            LookUpSet.add(p);
            return Positions.add(p);
        }
        else if(!LookUpSet.contains(p))
        {
            BoardPosition neighbour = Positions.peekLast();
            if( StartingState.get(p).isTunnelSpaceNode())
            //if( StartingState.get(p).isSpaceNode())
            {
                boolean up = ((neighbour.Row-p.Row ) == 1 && (neighbour.Column-p.Column ) == 0 );
                boolean down = ((p.Row-neighbour.Row ) == 1 && (neighbour.Column-p.Column ) == 0 );
                boolean left = ((neighbour.Row-p.Row ) == 0 && (neighbour.Column-p.Column ) == 1 );
                boolean right = ((neighbour.Row-p.Row ) == 0 && (p.Column-neighbour.Column ) == 1 );

                if(up || down)
                {
                    BoardPosition leftPos = new BoardPosition(p.Row, p.Column-1);
                    BoardPosition rightPos = new BoardPosition(p.Row, p.Column+1);
                    if(p.equals(leftPos) || p.equals(rightPos))
                    {
                        return false;
                    }
                    if(!StartingState.get(leftPos).isWallNode() || !StartingState.get(rightPos).isWallNode())
                    {
                        return false;
                    }
                }
                else if(left || right)
                {
                    BoardPosition upPos = new BoardPosition(p.Row-1, p.Column);
                    BoardPosition downPos = new BoardPosition(p.Row+1, p.Column);
                    if(p.equals(upPos) || p.equals(downPos))
                    {
                        return false;
                    }
                    if(!StartingState.get(upPos).isWallNode() || !StartingState.get(downPos).isWallNode())
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
                if(!ContainsGoal)
                    ContainsGoal = StartingState.get(p).isGoalNode();

                Direction dir = Positions.peekLast().getDirection(p);
                if(lastAddedDirection == Direction.NONE)
                {
                    lastAddedDirection = dir;
                }
                else if(IsOneWay && dir != lastAddedDirection)
                {
                    IsOneWay = false;
                    lastAddedDirection = dir;
                }
                LookUpSet.add(p);
                return Positions.add(p);
            }
        }
        return false;
    }

    public boolean contains(BoardPosition p)
    {
        return LookUpSet.contains(p);
    }

    public boolean isOneWay()
    {
        return IsOneWay;
    }

    public boolean containsGoal()
    {
        return ContainsGoal;
    }

    public int count()
    {
        return Positions.size();
    }

    public boolean isEmpty()
    {
        return Positions.isEmpty();
    }

    public Path getPath(BoardPosition from)
    {
        return getPath(from, null);
        /*Iterator<BoardPosition> iter;
        boolean reverse = false;
        if(Positions.peekFirst().equals(from))
        {
            if(Path != null && Path.getPath().size() == Positions.size())
                return Path;
            iter = Positions.iterator();
        }
        else if(Positions.peekLast().equals(from))
        {
            if(RevPath != null && RevPath.getPath().size() == Positions.size())
                return RevPath;
            iter = Positions.descendingIterator();
            reverse = true;
        }
        else
            return null;

        Path path = new Path();
        while(iter.hasNext())
        {
            path.append(iter.next());
        }
        if(reverse)
            this.RevPath = path;
        else
            this.Path = path;
        return path;*/
    }

    public Path getPath(BoardPosition from, BoardPosition to)
    {
        Iterator<BoardPosition> iter;
        boolean reverse = false;
        if(Positions.peekFirst().equals(from))
        {
            if(to == null && Path != null && Path.getPath().size() == Positions.size())
                return Path;
            iter = Positions.iterator();
        }
        else if(Positions.peekLast().equals(from))
        {
            if(to == null && RevPath != null && RevPath.getPath().size() == Positions.size())
                return RevPath;
            iter = Positions.descendingIterator();
            reverse = true;
        }
        else
            return null;

        if(to != null && !contains(to))
        {
            return null;
        }

        Path path = new Path();

        boolean stop = false;
        while(!stop && iter.hasNext())
        {
            BoardPosition tmp = iter.next();
            if(to != null && tmp.equals(to))
            {
                stop = true;
            }
            path.append(tmp);
        }
        if(reverse && to == null)
            this.RevPath = path;
        else if(to == null)
            this.Path = path;
        return path;
    }

    public Iterator<BoardPosition> getTunnelPath(BoardPosition from)
    {
        if(Positions.peekFirst().equals(from))
            return Positions.iterator();
        else if(Positions.peekLast().equals(from))
            return Positions.descendingIterator();
        else
            return null;
    }

    public BoardState getStartState()
    {
        return StartingState;
    }

    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        for(int r = 0; r < StartingState.getRowsCount(); r++)
        {
            for(int c = 0; c < StartingState.getColumnsCount();c++)
            {
                BoardPosition p = new BoardPosition(r, c);
                if(LookUpSet.contains(p))// && Board.getNode(p) != NodeType.WALL ) )
                {
                    sb.append("T");
                }
                else
                {
                    sb.append(StartingState.get(p).getChar());
                }
            }
            sb.append("\n");
        }

        return sb.toString();
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="task" name="DC.Type" />
<meta name="DC.Title" content="Using the Derby dblook tool with the Network Server" />
<meta content="dblook, using with Network Server, Network Server, dblook and" name="DC.subject" />
<meta content="dblook, using with Network Server, Network Server, dblook and" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="cadminappsusingthederbytoolswiththene.html" />
<meta scheme="URI" name="DC.Relation" content="tadminapps811302.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="tadminapps811345" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Using the Derby dblook tool with the Network Server</title>

Using the Derby dblook tool with the Network Server

To use the dblook tool with the Network Client driver, make sure
the Network Server is running (see Starting the Network Server),
and then include the necessary Derby and
Network Client driver connection attributes as part of the database URL, as
in the following example:

java org.apache.derby.tools.dblook -d 'jdbc:derby://localhost:1527/sample;
user=user1;password=secret4me;'

For details on using the dblook tool, see the
Derby Tools and Utilities Guide.

Parent topic: Using the Derby tools with the Network Server

Related tasks

Using the Derby ij tool with the Network Server


text:
define(function (require) {
    var registerSuite = require('intern!object');
    var assert = require('intern/chai!assert');

    registerSuite({
        name: 'index',

        'greeting form': function () {
            return this.remote
                .get(require.toUrl('index.html'))
                .setFindTimeout(5000)
                .findByCssSelector('body.loaded')
                .findById('nameField')
                    .click()
                    .type('Elaine')
                    .end()
                .findByCssSelector('#loginForm input[type=submit]')
                    .click()
                    .end()
                .findById('greeting')
                .getVisibleText()
                .then(function (text) {
                    assert.strictEqual(text, 'Hello, Elaine!',
                        'Greeting should be displayed when the form is submitted');
                });
        }
    });
});


text:
[[CRM Systems]]

* [[vTiger installation]]
* [[vTiger translation]]
* [[vTiger processes]]
* [[vTiger development]]
* [[PHP MySQL Performance]]
* [[vTiger Web services]]

== Logging ==

* http://logging.apache.org/log4php/docs/appenders/syslog.html
* http://www.outflux.net/blog/archives/2009/10/24/karmic-and-log-rotation/
* http://wiki.vtiger.com/index.php/Log4php


text:
<!doctype html>

<title>Play Thing</title>

The quick brown fox

jumped over the lazy dog

and headed to Dutch Bros

for some fun.

Contact Book

      Name
      DOB

      Edit

      {{dd}}
      {{name}}
      {{dob}}

      {{edit}}

Contact Book

      Name
      DOB

      Edit

      M
      Tobin
      10/13/69

      ...

Contact Book

      Name
      DOB

      Edit

      M
      Tobin
      10/13/69

      ...

  <template id="edit-menu">

<button data-evt="edit">Edit</button>

<button data-evt="remv">Remove</button>

<button data-evt="cncl">Cancel</button>

  </template>

  <template id="edit-record" data-bind="edit">
    {{data.key}} {{data.val}} {{data.value}}
  </template>


text:
package org.codingmatters.value.objects.values.optional;

import org.codingmatters.value.objects.values.PropertyValue;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class OptionalPropertyValue {

    private final Optional<PropertyValue> value;

    public OptionalPropertyValue(PropertyValue value) {
        this.value = Optional.ofNullable(value);
    }

    public Optional<PropertyValue.Type> type() {
        if(this.value.isEmpty()) return Optional.empty();
        return Optional.ofNullable(this.value.get().type());
    }

    public Optional<PropertyValue.Cardinality> cardinality() {
        if(this.value.isEmpty()) return Optional.empty();
        return Optional.ofNullable(this.value.get().cardinality());

    }

    public OptionalValue single() {
        if(this.value.isEmpty()) return new OptionalValue(null);
        if(! PropertyValue.Cardinality.SINGLE.equals(this.value.get().cardinality())) {
            return new OptionalValue(null);
        } else {
            return new OptionalValue(this.value.get().single());
        }
    }

    public OptionalMultipleValue multiple() {
        if(this.value.isEmpty()) return new OptionalMultipleValue(null);
        if(! PropertyValue.Cardinality.MULTIPLE.equals(this.value.get().cardinality())) {
            return new OptionalMultipleValue(null);
        } else {
            return new OptionalMultipleValue(this.value.get().multiple());
        }
    }

    public PropertyValue get() {
        return value.get();
    }

    public boolean isPresent() {
        return value.isPresent();
    }

    public boolean isEmpty() {
        return value.isEmpty();
    }

    public void ifPresent(Consumer<? super PropertyValue> consumer) {
        value.ifPresent(consumer);
    }

    public Optional<PropertyValue> filter(Predicate<? super PropertyValue> predicate) {
        return value.filter(predicate);
    }

    public <U> Optional<U> map(Function<? super PropertyValue, ? extends U> function) {
        return value.map(function);
    }

    public <U> Optional<U> flatMap(Function<? super PropertyValue, Optional<U>> function) {
        return value.flatMap(function);
    }

    public PropertyValue orElse(PropertyValue objectValue) {
        return value.orElse(objectValue);
    }

    public PropertyValue orElseGet(Supplier<? extends PropertyValue> supplier) {
        return value.orElseGet(supplier);
    }

    public <X extends Throwable> PropertyValue orElseThrow(Supplier<? extends X> supplier) throws X {
        return value.orElseThrow(supplier);
    }
}


text:
package org.asynchttpclient.providers.netty3;

import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.async.RedirectConnectionUsageTest;

public class NettyRedirectConnectionUsageTest extends RedirectConnectionUsageTest {
    @Override
    public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) {
        return NettyProviderUtil.nettyProvider(config);
    }
}


text:
var chai = require("chai");
var Promise = require("bluebird");
require("../lib/logger");

var Resource = require("../lib/resource");

describe("Resource", function() {
    it("should be awesome", function() {
        var contents = JSON.stringify({
            "myvalue": 56
        });

        return Resource.load("json", "myresource.json", contents);
    });
});


text:
APPNAME=${APPNAME:-`grep name manifest.yml | awk '{print $3}'`}
cf set-env $APPNAME AWS_ACCESS_KEY_ID $AWS_ACCESS_KEY_ID
cf set-env $APPNAME AWS_SECRET_ACCESS_KEY $AWS_SECRET_ACCESS_KEY
cf set-env $APPNAME BOOT_CHECK_PORT $BOOT_CHECK_PORT
cf set-env $APPNAME PROD_DB_PASSWORD $PROD_DB_PASSWORD
cf set-env $APPNAME PROD_DB_USER $PROD_DB_USER
cf set-env $APPNAME PROD_DB_URI $PROD_DB_URI
cf set-env $APPNAME SECURITY_USER_NAME $SECURITY_USER_NAME
cf set-env $APPNAME SECURITY_USER_PASSWORD $SECURITY_USER_PASSWORD
cf set-env $APPNAME SOURCE_INSTANCE_ID $SOURCE_INSTANCE_ID
cf set-env $APPNAME SUBNET_ID $SUBNET_ID


text:
<?php

namespace DvsaCommon\Model;

use DvsaCommon\Enum\FuelTypeCode;
use DvsaCommon\Enum\FuelTypeId;

class FuelTypeAndCylinderCapacity
{
    /**
     * Return a list of fuel types which Cylinder Capacity is irrelevant to them
     * @return array
     */
    public static function getAllFuelTypeCodesWithOptionalCylinderCapacity()
    {
        return [
            FuelTypeCode::ELECTRIC,
            FuelTypeCode::FUEL_CELLS,
            FuelTypeCode::STEAM,
        ];
    }

    /**
     * Return array of fuel type ids which Cylinder Capacity is required for them
     *
     * @return array
     */
    public static function getAllFuelTypeCodesWithCompulsoryCylinderCapacity()
    {
        return array_diff(
            FuelTypeCode::getAll(),
            self::getAllFuelTypeCodesWithOptionalCylinderCapacity()
        );
    }

    /**
     * Return the list of fuel type ids which Cylinder Capacity is required for them in a string format
     * (Comma separated by default)
     *
     * @param string $delimiter
     * @return string
     */
    public static function getAllFuelTypeCodesWithCompulsoryCylinderCapacityAsString($delimiter = ',')
    {
        return implode(
            $delimiter,
            self::getAllFuelTypeCodesWithCompulsoryCylinderCapacity()
        );
    }

    /**
     * To check if CC is optional for the given fuel type code.
     *
     * @param FuelTypeCode::getAll() $fuelType
     * @return bool
     */
    public static function isCylinderCapacityOptionalForFuelTypeCode($fuelType)
    {
        return in_array($fuelType, self::getAllFuelTypeCodesWithOptionalCylinderCapacity(), true);
    }

    /**
     * To check if CC is required for the given fuel type code.
     *
     * @param FuelTypeCode::getAll() $fuelType
     * @return bool
     */
    public static function isCylinderCapacityCompulsoryForFuelTypeCode($fuelType)
    {
        return !self::isCylinderCapacityOptionalForFuelTypeCode($fuelType);
    }

}


text:
require 'thor'
require 'ever2boost/evernote_authorizer'
require 'ever2boost/enex_converter'
require 'ever2boost/util'

module Ever2boost
  class CLI < Thor
    DEFAULT_OUTPUT_DIR = "#{ENV['HOME']}/evernote_storage".freeze
    DEFAULT_OUTPUT_DIR_ENEX = "#{ENV['HOME']}/evernote_storage_enex".freeze

    desc 'import', 'import from evernote'
    option :directory, aliases: :d, banner: 'DIRCTORY_PATH', desc: 'make Boostnote storage in the directory default: ~/evernote_storage'
    def import
      output_dir = options[:directory] || DEFAULT_OUTPUT_DIR
      developer_token = ask('DEVELOPER_TOKEN:')
      EvernoteAuthorizer.new(developer_token).import(output_dir)
    end

    desc 'convert', 'convert from .enex'
    option :directory, aliases: :d, banner: 'DIRCTORY_PATH', desc: 'make Boostnote storage in the directory default: ~/evernote_storage'
    def convert(path)
      output_dir = options[:directory] || DEFAULT_OUTPUT_DIR_ENEX
      abort Util.red_output("Error! No such file or directory: #{path}") unless File.exist?(path)
      enex = File.read(path)
      filename = File.basename(path, '.enex')
      EnexConverter.convert(enex, output_dir, filename)
    end

    map %w[--version -v] => :__print_version
    desc "--version, -v", "print the version"
    def __print_version
      puts Ever2boost::VERSION
    end
  end
end


text:
import {expect} from 'chai';

import { DefaultSettings, Kollavarsham } from '../../lib';
import { JulianDate } from '../../lib/dates/julianDate';
import { SakaDate } from '../../lib/dates/sakaDate';
import { KollavarshamDate } from '../../lib/dates/kollavarshamDate';

describe('Kollavarsham', function () {

  let kollavarsham;
  let date;
  let malayalamDate;
  let settings;
  let hinduDate;

  it('should be defined', function () {
    // eslint-disable-next-line no-unused-expressions
    expect(Kollavarsham).to.exist;
  });

  describe('fromGregorianDate 01', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
      date = new Date(1979, 4, 22);
      malayalamDate = kollavarsham.fromGregorianDate(date);
    });

    it('should return a valid malayalam date', function () {
      expect(malayalamDate.year).to.equal(1154);
      expect(malayalamDate.month).to.equal(10);
      expect(malayalamDate.date).to.equal(8);
      expect(malayalamDate.sauraMasaName).to.equal('Vrsa      ');
      expect(malayalamDate.masaName).to.equal('Idavam    ');
      expect(malayalamDate.mlMasaName).to.equal('ഇടവം');
      expect(malayalamDate.naksatraName).to.equal('Uthrattathi');
      expect(malayalamDate.mlNaksatraName).to.equal('ഉത്രട്ടാതി');
      expect(malayalamDate.julianDay).to.equal(2444016);
      expect(malayalamDate.weekdayName).to.equal('Tuesday');
      expect(malayalamDate.mlWeekdayName).to.equal('ചൊവ്വ');
      expect(malayalamDate.ahargana).to.equal(1855550);
    });
  });

  describe('fromGregorianDate 02', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
      date = new Date(1983, 8, 7);
      malayalamDate = kollavarsham.fromGregorianDate(date);
    });

    it('should return a valid malayalam date', function () {
      expect(malayalamDate.year).to.equal(1159);
      expect(malayalamDate.month).to.equal(1);
      expect(malayalamDate.date).to.equal(22);
      expect(malayalamDate.sauraMasaName).to.equal('Simha     ');
      expect(malayalamDate.masaName).to.equal('Chingam   ');
      expect(malayalamDate.mlMasaName).to.equal('ചിങ്ങം');
      expect(malayalamDate.naksatraName).to.equal('Pooram');
      expect(malayalamDate.mlNaksatraName).to.equal('പൂരം');
      expect(malayalamDate.julianDay).to.equal(2445585);
      expect(malayalamDate.weekdayName).to.equal('Wednesday');
      expect(malayalamDate.mlWeekdayName).to.equal('ബുധൻ');
      expect(malayalamDate.ahargana).to.equal(1857119);
    });
  });

  describe('fromGregorianDate 03', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
      date = new Date(1983, 8, 21);
      malayalamDate = kollavarsham.fromGregorianDate(date);
    });

    it('should return a valid malayalam date', function () {
      expect(malayalamDate.year).to.equal(1159);
      expect(malayalamDate.month).to.equal(2);
      expect(malayalamDate.date).to.equal(5);
      expect(malayalamDate.sauraMasaName).to.equal('Kanya     ');
      expect(malayalamDate.masaName).to.equal('Kanni     ');
      expect(malayalamDate.mlMasaName).to.equal('കന്നി');
      expect(malayalamDate.naksatraName).to.equal('Chathayam');
      expect(malayalamDate.mlNaksatraName).to.equal('ചതയം');
      expect(malayalamDate.julianDay).to.equal(2445599);
      expect(malayalamDate.weekdayName).to.equal('Wednesday');
      expect(malayalamDate.mlWeekdayName).to.equal('ബുധൻ');
      expect(malayalamDate.ahargana).to.equal(1857133);
    });
  });

  describe('fromGregorianDate 04', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
      date = new Date(1979, 4, 22, 13, 45, 30);
      malayalamDate = kollavarsham.fromGregorianDate(date);
    });

    it('should return a valid malayalam date', function () {
      expect(malayalamDate.year).to.equal(1154);
      expect(malayalamDate.month).to.equal(10);
      expect(malayalamDate.date).to.equal(8);
      expect(malayalamDate.sauraMasaName).to.equal('Vrsa      ');
      expect(malayalamDate.masaName).to.equal('Idavam    ');
      expect(malayalamDate.mlMasaName).to.equal('ഇടവം');
      expect(malayalamDate.naksatraName).to.equal('Revathi');
      expect(malayalamDate.mlNaksatraName).to.equal('രേവതി');
      expect(malayalamDate.julianDay).to.equal(2444016);
      expect(malayalamDate.weekdayName).to.equal('Tuesday');
      expect(malayalamDate.mlWeekdayName).to.equal('ചൊവ്വ');
      expect(malayalamDate.ahargana).to.equal(1855550);
    });
  });

  describe('default settings', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
      settings = kollavarsham.settings;
    });

    it('should return default settings', function () {
      expect(settings.system).to.equal('SuryaSiddhanta');
      expect(settings.latitude).to.equal(23.2);
      expect(settings.longitude).to.equal(75.8);
    });
  });

  describe('non-default settings', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham({system : 'InPancasiddhantika', latitude : 10.5, longitude : 77.2});
      settings = kollavarsham.settings;
    });

    it('should return default settings', function () {
      expect(settings.system).to.equal('InPancasiddhantika');
      expect(settings.latitude).to.equal(10.5);
      expect(settings.longitude).to.equal(77.2);
    });
  });

  describe('toGregorianDate', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
    });

    it('should throw appropriate exception', function () {
      expect(function () {
        kollavarsham.toGregorianDate(new KollavarshamDate());
      }).to.throw('When the API is implemented, will convert 0001 01 01');
    });
  });

  describe('toGregorianDateFromSaka - with invalid Saka Date', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
      hinduDate = {
        year  : 1937,
        month : 4,
        paksa : 'Krsnapaksa',
        tithi : 12
      };
    });

    it('should throw appropriate exception', function () {
      expect(function () {
        kollavarsham.toGregorianDateFromSaka(hinduDate);
      }).to.throw('Parameter sakaDate should be an instance of the \'SakaDate\' class');
    });
  });

  describe('toGregorianDateFromSaka 01', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
      hinduDate = new SakaDate(1937, 4, 12, 'Krsnapaksa');
      date = kollavarsham.toGregorianDateFromSaka(hinduDate);
    });

    it('should return a valid date', function () {
      expect(date.gregorianDate.getFullYear()).to.equal(2015);
      expect(date.gregorianDate.getMonth()).to.equal(8);
      expect(date.gregorianDate.getDate()).to.equal(10);

      expect(date.julianDay).to.equal(2457276);
      expect(date.weekdayName).to.equal('Thursday');
      expect(date.ahargana).to.equal(1868810);
    });
  });

  describe('toGregorianDateFromSaka 02', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
      hinduDate = new SakaDate(1937, 4, 12, 'Suklapaksa');
      date = kollavarsham.toGregorianDateFromSaka(hinduDate);
    });

    it('should return a valid date', function () {
      expect(date.gregorianDate.getFullYear()).to.equal(2015);
      expect(date.gregorianDate.getMonth()).to.equal(7);
      expect(date.gregorianDate.getDate()).to.equal(26);

      expect(date.julianDay).to.equal(2457261);
      expect(date.weekdayName).to.equal('Wednesday');
      expect(date.ahargana).to.equal(1868795);
    });
  });

  describe('toGregorianDateFromSaka 03', function () {
    beforeEach(function () {
      kollavarsham = new Kollavarsham(DefaultSettings);
      hinduDate = new SakaDate(1437, 4, 12, 'Suklapaksa');
      date = kollavarsham.toGregorianDateFromSaka(hinduDate);
    });

    it('should return a valid Julian Date', function () {
      // eslint-disable-next-line no-unused-expressions
      expect(JulianDate.prototype.isPrototypeOf(date.gregorianDate)).to.be.true; // eslint-disable-line no-prototype-builtins
      expect(date.gregorianDate.year).to.equal(1515);
      expect(date.gregorianDate.month).to.equal(7);
      expect(date.gregorianDate.date).to.equal(23);

      expect(date.julianDay).to.equal(2274615);
      expect(date.weekdayName).to.equal('Monday');
      expect(date.ahargana).to.equal(1686149);
    });
  });

});


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<title>Standard Flavored Markdown</title>
<meta name="description" content=""/>
<meta name="HandheldFriendly" content="True"/>
<meta name="MobileOptimized" content="320"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="shortcut icon" href="/assets/images/favicon.ico?v=8684b6a35e">
<link rel="apple-touch-icon" href="/assets/images/codinghorror-app-icon.png?v=8684b6a35e">
<meta name="google-site-verification" content="sl0m9SU_4V0JcvjWlOX4dUFBR6VS2P4tlxjJMo0gphU"/>
<link rel="stylesheet" type="text/css" href="/assets/css/screen.css?v=8684b6a35e"/>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700"/>
<link rel="alternate" type="application/rss+xml" title="Coding Horror" href="http://feeds.feedburner.com/codinghorror">

Coding Horror

programming and human factors

<gcse:search></gcse:search>

<time datetime="2014-09-03">03 Sep 2014</time>

Standard Flavored Markdown

In 2009 I lamented the state of Markdown:

Right now we have the worst of both worlds. Lack of leadership from the top, and a bunch of fragmented, poorly coordinated community efforts to advance Markdown, none of which are officially canon. This isn't merely incovenient for anyone trying to find accurate information about Markdown; it's actually harming the project's future.

In late 2012, David Greenspan from Meteor approached me and proposed we move forward, and a project crystallized:

I propose that Stack Exchange, GitHub, Meteor, Reddit, and any other company with lots of traffic and a strategic investment in Markdown, all work together to come up with an official Markdown specification, and standard test suites to validate Markdown implementations. We've all been working at cross purposes for too long, accidentally fragmenting Markdown while popularizing it.

We formed a small private working group with key representatives from GitHub, from Reddit, from Stack Exchange, from the open source community. We spent months hashing out the details and agreeing on the necessary changes to turn Markdown into a language you can parse without feeling like you just walked through a sewer – while preserving the simple, clear, ASCII email inspired spirit of Markdown.

We really struggled with this at Discourse, which is also based on Markdown, but an even more complex dialect than the one we built at Stack Overflow. In Discourse, you can mix three forms of markup interchangeably:

Markdown

HTML (safe subset)

BBCode (subset)

Discourse is primarily a JavaScript app, so naturally we needed a nice, compliant implementation of Markdown in JavaScript. Surely such a thing exists, yes? Nope. Even in 2012, we found zero JavaScript implementations of Markdown that could pass the only Markdown test suite I know of, MDTest. It isn't authoritative, it's a community created initiative that embodies its own decisions about rendering ambiguities in Markdown, but it's all we've got. We contributed many upstream fixes to markdown.js to make it pass MDTest – but it still only passes in our locally extended version.

As an open source project ourselves, we're perfectly happy contributing upstream code to improve it for everyone. But it's an indictment of the state of the Markdown ecosystem that any remotely popular implementation wasn't already testing itself against a formal spec and test suite. But who can blame them, because it didn't exist!

Well, now it does.

It took a while, but I'm pleased to announce that Standard Markdown is now finally ready for public review.

standardmarkdown.com

It's a spec, including embedded examples, and implementations in portable C and JavaScript. We strived mightily to stay true to the spirit of Markdown in writing it. The primary author, John MacFarlane, explains in the introduction to the spec:

Because Gruber's syntax description leaves many aspects of the syntax undetermined, writing a precise spec requires making a large number of decisions, many of them somewhat arbitrary. In making them, I have appealed to existing conventions and considerations of simplicity, readability, expressive power, and consistency. I have tried to ensure that "normal" documents in the many incompatible existing implementations of markdown will render, as far as possible, as their authors intended. And I have tried to make the rules for different elements work together harmoniously. In places where different decisions could have been made (for example, the rules governing list indentation), I have explained the rationale for my choices. In a few cases, I have departed slightly from the canonical syntax description, in ways that I think further the goals of markdown as stated in that description.

Part of my contribution to the project is to host the discussion / mailing list for Standard Markdown in a Discourse instance.

talk.standardmarkdown.com

Fortunately, Discourse itself just reached version 1.0. If the only thing Standard Markdown does is help save a few users from the continuing horror that is mailing list web UI, we all win.

What I'm most excited about is that we got a massive contribution from the one person who, in my mind, was the most perfect person in the world to work on this project: John MacFarlane. He took our feedback and wrote the entire Standard Markdown spec and both implementations.

A lot of people know of John through his Pandoc project, which is amazing in its own right, but I found out about him because he built Babelmark. I learned to refer to Babelmark extensively while working on Stack Overflow and MarkdownSharp, a C# implementation of Markdown.

Here's how crazy Markdown is: to decide what the "correct" behavior is, you provide sample Markdown input to 20+ different Markdown parsers … and then pray that some consensus emerges in all their output. That's what Babelmark does.

Consider this simple Markdown example:

# Hello there

This is a paragraph.

- one
- two
- three
- four

1. pirate
2. ninja
3. zombie

Just for that, I count fifteen different rendered outputs from 22 different Markdown parsers.

In Markdown, we literally built a Tower of Babel.

Have I mentioned that it's a good idea for a language to have a formal specification and test suites? Maybe now you can see why that is.

Oh, and in his spare time, John is also the chair of the department of philosophy at the University of California, Berkeley. No big deal. While I don't mean to minimize the contributions of anyone to the Standard Markdown project, we all owe a special thanks to John.

Markdown is indeed everywhere. And that's a good thing. But it needs to be sane, parseable, and standard. That's the goal of Standard Markdown — but we need your help to get there. If you use Markdown on a website, ask what it would take for that site to become compatible with Standard Markdown; when you see the word "Markdown" you have the right to expect consistent rendering across all the websites you visit. If you implement Markdown, take a look at the spec, try to make your parser compatible with Standard Markdown, and discuss improvements or refinements to the spec.

Update: The project was renamed CommonMark. See my subsequent blog post.

[advertisement] How are you showing off your awesome? Create a Stack Overflow Careers profile and show off all of your hard work from Stack Overflow, Github, and virtually every other coding site. Who knows, you might even get recruited for a great new position!

Written by Jeff Atwood

Indoor enthusiast. Co-founder of Stack Exchange and Discourse. Disclaimer: I have no idea what I'm talking about. Find me here: http://twitter.com/codinghorror

[ad] Enjoy the blog? Read Effective Programming: More than Writing Code and How to Stop Sucking and Be Awesome Instead on your Kindle, iPad, Nook, or as a PDF.

Resources

About Me

@codinghorror

discourse.org

stackexchange.com

Recommended Reading

 Subscribe in a reader

 Subscribe via email

Coding Horror has been continuously published since 2004

Traffic Stats

Copyright Jeff Atwood © 2014

Logo image © 1993 Steven C. McConnell

Proudly published with Ghost


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr-osx64-bld/build/xpcom/base/nsIUUIDGenerator.idl
 */

#ifndef __gen_nsIUUIDGenerator_h__
#define __gen_nsIUUIDGenerator_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif

/* starting interface:    nsIUUIDGenerator */
#define NS_IUUIDGENERATOR_IID_STR "138ad1b2-c694-41cc-b201-333ce936d8b8"

#define NS_IUUIDGENERATOR_IID \
  {0x138ad1b2, 0xc694, 0x41cc, \
    { 0xb2, 0x01, 0x33, 0x3c, 0xe9, 0x36, 0xd8, 0xb8 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIUUIDGenerator : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IUUIDGENERATOR_IID)

  /* nsIDPtr generateUUID (); */
  NS_SCRIPTABLE NS_IMETHOD GenerateUUID(nsID **_retval NS_OUTPARAM) = 0;

  /* [noscript] void generateUUIDInPlace (in nsNonConstIDPtr id); */
  NS_IMETHOD GenerateUUIDInPlace(nsID *id) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIUUIDGenerator, NS_IUUIDGENERATOR_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIUUIDGENERATOR \
  NS_SCRIPTABLE NS_IMETHOD GenerateUUID(nsID **_retval NS_OUTPARAM); \
  NS_IMETHOD GenerateUUIDInPlace(nsID *id);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIUUIDGENERATOR(_to) \
  NS_SCRIPTABLE NS_IMETHOD GenerateUUID(nsID **_retval NS_OUTPARAM) { return _to GenerateUUID(_retval); } \
  NS_IMETHOD GenerateUUIDInPlace(nsID *id) { return _to GenerateUUIDInPlace(id); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIUUIDGENERATOR(_to) \
  NS_SCRIPTABLE NS_IMETHOD GenerateUUID(nsID **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GenerateUUID(_retval); } \
  NS_IMETHOD GenerateUUIDInPlace(nsID *id) { return !_to ? NS_ERROR_NULL_POINTER : _to->GenerateUUIDInPlace(id); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsUUIDGenerator : public nsIUUIDGenerator
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIUUIDGENERATOR

  nsUUIDGenerator();

private:
  ~nsUUIDGenerator();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsUUIDGenerator, nsIUUIDGenerator)

nsUUIDGenerator::nsUUIDGenerator()
{
  /* member initializers and constructor code */
}

nsUUIDGenerator::~nsUUIDGenerator()
{
  /* destructor code */
}

/* nsIDPtr generateUUID (); */
NS_IMETHODIMP nsUUIDGenerator::GenerateUUID(nsID **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* [noscript] void generateUUIDInPlace (in nsNonConstIDPtr id); */
NS_IMETHODIMP nsUUIDGenerator::GenerateUUIDInPlace(nsID *id)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIUUIDGenerator_h__ */


text:
package com.amazonaws.services.kafkaconnect.model;

import javax.annotation.Generated;

/**
 * <p>
 * HTTP Status Code 400: Bad request due to incorrect input. Correct your request and then retry it.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BadRequestException extends com.amazonaws.services.kafkaconnect.model.AWSKafkaConnectException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new BadRequestException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public BadRequestException(String message) {
        super(message);
    }

}


text:
module Bosh
  module AzureCloud; end
end

require 'base64'
require 'concurrent'
require 'date'
require 'etc'
require 'fcntl'
require 'fileutils'
require 'logging'
require 'json'
require 'jwt'
require 'open3'
require 'pp'
require 'set'
require 'securerandom'
require 'socket'
require 'tempfile'
require 'time'
require 'tmpdir'
require 'yaml'

# Use resolv-replace.rb to replace the libc resolver
# Reference:
#  https://makandracards.com/ninjaconcept/30815-fixing-socketerror-getaddrinfo-name-or-service-not-known-with-ruby-s-resolv-replace-rb
#  http://www.subelsky.com/2014/05/fixing-socketerror-getaddrinfo-name-or.html
require 'resolv-replace.rb'

require 'digest/md5'
require 'net/http'

# Load Azure Libs before cloud/azure/* in case they are used by the latter
require 'azure/storage'
require 'azure/core/http/debug_filter'

require 'common/exec'
require 'common/thread_pool'
require 'common/thread_formatter'
require 'common/common'

require 'bosh/cpi'
require 'bosh/cpi/registry_client'

require 'cloud'
require 'cloud/azure/utils/helpers'
require 'cloud/azure/utils/bosh_agent_util'
require 'cloud/azure/logging/logger'
require 'cloud/azure/models/bosh_vm_meta'
require 'cloud/azure/utils/command_runner'
require 'cloud/azure/models/error_msg'
require 'cloud/azure/models/config'
require 'cloud/azure/models/config_factory'
require 'cloud/azure/models/object_id'
require 'cloud/azure/models/res_object_id'
require 'cloud/azure/models/disk_id'
require 'cloud/azure/models/ephemeral_disk'
require 'cloud/azure/models/instance_id'
require 'cloud/azure/models/props_factory'
require 'cloud/azure/models/root_disk'
require 'cloud/azure/models/security_group'
require 'cloud/azure/models/vm_cloud_props'
require 'cloud/azure/cloud'
require 'cloud/azure/restapi/azure_client'
require 'cloud/azure/restapi/azure_client_param_builder'

require 'cloud/azure/network/network'
require 'cloud/azure/network/manual_network'
require 'cloud/azure/network/dynamic_network'
require 'cloud/azure/network/vip_network'
require 'cloud/azure/network/network_configurator'
require 'cloud/azure/vms/vm_manager_disk'
require 'cloud/azure/vms/vm_manager_availability_set'
require 'cloud/azure/vms/vm_manager_network'
require 'cloud/azure/vms/vm_manager_storage'
require 'cloud/azure/vms/vm_manager'
require 'cloud/azure/disk/vhd_utils'
require 'cloud/azure/storage/blob_manager'
require 'cloud/azure/disk/disk_manager'
require 'cloud/azure/disk/config_disk_manager'
require 'cloud/azure/stemcell/stemcell_manager'
require 'cloud/azure/meta_store/meta_store'
require 'cloud/azure/meta_store/stemcell_meta'
require 'cloud/azure/meta_store/table_manager'
require 'cloud/azure/stemcell/light_stemcell_manager'

require 'cloud/azure/disk/disk_manager2'
require 'cloud/azure/stemcell/stemcell_manager2'
require 'cloud/azure/storage/storage_account_manager'

require 'cloud/azure/vms/instance_type_mapper'

require 'cloud/azure/version'
require 'cloud/azure/telemetry/telemetry_manager'
require 'cloud/azure/telemetry/telemetry_event'
require 'cloud/azure/telemetry/telemetry_event_handler'
require 'cloud/azure/telemetry/wire_client'

module Bosh
  module Clouds
    Azure = Bosh::AzureCloud::Cloud
  end
end


text:
'use strict';

var gulp = require('gulp');

var ghPages = require('gulp-gh-pages');

var config = require('../config');

module.exports = gulp.task('publish', ['prod'], function () {

	return gulp.src('./build/**/*')
		.pipe(ghPages());
});


text:
namespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas
{
    using namespace ::Microsoft::WRL;
    using namespace WinRTDirectX;
    using namespace Brushes;
    using namespace Text;
    using namespace UI;
    using namespace UI::Xaml;
    using namespace Geometry;

    template<typename TOutput, typename TInput> TOutput ReinterpretAs(TInput value)
    {
        static_assert(std::is_pointer<TInput>::value, "Types must be pointers");
        static_assert(std::is_pointer<TOutput>::value, "Types must be pointers");

        static_assert(sizeof(TInput) == sizeof(TOutput), "Types must be the same size");

        // Replace eg. "Foo const*" with "Foo*".
        typedef std::add_pointer<std::remove_const<std::remove_pointer<TOutput>::type>::type>::type TOutputWithoutConst;
        typedef std::add_pointer<std::remove_const<std::remove_pointer<TInput> ::type>::type>::type TInputWithoutConst;

        static_assert(ValidateReinterpretAs<TOutputWithoutConst, TInputWithoutConst> ::value ||
                      ValidateReinterpretAs<TInputWithoutConst,  TOutputWithoutConst>::value, "Invalid ReinterpretAs type parameters");

        return reinterpret_cast<TOutput>(value);
    }

    template<typename TOutput, typename TInput> TOutput StaticCastAs(TInput value)
    {
        static_assert(ValidateStaticCastAs<TOutput, TInput> ::value ||
                      ValidateStaticCastAs<TInput,  TOutput>::value, "Invalid StaticCastAs type parameters");

        return static_cast<TOutput>(value);
    }

    template<typename TOutput, typename TInput>
    struct ValidateReinterpretAs : std::false_type
    {
    };

    template<typename TOutput, typename TInput>
    struct ValidateStaticCastAs : std::false_type
    {
    };

    template<> struct ValidateReinterpretAs<D2D1_MATRIX_3X2_F*, Numerics::Matrix3x2*> : std::true_type
    {
        static_assert(offsetof(D2D1_MATRIX_3X2_F, _11) == offsetof(Numerics::Matrix3x2, M11), "Matrix3x2 layout must match D2D1_MATRIX_3X2_F");
        static_assert(offsetof(D2D1_MATRIX_3X2_F, _12) == offsetof(Numerics::Matrix3x2, M12), "Matrix3x2 layout must match D2D1_MATRIX_3X2_F");
        static_assert(offsetof(D2D1_MATRIX_3X2_F, _21) == offsetof(Numerics::Matrix3x2, M21), "Matrix3x2 layout must match D2D1_MATRIX_3X2_F");
        static_assert(offsetof(D2D1_MATRIX_3X2_F, _22) == offsetof(Numerics::Matrix3x2, M22), "Matrix3x2 layout must match D2D1_MATRIX_3X2_F");
        static_assert(offsetof(D2D1_MATRIX_3X2_F, _31) == offsetof(Numerics::Matrix3x2, M31), "Matrix3x2 layout must match D2D1_MATRIX_3X2_F");
        static_assert(offsetof(D2D1_MATRIX_3X2_F, _32) == offsetof(Numerics::Matrix3x2, M32), "Matrix3x2 layout must match D2D1_MATRIX_3X2_F");
    };

    template<> struct ValidateReinterpretAs<DXGI_MATRIX_3X2_F*, Numerics::Matrix3x2*> : std::true_type
    {
        static_assert(offsetof(DXGI_MATRIX_3X2_F, _11) == offsetof(Numerics::Matrix3x2, M11), "Matrix3x2 layout must match DXGI_MATRIX_3X2_F");
        static_assert(offsetof(DXGI_MATRIX_3X2_F, _12) == offsetof(Numerics::Matrix3x2, M12), "Matrix3x2 layout must match DXGI_MATRIX_3X2_F");
        static_assert(offsetof(DXGI_MATRIX_3X2_F, _21) == offsetof(Numerics::Matrix3x2, M21), "Matrix3x2 layout must match DXGI_MATRIX_3X2_F");
        static_assert(offsetof(DXGI_MATRIX_3X2_F, _22) == offsetof(Numerics::Matrix3x2, M22), "Matrix3x2 layout must match DXGI_MATRIX_3X2_F");
        static_assert(offsetof(DXGI_MATRIX_3X2_F, _31) == offsetof(Numerics::Matrix3x2, M31), "Matrix3x2 layout must match DXGI_MATRIX_3X2_F");
        static_assert(offsetof(DXGI_MATRIX_3X2_F, _32) == offsetof(Numerics::Matrix3x2, M32), "Matrix3x2 layout must match DXGI_MATRIX_3X2_F");
    };

    template<> struct ValidateReinterpretAs<D2D1_MATRIX_4X4_F*, Numerics::Matrix4x4*> : std::true_type
    {
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _11) == offsetof(Numerics::Matrix4x4, M11), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _12) == offsetof(Numerics::Matrix4x4, M12), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _13) == offsetof(Numerics::Matrix4x4, M13), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _14) == offsetof(Numerics::Matrix4x4, M14), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _21) == offsetof(Numerics::Matrix4x4, M21), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _22) == offsetof(Numerics::Matrix4x4, M22), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _23) == offsetof(Numerics::Matrix4x4, M23), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _24) == offsetof(Numerics::Matrix4x4, M24), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _31) == offsetof(Numerics::Matrix4x4, M31), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _32) == offsetof(Numerics::Matrix4x4, M32), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _33) == offsetof(Numerics::Matrix4x4, M33), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _34) == offsetof(Numerics::Matrix4x4, M34), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _41) == offsetof(Numerics::Matrix4x4, M41), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _42) == offsetof(Numerics::Matrix4x4, M42), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _43) == offsetof(Numerics::Matrix4x4, M43), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
        static_assert(offsetof(D2D1_MATRIX_4X4_F, _44) == offsetof(Numerics::Matrix4x4, M44), "Matrix4x4 layout must match D2D1_MATRIX_4X4_F");
    };

    template<> struct ValidateReinterpretAs<Numerics::Vector4*, D2D1_COLOR_F*> : std::true_type
    {
        static_assert(offsetof(D2D1_COLOR_F, r) == offsetof(Numerics::Vector4, X), "Vector4 layout must match D2D1_COLOR_F");
        static_assert(offsetof(D2D1_COLOR_F, g) == offsetof(Numerics::Vector4, Y), "Vector4 layout must match D2D1_COLOR_F");
        static_assert(offsetof(D2D1_COLOR_F, b) == offsetof(Numerics::Vector4, Z), "Vector4 layout must match D2D1_COLOR_F");
        static_assert(offsetof(D2D1_COLOR_F, a) == offsetof(Numerics::Vector4, W), "Vector4 layout must match D2D1_COLOR_F");
    };

    template<> struct ValidateReinterpretAs<Numerics::Vector4*, D2D1_RECT_F*> : std::true_type
    {
        static_assert(offsetof(D2D1_RECT_F, left)   == offsetof(Numerics::Vector4, X), "Vector4 layout must match D2D1_RECT_F");
        static_assert(offsetof(D2D1_RECT_F, top)    == offsetof(Numerics::Vector4, Y), "Vector4 layout must match D2D1_RECT_F");
        static_assert(offsetof(D2D1_RECT_F, right)  == offsetof(Numerics::Vector4, Z), "Vector4 layout must match D2D1_RECT_F");
        static_assert(offsetof(D2D1_RECT_F, bottom) == offsetof(Numerics::Vector4, W), "Vector4 layout must match D2D1_RECT_F");
    };

    template<> struct ValidateReinterpretAs<DXGI_SURFACE_DESC*, Direct3DSurfaceDescription*> : std::true_type
    {
        static_assert(offsetof(DXGI_SURFACE_DESC, Width)      == offsetof(Direct3DSurfaceDescription,     Width),                  "Direct3DSurfaceDescription layout must match DXGI_SURFACE_DESC layout");
        static_assert(offsetof(DXGI_SURFACE_DESC, Height)     == offsetof(Direct3DSurfaceDescription,     Height),                 "Direct3DSurfaceDescription layout must match DXGI_SURFACE_DESC layout");
        static_assert(offsetof(DXGI_SURFACE_DESC, Format)     == offsetof(Direct3DSurfaceDescription,     Format),                 "Direct3DSurfaceDescription layout must match DXGI_SURFACE_DESC layout");
        static_assert(offsetof(DXGI_SURFACE_DESC, SampleDesc) == offsetof(Direct3DSurfaceDescription,     MultisampleDescription), "Direct3DSurfaceDescription layout must match DXGI_SURFACE_DESC layout");
        static_assert(offsetof(DXGI_SAMPLE_DESC,  Count)      == offsetof(Direct3DMultisampleDescription, Count),                  "GraphicsMultisampleDescription layout must match DXGI_SAMPLE_DESC layout");
        static_assert(offsetof(DXGI_SAMPLE_DESC,  Quality)    == offsetof(Direct3DMultisampleDescription, Quality),                "GraphicsMultisampleDescription layout must match DXGI_SAMPLE_DESC layout");
    };

    template<> struct ValidateReinterpretAs<D2D1_TRIANGLE*, CanvasTriangleVertices*> : std::true_type
    {
        static_assert(offsetof(D2D1_TRIANGLE, point1) == offsetof(CanvasTriangleVertices, Vertex1), "CanvasTriangleVertices layout must match D2D1_TRIANGLE");
        static_assert(offsetof(D2D1_TRIANGLE, point2) == offsetof(CanvasTriangleVertices, Vertex2), "CanvasTriangleVertices layout must match D2D1_TRIANGLE");
        static_assert(offsetof(D2D1_TRIANGLE, point3) == offsetof(CanvasTriangleVertices, Vertex3), "CanvasTriangleVertices layout must match D2D1_TRIANGLE");
    };

    template<> struct ValidateStaticCastAs<CanvasEdgeBehavior, D2D1_EXTEND_MODE> : std::true_type
    {
        static_assert(static_cast<uint32_t>(D2D1_EXTEND_MODE_CLAMP)  == static_cast<uint32_t>(CanvasEdgeBehavior::Clamp),  "CanvasEdgeBehavior must match D2D1_EXTEND_MODE");
        static_assert(static_cast<uint32_t>(D2D1_EXTEND_MODE_WRAP)   == static_cast<uint32_t>(CanvasEdgeBehavior::Wrap),   "CanvasEdgeBehavior must match D2D1_EXTEND_MODE");
        static_assert(static_cast<uint32_t>(D2D1_EXTEND_MODE_MIRROR) == static_cast<uint32_t>(CanvasEdgeBehavior::Mirror), "CanvasEdgeBehavior must match D2D1_EXTEND_MODE");
    };

    template<> struct ValidateStaticCastAs<CanvasColorSpace, D2D1_COLOR_SPACE> : std::true_type
    {
        static_assert(static_cast<uint32_t>(D2D1_COLOR_SPACE_CUSTOM) == static_cast<uint32_t>(CanvasColorSpace::Custom), "CanvasColorSpace must match D2D1_COLOR_SPACE");
        static_assert(static_cast<uint32_t>(D2D1_COLOR_SPACE_SRGB)   == static_cast<uint32_t>(CanvasColorSpace::Srgb),   "CanvasColorSpace must match D2D1_COLOR_SPACE");
        static_assert(static_cast<uint32_t>(D2D1_COLOR_SPACE_SCRGB)  == static_cast<uint32_t>(CanvasColorSpace::ScRgb),  "CanvasColorSpace must match D2D1_COLOR_SPACE");
    };

    template<> struct ValidateStaticCastAs<CanvasDrawTextOptions, D2D1_DRAW_TEXT_OPTIONS> : std::true_type
    {
        static_assert(static_cast<uint32_t>(D2D1_DRAW_TEXT_OPTIONS_NONE) == static_cast<uint32_t>(CanvasDrawTextOptions::Default), "CanvasDrawTextOptions must match D2D1_DRAW_TEXT_OPTIONS");
        static_assert(static_cast<uint32_t>(D2D1_DRAW_TEXT_OPTIONS_NO_SNAP) == static_cast<uint32_t>(CanvasDrawTextOptions::NoPixelSnap), "CanvasDrawTextOptions must match D2D1_DRAW_TEXT_OPTIONS");
        static_assert(static_cast<uint32_t>(D2D1_DRAW_TEXT_OPTIONS_CLIP) == static_cast<uint32_t>(CanvasDrawTextOptions::Clip), "CanvasDrawTextOptions must match D2D1_DRAW_TEXT_OPTIONS");

        // Using hardcoded constant instead of D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT, because that enum entry is missing from the VS2013 Windows Phone version of d2d1.h
        static_assert(static_cast<uint32_t>(4U) == static_cast<uint32_t>(CanvasDrawTextOptions::EnableColorFont), "CanvasDrawTextOptions must match D2D1_DRAW_TEXT_OPTIONS");
    };

    inline float ToNormalizedFloat(uint8_t v)
    {
        return static_cast<float>(v) / 255.0f;
    }

    inline uint8_t NormalizedToUint8(float f)
    {
        return static_cast<uint8_t>(f * 255.0f);
    }

    inline float Saturate(float f) // Named after the clamping behavior of HLSL saturate().
    {
        f = std::min<float>(1, f);
        f = std::max<float>(0, f);
        return f;
    }

    inline uint8_t SaturateAndNormalizeToUint8(float f)
    {
        return NormalizedToUint8(Saturate(f));
    }

    inline D2D1_COLOR_F ToD2DColor(ABI::Windows::UI::Color const& color)
    {
        return D2D1::ColorF(
            ToNormalizedFloat(color.R),
            ToNormalizedFloat(color.G),
            ToNormalizedFloat(color.B),
            ToNormalizedFloat(color.A));
    }

    inline Numerics::Vector4 ToVector4(ABI::Windows::UI::Color const& color)
    {
        auto d2dColor = ToD2DColor(color);
        return *ReinterpretAs<Numerics::Vector4 const*>(&d2dColor);
    }

    inline Numerics::Vector3 ToVector3(ABI::Windows::UI::Color const& color)
    {
        auto d2dColor = ToD2DColor(color);
        return Numerics::Vector3{ d2dColor.r, d2dColor.g, d2dColor.b };
    }

    inline ABI::Windows::UI::Color ToWindowsColor(D2D1_COLOR_F const& color)
    {
        ABI::Windows::UI::Color windowsColor;
        windowsColor.A = SaturateAndNormalizeToUint8(color.a);
        windowsColor.R = SaturateAndNormalizeToUint8(color.r);
        windowsColor.G = SaturateAndNormalizeToUint8(color.g);
        windowsColor.B = SaturateAndNormalizeToUint8(color.b);
        return windowsColor;
    }

    inline ABI::Windows::UI::Color ToWindowsColor(Numerics::Vector4 const& vector)
    {
        return ToWindowsColor(*ReinterpretAs<D2D1_COLOR_F const*>(&vector));
    }

    inline ABI::Windows::UI::Color ToWindowsColor(Numerics::Vector3 const& vector)
    {
        return ToWindowsColor(D2D1_COLOR_F{ vector.X, vector.Y, vector.Z, 1 });
    }

    inline D2D1_POINT_2F ToD2DPoint(Numerics::Vector2 const& point)
    {
        return D2D1_POINT_2F{ point.X, point.Y };
    }

    inline Numerics::Vector2 FromD2DPoint(D2D1_POINT_2F const& point)
    {
        return Numerics::Vector2{ point.x, point.y };
    }

    inline D2D1_RECT_F ToD2DRect(ABI::Windows::Foundation::Rect const& rect)
    {
        auto left = rect.X;
        auto right = isinf(rect.Width) ? rect.Width : rect.X + rect.Width;
        auto top = rect.Y;
        auto bottom = isinf(rect.Height) ? rect.Height : rect.Y + rect.Height;

        return D2D1_RECT_F{ left, top, right, bottom };
    }

    inline ABI::Windows::Foundation::Rect FromD2DRect(D2D1_RECT_F const& d2dRect)
    {
        auto x = d2dRect.left;
        auto width = d2dRect.right - x;
        auto y = d2dRect.top;
        auto height = d2dRect.bottom - y;

        ABI::Windows::Foundation::Rect rect{ x, y, width, height };
        return rect;
    }

    inline D2D1_RECT_U ToD2DRectU(int32_t left, int32_t top, int32_t width, int32_t height)
    {
        if (left < 0) ThrowHR(E_INVALIDARG);
        if (top < 0) ThrowHR(E_INVALIDARG);
        if (width < 0) ThrowHR(E_INVALIDARG);
        if (height < 0) ThrowHR(E_INVALIDARG);

        D2D1_RECT_U d2dRect;
        d2dRect.left = static_cast<UINT32>(left);
        d2dRect.top = static_cast<UINT32>(top);
        d2dRect.right = d2dRect.left + static_cast<UINT32>(width);
        d2dRect.bottom = d2dRect.top + static_cast<UINT32>(height);

        return d2dRect;
    }

    inline D2D1_POINT_2U ToD2DPointU(int32_t x, int32_t y)
    {
        if (x < 0) ThrowHR(E_INVALIDARG);
        if (y < 0) ThrowHR(E_INVALIDARG);

        return D2D1::Point2U(x, y);
    }

    inline D2D1_ROUNDED_RECT ToD2DRoundedRect(ABI::Windows::Foundation::Rect const& rect, float rx, float ry)
    {
        return D2D1_ROUNDED_RECT{ ToD2DRect(rect), rx, ry };
    }

    inline D2D1_ELLIPSE ToD2DEllipse(Numerics::Vector2 const& point, float rx, float ry)
    {
        return D2D1::Ellipse(ToD2DPoint(point), rx, ry);
    }

    inline D2D1_COLOR_INTERPOLATION_MODE ToD2DColorInterpolation(CanvasAlphaMode alphaMode)
    {
        switch (alphaMode)
        {
            case CanvasAlphaMode::Premultiplied: return D2D1_COLOR_INTERPOLATION_MODE_PREMULTIPLIED;
            case CanvasAlphaMode::Straight: return D2D1_COLOR_INTERPOLATION_MODE_STRAIGHT;
            case CanvasAlphaMode::Ignore:
            default: return D2D1_COLOR_INTERPOLATION_MODE_FORCE_DWORD;
        }
    }

    inline D2D1_ALPHA_MODE ConvertDxgiAlphaModeToD2DAlphaMode(DXGI_ALPHA_MODE alphaMode)
    {
        switch (alphaMode)
        {
            case DXGI_ALPHA_MODE_PREMULTIPLIED: return D2D1_ALPHA_MODE_PREMULTIPLIED;
            case DXGI_ALPHA_MODE_STRAIGHT: return D2D1_ALPHA_MODE_STRAIGHT;
            case DXGI_ALPHA_MODE_IGNORE: return D2D1_ALPHA_MODE_IGNORE;
            default:
                assert(false); // Unexpected
                ThrowHR(E_UNEXPECTED);
        }
    }

    inline CanvasAlphaMode FromD2DAlphaMode(D2D1_ALPHA_MODE alphaMode)
    {
        switch (alphaMode)
        {
            case D2D1_ALPHA_MODE_PREMULTIPLIED: return CanvasAlphaMode::Premultiplied;
            case D2D1_ALPHA_MODE_STRAIGHT: return CanvasAlphaMode::Straight;
            case D2D1_ALPHA_MODE_IGNORE: return CanvasAlphaMode::Ignore;
            default: assert(false); return CanvasAlphaMode::Premultiplied;
        }
    }

    inline D2D1_ALPHA_MODE ToD2DAlphaMode(CanvasAlphaMode alphaMode)
    {
        switch (alphaMode)
        {
            case CanvasAlphaMode::Premultiplied: return D2D1_ALPHA_MODE_PREMULTIPLIED;
            case CanvasAlphaMode::Straight: return D2D1_ALPHA_MODE_STRAIGHT;
            case CanvasAlphaMode::Ignore: return D2D1_ALPHA_MODE_IGNORE;
            default: return D2D1_ALPHA_MODE_FORCE_DWORD;
        }
    }

#if WINVER > _WIN32_WINNT_WINBLUE

    inline D2D1_ALPHA_MODE ToD2DAlphaMode(ABI::Windows::Graphics::Imaging::BitmapAlphaMode alphaMode)
    {
        using namespace ABI::Windows::Graphics::Imaging;

        switch (alphaMode)
        {
            case BitmapAlphaMode_Premultiplied: return D2D1_ALPHA_MODE_PREMULTIPLIED;
            case BitmapAlphaMode_Straight: return D2D1_ALPHA_MODE_STRAIGHT;
            case BitmapAlphaMode_Ignore: return D2D1_ALPHA_MODE_IGNORE;
            default: return D2D1_ALPHA_MODE_FORCE_DWORD;
        }
    }

#endif

    inline CanvasAlphaMode FromD2DColorInterpolation(D2D1_COLOR_INTERPOLATION_MODE colorInterpolation)
    {
        switch (colorInterpolation)
        {
            case D2D1_COLOR_INTERPOLATION_MODE_PREMULTIPLIED: return CanvasAlphaMode::Premultiplied;
            case D2D1_COLOR_INTERPOLATION_MODE_STRAIGHT: return CanvasAlphaMode::Straight;
            default: assert(false); break;
        }
        return CanvasAlphaMode::Premultiplied;
    }

    inline CanvasAlphaMode FromDxgiAlphaMode(DXGI_ALPHA_MODE alphaMode)
    {
        switch (alphaMode)
        {
            case DXGI_ALPHA_MODE_PREMULTIPLIED: return CanvasAlphaMode::Premultiplied;
            case DXGI_ALPHA_MODE_STRAIGHT: return CanvasAlphaMode::Straight;
            case DXGI_ALPHA_MODE_IGNORE: return CanvasAlphaMode::Ignore;
            default: assert(false); return CanvasAlphaMode::Premultiplied;
        }
    }

    inline DXGI_ALPHA_MODE ToDxgiAlphaMode(CanvasAlphaMode alphaMode)
    {
        switch (alphaMode)
        {
            case CanvasAlphaMode::Premultiplied: return DXGI_ALPHA_MODE_PREMULTIPLIED;
            case CanvasAlphaMode::Straight: return DXGI_ALPHA_MODE_STRAIGHT;
            case CanvasAlphaMode::Ignore: return DXGI_ALPHA_MODE_IGNORE;
            default: assert(false); return DXGI_ALPHA_MODE_PREMULTIPLIED;
        }
    }

    inline D2D1_BUFFER_PRECISION ToD2DBufferPrecision(CanvasBufferPrecision bufferPrecision)
    {
        switch (bufferPrecision)
        {
            case CanvasBufferPrecision::Precision8UIntNormalized: return D2D1_BUFFER_PRECISION_8BPC_UNORM;
            case CanvasBufferPrecision::Precision8UIntNormalizedSrgb: return D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB;
            case CanvasBufferPrecision::Precision16UIntNormalized: return D2D1_BUFFER_PRECISION_16BPC_UNORM;
            case CanvasBufferPrecision::Precision16Float: return D2D1_BUFFER_PRECISION_16BPC_FLOAT;
            case CanvasBufferPrecision::Precision32Float: return D2D1_BUFFER_PRECISION_32BPC_FLOAT;
            default: return D2D1_BUFFER_PRECISION_FORCE_DWORD;
        }
    }

    inline CanvasBufferPrecision FromD2DBufferPrecision(D2D1_BUFFER_PRECISION bufferPrecision)
    {
        switch (bufferPrecision)
        {
            case D2D1_BUFFER_PRECISION_8BPC_UNORM: return CanvasBufferPrecision::Precision8UIntNormalized;
            case D2D1_BUFFER_PRECISION_8BPC_UNORM_SRGB: return CanvasBufferPrecision::Precision8UIntNormalizedSrgb;
            case D2D1_BUFFER_PRECISION_16BPC_UNORM: return CanvasBufferPrecision::Precision16UIntNormalized;
            case D2D1_BUFFER_PRECISION_16BPC_FLOAT: return CanvasBufferPrecision::Precision16Float;
            case D2D1_BUFFER_PRECISION_32BPC_FLOAT: return CanvasBufferPrecision::Precision32Float;
            default: assert(false); return CanvasBufferPrecision::Precision8UIntNormalized;
        }
    }

    inline CanvasSwapChainRotation FromDxgiRotation(DXGI_MODE_ROTATION rotation)
    {
        switch (rotation)
        {
            case DXGI_MODE_ROTATION_UNSPECIFIED:
            case DXGI_MODE_ROTATION_IDENTITY: return CanvasSwapChainRotation::None;
            case DXGI_MODE_ROTATION_ROTATE90: return CanvasSwapChainRotation::Rotate90;
            case DXGI_MODE_ROTATION_ROTATE180: return CanvasSwapChainRotation::Rotate180;
            case DXGI_MODE_ROTATION_ROTATE270: return CanvasSwapChainRotation::Rotate270;
            default: assert(false); return CanvasSwapChainRotation::None;
        }
    }

    inline DXGI_MODE_ROTATION ToDxgiRotation(CanvasSwapChainRotation rotation)
    {
        switch (rotation)
        {
            case CanvasSwapChainRotation::None: return DXGI_MODE_ROTATION_IDENTITY;
            case CanvasSwapChainRotation::Rotate90: return DXGI_MODE_ROTATION_ROTATE90;
            case CanvasSwapChainRotation::Rotate180: return DXGI_MODE_ROTATION_ROTATE180;
            case CanvasSwapChainRotation::Rotate270: return DXGI_MODE_ROTATION_ROTATE270;
            default: assert(false); return DXGI_MODE_ROTATION_IDENTITY;
        }
    }

    inline DWRITE_TEXT_RANGE ToDWriteTextRange(int32_t position, int32_t characterCount)
    {
        ThrowIfNegative(position);
        ThrowIfNegative(characterCount);

        return DWRITE_TEXT_RANGE{ static_cast<uint32_t>(position), static_cast<uint32_t>(characterCount) };
    }

    inline float PixelsToDips(int pixels, float dpi)
    {
        return pixels * DEFAULT_DPI / dpi;
    }

    inline int DipsToPixels(
        float dips,
        float dpi,
        CanvasDpiRounding dpiRounding)
    {
        float scaled = dips * dpi / DEFAULT_DPI;
        switch (dpiRounding)
        {
            case CanvasDpiRounding::Floor: scaled = floorf(scaled); break;
            case CanvasDpiRounding::Round: scaled = roundf(scaled); break;
            case CanvasDpiRounding::Ceiling: scaled = ceilf(scaled); break;
            default: ThrowHR(E_INVALIDARG);
        }

        return (int)(scaled);
    }

    inline int SizeDipsToPixels(
        float dips,
        float dpi)
    {
        int result = DipsToPixels(dips, dpi, CanvasDpiRounding::Round);

        // Zero versus non-zero is pretty important for things like control sizes, so we want
        // to avoid ever rounding non-zero input sizes down to zero during conversion to pixels.
        // If the input value was small but positive, it's safer to round up to one instead.
        if (result == 0 && dips > 0)
        {
            return 1;
        }

        return result;
    }

    inline RECT ToRECT(ABI::Windows::Foundation::Rect const& rect, float dpi)
    {
        auto left = SizeDipsToPixels(rect.X, dpi);
        auto top = SizeDipsToPixels(rect.Y, dpi);
        auto right = SizeDipsToPixels(rect.X + rect.Width, dpi);
        auto bottom = SizeDipsToPixels(rect.Y + rect.Height, dpi);

        return RECT{ left, top, right, bottom };
    }

    inline ABI::Windows::Foundation::Rect ToRect(RECT const& rect, float dpi)
    {
        auto x = PixelsToDips(rect.left, dpi);
        auto y = PixelsToDips(rect.top, dpi);
        auto width = PixelsToDips(rect.right - rect.left, dpi);
        auto height = PixelsToDips(rect.bottom - rect.top, dpi);

        return ABI::Windows::Foundation::Rect{ x, y, width, height };
    }

#if WINVER > _WIN32_WINNT_WINBLUE
    inline D2D1_PATCH_EDGE_MODE ToD2DPatchEdgeMode(CanvasGradientMeshPatchEdge edge)
    {
        switch (edge)
        {
            case CanvasGradientMeshPatchEdge::Aliased: return D2D1_PATCH_EDGE_MODE_ALIASED;
            case CanvasGradientMeshPatchEdge::Antialiased: return D2D1_PATCH_EDGE_MODE_ANTIALIASED;
            case CanvasGradientMeshPatchEdge::AliasedAndInflated: return D2D1_PATCH_EDGE_MODE_ALIASED_INFLATED;
            default: assert(false); return D2D1_PATCH_EDGE_MODE_ALIASED;
        }
    }

    inline CanvasGradientMeshPatchEdge FromD2DPatchEdgeMode(D2D1_PATCH_EDGE_MODE edge)
    {
        switch (edge)
        {
            case D2D1_PATCH_EDGE_MODE_ALIASED: return CanvasGradientMeshPatchEdge::Aliased;
            case D2D1_PATCH_EDGE_MODE_ANTIALIASED: return CanvasGradientMeshPatchEdge::Antialiased;
            case D2D1_PATCH_EDGE_MODE_ALIASED_INFLATED: return CanvasGradientMeshPatchEdge::AliasedAndInflated;
            default: assert(false); return CanvasGradientMeshPatchEdge::Aliased;
        }
    }

#endif
}}}}


text:
'use strict';

notesApp.controller('notesController', function notesController($scope, $timeout, NotesData) {

    $scope.notes = NotesData.getNotes();

    $scope.note = NotesData.getLastNote();
    $scope.saved = false;
    $scope.searchFor = '';

    $scope.$watch('[searchFor]', function () {
        if ($scope.searchFor.trim() === '') {
            $scope.notes = NotesData.getNotes();
        } else {
            $scope.notes = NotesData.search($scope.searchFor);
            $scope.note = $scope.notes[0];
        }
    }, true);

    $scope.edit2 = function (note) {
        $scope.note = note;
    };

    $scope.edit = function (id) {
        if (id === undefined) {
            $scope.note = {'id': -1, 'title': '', 'text': ''};
        } else {
            $scope.note = NotesData.getNoteById(id);
        }

        $scope.saved = false;

        var timeout = null;

        $scope.$watch('[note.title, note.text]', function () {
            $scope.saved = false;

            if (timeout !== null) {
                $timeout.cancel(timeout);
            }

            timeout = $timeout($scope.save, 1000);
        }, true);

    };

    $scope.save = function () {
        if ($scope.note.id === -1) {
            $scope.note.id = NotesData.getLastId() + 1;
        }
        if ($scope.note.title.trim() === '') {
            return;
        }

        NotesData.addNote($scope.note);
        $scope.saved = true;
    };

});


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.log;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;

/**
 * Note that the log levels defined in VESPA applications are the
 * following.
 *
 *

 *
 LogLevel.EVENT   (1201)
 *
 LogLevel.FATAL   (1151)
 *
 LogLevel.ERROR   (1101)
 *
 LogLevel.SEVERE  (1000)
 *
 LogLevel.WARNING  (900)
 *
 LogLevel.INFO     (800)
 *
 LogLevel.CONFIG   (700)
 *
 LogLevel.DEBUG    (501)
 *
 LogLevel.SPAM     (299)
 *

 *
 *

 * Note that the EVENT level is somewhat special and you must
 * never log one of these messages manually, but use
 * the {@link com.yahoo.log.event.Event} class for this.
 *
 * @author  Bjorn Borud
 * @author arnej27959
 *
 * @deprecated  Use {@link java.util.logging.Level} instead.
 */
// TODO Vespa 9: move to non-PublicApi package
@Deprecated(since = "7")
public class LogLevel extends Level {
    /** A map from the name of the log level to the instance */
    private static final Map<String, Level> nameToLevel;
    private static final Map<String, Level> uppercasedNameToLevel;

    /** A map from the java.util.logging loglevel to VESPA's loglevel */
    private static final Map<Level, Level> javaToVespa;

    public static final int IntValEVENT   = 1201;
    public static final int IntValFATAL   = 1161;
    public static final int IntValERROR   = 1101;
    public static final int IntValUNKNOWN = 1001;
    public static final int IntValSEVERE  = 1000;
    public static final int IntValWARNING = 900;
    public static final int IntValINFO    = 800;
    public static final int IntValCONFIG  = 700;
    public static final int IntValDEBUG   = 501;
    public static final int IntValFINE    = 500;
    public static final int IntValFINER   = 400;
    public static final int IntValFINEST  = 300;
    public static final int IntValSPAM    = 299;

    // these define the ordering of the Vespa levels logcontrol files.
    // it must match the values of the LogLevel enum in <log/log.h>
    // for the C++ framework:
    // fatal, error, warning, config, info, event, debug, spam, NUM_LOGLEVELS

    public static final int LogCtlFATAL   = 0;
    public static final int LogCtlERROR   = 1;
    public static final int LogCtlWARNING = 2;
    public static final int LogCtlCONFIG  = 3;
    public static final int LogCtlINFO    = 4;
    public static final int LogCtlEVENT   = 5;
    public static final int LogCtlDEBUG   = 6;
    public static final int LogCtlSPAM    = 7;
    public static final int LogCtlNumLevels = 8;

    // ordinary log levels
    public static LogLevel UNKNOWN = new LogLevel("UNKNOWN", IntValUNKNOWN);
    public static LogLevel EVENT   = new LogLevel("EVENT",   IntValEVENT);
    public static LogLevel FATAL   = new LogLevel("FATAL",   IntValFATAL);
    public static LogLevel ERROR   = new LogLevel("ERROR",   IntValERROR);
    public static LogLevel DEBUG   = new LogLevel("DEBUG",   IntValDEBUG);
    public static LogLevel SPAM    = new LogLevel("SPAM",    IntValSPAM);

    // overlapping ones, only mentioned for illustration
    //
    // public static LogLevel WARNING = new LogLevel("WARNING",900);
    // public static LogLevel INFO    = new LogLevel("INFO",800);
    // public static LogLevel CONFIG  = new LogLevel("CONFIG",700);

    static {
        // define mapping from Java log levels to VESPA log
        // levels.
        javaToVespa = new HashMap<>();
        javaToVespa.put(Level.SEVERE, ERROR);
        javaToVespa.put(Level.WARNING, WARNING);
        javaToVespa.put(Level.INFO, INFO);
        javaToVespa.put(Level.CONFIG, CONFIG);
        javaToVespa.put(Level.FINE, DEBUG);
        javaToVespa.put(Level.FINER, DEBUG);
        javaToVespa.put(Level.FINEST, SPAM);

        // need the VESPA ones too
        javaToVespa.put(FATAL, FATAL);
        javaToVespa.put(ERROR, ERROR);
        javaToVespa.put(EVENT, EVENT);
        javaToVespa.put(DEBUG, DEBUG);
        javaToVespa.put(SPAM, SPAM);

        // manually enter the valid log levels we shall recognize in VESPA
        nameToLevel = new LinkedHashMap<>(16);

        nameToLevel.put("fatal", FATAL);
        nameToLevel.put("error", ERROR);
        nameToLevel.put("warning", WARNING);
        nameToLevel.put("config", CONFIG);
        nameToLevel.put("info", INFO);
        nameToLevel.put("event", EVENT);
        nameToLevel.put("debug", DEBUG);
        nameToLevel.put("spam", SPAM);

        uppercasedNameToLevel = new LinkedHashMap<>(16);
        nameToLevel.forEach((name, level) -> uppercasedNameToLevel.put(name.toUpperCase(), level));
    }

    private LogLevel(String name, int value) {
        super(name, value);
    }

    /**
     * Semi-Case sensitive parsing of log levels.  Log levels are
     * in either all upper case or all lower case.  Not mixed
     * case. . Returns static instance representing log level or
     * the UNKNOWN LogLevel instance.
     *
     * @param name Name of loglevel in uppercase or lowercase.
     * @return Returns the static (immutable) LogLevel instance
     *         equivalent to the name given.
     *
     */
    public static Level parse(String name) {
        Level l = nameToLevel.get(name);
        if (l != null)
            return l;

        l = uppercasedNameToLevel.get(name);
        if (l != null)
            return l;

        return UNKNOWN;
    }

    /**
     * Static method for mapping Java log level to VESPA log level.
     *
     * @param level The Java loglevel we want mapped to its VESPA
     *              counterpart
     * @return The VESPA LogLevel instance representing the corresponding
     *         log level (or nearest normal level numerically if not in map)
     */
    public static Level getVespaLogLevel(Level level) {
        Level ll = javaToVespa.get(level);
        if (ll != null) {
            return ll;
        }
        int lv = level.intValue();
        if (lv > WARNING.intValue()) {
            return ERROR;
        }
        if (lv > INFO.intValue()) {
            return WARNING;
        }
        if (lv > DEBUG.intValue()) {
            return INFO;
        }
        if (lv > FINEST.intValue()) {
            return DEBUG;
        }
        return SPAM;
    }

    /**
     * Static method returning a map from Vespa level name to Level
     *
     * @return a map from Vespa level name to Level
     */
    public static Map<String, Level> getLevels() {
        return nameToLevel;
    }
}


text:
import numpy as np
import dlib
import face_recognition_models

predictor_model = face_recognition_models.pose_predictor_model_location()
pose_predictor = dlib.shape_predictor(predictor_model)

face_recognition_model = face_recognition_models.face_recognition_model_location()
face_encoder = dlib.face_recognition_model_v1(face_recognition_model)
face_detector = dlib.get_frontal_face_detector()

def _rect_to_css(rect):
    """
    Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order
    :param rect: a dlib 'rect' object
    :return: a plain tuple representation of the rect in (top, right, bottom, left) order
    """
    return rect.top(), rect.right(), rect.bottom(), rect.left()

def _css_to_rect(css):
    """
    Convert a tuple in (top, right, bottom, left) order to a dlib `rect` object
    :param css:  plain tuple representation of the rect in (top, right, bottom, left) order
    :return: a dlib `rect` object
    """
    return dlib.rectangle(css[3], css[0], css[1], css[2])

def _trim_css_to_bounds(css, image_shape):
    """
    Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image.
    :param css:  plain tuple representation of the rect in (top, right, bottom, left) order
    :param image_shape: numpy shape of the image array
    :return: a trimmed plain tuple representation of the rect in (top, right, bottom, left) order
    """
    return max(
        css[0], 0), min(
        css[1], image_shape[1]), min(
            css[2], image_shape[0]), max(
                css[3], 0)

def face_distance(face_encodings, face_to_compare):
    """
    Given a list of face encodings, compare them to a known face encoding and get a euclidean distance
    for each comparison face. The distance tells you how similar the faces are.
    :param faces: List of face encodings to compare
    :param face_to_compare: A face encoding to compare against
    :return: A numpy ndarray with the distance for each face in the same order as the 'faces' array
    """
    if len(face_encodings) == 0:
        return np.empty((0))

    return np.linalg.norm(face_encodings - face_to_compare, axis=1)

def load_image_file(filename, mode='RGB'):
    """
    Loads an image file (.jpg, .png, etc) into a numpy array
    :param filename: image file to load
    :param mode: format to convert the image to. Only 'RGB' (8-bit RGB, 3 channels) and 'L' (black and white) are supported.
    :return: image contents as numpy array
    """
    return scipy.misc.imread(filename, mode=mode)

def _raw_face_locations(img, number_of_times_to_upsample=1):
    """
    Returns an array of bounding boxes of human faces in a image
    :param img: An image (as a numpy array)
    :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.
    :return: A list of dlib 'rect' objects of found face locations
    """
    return face_detector(img, number_of_times_to_upsample)

def face_locations(img, number_of_times_to_upsample=1):
    """
    Returns an array of bounding boxes of human faces in a image
    :param img: An image (as a numpy array)
    :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.
    :return: A list of tuples of found face locations in css (top, right, bottom, left) order
    """
    return [
        _trim_css_to_bounds(
            _rect_to_css(face),
            img.shape) for face in _raw_face_locations(
            img,
            number_of_times_to_upsample)]

def _raw_face_landmarks(face_image, face_locations=None):
    if face_locations is None:
        face_locations = _raw_face_locations(face_image)
    else:
        face_locations = [_css_to_rect(face_location)
                          for face_location in face_locations]

    return [pose_predictor(face_image, face_location)
            for face_location in face_locations]

def face_landmarks(face_image, face_locations=None):
    """
    Given an image, returns a dict of face feature locations (eyes, nose, etc) for each face in the image
    :param face_image: image to search
    :param face_locations: Optionally provide a list of face locations to check.
    :return: A list of dicts of face feature locations (eyes, nose, etc)
    """
    landmarks = _raw_face_landmarks(face_image, face_locations)
    landmarks_as_tuples = [[(p.x, p.y) for p in landmark.parts()]
                           for landmark in landmarks]

    # For a definition of each point index, see
    # https://cdn-images-1.medium.com/max/1600/1*AbEg31EgkbXSQehuNJBlWg.png
    return [{
        "chin": points[0:17],
        "left_eyebrow": points[17:22],
        "right_eyebrow": points[22:27],
        "nose_bridge": points[27:31],
        "nose_tip": points[31:36],
        "left_eye": points[36:42],
        "right_eye": points[42:48],
        "top_lip": points[48:55] + [points[64]] + [points[63]] + [points[62]] + [points[61]] + [points[60]],
        "bottom_lip": points[54:60] + [points[48]] + [points[60]] + [points[67]] + [points[66]] + [points[65]] + [points[64]]
    } for points in landmarks_as_tuples]

def face_encodings(face_image, known_face_locations=None, num_jitters=1):
    """
    Given an image, return the 128-dimension face encoding for each face in the image.
    :param face_image: The image that contains one or more faces
    :param known_face_locations: Optional - the bounding boxes of each face if you already know them.
    :param num_jitters: How many times to re-sample the face when calculating encoding. Higher is more accurate, but slower (i.e. 100 is 100x slower)
    :return: A list of 128-dimentional face encodings (one for each face in the image)
    """
    raw_landmarks = _raw_face_landmarks(face_image, known_face_locations)

    return [
        np.array(
            face_encoder.compute_face_descriptor(
                face_image,
                raw_landmark_set,
                num_jitters)) for raw_landmark_set in raw_landmarks]

def compare_faces(known_face_encodings, face_encoding_to_check, tolerance=0.4):
    """
    Compare a list of face encodings against a candidate encoding to see if they match.
    :param known_face_encodings: A list of known face encodings
    :param face_encoding_to_check: A single face encoding to compare against the list
    :param tolerance: How much distance between faces to consider it a match. Lower is more strict. 0.6 is typical best performance.
    :return: A list of True/False values indicating which known_face_encodings match the face encoding to check
    """
    return list(
        face_distance(
            known_face_encodings,
            face_encoding_to_check) <= tolerance)


text:
jQuery(document).ready(function() {
    var $ = jQuery;
    var screenRes = $(window).width(),
        screenHeight = $(window).height(),
        html = $('html');

// IE<8 Warning
    if (html.hasClass("ie6") || html.hasClass("ie7")) {
        $("body").empty().html('Please, Update your Browser to at least IE8');
    }

// Disable Empty Links
    $("[href=#]").click(function(event){
        event.preventDefault();
    });

// Comment list odd/even
    $(".comment-list li:even , .product-list .product-item:even").addClass("even");
    $(".comment-list li:odd , .product-list .product-item:odd").addClass("odd");

// Body Wrap
    $(".body-wrap").css("min-height", screenHeight);
    $(window).resize(function() {
        screenHeight = $(window).height();
        $(".body-wrap").css("min-height", screenHeight);
    });

// Hide Product items
    $("body").on("click",".product-remove a", function(){
        $(this).parent().parent().hide();
    });

// Remove outline in IE
    $("a, input, textarea").attr("hideFocus", "true").css("outline", "none");

// styled Select, Radio, Checkbox
    if ($("select").hasClass("select_styled")) {
        cuSel({changedEl: ".select_styled", visRows: 8, scrollArrows: true});
    }
    if ($("div,p").hasClass("input_styled")) {
        $(".input_styled input").customInput();
    }

// Menu
    $(".menu ul").parents("li").addClass("parent");

    $(".menu li").hover(function(){
        $(this).addClass('hover');
    },function(){
        $(this).removeClass('hover');
    });

// Tabs
    var $tabs_on_page = $('.tabs').length;
    var $bookmarks = 0;

    for(var i = 1; i <= $tabs_on_page; i++){
        $('.tabs').eq(i-1).addClass('tab-id'+i);
        $bookmarks = $('.tab-id'+i+' li').length;
        $('.tab-id'+i).addClass('bookmarks'+$bookmarks);
    };

    $('.tabs li, .payment-form .btn').click(function() {
        setTimeout(function () {
            for(var i = 1; i <= $tabs_on_page; i++){
                $bookmarks = $('.tab-id'+i+' li').length;
                for(var j = 1; j <= $bookmarks; j++){
                    $('.tab-id'+i).removeClass('active-bookmark'+j);

                    if($('.tab-id'+i+' li').eq(j-1).hasClass('active')){
                        $('.tab-id'+i).addClass('active-bookmark'+j);
                    }
                }
            }
        }, 0)
    });

// Toggles
    $('.toggle-link').click(function(){
        $(this).parents('.toggle').removeClass('collapsed');

        if(!$(this).hasClass('collapsed')) {
            $(this).parents('.toggle').addClass('collapsed');
        }
    });

// Payment Form
    $('.payment-form #billing .btn-next, .payment-form #payment .btn-prev').click(function() {
        $('a[href="#shipping"]').tab('show');
    });
    $('.payment-form #shipping .btn-prev').click(function() {
        $('a[href="#billing"]').tab('show');
    });
    $('.payment-form #shipping .btn-next').click(function() {
        $('a[href="#payment"]').tab('show');
    });

// prettyPhoto lightbox, check if <a> has atrr data-rel and hide for Mobiles
    if($('a').is('[data-rel]') && screenRes > 600) {
        $('a[data-rel]').each(function() {
            $(this).attr('rel', $(this).data('rel'));
        });
        $("a[rel^='prettyPhoto']").prettyPhoto({social_tools:false});
    };

// Smooth Scroling of ID anchors
    function filterPath(string) {
        return string
            .replace(/^\//,'')
            .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
            .replace(/\/$/,'');
    }
    var locationPath = filterPath(location.pathname);
    var scrollElem = scrollableElement('html', 'body');

    $('a[href*=#].anchor').each(function() {
        $(this).click(function(event) {
            var thisPath = filterPath(this.pathname) || locationPath;
            if (  locationPath == thisPath
                && (location.hostname == this.hostname || !this.hostname)
                && this.hash.replace(/#/,'') ) {
                var $target = $(this.hash), target = this.hash;
                if (target && $target.length != 0) {
                    var targetOffset = $target.offset().top;
                    event.preventDefault();
                    $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
                        location.hash = target;
                    });
                }
            }
        });
    });

    // use the first element that is "scrollable"
    function scrollableElement(els) {
        for (var i = 0, argLength = arguments.length; i <argLength; i++) {
            var el = arguments[i],
                $scrollElement = $(el);
            if ($scrollElement.scrollTop()> 0) {
                return el;
            } else {
                $scrollElement.scrollTop(1);
                var isScrollable = $scrollElement.scrollTop()> 0;
                $scrollElement.scrollTop(0);
                if (isScrollable) {
                    return el;
                }
            }
        }
        return [];
    };

// Audio Player
    var $players_on_page = $('.jp-audio').length;
    var $song_title = '';

    if($players_on_page > 0){
        for(var i = 1; i <= $players_on_page; i++){
            $('.jp-audio').eq(i-1).addClass('jp-audio'+i);
        };

        setTimeout(function () {
            for(var i = 1; i <= $players_on_page; i++){
                $song_title = $('.jp-audio'+i+' .jp-playlist ul li.jp-playlist-current .jp-playlist-item').html();
                $('.jp-audio'+i+' .song-title').html($song_title);
            };
        }, 1000);

        function switchSong() {
            setTimeout(function () {
                for(var i = 1; i <= $players_on_page; i++){
                    $('.jp-audio'+i+' .jp-previous, .jp-audio'+i+' .jp-next').removeClass('disabled');

                    if ($('.jp-audio'+i+' .jp-playlist ul li:last-child').hasClass('jp-playlist-current')) {
                        $('.jp-audio'+i+' .jp-next').addClass('disabled');
                    }
                    if ($('.jp-audio'+i+' .jp-playlist ul li:first-child').hasClass('jp-playlist-current')) {
                        $('.jp-audio'+i+' .jp-previous').addClass('disabled');
                    }
                    $song_title = $('.jp-audio'+i+' .jp-playlist ul li.jp-playlist-current .jp-playlist-item').html();
                    $('.jp-audio'+i+' .song-title').html($song_title);
                }
            }, 0)
        };

        $('.jp-previous, .jp-next, .jp-playlist ul').click(function() {
            switchSong()
        });
        $(".jp-jplayer").on($.jPlayer.event.ended, function(event) {
            switchSong()
        });
    };

// Rating Stars
    $(".rating span.star").hover(
        function() {
            $('.rating span.star').removeClass('on').addClass('off');
            $(this).prevAll().addClass('over');
        }
        , function() {
            $(this).removeClass('over');
        }
    );

    $(".rating").mouseleave(function(){
        $(this).parent().find('.over').removeClass('over');
    });

    $( ".rating span.star" ).click( function() {
        $(this).prevAll().removeClass('off').addClass('on');
        $(this).removeClass('off').addClass('on');
    });

// Crop Images in Image Slider

    // adds .naturalWidth() and .naturalHeight() methods to jQuery for retrieving a normalized naturalWidth and naturalHeight.
    (function($){
        var
            props = ['Width', 'Height'],
            prop;

        while (prop = props.pop()) {
            (function (natural, prop) {
                $.fn[natural] = (natural in new Image()) ?
                    function () {
                        return this[0][natural];
                    } :
                    function () {
                        var
                            node = this[0],
                            img,
                            value;

                        if (node.tagName.toLowerCase() === 'img') {
                            img = new Image();
                            img.src = node.src,
                                value = img[prop];
                        }
                        return value;
                    };
            }('natural' + prop, prop.toLowerCase()));
        }
    }(jQuery));

    var
        carousels_on_page = $('.carousel-inner').length,
        carouselWidth,
        carouselHeight,
        ratio,
        imgWidth,
        imgHeight,
        imgRatio,
        imgMargin,
        this_image,
        images_in_carousel;

    for(var i = 1; i <= carousels_on_page; i++){
        $('.carousel-inner').eq(i-1).addClass('id'+i);
    };

    function imageSize() {
        setTimeout(function () {
            for(var i = 1; i <= carousels_on_page; i++){
                carouselWidth = $('.carousel-inner.id'+i+' .item').width();
                carouselHeight = $('.carousel-inner.id'+i+' .item').height();
                ratio = carouselWidth/carouselHeight;

                images_in_carousel = $('.carousel-inner.id'+i+' .item img').length;

                for(var j = 1; j <= images_in_carousel; j++){
                    this_image = $('.carousel-inner.id'+i+' .item img').eq(j-1);
                    imgWidth = this_image.naturalWidth();
                    imgHeight = this_image.naturalHeight();
                    imgRatio = imgWidth/imgHeight;

                    if(ratio <= imgRatio){
                        imgMargin = parseInt((carouselHeight/imgHeight*imgWidth-carouselWidth)/2, 10);
                        this_image.css("cssText", "height: "+carouselHeight+"px; margin-left:-"+imgMargin+"px;");
                    }
                    else{
                        imgMargin = parseInt((carouselWidth/imgWidth*imgHeight-carouselHeight)/2, 10);
                        this_image.css("cssText", "width: "+carouselWidth+"px; margin-top:-"+imgMargin+"px;");
                    }
                }
            };
        },1000);
    };

    imageSize();
    $(window).resize(function() {
        $('.carousel-indicators li:first-child').click();
        imageSize();
    });

});


text:
<?php

namespace HMS\Repositories\Membership;

use HMS\Entities\Membership\RejectedLog;
use HMS\Entities\User;

interface RejectedLogRepository
{
    /**
     * @param User $user
     *
     * @return RejectedLog[]
     */
    public function findByUser(User $user);

    /**
     * Save RejectedLog to the DB.
     *
     * @param RejectedLog $rejectedLog
     */
    public function save(RejectedLog $rejectedLog);
}