text:
<?php

namespace Drupal\Tests\Component\Utility;

use Drupal\Component\Utility\Bytes;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\PhpUnit\ExpectDeprecationTrait;

/**
 * Tests bytes size parsing helper methods.
 *
 * @group Utility
 *
 * @coversDefaultClass \Drupal\Component\Utility\Bytes
 */
class BytesTest extends TestCase {

  use ExpectDeprecationTrait;

  /**
   * Tests \Drupal\Component\Utility\Bytes::toInt().
   *
   * @param int $size
   *   The value for the size argument for
   *   \Drupal\Component\Utility\Bytes::toInt().
   * @param int $expected_int
   *   The expected return value from
   *   \Drupal\Component\Utility\Bytes::toInt().
   *
   * @dataProvider providerTestToNumber
   * @covers ::toInt
   *
   * @group legacy
   */
  public function testToInt($size, $expected_int) {
    $this->expectDeprecation('\Drupal\Component\Utility\Bytes::toInt() is deprecated in drupal:9.1.0 and is removed from drupal:10.0.0. Use \Drupal\Component\Utility\Bytes::toNumber() instead. See https://www.drupal.org/node/3162663');
    $this->assertEquals($expected_int, Bytes::toInt($size));
  }

  /**
   * Tests \Drupal\Component\Utility\Bytes::toNumber().
   *
   * @param string $size
   *   The value for the size argument for
   *   \Drupal\Component\Utility\Bytes::toNumber().
   * @param float $expected_number
   *   The expected return value from
   *   \Drupal\Component\Utility\Bytes::toNumber().
   *
   * @dataProvider providerTestToNumber
   * @covers ::toNumber
   */
  public function testToNumber($size, float $expected_number): void {
    $this->assertSame($expected_number, Bytes::toNumber($size));
  }

  /**
   * Provides data for testToNumber().
   *
   * @return array
   *   An array of arrays, each containing the argument for
   *   \Drupal\Component\Utility\Bytes::toNumber(): size, and the expected
   *   return value with the expected type (float).
   */
  public function providerTestToNumber(): array {
    return [
      ['1', 1.0],
      ['1 byte', 1.0],
      ['1 KB'  , (float) Bytes::KILOBYTE],
      ['1 MB'  , (float) pow(Bytes::KILOBYTE, 2)],
      ['1 GB'  , (float) pow(Bytes::KILOBYTE, 3)],
      ['1 TB'  , (float) pow(Bytes::KILOBYTE, 4)],
      ['1 PB'  , (float) pow(Bytes::KILOBYTE, 5)],
      ['1 EB'  , (float) pow(Bytes::KILOBYTE, 6)],
      // Zettabytes and yottabytes cannot be represented by integers on 64-bit
      // systems, so pow() returns a float.
      ['1 ZB'  , pow(Bytes::KILOBYTE, 7)],
      ['1 YB'  , pow(Bytes::KILOBYTE, 8)],
      ['23476892 bytes', 23476892.0],
      // 76 MB.
      ['76MRandomStringThatShouldBeIgnoredByParseSize.', 79691776.0],
      // 76.24 GB (with typo).
      ['76.24 Giggabyte', 81862076662.0],
      ['1.5', 2.0],
      [1.5, 2.0],
      ['2.4', 2.0],
      [2.4, 2.0],
      ['', 0.0],
      ['9223372036854775807', 9223372036854775807.0],
    ];
  }

  /**
   * Tests \Drupal\Component\Utility\Bytes::validate().
   *
   * @param string $string
   *   The value for the string argument for
   *   \Drupal\Component\Utility\Bytes::validate().
   * @param bool $expected_result
   *   The expected return value from
   *   \Drupal\Component\Utility\Bytes::validate().
   *
   * @dataProvider providerTestValidate
   * @covers ::validate
   */
  public function testValidate($string, bool $expected_result): void {
    $this->assertSame($expected_result, Bytes::validate($string));
  }

  /**
   * Provides data for testValidate().
   *
   * @return array
   *   An array of arrays, each containing the argument for
   *   \Drupal\Component\Utility\Bytes::validate(): string, and the expected
   *   return value with the expected type (bool).
   */
  public function providerTestValidate(): array {
    return [
      // String not starting with a number.
      ['foo', FALSE],
      ['fifty megabytes', FALSE],
      ['five', FALSE],
      // Test spaces and capital combinations.
      [5, TRUE],
      ['5M', TRUE],
      ['5m', TRUE],
      ['5 M', TRUE],
      ['5 m', TRUE],
      ['5Mb', TRUE],
      ['5mb', TRUE],
      ['5 Mb', TRUE],
      ['5 mb', TRUE],
      ['5Gb', TRUE],
      ['5gb', TRUE],
      ['5 Gb', TRUE],
      ['5 gb', TRUE],
      // Test all allowed suffixes.
      ['5', TRUE],
      ['5 b', TRUE],
      ['5 byte', TRUE],
      ['5 bytes', TRUE],
      ['5 k', TRUE],
      ['5 kb', TRUE],
      ['5 kilobyte', TRUE],
      ['5 kilobytes', TRUE],
      ['5 m', TRUE],
      ['5 mb', TRUE],
      ['5 megabyte', TRUE],
      ['5 megabytes', TRUE],
      ['5 g', TRUE],
      ['5 gb', TRUE],
      ['5 gigabyte', TRUE],
      ['5 gigabytes', TRUE],
      ['5 t', TRUE],
      ['5 tb', TRUE],
      ['5 terabyte', TRUE],
      ['5 terabytes', TRUE],
      ['5 p', TRUE],
      ['5 pb', TRUE],
      ['5 petabyte', TRUE],
      ['5 petabytes', TRUE],
      ['5 e', TRUE],
      ['5 eb', TRUE],
      ['5 exabyte', TRUE],
      ['5 exabytes', TRUE],
      ['5 z', TRUE],
      ['5 zb', TRUE],
      ['5 zettabyte', TRUE],
      ['5 zettabytes', TRUE],
      ['5 y', TRUE],
      ['5 yb', TRUE],
      ['5 yottabyte', TRUE],
      ['5 yottabytes', TRUE],
      // Test with decimal.
      [5.1, TRUE],
      ['5.1M', TRUE],
      ['5.1mb', TRUE],
      ['5.1 M', TRUE],
      ['5.1 Mb', TRUE],
      ['5.1 megabytes', TRUE],
      // Test with an unauthorized string.
      ['1five', FALSE],
      ['1 1 byte', FALSE],
      ['1,1 byte', FALSE],
      // Test with leading and trailing spaces.
      [' 5.1mb', FALSE],
      ['5.1mb ', TRUE],
      [' 5.1mb ', FALSE],
      [' 5.1 megabytes', FALSE],
      ['5.1 megabytes ', TRUE],
      [' 5.1 megabytes ', FALSE],
      ['300 0', FALSE],
    ];
  }

}


text:
<?php

namespace Vierbeuter\WordPress\Feature\CustomField;

/**
 * Dropdown-selection to be used for a post-type's custom-field.
 *
 * @package Vierbeuter\WordPress\Feature\CustomField
 */
abstract class DropdownSelection extends Selection
{

    /**
     * Renders the input's markup.
     *
     * @param \WP_Post|\WP_Term|null $postOrTerm
     * @param string $fieldId
     * @param string|null $value
     */
    function renderField($postOrTerm = null, string $fieldId, string $value = null): void
    {
        echo '<select id="' . $fieldId . '" name="' . $fieldId . '" size="1">';

        //  get data for selection
        $selectionData = $this->getSelectionData();

        //  if no value given
        if (empty($value)) {
            //  first value of $selectionData is the one to use (as default)
            reset($selectionData);
            $value = key($selectionData);
        }

        //  iterate all data entries
        foreach ($selectionData as $optionValue => $optionLabel) {
            //  check if current option-entry has to be selected by default
            $selected = $optionValue == $value ? 'selected="selected"' : '';

            //  render the option
            echo '<option value="' . $optionValue . '" ' . $selected . '>' . $optionLabel . '</option>';
        }

        echo '</select>';
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface DiffMatchPatch (Simperium)

- (NSArray *)patch_apply:(NSArray *)sourcePatches toString:(NSString *)text error:(NSError **)error;

@end


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for DvsMergedEvent complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="DvsMergedEvent">
 *   <complexContent>
 *     <extension base="{urn:vim25}DvsEvent">
 *       <sequence>
 *         <element name="sourceDvs" type="{urn:vim25}DvsEventArgument"/>
 *         <element name="destinationDvs" type="{urn:vim25}DvsEventArgument"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DvsMergedEvent", propOrder = {
    "sourceDvs",
    "destinationDvs"
})
public class DvsMergedEvent
    extends DvsEvent
{

    @XmlElement(required = true)
    protected DvsEventArgument sourceDvs;
    @XmlElement(required = true)
    protected DvsEventArgument destinationDvs;

    /**
     * Gets the value of the sourceDvs property.
     *
     * @return
     *     possible object is
     *     {@link DvsEventArgument }
     *
     */
    public DvsEventArgument getSourceDvs() {
        return sourceDvs;
    }

    /**
     * Sets the value of the sourceDvs property.
     *
     * @param value
     *     allowed object is
     *     {@link DvsEventArgument }
     *
     */
    public void setSourceDvs(DvsEventArgument value) {
        this.sourceDvs = value;
    }

    /**
     * Gets the value of the destinationDvs property.
     *
     * @return
     *     possible object is
     *     {@link DvsEventArgument }
     *
     */
    public DvsEventArgument getDestinationDvs() {
        return destinationDvs;
    }

    /**
     * Sets the value of the destinationDvs property.
     *
     * @param value
     *     allowed object is
     *     {@link DvsEventArgument }
     *
     */
    public void setDestinationDvs(DvsEventArgument value) {
        this.destinationDvs = value;
    }

}


text:
 Order Details

<template #menu_content let-c="close" let-d="dismiss">

{{order.restaurant_name}}

    <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
      ×
    </button>

    <button type="button" class="btn btn-secondary" (click)="c('Close click')">Close</button>

</template>

         {{order.restaurant_name}}
        <button class="btn btn-sm btn-secondary pull-right" (click)="viewMenu(menu_content)">
          View Menu
        </button>

          Person
          Item
          Amount
          Price
          Comment
          #

          {{meal.owner.name}}
          {{meal.name}}
          {{meal.amount}}
          {{meal.price | currency:'EGP':true:'1.2-2'}}
          {{meal.comment}}

            <button *ngIf="meal.owner._id == _auth.getCurrentUser()._id || order.owner._id == _auth.getCurrentUser()._id" (click)="removeMeal(meal._id)"
                    class="btn btn-sm btn-danger"></button>

          Totals

          {{totals.quantity}}
          {{totals.price | currency:'EGP':true:'1.2-2'}}

      <form *ngIf="addPermession" name="form" (ngSubmit)="f.form.valid && addMeal()" #f="ngForm" novalidate>

              Item
              <input type="text" class="form-control" name="name" placeholder="Item" [(ngModel)]="model.name"
                     #name="ngModel" required>

              Amount
              <input type="number" class="form-control" name="amount" placeholder="Amount" value="1"
                     [(ngModel)]="model.amount" #amount="ngModel" required>

              Price
              <input type="number" class="form-control" name="price" placeholder="Price" [(ngModel)]="model.price"
                     #price="ngModel" required>

              Comment
              <input type="text" class="form-control" name="comment" placeholder="Comment" [(ngModel)]="model.comment"
                     #comment="ngModel">

            <button [disabled]="loading" class="btn btn-secondary">Add</button>
            <img *ngIf="loading"
                 src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="/>

      </form>

 Friends Invited

          <user-card *ngIf="order.owner._id == _auth.getCurrentUser()._id" [user]="user" [badge]="user.badge"
                     [button]="{text:'Remove',class:'btn-danger'}"
                     (buttonClicked)="removeUser(user._id)"></user-card>
          <user-card *ngIf="order.owner._id != _auth.getCurrentUser()._id" [user]="user"
                     [badge]="user.badge"></user-card>


text:
package org.jboss.community.trts.rest;

import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.jboss.community.trts.model.AxisConfig;
import org.jboss.community.trts.service.AxisConfigService;
import org.jboss.community.trts.service.AxisService;
import org.jboss.community.trts.service.ProductVersionService;

@RequestScoped
@RolesAllowed({"Manager"})
@Path("/axis/{aid:[0-9][0-9]*}/version/{vid:[0-9][0-9]*}/configurations")
public class AxisConfigurationREST {

	@Inject
	private AxisService service;

	@Inject
	private AxisConfigService configService;

	@Inject
	private ProductVersionService versionService;

	@PUT
	@Path("/{id:[0-9][0-9]*}")
	@Consumes(MediaType.APPLICATION_JSON)
	public void editConfiguration(@PathParam("aid") Long aid,
			@PathParam("vid") Long vid, @PathParam("id") Long id, AxisConfig ac) {
		configService.update(ac);
	}

	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public void addAxisConfig(@PathParam("aid") Long aid,
			@PathParam("vid") Long vid, AxisConfig c) {

		c.setProductVersion(versionService.getById(vid));
		configService.persist(c);
	}

	@GET
	@RolesAllowed({"Tester, Manager"})
	public List<AxisConfig> listConfigurations(@PathParam("aid") Long aid,
			@PathParam("vid") Long vid) {
		return configService.getAxisConfigs(service.getById(aid),
				versionService.getById(vid));
	}

	@GET
	@Path("/{id:[0-9][0-9]*}")
	@RolesAllowed({"Tester, Manager"})
	@Produces(MediaType.APPLICATION_JSON)
	public AxisConfig getById(@PathParam("aid") Long aid,
			@PathParam("vid") Long vid, @PathParam("id") Long id) {
		return configService.getById(id);
	}

	@DELETE
	@Path("/{id:[0-9][0-9]*}")
	public void removeAxisConfig(@PathParam("aid") Long aid,
			@PathParam("vid") Long vid, @PathParam("id") Long id) {
		configService.delete(configService.getById(id));
	}
}


text:
package com.zuppelli.storage;

import com.zuppelli.cake.modelo.Entity;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by pedro.com.zuppelli on 07/10/2015.
 */
@Component
public class InMemoryStorage implements Storage{
    private Map<Class<?>, Map<Object, Object>> content = new HashMap<Class<?>, Map<Object, Object>>();
    private final Random random = new Random(  );

    @Override
    public <T> T store( Class<T> clazz, Entity entity ) {
        if ( null == entity.getId() ) {
            entity.setId( Math.abs( random.nextLong() ) );
        }
        Map<Object, Object> map = content.get( clazz );
        if ( null == map  ) {
            map = new HashMap<Object, Object>();
            content.put( clazz, map );
        }
        content.get( clazz ).put( entity.getId(), entity );
        return (T) entity;
    }

    @Override
    public <T, K> T retrieve( Class<T> clazz, K id ) {
        Map<Object, Object> map = content.get( clazz );
        if ( null != map ) {
            return (T) map.get( id );
        }
        return null;
    }

    @Override
    public <T> Collection<T> retrieve( Class<T> clazz) {
        Map<Object, Object> map = content.get( clazz );
        if ( null != map ) {
            return (Collection<T> )map.values();
        }
        return null;
    }

    @Override
    public <T, K> void delete( Class<T> clazz, K id ) {
        Map<Object, Object> map = content.get( clazz );
        if ( null != map ) {
            map.remove( id );
        }
    }
}


text:
import { AsyncIterableX } from '../asynciterable';
import { PartialAsyncObserver } from '../observer';

class TapAsyncIterable<TSource> extends AsyncIterableX<TSource> {
  private _source: AsyncIterable<TSource>;
  private _observer: PartialAsyncObserver<TSource>;

  constructor(source: AsyncIterable<TSource>, observer: PartialAsyncObserver<TSource>) {
    super();
    this._source = source;
    this._observer = observer;
  }

  async *[Symbol.asyncIterator]() {
    const it = this._source[Symbol.asyncIterator]();
    while (1) {
      let next;
      try {
        next = await it.next();
      } catch (e) {
        if (this._observer.error) { await this._observer.error(e); }
        throw e;
      }

      if (next.done) {
        if (this._observer.complete) { await this._observer.complete(); }
        break;
      }

      if (this._observer.next) { await this._observer.next(next.value); }
      yield next.value;
    }
  }
}

export function tap<TSource>(
    source: AsyncIterable<TSource>,
    observer: PartialAsyncObserver<TSource>): AsyncIterableX<TSource> {
  return new TapAsyncIterable<TSource>(source, observer);
}


text:
set -euo pipefail

# gracefully handle the TERM signal sent when deleting the daemonset
trap 'exit' TERM
SELINUX_TAG=$(ls -Z)

mkdir -p /images/datavolume1 /images/datavolume2 /images/datavolume3

echo "copy all images to host mount directory"
cp -R /images/* /hostImages/
echo "make the alpine image ready for parallel use"
cp -r /hostImages/alpine hostImages/alpine1
cp -r /hostImages/alpine hostImages/alpine2
cp -r /hostImages/alpine hostImages/alpine3
rm -rf /hostImages/alpine
mkdir -p /local-storage/hotplug-test
cp -r /hostImages/custom/disk.img /local-storage/hotplug-test/disk.img
chmod -R 777 /local-storage/hotplug-test

echo "make the custom image ready for parallel use"
cp -r /hostImages/custom hostImages/custom1
cp -r /hostImages/custom hostImages/custom2
cp -r /hostImages/custom hostImages/custom3
rm -rf /hostImages/custom
chmod -R 777 /hostImages

# Create a 4Gi blank disk image
dd if=/dev/zero of=/local-storage/hp_file.img bs=4k count=1024k
ls -al /local-storage/hp_file.img
# Put LOOP_DEVICE_HP in /etc/bashrc in order to detach this loop device when the pod stopped.
LOOP_DEVICE_HP=$(chroot /host losetup --verbose --find --show /mnt/local-storage/hp_file.img)
echo LOOP_DEVICE_HP=${LOOP_DEVICE_HP} >>/etc/bashrc
chroot /host mkfs.ext4 $LOOP_DEVICE_HP
mkdir -p /hostImages/mount_hp
ls -al /host${LOOP_DEVICE_HP}
chroot /host mount ${LOOP_DEVICE_HP} /tmp/hostImages/mount_hp
mkdir -p /host/tmp/hostImages/mount_hp/test
# When the host is ubuntu, by default, selinux is not used, so chcon is not necessary.
# If selinux tag is set, use chcon to change /hostImages privileges.
if [ ${SELINUX_TAG:0:1} != "?" ]; then
    chcon -Rt svirt_sandbox_file_t /host/tmp/hostImages
    chcon -R unconfined_u:object_r:svirt_sandbox_file_t:s0 /host/mnt/local-storage/
fi
chmod 777 /host/tmp/hostImages/mount_hp
chmod 777 /host/tmp/hostImages/mount_hp/test

cat /etc/bashrc

# for some reason without sleep, container sometime fails to create the file
sleep 10

# let the monitoring script know we're done
echo "done" >/ready

while true; do
    sleep 60
done


text:
import CGAlgorithms from '../algorithm/CGAlgorithms';
import CoordinateFilter from '../geom/CoordinateFilter';
import Coordinate from '../geom/Coordinate';
import Double from '../../../../java/lang/Double';
import extend from '../../../../extend';
import LineSegment from '../geom/LineSegment';
import CoordinateSequenceFilter from '../geom/CoordinateSequenceFilter';
export default function SimpleMinimumClearance() {
	this.inputGeom = null;
	this.minClearance = null;
	this.minClearancePts = null;
	let geom = arguments[0];
	this.inputGeom = geom;
}
extend(SimpleMinimumClearance.prototype, {
	getLine: function () {
		this.compute();
		return this.inputGeom.getFactory().createLineString(this.minClearancePts);
	},
	updateClearance: function () {
		if (arguments.length === 3) {
			let candidateValue = arguments[0], p0 = arguments[1], p1 = arguments[2];
			if (candidateValue < this.minClearance) {
				this.minClearance = candidateValue;
				this.minClearancePts[0] = new Coordinate(p0);
				this.minClearancePts[1] = new Coordinate(p1);
			}
		} else if (arguments.length === 4) {
			let candidateValue = arguments[0], p = arguments[1], seg0 = arguments[2], seg1 = arguments[3];
			if (candidateValue < this.minClearance) {
				this.minClearance = candidateValue;
				this.minClearancePts[0] = new Coordinate(p);
				var seg = new LineSegment(seg0, seg1);
				this.minClearancePts[1] = new Coordinate(seg.closestPoint(p));
			}
		}
	},
	compute: function () {
		if (this.minClearancePts !== null) return null;
		this.minClearancePts = new Array(2).fill(null);
		this.minClearance = Double.MAX_VALUE;
		this.inputGeom.apply(new VertexCoordinateFilter(this));
	},
	getDistance: function () {
		this.compute();
		return this.minClearance;
	},
	interfaces_: function () {
		return [];
	},
	getClass: function () {
		return SimpleMinimumClearance;
	}
});
SimpleMinimumClearance.getLine = function (g) {
	var rp = new SimpleMinimumClearance(g);
	return rp.getLine();
};
SimpleMinimumClearance.getDistance = function (g) {
	var rp = new SimpleMinimumClearance(g);
	return rp.getDistance();
};
function VertexCoordinateFilter() {
	this.smc = null;
	let smc = arguments[0];
	this.smc = smc;
}
extend(VertexCoordinateFilter.prototype, {
	filter: function (coord) {
		this.smc.inputGeom.apply(new ComputeMCCoordinateSequenceFilter(this.smc, coord));
	},
	interfaces_: function () {
		return [CoordinateFilter];
	},
	getClass: function () {
		return VertexCoordinateFilter;
	}
});
function ComputeMCCoordinateSequenceFilter() {
	this.smc = null;
	this.queryPt = null;
	let smc = arguments[0], queryPt = arguments[1];
	this.smc = smc;
	this.queryPt = queryPt;
}
extend(ComputeMCCoordinateSequenceFilter.prototype, {
	isGeometryChanged: function () {
		return false;
	},
	checkVertexDistance: function (vertex) {
		var vertexDist = vertex.distance(this.queryPt);
		if (vertexDist > 0) {
			this.smc.updateClearance(vertexDist, this.queryPt, vertex);
		}
	},
	filter: function (seq, i) {
		this.checkVertexDistance(seq.getCoordinate(i));
		if (i > 0) {
			this.checkSegmentDistance(seq.getCoordinate(i - 1), seq.getCoordinate(i));
		}
	},
	checkSegmentDistance: function (seg0, seg1) {
		if (this.queryPt.equals2D(seg0) || this.queryPt.equals2D(seg1)) return null;
		var segDist = CGAlgorithms.distancePointLine(this.queryPt, seg1, seg0);
		if (segDist > 0) this.smc.updateClearance(segDist, this.queryPt, seg1, seg0);
	},
	isDone: function () {
		return false;
	},
	interfaces_: function () {
		return [CoordinateSequenceFilter];
	},
	getClass: function () {
		return ComputeMCCoordinateSequenceFilter;
	}
});
SimpleMinimumClearance.VertexCoordinateFilter = VertexCoordinateFilter;
SimpleMinimumClearance.ComputeMCCoordinateSequenceFilter = ComputeMCCoordinateSequenceFilter;


text:
/**
* This package contains service provider interfaces (SPI) that enable applications to
* replace, extend and customize different configuration aspects such as storage, caching behaviour,
* runtime environment and so forth.
*

* Each SPI deals with a very specific concern within the architecture and service providers are
* free to implement any of them. A key design goal for each SPI is to be decoupled from other SPI to
* enable providers to create modular implementations that are orthogonal and cohesive with
* respect to other SPI. This enables interaction between unforseen combinations of service providers.
*

* Provider services are registered and automatically bound to core functionality when
* the application is started/loaded. It is the responsibility of the core to glue/mediate communication
* between different providers. The mechanism used is the standard {@link java.util.ServiceLoader}
* at the moment, but other lookup/registrations (OSGi, CDI SPI extensions, JNDI etc) are envisioned.
*

* A Test Compability Kit (TCK) is available for providers to verify that their
* implementation behaves correctly.
*

*

* Each SPI have a default implementation that will be used if no other is provided.
*

*
*

* The following SPIs are available at the moment:
*

*
 {@link org.deephacks.confit.spi.BeanManager}

*
 {@link org.deephacks.confit.spi.SchemaManager}

*
 {@link org.deephacks.confit.spi.ValidationManager}

*
 {@link org.deephacks.tools4j.support.conversion.Converter}

* This interface takes care of converting configuration property types to-and-from String
* (which is the format for storing property values).
*

*

*
*

* The following SPIs are envisioned in the future:
*

*
 SessionManager

* Doing configuration changes in the context of a session that can commit and validate (or rollback) atomically.
*
 CachingManager

* Implements a cache policy of runtime instances, such as eviction, memory size, storage, passivation etc.
*
 NotificationManager

* Provide applications with notification guarantees, making them aware of changes made to their configuration
* in case an adjusting actions needs to be taken within their runtime environment.
*

*

*
Usage

*
* TODO:
*/
package org.deephacks.confit.spi;

;


text:
<?php
/**
 * Plugin Name: Feed Post Writer
 * Plugin URI: https://github.com/goodevilgenius/feed-post-writer
 * Description: Populate a post with the first entry from a feed
 * Version: 0.6.1
 * Author: Dan Jones
 * Author URI: http://goodevilgenius.org/
 * License: MIT
 */

// Add Admin Settings
require_once(plugin_dir_path(__FILE__) . 'fpw_admin.php');

// Add necessary functions
require_once(plugin_dir_path(__FILE__) . 'fpw_functions.php');

// Setup plugin
require_once(plugin_dir_path(__FILE__) . 'fpw_setup.php');


text:
package org.scalatest

import events.InfoProvided

class GivenWhenThenSpec extends Spec with SharedHelpers {
  describe("The GivenWhenThen trait") {

    val theGiven = "an invalid zip code"
    val theAnd = "the zip code validator has been initialized"
    val theWhen = "validate is invoked with the invalid zip code"
    val theThen = "the validator should return false"
    class GivenWhenThenInsideTestSpec extends Spec with GivenWhenThen {
      it("should do something") {
        given(theGiven)
        and(theAnd)
        when(theWhen)
        then(theThen)
      }
    }
    val spec = new GivenWhenThenInsideTestSpec
    val myRep = new EventRecordingReporter
    spec.run(None, myRep, new Stopper {}, Filter(), Map(), None, new Tracker)
    val indexedList = myRep.eventsReceived.zipWithIndex
    val infoProvidedList: List[InfoProvided] =
      for ((infoProvided: InfoProvided, _) <- indexedList)
      yield infoProvided

    it("should pass given through to the reporter") {
      assert(infoProvidedList.exists(_.message == "Given " + theGiven))
    }
    it("should pass and through to the reporter") {
      assert(infoProvidedList.exists(_.message == "And " + theAnd))
    }
    it("should pass when through to the reporter") {
      assert(infoProvidedList.exists(_.message == "When " + theWhen))
    }
    it("should pass then through to the reporter") {
      assert(infoProvidedList.exists(_.message == "Then " + theThen))
    }
  }
}


text:
<resources>

    <!--
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
    -->

    <!-- Application theme. -->

    <style name="Anim_style2" parent="android:Theme.NoTitleBar">
        <item name="android:windowAnimationStyle">@style/activityAnimation</item>
	</style>
	<style name="activityAnimation" parent="@android:style/Animation">
        <item name="android:activityOpenEnterAnimation">@anim/slide_right_in</item>
        <item name="android:activityOpenExitAnimation">@anim/slide_left_out</item>
        <item name="android:activityCloseEnterAnimation">@anim/slide_left_in</item>
        <item name="android:activityCloseExitAnimation">@anim/slide_right_out</item>
    </style>

</resources>


text:
#include "log.h"

namespace blr
{
namespace nn
{

const Timer* LogTimer()
{
  static Timer s_timer;
  return &s_timer;
}

}
}


text:
if [ -n "$(cat /etc/redhat-release | grep release\ 7)" ]; then
# CentOS 7, Fedora 20/21
  sudo yum -y install qemu-kvm libvirt virt-install bridge-utils libvirt-daemon-kvm
  sudo systemctl start libvirtd
  sudo systemctl enable libvirtd
else
  echo "$rhelversion"
  sudo yum -y install qemu-kvm libvirt virt-install bridge-utils
  chkconfig libvirtd on
  service libvirtd start
fi


text:
void shifter(virtual_machine*);

#endif


text:
package com.jdon.controller.context;

public interface SessionWrapper {

	Object getAttribute(String key);

	void setAttribute(String key, Object o);
}


text:
using System;
using Microsoft.AspNetCore.Mvc;

namespace RESTyard.AspNetCore.WebApi.RouteResolver
{
    public interface IRouteResolverFactory
    {
        IHypermediaRouteResolver CreateRouteResolver(IUrlHelper urlHelper, IRouteKeyFactory routeKeyFactory, IHypermediaUrlConfig hypermediaUrlConfig = null);
    }
}


text:
Content-Type: text/html

<title>Our Daily Bard: Shakespeare plays, delivered one day at a time</title>

Our Daily Bard

Shakespeare plays, delivered one day at a time, via RSS feeds.

Just select a link and this will give you a custom RSS feed where the play
starts today.

The code for this site is available on GitHub.

$rss_links


text:
import * as React from 'react'
import ReactDOM from 'react-dom'
import LoadComponent from './LoadComponent'

class App extends React.Component {

  state = {
    showChart: false
  }

  showChart = () => {
    this.setState({
      showChart: !this.state.showChart
    })
  }

  render() {
    return (

      <button onClick={this.showChart}>load chart</button>
      {this.state.showChart ? (
        <LoadComponent path='Chart' render={(Chart)=> {
          if(Chart) {
            return <Chart />
          } else {
            return
Loading...

          }
        }}/>
      ) : null}

    )
  }
}

window.onload = function() {
  ReactDOM.render(<App/>, document.querySelector('#render'))
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Mock class for Background.
 * @constructor
 */
function MockBackground() {
  this.fileOperationManager = new MockFileOperationManager();
  this.progressCenter = new MockProgressCenter();
  this.closeRequestCount = 0;
}

/**
 * Increments the close request counter.
 */
MockBackground.prototype.tryClose = function() {
  this.closeRequestCount++;
};


text:
import { templateOnlyComponentTemplate } from '@cardstack/core/tests/helpers';
import { expect } from 'chai';
import { configureHubWithCompiler } from '../helpers/cards';
import { parse, isSameDay } from 'date-fns';

function p(dateString: string): Date {
  return parse(dateString, 'yyyy-MM-dd', new Date());
}

if (process.env.COMPILER) {
  describe('computed', function () {
    let { realmURL: realm, cards } = configureHubWithCompiler(this);

    this.beforeEach(async function () {
      await cards.create({
        realm,
        id: 'bio',
        schema: 'schema.js',
        files: {
          'schema.js': `
            import { contains } from "@cardstack/types";
            import string from "https://cardstack.com/base/string";

            export default class Bio {
              @contains(string) short;
              @contains(string) favoriteColor;
            }
          `,
        },
      });
      await cards.create({
        realm,
        id: 'person',
        schema: 'schema.js',
        isolated: 'isolated.js',
        files: {
          'schema.js': `
            import { contains } from "@cardstack/types";
            import string from "https://cardstack.com/base/string";
            import bio from "../bio";
            export default class Person {
              getRawField = "don't collide!";
              @contains(string) firstName;
              @contains(string) lastName;
              @contains(bio) aboutMe;

              @contains(string)
              get fullName() {
                return this.firstName + " " + this.lastName;
              }

              @contains(string)
              get summary() {
                return this.fullName + " is a person. Their story is: " + this.aboutMe.short;
              }

              @contains(string, { computeVia: "computeSlowSummary" }) slowSummary;
              async computeSlowSummary() {
                await new Promise(resolve => setTimeout(resolve, 10));
                return this.summary;
              }

              @contains(string)
              get loudSummary() {
                return this.slowSummary + "!";
              }
            }
          `,
          // firstName, lastName, summary, and bio.short should be considered as used
          // fields since summary depends on all of them, right?
          'isolated.js': templateOnlyComponentTemplate(`<div><@fields.summary/></div>`),
        },
      });

      await cards.create({
        realm,
        id: 'arthur',
        adoptsFrom: '../person',
        data: {
          firstName: 'Arthur',
          lastName: 'Faulkner',
          aboutMe: {
            short: 'son of Ed',
            favoriteColor: 'blue',
          },
        },
      });
    });

    it(`can access a synchronous computed field`, async function () {
      let card = await cards.loadModel(`${realm}arthur`, 'isolated');
      expect(await card.getField('fullName')).to.equal('Arthur Faulkner');
    });

    it(`can access a two-level-deep synchronous computed field`, async function () {
      let card = await cards.loadModel(`${realm}arthur`, 'isolated');
      expect(await card.getField('summary')).to.equal('Arthur Faulkner is a person. Their story is: son of Ed');
    });

    it('can access a composite field', async function () {
      let card = await cards.loadModel(`${realm}arthur`, 'isolated');
      let aboutMe = await card.getField('aboutMe');
      expect(aboutMe.short).to.equal('son of Ed');
      expect(aboutMe.favoriteColor).to.equal('blue');
    });

    it('can access an asynchronous computed field', async function () {
      let card = await cards.loadModel(`${realm}arthur`, 'isolated');
      expect(await card.getField('slowSummary')).to.equal('Arthur Faulkner is a person. Their story is: son of Ed');
    });

    it('can indirectly access an asynchronous computed field', async function () {
      let card = await cards.loadModel(`${realm}arthur`, 'isolated');
      expect(await card.getField('loudSummary')).to.equal('Arthur Faulkner is a person. Their story is: son of Ed!');
    });

    it('can access a synchronous computed field defined in parent card', async function () {
      await cards.create({
        realm,
        id: 'ains',
        adoptsFrom: '../person',
        schema: 'schema.js',
        files: {
          'schema.js': `
            import { adopts, contains } from "@cardstack/types";
            import string from "https://cardstack.com/base/string";
            import person from "../person";
            export default @adopts(person) class Isekai {
              @contains(string) seriesName;
            }
          `,
        },
        data: {
          firstName: 'Ains Ooal',
          lastName: 'Gown',
          seriesName: 'Overlord',
          aboutMe: {
            short: 'Supreme overlord of darkness',
            favoriteColor: 'black',
          },
        },
      });
      let card = await cards.loadModel(`${realm}ains`, 'isolated');
      expect(await card.getField('fullName')).to.equal('Ains Ooal Gown');
      expect(await card.getField('seriesName')).to.equal('Overlord');
    });

    it('can access an asynchronous computed field defined in parent card', async function () {
      await cards.create({
        realm,
        id: 'ains',
        adoptsFrom: '../person',
        schema: 'schema.js',
        files: {
          'schema.js': `
            import { adopts, contains } from "@cardstack/types";
            import string from "https://cardstack.com/base/string";
            import person from "../person";
            export default @adopts(person) class Isekai {
              @contains(string) seriesName;
            }
          `,
        },
        data: {
          firstName: 'Ains Ooal',
          lastName: 'Gown',
          seriesName: 'Overlord',
          aboutMe: {
            short: 'Supreme overlord of darkness',
            favoriteColor: 'black',
          },
        },
      });
      let card = await cards.loadModel(`${realm}ains`, 'isolated');
      expect(await card.getField('fullName')).to.equal('Ains Ooal Gown');
      expect(await card.getField('loudSummary')).to.equal(
        'Ains Ooal Gown is a person. Their story is: Supreme overlord of darkness!'
      );
    });

    it('can access a field that requires deserialization', async function () {
      await cards.create({
        realm,
        id: 'test',
        schema: 'schema.js',
        data: {
          date: '2022-03-24',
        },
        files: {
          'schema.js': `
            import { contains } from "@cardstack/types";
            import date from "https://cardstack.com/base/date";
            export default class Test {
              @contains(date) date;
              @contains(date)
              get nextDay() {
                return new Date(this.date.getTime() + (24 * 60 * 60 * 1000));
              }
            }
          `,
        },
      });

      let card = await cards.loadModel(`${realm}test`, 'isolated');
      expect(isSameDay(await card.getField('nextDay'), p('2022-03-25')), 'Dates are serialized to Dates').to.be.ok;
      expect(isSameDay(card.data['nextDay'], p('2022-03-25')), 'Dates are serialized to Dates').to.be.ok;
      expect(card.serialize().attributes?.nextDay).to.equal('2022-03-25');
    });
  });
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.11.29 at 12:35:53 PM GMT
//

package org.mule.modules.hybris.model;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for commentUserSettingsDTO complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="commentUserSettingsDTO">
 *   <complexContent>
 *     <extension base="{}abstractCollectionDTO">
 *       <sequence>
 *         <element ref="{}commentusersetting" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "commentUserSettingsDTO", propOrder = {
    "commentusersetting"
})
public class CommentUserSettingsDTO
    extends AbstractCollectionDTO
{

    protected List<CommentUserSettingDTO> commentusersetting;

    /**
     * Gets the value of the commentusersetting property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the commentusersetting property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getCommentusersetting().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link CommentUserSettingDTO }
     *
     *
     */
    public List<CommentUserSettingDTO> getCommentusersetting() {
        if (commentusersetting == null) {
            commentusersetting = new ArrayList<CommentUserSettingDTO>();
        }
        return this.commentusersetting;
    }

}


text:
using Cosmos.Debug.Kernel;
using IL2CPU.API.Attribs;
using System;
using System.Collections.Generic;

namespace Cosmos.Core_Plugs.System.Collections.Generic
{
    [Plug("System.Collections.Generic.ComparerHelpers, System.Private.CoreLib")]
    public static class ComparerHelpersImpl
    {
        private static readonly Debugger mDebugger = new Debugger("Core", "ComparerHelpersImpl");

        public static object CreateDefaultComparer(Type aType)
        {
            Debugger.DoBochsBreak();

            if (aType == typeof(string))
            {
                return new StringComparer();
            }

            return null;
        }

        public static object CreateDefaultEqualityComparer(Type aType)
        {
            Debugger.DoBochsBreak();

            if (aType == typeof(string))
            {
                return new StringEqualityComparer();
            }

            if (aType == typeof(int))
            {
                return new Int32EqualityComparer();
            }

            // TODO: Nullable<>

            // TODO: Enum (Comparer is special to avoid boxing)

            //else
            //{
            //    xResult = new ObjectComparer<object>();
            //}
            mDebugger.Send($"No EqualityComparer for type {aType}");
            return null;
        }
    }

    public class StringComparer : Comparer<string>
    {
        private readonly Debugger mDebugger = new Debugger("Core", "String Comparer");

        public override int Compare(string x, string y)
        {
            mDebugger.Send("StringComparer.Compare");

            throw new NotImplementedException();
        }
    }

    public class StringEqualityComparer : EqualityComparer<string>
    {
        private readonly Debugger mDebugger = new Debugger("Core", "String Equality Comparer");

        public override bool Equals(string x, string y)
        {
            mDebugger.Send("StringEqualityComparer.Equals");
            return String.Equals(x, y);
        }

        public override int GetHashCode(string obj)
        {
            mDebugger.Send("StringEqualityComparer.GetHashCode");

            return obj.GetHashCode();
        }
    }

    public class Int32EqualityComparer : EqualityComparer<int>
    {
        private readonly Debugger mDebugger = new Debugger("Core", "Int32 Equality Comparer");

        public override bool Equals(int x, int y)
        {
            mDebugger.Send("Int32EqualityComparer.Equals");
            return x == y;
        }

        public override int GetHashCode(int val)
        {
            mDebugger.Send("Int32EqualityComparer.GetHashCode");

            return val.GetHashCode();
        }
    }
}


text:
var helper = require("../../helper");
var Manager = require("../../../src/etl/dim-supplier-etl-manager");
var instanceManager = null;
var should = require("should");
var sqlHelper = require("../../sql-helper");

before("#00. connect db", function (done) {
    Promise.all([helper, sqlHelper])
        .then((result) => {
            var db = result[0];
            var sql = result[1];
            db.getDb().then((db) => {
                instanceManager = new Manager(db, {
                    username: "unit-test"
                }, sql);
                done();
            })
                .catch((e) => {
                    done(e);
                });
        });
});

it("#01. should success when create etl for dim-supplier", function (done) {
    instanceManager.run()
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#02. should success when transforming data for dim-category", function(done) {
    var data = [{}, {}];
    instanceManager.transform(data)
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#03. should error when load empty data", function (done) {
    instanceManager.load({})
        .then(id => {
            done("should error when create with empty data");
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});

it("#04. should error when insert empty data", function (done) {
    instanceManager.insertQuery(this.sql, "")
        .then((id) => {
            done("should error when create with empty data");
        })
        .catch((e) => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});


text:
/**
 * construct a new http response util
 *
 * @api public
 * @param response
 * the user get
 * @since 0.0.1 (06/26/2012)
 */
var HTTPResponseUtil = function(response) {

  if(typeof(response) === 'undefined') throw 'response is required';

  /**
   * answer with a file download
   *
   * @api public
   * @param {String} download
   * absolute path of download file
   * @param {Object} options
   * clientname the name of the file as presented to the client (browser decision by default, no header set)
   * @return {Integer} status code
   */
  this.download = function(download, options) {
    if (typeof (download) == 'undefined') throw 'download is required';
    var fs = require('fs');
    var data = fs.readFileSync(download);
    options = options || {};
    if(options.clientname) {
      response.setHeader('Content-Disposition', 'attachment; filename="'+options.clientname+'"');
    }
    response.setHeader('Content-Type', 'application/octet-stream');
    response.setHeader('Content-Length', data.length);
    response.write(data);
    response.end();
    return response.statusCode;
  };

  /**
   * answer with json (header is utf-8 and application/json)
   *
   * @api public
   * @param {Object} thing
   * an object or array to print out as json to the response
   * @return {Integer} status code
   */
  this.json = function(thing) {
    var result = null;
    try {
      response.charset = 'UTF-8';
      response.setHeader('Content-Type', 'application/json');
      result = thing;
    } catch(e) {
      result = {"error": e.message};
    }
    response.end(JSON.stringify(result));
    return response.statusCode;
  };

  /**
   * answer with jsonp (header is utf-8 and application/javascript)
   *
   * @api public
   * @param {Object} json
   * @param {string} name of callback function
   * an object or array to print out as json to the response
   * @return {Integer} status code
   */
  this.jsonp = function(json, callback) {
    var result = null;
    callback = callback || 'callback';
    try {
      response.charset = 'UTF-8';
      response.setHeader('Content-Type', 'application/javascript');
      result = json;
    } catch(e) {
      result = {"error": e.message};
    }
    response.end(callback + '(' + JSON.stringify(result) + ')');
    return response.statusCode;
  };

  /**
   * answer with xml (header is utf-8 and application/xml)
   *
   * @api public
   * @param {String} thing that is already xml. no check, no parsing here!
   * @return {Integer} status code
   */
  this.xml = function(thing) {
    var result = null;
    try {
      response.charset = 'UTF-8';
      response.setHeader('Content-Type', 'application/xml');
      result = thing;
    } catch(e) {
      result = {"error": e.message};
    }
    response.end(result);
    return response.statusCode;
  };
};

// line for node.js
if(typeof(exports) !== 'undefined' && typeof(exports.HTTPResponseUtil) === 'undefined') exports.HTTPResponseUtil = HTTPResponseUtil;


text:
<?php

/**
 * This is the model class for table "lookup".
 *
 * The followings are the available columns in table 'lookup':
 * @property integer $id
 * @property string $name
 * @property integer $code
 * @property string $type
 * @property integer $position
 */
class Lookup extends CActiveRecord
{
	private static $_items=array();

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'lookup';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, code, type, position', 'required'),
			array('code, position', 'numerical', 'integerOnly'=>true),
			array('name, type', 'length', 'max'=>255),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, name, code, type, position', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => 'Name',
			'code' => 'Code',
			'type' => 'Type',
			'position' => 'Position',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('code',$this->code);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('position',$this->position);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Lookup the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    public static function items($type)
    {
        if(!isset(self::$_items[$type]))
            self::loadItems($type);
        return self::$_items[$type];
    }

    public static function item($type,$code)
    {
        if(!isset(self::$_items[$type]))
            self::loadItems($type);
        return isset(self::$_items[$type][$code]) ? self::$_items[$type][$code] : false;
    }

    private static function loadItems($type)
    {
        self::$_items[$type]=array();
        $models=self::model()->findAll(array(
            'condition'=>'type=:type',
            'params'=>array(':type'=>$type),
            'order'=>'position',
        ));
        foreach($models as $model)
            self::$_items[$type][$model->code]=$model->name;
    }
}


text:
package com.google.debugging.sourcemap;

import com.google.debugging.sourcemap.proto.Mapping.OriginalMapping;

import java.util.Collection;

/**
 * A SourceMappingReversable is a SourceMapping that can provide the reverse
 * (source → target) source mapping.
 */
public interface SourceMappingReversable extends SourceMapping {

  /**
   * @return the collection of original sources in this source mapping
   */
  public Collection<String> getOriginalSources();

  /**
   * Given a source file, line, and column, return the reverse mapping (source → target).
   * A collection is returned as in some cases (like a function being inlined), one source line
   * may map to more then one target location. An empty collection is returned if there were
   * no matches.
   * @param originalFile the source file
   * @param line the source line
   * @param column the source column
   * @return the reverse mapping (source → target)
   */
  public Collection<OriginalMapping> getReverseMapping(String originalFile, int line, int column);

}


text:
Adds text to the text fragment.

**Arguments:**

- **str** - the string
- **opts** - styling options

**Options:**

Same as [doc.text([text], [opts])](document.md#texttext-opts)

### .line(text, [opts])

Same as [text.add(text, [opts])](#addtext-opts), but adds an additional line break add the end of the provided text.

### .append(text, [opts])

Same as [text.add(text, [opts])](#addtext-opts), but directly appends the text, i.e., adds the text without a space.

### .br()

Adds a line break.

### .pageNumber([opts])
### .appendPageNumber([opts])

Adds/appends the current page number to the text fragment.

**Arguments:**

- **opts** - styling options

**Options:**

Same as [doc.text([text], [opts])](document.md#texttext-opts)

### .pageCount([opts])
### .appendPageCount([opts])

Adds/appends the documents total page count to the text fragment.

**Arguments:**

- **opts** - styling options

**Options:**

Same as [doc.text([text], [opts])](document.md#texttext-opts)


text:
var express = require('express');
var app = express();
var mValue = 'f.value';

app.get('/p.math.numberlist/v.math.sum', function (req, res){
	var numbers = req.query[mValue]?req.query[mValue].split(','):[];
	var sum = numbers.reduce(function(a,b){return parseFloat(a)+parseFloat(b);});
	res.send(sum.toString());
});

var server = app.listen(8280,function(){
	var host = server.address().address;
	var port = server.address().port;

	console.log('Sample math service listening at http://%s:%s', host, port);
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Azure.AI.FormRecognizer.Training;
using Azure.Core;

namespace Azure.AI.FormRecognizer.Models
{
    /// <summary> Custom model training result. </summary>
    internal partial class TrainResult
    {
        /// <summary> Initializes a new instance of TrainResult. </summary>
        /// <param name="trainingDocuments"> List of the documents used to train the model and any errors reported in each document. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="trainingDocuments"/> is null. </exception>
        internal TrainResult(IEnumerable<TrainingDocumentInfo> trainingDocuments)
        {
            Argument.AssertNotNull(trainingDocuments, nameof(trainingDocuments));

            TrainingDocuments = trainingDocuments.ToList();
            Fields = new ChangeTrackingList<CustomFormModelField>();
            Errors = new ChangeTrackingList<FormRecognizerError>();
        }

        /// <summary> Initializes a new instance of TrainResult. </summary>
        /// <param name="trainingDocuments"> List of the documents used to train the model and any errors reported in each document. </param>
        /// <param name="fields"> List of fields used to train the model and the train operation error reported by each. </param>
        /// <param name="averageModelAccuracy"> Average accuracy. </param>
        /// <param name="modelId"> Model identifier. </param>
        /// <param name="errors"> Errors returned during the training operation. </param>
        internal TrainResult(IReadOnlyList<TrainingDocumentInfo> trainingDocuments, IReadOnlyList<CustomFormModelField> fields, float? averageModelAccuracy, string modelId, IReadOnlyList<FormRecognizerError> errors)
        {
            TrainingDocuments = trainingDocuments;
            Fields = fields;
            AverageModelAccuracy = averageModelAccuracy;
            ModelId = modelId;
            Errors = errors;
        }

        /// <summary> List of the documents used to train the model and any errors reported in each document. </summary>
        public IReadOnlyList<TrainingDocumentInfo> TrainingDocuments { get; }
        /// <summary> List of fields used to train the model and the train operation error reported by each. </summary>
        public IReadOnlyList<CustomFormModelField> Fields { get; }
        /// <summary> Average accuracy. </summary>
        public float? AverageModelAccuracy { get; }
        /// <summary> Errors returned during the training operation. </summary>
        public IReadOnlyList<FormRecognizerError> Errors { get; }
    }
}


text:
var gulp = require('gulp')
var sass = require('gulp-ruby-sass')
var autoprefixer = require('gulp-autoprefixer')

gulp.task('build', function () {
  return sass('scss/*.scss', {
    style: 'compressed',
    noCache: true
  }).on('error', function (err) {
    console.error(err)
  }).pipe(autoprefixer())
  .pipe(gulp.dest('css'))
})

gulp.task('watch', function () {
  gulp.watch('scss/*.scss', ['build'])
})


text:
.class public final Lorg/codehaus/jackson/node/BigIntegerNode;
.super Lorg/codehaus/jackson/node/NumericNode;
.source "BigIntegerNode.java"

# instance fields
.field protected final _value:Ljava/math/BigInteger;

# direct methods
.method public constructor <init>(Ljava/math/BigInteger;)V
    .locals 0
    .param p1, "v"    # Ljava/math/BigInteger;

    .prologue
    .line 24
    invoke-direct {p0}, Lorg/codehaus/jackson/node/NumericNode;-><init>()V

    iput-object p1, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    return-void
.end method

.method public static valueOf(Ljava/math/BigInteger;)Lorg/codehaus/jackson/node/BigIntegerNode;
    .locals 1
    .param p0, "v"    # Ljava/math/BigInteger;

    .prologue
    .line 26
    new-instance v0, Lorg/codehaus/jackson/node/BigIntegerNode;

    invoke-direct {v0, p0}, Lorg/codehaus/jackson/node/BigIntegerNode;-><init>(Ljava/math/BigInteger;)V

    return-object v0
.end method

# virtual methods
.method public asBoolean(Z)Z
    .locals 2
    .param p1, "defaultValue"    # Z

    .prologue
    .line 79
    sget-object v0, Ljava/math/BigInteger;->ZERO:Ljava/math/BigInteger;

    iget-object v1, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    invoke-virtual {v0, v1}, Ljava/math/BigInteger;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-nez v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public asText()Ljava/lang/String;
    .locals 1

    .prologue
    .line 74
    iget-object v0, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    invoke-virtual {v0}, Ljava/math/BigInteger;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public asToken()Lorg/codehaus/jackson/JsonToken;
    .locals 1

    .prologue
    .line 35
    sget-object v0, Lorg/codehaus/jackson/JsonToken;->VALUE_NUMBER_INT:Lorg/codehaus/jackson/JsonToken;

    return-object v0
.end method

.method public equals(Ljava/lang/Object;)Z
    .locals 3
    .param p1, "o"    # Ljava/lang/Object;

    .prologue
    const/4 v0, 0x0

    .line 92
    if-ne p1, p0, :cond_1

    const/4 v0, 0x1

    .line 97
    .end local p1    # "o":Ljava/lang/Object;
    :cond_0
    :goto_0
    return v0

    .line 93
    .restart local p1    # "o":Ljava/lang/Object;
    :cond_1
    if-eqz p1, :cond_0

    .line 94
    invoke-virtual {p1}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    if-ne v1, v2, :cond_0

    .line 97
    check-cast p1, Lorg/codehaus/jackson/node/BigIntegerNode;

    .end local p1    # "o":Ljava/lang/Object;
    iget-object v0, p1, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    iget-object v1, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    invoke-virtual {v0, v1}, Ljava/math/BigInteger;->equals(Ljava/lang/Object;)Z

    move-result v0

    goto :goto_0
.end method

.method public getBigIntegerValue()Ljava/math/BigInteger;
    .locals 1

    .prologue
    .line 58
    iget-object v0, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    return-object v0
.end method

.method public getDecimalValue()Ljava/math/BigDecimal;
    .locals 2

    .prologue
    .line 64
    new-instance v0, Ljava/math/BigDecimal;

    iget-object v1, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    invoke-direct {v0, v1}, Ljava/math/BigDecimal;-><init>(Ljava/math/BigInteger;)V

    return-object v0
.end method

.method public getDoubleValue()D
    .locals 2

    .prologue
    .line 61
    iget-object v0, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    invoke-virtual {v0}, Ljava/math/BigInteger;->doubleValue()D

    move-result-wide v0

    return-wide v0
.end method

.method public getIntValue()I
    .locals 1

    .prologue
    .line 52
    iget-object v0, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    invoke-virtual {v0}, Ljava/math/BigInteger;->intValue()I

    move-result v0

    return v0
.end method

.method public getLongValue()J
    .locals 2

    .prologue
    .line 55
    iget-object v0, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    invoke-virtual {v0}, Ljava/math/BigInteger;->longValue()J

    move-result-wide v0

    return-wide v0
.end method

.method public getNumberType()Lorg/codehaus/jackson/JsonParser$NumberType;
    .locals 1

    .prologue
    .line 38
    sget-object v0, Lorg/codehaus/jackson/JsonParser$NumberType;->BIG_INTEGER:Lorg/codehaus/jackson/JsonParser$NumberType;

    return-object v0
.end method

.method public getNumberValue()Ljava/lang/Number;
    .locals 1

    .prologue
    .line 48
    iget-object v0, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    return-object v0
.end method

.method public hashCode()I
    .locals 1

    .prologue
    .line 102
    iget-object v0, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    invoke-virtual {v0}, Ljava/math/BigInteger;->hashCode()I

    move-result v0

    return v0
.end method

.method public isBigInteger()Z
    .locals 1

    .prologue
    .line 44
    const/4 v0, 0x1

    return v0
.end method

.method public isIntegralNumber()Z
    .locals 1

    .prologue
    .line 41
    const/4 v0, 0x1

    return v0
.end method

.method public final serialize(Lorg/codehaus/jackson/JsonGenerator;Lorg/codehaus/jackson/map/SerializerProvider;)V
    .locals 1
    .param p1, "jg"    # Lorg/codehaus/jackson/JsonGenerator;
    .param p2, "provider"    # Lorg/codehaus/jackson/map/SerializerProvider;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;,
            Lorg/codehaus/jackson/JsonProcessingException;
        }
    .end annotation

    .prologue
    .line 86
    iget-object v0, p0, Lorg/codehaus/jackson/node/BigIntegerNode;->_value:Ljava/math/BigInteger;

    invoke-virtual {p1, v0}, Lorg/codehaus/jackson/JsonGenerator;->writeNumber(Ljava/math/BigInteger;)V

    .line 87
    return-void
.end method


text:
int main()
{
  printf("Reverse Polish notation calculator with long arithmetic.\nBig numbers will be saved in Stack.\n'+' '-' '*' '/' -- standard operations.\n'=' -- output Stack head.\n's' -- output entire Stack.\n'q' -- quit.\n");
  while (1) {
    char c = getchar();
    switch (c) {
    case '+':
      if(stack_head && stack_head->next) {
        Addition( stack_head->next->sign, stack_head->sign);
        break;
      } else {
        printf("Not enough operands! -- empty stack.\n");
        break;
      }
    case '*':
      if(stack_head && stack_head->next) {
        Multiplication(stack_head->next->sign, stack_head->sign);
        break;
      } else {
        printf("Not enough operands! -- empty stack.\n");
        break;
      }
    case '/':
      if(stack_head && stack_head->next) {
        Division(stack_head->next->sign, stack_head->sign, stack_head->next->head, stack_head->head);
        break;
      } else {
        printf("Not enough operands! -- empty stack.\n");
        break;
      }
    case '-':
      if ((c = getchar()) != '\n') {
        BignumInput(c, '1');
        break;
      }
      if(stack_head && stack_head->next) {
        Subtraction( stack_head->next->sign, stack_head->sign);
        break;
      } else {
        printf("Not enough operands! -- empty stack.\n");
        break;
      }
    case '=':
      if (stack_head->sign == '1') {
        printf("-");
      };
      BignumOutput(stack_head->tail);
      break;
    case 's':
      StackOutput();
      break;
    case 'q':
      StackFree();
      return 0;
    default:
      if (c != '\n') {
        BignumInput(c, '0');
        break;
      }
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 321901 $ -->

<refentry xml:id="gmagickpixel.construct" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>GmagickPixel::__construct</refname>
  <refpurpose>The GmagickPixel constructor</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <modifier>public</modifier> <methodname>GmagickPixel::__construct</methodname>
   <methodparam choice="opt"><type>string</type><parameter>color</parameter></methodparam>
  </methodsynopsis>
  <para>
   Constructs an GmagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.
  </para>

 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>color</parameter></term>
     <listitem>
      <para>
       The optional color string to use as the initial value of this object.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   The GmagickPixel object on success.
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// Main header first:
#include "nsSVGContainerFrame.h"

// Keep others in (case-insensitive) order:
#include "nsError.h"
#include "nsSVGGlyphFrame.h"
#include "nsSVGTextFrame.h"
#include "nsSVGUtils.h"
#include "SVGAnimatedNumberList.h"
#include "SVGLengthList.h"
#include "SVGNumberList.h"

using namespace mozilla;

//----------------------------------------------------------------------
// nsQueryFrame methods

NS_QUERYFRAME_HEAD(nsSVGTextContainerFrame)
  NS_QUERYFRAME_ENTRY(nsSVGTextContainerFrame)
NS_QUERYFRAME_TAIL_INHERITING(nsSVGDisplayContainerFrame)

NS_IMPL_FRAMEARENA_HELPERS(nsSVGTextContainerFrame)

void
nsSVGTextContainerFrame::NotifyGlyphMetricsChange()
{
  nsSVGTextFrame *textFrame = GetTextFrame();
  if (textFrame)
    textFrame->NotifyGlyphMetricsChange();
}

void
nsSVGTextContainerFrame::GetXY(SVGUserUnitList *aX, SVGUserUnitList *aY)
{
  static_cast<nsSVGElement*>(mContent)->
    GetAnimatedLengthListValues(aX, aY, nullptr);
}

void
nsSVGTextContainerFrame::GetDxDy(SVGUserUnitList *aDx, SVGUserUnitList *aDy)
{
  // SVGUserUnitList is lazy, so there's little overhead it getting the x
  // and y lists even though we ignore them.
  SVGUserUnitList xLengthList, yLengthList;
  static_cast<nsSVGElement*>(mContent)->
    GetAnimatedLengthListValues(&xLengthList, &yLengthList, aDx, aDy, nullptr);
}

const SVGNumberList*
nsSVGTextContainerFrame::GetRotate()
{
  SVGAnimatedNumberList *animList =
    static_cast<nsSVGElement*>(mContent)->
      GetAnimatedNumberList(nsGkAtoms::rotate);
  return animList ? &animList->GetAnimValue() : nullptr;
}

//----------------------------------------------------------------------
// nsIFrame methods

NS_IMETHODIMP
nsSVGTextContainerFrame::InsertFrames(ChildListID aListID,
                                      nsIFrame* aPrevFrame,
                                      nsFrameList& aFrameList)
{
  nsresult rv = nsSVGDisplayContainerFrame::InsertFrames(aListID,
                                                         aPrevFrame,
                                                         aFrameList);

  NotifyGlyphMetricsChange();
  return rv;
}

NS_IMETHODIMP
nsSVGTextContainerFrame::RemoveFrame(ChildListID aListID, nsIFrame *aOldFrame)
{
  nsSVGTextFrame *textFrame = GetTextFrame();

  nsresult rv = nsSVGDisplayContainerFrame::RemoveFrame(aListID, aOldFrame);

  if (textFrame)
    textFrame->NotifyGlyphMetricsChange();

  return rv;
}

NS_IMETHODIMP
nsSVGTextContainerFrame::GetStartPositionOfChar(uint32_t charnum, nsIDOMSVGPoint **_retval)
{
  *_retval = nullptr;

  if (charnum >= GetNumberOfChars()) {
    return NS_ERROR_DOM_INDEX_SIZE_ERR;
  }

  nsISVGGlyphFragmentNode *node = GetFirstGlyphFragmentChildNode();
  if (!node) {
    return NS_ERROR_FAILURE;
  }

  uint32_t offset;
  nsSVGGlyphFrame *frame = GetGlyphFrameAtCharNum(node, charnum, &offset);
  if (!frame) {
    return NS_ERROR_FAILURE;
  }

  return frame->GetStartPositionOfChar(charnum - offset, _retval);
}

NS_IMETHODIMP
nsSVGTextContainerFrame::GetEndPositionOfChar(uint32_t charnum, nsIDOMSVGPoint **_retval)
{
  *_retval = nullptr;

  if (charnum >= GetNumberOfChars()) {
    return NS_ERROR_DOM_INDEX_SIZE_ERR;
  }

  nsISVGGlyphFragmentNode *node = GetFirstGlyphFragmentChildNode();
  if (!node) {
    return NS_ERROR_FAILURE;
  }

  uint32_t offset;
  nsSVGGlyphFrame *frame = GetGlyphFrameAtCharNum(node, charnum, &offset);
  if (!frame) {
    return NS_ERROR_FAILURE;
  }

  return frame->GetEndPositionOfChar(charnum - offset, _retval);
}

NS_IMETHODIMP
nsSVGTextContainerFrame::GetExtentOfChar(uint32_t charnum, nsIDOMSVGRect **_retval)
{
  *_retval = nullptr;

  if (charnum >= GetNumberOfChars()) {
    return NS_ERROR_DOM_INDEX_SIZE_ERR;
  }

  nsISVGGlyphFragmentNode *node = GetFirstGlyphFragmentChildNode();
  if (!node) {
    return NS_ERROR_FAILURE;
  }

  uint32_t offset;
  nsSVGGlyphFrame *frame = GetGlyphFrameAtCharNum(node, charnum, &offset);
  if (!frame) {
    return NS_ERROR_FAILURE;
  }

  return frame->GetExtentOfChar(charnum - offset, _retval);
}

NS_IMETHODIMP
nsSVGTextContainerFrame::GetRotationOfChar(uint32_t charnum, float *_retval)
{
  *_retval = 0.0f;

  if (charnum >= GetNumberOfChars()) {
    return NS_ERROR_DOM_INDEX_SIZE_ERR;
  }

  nsISVGGlyphFragmentNode *node = GetFirstGlyphFragmentChildNode();
  if (!node) {
    return NS_ERROR_FAILURE;
  }

  uint32_t offset;
  nsSVGGlyphFrame *frame = GetGlyphFrameAtCharNum(node, charnum, &offset);
  if (!frame) {
    return NS_ERROR_FAILURE;
  }

  return frame->GetRotationOfChar(charnum - offset, _retval);
}

uint32_t
nsSVGTextContainerFrame::GetNumberOfChars()
{
  uint32_t nchars = 0;
  nsISVGGlyphFragmentNode* node = GetFirstGlyphFragmentChildNode();

  while (node) {
    nchars += node->GetNumberOfChars();
    node = GetNextGlyphFragmentChildNode(node);
  }

  return nchars;
}

float
nsSVGTextContainerFrame::GetComputedTextLength()
{
  float length = 0.0f;
  nsISVGGlyphFragmentNode* node = GetFirstGlyphFragmentChildNode();

  while (node) {
    length += node->GetComputedTextLength();
    node = GetNextGlyphFragmentChildNode(node);
  }

  return length;
}

float
nsSVGTextContainerFrame::GetSubStringLength(uint32_t charnum, uint32_t nchars)
{
  float length = 0.0f;
  nsISVGGlyphFragmentNode *node = GetFirstGlyphFragmentChildNode();

  while (node) {
    uint32_t count = node->GetNumberOfChars();
    if (count > charnum) {
      uint32_t fragmentChars = NS_MIN(nchars, count - charnum);
      float fragmentLength = node->GetSubStringLength(charnum, fragmentChars);
      length += fragmentLength;
      nchars -= fragmentChars;
      if (nchars == 0) break;
    }
    charnum -= NS_MIN(charnum, count);
    node = GetNextGlyphFragmentChildNode(node);
  }

  return length;
}

int32_t
nsSVGTextContainerFrame::GetCharNumAtPosition(nsIDOMSVGPoint *point)
{
  int32_t index = -1;
  int32_t offset = 0;
  nsISVGGlyphFragmentNode *node = GetFirstGlyphFragmentChildNode();

  while (node) {
    uint32_t count = node->GetNumberOfChars();
    if (count > 0) {
      int32_t charnum = node->GetCharNumAtPosition(point);
      if (charnum >= 0) {
        index = charnum + offset;
      }
      offset += count;
      // Keep going, multiple characters may match
      // and we must return the last one
    }
    node = GetNextGlyphFragmentChildNode(node);
  }

  return index;
}

// -------------------------------------------------------------------------
// Protected functions
// -------------------------------------------------------------------------

nsISVGGlyphFragmentNode *
nsSVGTextContainerFrame::GetFirstGlyphFragmentChildNode()
{
  nsISVGGlyphFragmentNode *retval = nullptr;
  nsIFrame* kid = mFrames.FirstChild();
  while (kid) {
    retval = do_QueryFrame(kid);
    if (retval) break;
    kid = kid->GetNextSibling();
  }
  return retval;
}

nsISVGGlyphFragmentNode *
nsSVGTextContainerFrame::GetNextGlyphFragmentChildNode(nsISVGGlyphFragmentNode *node)
{
  nsISVGGlyphFragmentNode *retval = nullptr;
  nsIFrame *frame = do_QueryFrame(node);
  NS_ASSERTION(frame, "interface not implemented");
  frame = frame->GetNextSibling();
  while (frame) {
    retval = do_QueryFrame(frame);
    if (retval) break;
    frame = frame->GetNextSibling();
  }
  return retval;
}

// -------------------------------------------------------------------------
// Private functions
// -------------------------------------------------------------------------

nsSVGGlyphFrame *
nsSVGTextContainerFrame::GetGlyphFrameAtCharNum(nsISVGGlyphFragmentNode* node,
                                                uint32_t charnum,
                                                uint32_t *offset)
{
  nsSVGGlyphFrame *frame = node->GetFirstGlyphFrame();
  *offset = 0;

  while (frame) {
    uint32_t count = frame->GetNumberOfChars();
    if (count > charnum)
      return frame;
    charnum -= count;
    *offset += count;
    frame = frame->GetNextGlyphFrame();
  }

  // not found
  return nullptr;
}

nsSVGTextFrame *
nsSVGTextContainerFrame::GetTextFrame()
{
  for (nsIFrame *frame = this; frame != nullptr; frame = frame->GetParent()) {
    if (frame->GetType() == nsGkAtoms::svgTextFrame) {
      return static_cast<nsSVGTextFrame*>(frame);
    }
  }
  return nullptr;
}

void
nsSVGTextContainerFrame::CopyPositionList(nsTArray<float> *parentList,
                                        SVGUserUnitList *selfList,
                                        nsTArray<float> &dstList,
                                        uint32_t aOffset)
{
  dstList.Clear();

  uint32_t strLength = GetNumberOfChars();
  uint32_t parentCount = 0;
  if (parentList && parentList->Length() > aOffset) {
    parentCount = NS_MIN(parentList->Length() - aOffset, strLength);
  }

  uint32_t selfCount = NS_MIN(selfList->Length(), strLength);

  uint32_t count = NS_MAX(parentCount, selfCount);

  if (!dstList.SetLength(count))
    return;

  for (uint32_t i = 0; i < selfCount; i++) {
    dstList[i] = (*selfList)[i];
  }
  for (uint32_t i = selfCount; i < parentCount; i++) {
    dstList[i] = (*parentList)[aOffset + i];
  }

}

void
nsSVGTextContainerFrame::CopyRotateList(nsTArray<float> *parentList,
                                        const SVGNumberList *selfList,
                                        nsTArray<float> &dstList,
                                        uint32_t aOffset)
{
  dstList.Clear();

  uint32_t strLength = GetNumberOfChars();
  uint32_t parentCount = 0;
  if (parentList && parentList->Length() > aOffset) {
    parentCount = NS_MIN(parentList->Length() - aOffset, strLength);
  }

  uint32_t selfCount = NS_MIN(selfList ? selfList->Length() : 0, strLength);
  uint32_t count = NS_MAX(parentCount, selfCount);

  if (count > 0) {
    if (!dstList.SetLength(count))
      return;
    for (uint32_t i = 0; i < selfCount; i++) {
      dstList[i] = (*selfList)[i];
    }
    for (uint32_t i = selfCount; i < parentCount; i++) {
      dstList[i] = (*parentList)[aOffset + i];
    }
  } else if (parentList && !parentList->IsEmpty()) {
    // rotate is applied to extra characters too
    dstList.AppendElement((*parentList)[parentList->Length() - 1]);
  }
}

uint32_t
nsSVGTextContainerFrame::BuildPositionList(uint32_t aOffset,
                                           uint32_t aDepth)
{
  nsSVGTextContainerFrame *parent = do_QueryFrame(mParent);
  nsTArray<float> *parentX = nullptr, *parentY = nullptr;
  nsTArray<float> *parentDx = nullptr, *parentDy = nullptr;
  nsTArray<float> *parentRotate = nullptr;
  if (parent) {
    parentX = &(parent->mX);
    parentY = &(parent->mY);
    parentDx = &(parent->mDx);
    parentDy = &(parent->mDy);
    parentRotate = &(parent->mRotate);
  }

  SVGUserUnitList x, y;
  GetXY(&x, &y);
  CopyPositionList(parentX, &x, mX, aOffset);
  CopyPositionList(parentY, &y, mY, aOffset);

  SVGUserUnitList dx, dy;
  GetDxDy(&dx, &dy);
  CopyPositionList(parentDx, &dx, mDx, aOffset);
  CopyPositionList(parentDy, &dy, mDy, aOffset);

  const SVGNumberList *rotate = GetRotate();
  CopyRotateList(parentRotate, rotate, mRotate, aOffset);

  uint32_t startIndex = 0;
  nsIFrame* kid = mFrames.FirstChild();
  while (kid) {
    nsSVGTextContainerFrame *text = do_QueryFrame(kid);
    if (text) {
      startIndex += text->BuildPositionList(startIndex, aDepth + 1);
    } else if (kid->GetType() == nsGkAtoms::svgGlyphFrame) {
      nsSVGGlyphFrame *leaf = static_cast<nsSVGGlyphFrame*>(kid);
      leaf->SetStartIndex(startIndex);
      startIndex += leaf->GetNumberOfChars();
    }
    kid = kid->GetNextSibling();
  }
  return startIndex;
}

void
nsSVGTextContainerFrame::GetEffectiveXY(nsTArray<float> &aX,
                                        nsTArray<float> &aY)
{
  aX.AppendElements(mX);
  aY.AppendElements(mY);
}

void
nsSVGTextContainerFrame::GetEffectiveDxDy(nsTArray<float> &aDx,
                                          nsTArray<float> &aDy)
{
  aDx.AppendElements(mDx);
  aDy.AppendElements(mDy);
}

void
nsSVGTextContainerFrame::GetEffectiveRotate(nsTArray<float> &aRotate)
{
  aRotate.AppendElements(mRotate);
}

void
nsSVGTextContainerFrame::SetWhitespaceCompression()
{
  bool compressWhitespace = true;

  for (const nsIFrame *frame = this; frame != nullptr; frame = frame->GetParent()) {
    static const nsIContent::AttrValuesArray strings[] =
      {&nsGkAtoms::preserve, &nsGkAtoms::_default, nullptr};

    int32_t index = frame->GetContent()->FindAttrValueIn(
                                           kNameSpaceID_XML,
                                           nsGkAtoms::space,
                                           strings, eCaseMatters);
    if (index == 0) {
      compressWhitespace = false;
      break;
    }
    if (index != nsIContent::ATTR_MISSING ||
        (frame->GetStateBits() & NS_STATE_IS_OUTER_SVG))
      break;
  }

  nsISVGGlyphFragmentNode* node = GetFirstGlyphFragmentChildNode();

  while (node) {
    node->SetWhitespaceCompression(compressWhitespace);
    node = GetNextGlyphFragmentChildNode(node);
  }
}


text:
This package has been renamed, and so this version has been deprecated.

Development is continuing under the name [@sipcentric/pbx-client](https://www.npmjs.com/package/@sipcentric/pbx-client), please use that instead.

---

# Nimvelo Node.js Client

Node.js client for the [Nimvelo/Sipcentric API](https://developer.nimvelo.com/).

## Usage

```
npm install @nimvelo/phone-api-client
```

```js
const Nimvelo = require("@nimvelo/phone-api-client");

// ...
```

## Getting started

### Examples

The techniques shown in these examples work in the same way across the majority of resources. Refer to the API documentation for more information on those specific resources.

The examples below use Promises with async/await, however the library also supports callbacks. To use callbacks, simply pass a callback as the final parameter.

```js
// Using async/await
const customers = await nimvelo.customers.get();
doStuffWith(customers);

// Using callbacks
nimvelo.customers.get((err, customers) => {
  doStuffWith(customers);
});
```

There are further examples in the `examples/` directory. To try them, just clone the project, run an install in the project root, then again in the directory of the example you want to run. Finally, run `npm start` and the example will run.

#### Get all customers a user has access to

```js
const Nimvelo = require("@nimvelo/phone-api-client");

(async () => {
  const nimvelo = new Nimvelo({
    username: "myusername",
    password: "mypassword"
  });

  const customers = await nimvelo.customers.get();
  console.log(customers);
})();
```

#### Get a specific customer

```js
const Nimvelo = require("@nimvelo/phone-api-client");

(async () => {
  const nimvelo = new Nimvelo({
    username: "myusername",
    password: "mypassword"
  });

  const customerId = 1234;

  const customer = await nimvelo.customers.get(customerId);
  console.log(customer);
})();
```

#### Get a customer's phone book

```js
const Nimvelo = require("@nimvelo/phone-api-client");

(async () => {
  const nimvelo = new Nimvelo({
    username: "myusername",
    password: "mypassword"
  });

  const customerId = 1234;

  const customer = await nimvelo.customers.get(customerId);
  const phonebook = await customer.phonebook.get();

  console.log(phonebook);
})();
```

#### Create phone book entry

```js
const Nimvelo = require("@nimvelo/phone-api-client");

(async () => {
  const nimvelo = new Nimvelo({
    username: "myusername",
    password: "mypassword"
  });

  const customerId = 1234;

  const customer = await nimvelo.customers.get(customerId);
  const phonebookentry = {
    name: "Nimvelo",
    phoneNumber: "03301200030",
    email: "hello@nimvelo.com"
  };

  const createdEntry = await customer.phonebook.create(phonebookentry).save();

  console.log(createdEntry);
})();
```

#### Update phone book entry

```js
const Nimvelo = require("@nimvelo/phone-api-client");

(async () => {
  const nimvelo = new Nimvelo({
    username: "myusername",
    password: "mypassword"
  });

  const customerId = 1234;
  const phonebookentryId = 5678;

  const customer = await nimvelo.customers.get(customerId);
  const phonebookentry = await customer.phonebook.get(phonebookentryId);

  phonebookentry.name = "Updated name";

  const savedEntry = await phonebookentry.save();

  console.log(savedEntry);
})();
```

#### Delete phone book entry

```js
const Nimvelo = require("@nimvelo/phone-api-client");

(async () => {
  const nimvelo = new Nimvelo({
    username: "myusername",
    password: "mypassword"
  });

  const customerId = 1234;
  const phonebookentryId = 5678;

  const customer = await nimvelo.customers.get(customerId);
  const phonebookentry = await customer.phonebook.get(phonebookentryId);

  await phonebookentry.delete();
})();
```

#### Subscribe to incoming call events

```js
const Nimvelo = require("@nimvelo/phone-api-client");

const nimvelo = new Nimvelo({
  username: "myusername",
  password: "mypassword"
});

nimvelo.stream.subscribe("incomingcall", function(call) {
  console.log(call);
});
```

#### Monitor presence of an extension

```js
const Nimvelo = require("@nimvelo/phone-api-client");

const nimvelo = new Nimvelo({
  username: "myusername",
  password: "mypassword"
});

const myCustomerId = 1; // Change this to your customer ID

// Returns an array of subscriptions
const subscriptions = await nimvelo.presenceWatcher.subscribe({
  customerId: myCustomerId,
  targets: ["012345"], // The extensions you'd like to monitor
  onStateChange: (extension, newState) => {
    console.log(extension); // 012345
    console.log(newState); // AVAILABLE, BUSY, or RINGING
  }
});
```

#### Monitor presence of all extensions on an account

```js
const Nimvelo = require("@nimvelo/phone-api-client");

const nimvelo = new Nimvelo({
  username: "myusername",
  password: "mypassword"
});

const subscribeToAll = async () => {
  const myCustomerId = 1; // Change this to your customer ID
  // Get your customer
  const customer = await nimvelo.customers.get(myCustomerId);
  // Get a list of all regular extensions
  const phones = await customer.phones.get();

  // Get the ids of each extension
  const extensionIds = phones.items.map(x => x.id);

  // Subscribe to each extension
  const subscriptions = await nimvelo.presenceWatcher.subscribe({
    customerId: myCustomerId,
    targets: extensionIds,
    onStateChange: (extension, newState) => {
      console.log(extension);
      console.log(newState);
    }
  });
};

try {
  subscribeToAll();
} catch (err) {
  console.error("Error: ", err);
}
```


text:
package liquibase.sqlgenerator.core;

import liquibase.database.Database;
import liquibase.datatype.DataTypeFactory;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.exception.ValidationErrors;
import liquibase.sql.Sql;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.sqlgenerator.SqlGeneratorFactory;
import liquibase.statement.core.LockDatabaseChangeLogStatement;
import liquibase.statement.core.UpdateStatement;
import liquibase.util.NetUtil;

import java.net.InetAddress;
import java.sql.Timestamp;

public class LockDatabaseChangeLogGenerator extends AbstractSqlGenerator<LockDatabaseChangeLogStatement> {

    @Override
    public ValidationErrors validate(LockDatabaseChangeLogStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
        return new ValidationErrors();
    }

    protected static String hostname;
    protected static String hostaddress;

    static {
        InetAddress localHost;
        try {
            localHost = NetUtil.getLocalHost();
            hostname = localHost.getHostName();
            hostaddress = localHost.getHostAddress();
        } catch (Exception e) {
            throw new UnexpectedLiquibaseException(e);
        }
    }

    @Override
    public Sql[] generateSql(LockDatabaseChangeLogStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    	String liquibaseSchema = database.getLiquibaseSchemaName();
        String liquibaseCatalog = database.getLiquibaseCatalogName();

        UpdateStatement updateStatement = new UpdateStatement(liquibaseCatalog, liquibaseSchema, database.getDatabaseChangeLogLockTableName());
        updateStatement.addNewColumnValue("LOCKED", true);
        updateStatement.addNewColumnValue("LOCKGRANTED", new Timestamp(new java.util.Date().getTime()));
        updateStatement.addNewColumnValue("LOCKEDBY", hostname + " (" + hostaddress + ")");
        updateStatement.setWhereClause(database.escapeColumnName(liquibaseCatalog, liquibaseSchema, database.getDatabaseChangeLogTableName(), "ID") + " = 1 AND " + database.escapeColumnName(liquibaseCatalog, liquibaseSchema, database.getDatabaseChangeLogTableName(), "LOCKED") + " = "+ DataTypeFactory.getInstance().fromDescription("boolean").objectToSql(false, database));

        return SqlGeneratorFactory.getInstance().generateSql(updateStatement, database);

    }
}


text:
import R from 'ramda'
import {
  LOGIN_SUCCESS,
  REGISTER_SUCCESS,
  LOAD_INVITE_API_SUCCESS,
  ACCEPT_INVITE_SUCCESS,
  SELECT_ACCOUNT,
  COMMIT_SANITIZED_ACTION_LOG_REQUEST,
  COMMIT_SANITIZED_ACTION_LOG_FAILED,
  COMMIT_SANITIZED_ACTION_LOG_SUCCESS,
  SELECT_ORG,
  API_SUCCESS,
  API_FAILED
} from "actions"
import {isClearSessionAction} from './helpers'
import {sanitizeAction, sanitizeState} from '../lib/log'
import diff from 'deep-diff'

function renderDiff(diff) {
  const { kind, path, index, item, lhs, rhs } = diff

  switch (kind) {
    case 'E':
      return [path.join('.'), lhs, '→', rhs]
    case 'N':
      return [path.join('.'), rhs]
    case 'D':
      return [path.join('.')]
    case 'A':
      return [`${path.join('.')}[${index}]`, item]
    default:
      return []
  }
}

const sessionId = (state = null, action)=>{
    if (isClearSessionAction(action, {except: [SELECT_ORG, SELECT_ACCOUNT]})){
      return null
    }

    switch (action.type){
      case LOGIN_SUCCESS:
      case REGISTER_SUCCESS:
      case LOAD_INVITE_API_SUCCESS:
      case ACCEPT_INVITE_SUCCESS:
      case SELECT_ACCOUNT:
        return action.meta.sessionId
      default:
        return state || (action.meta && action.meta.sessionId) || null
    }
  },

  getSanitizedActionLogReducer = (prevState, nextState) => (state = {}, action)=> {
    if (action.type == COMMIT_SANITIZED_ACTION_LOG_REQUEST){
      return R.omit(R.keys(action.payload.clientSessions), state)
    } else if (action.type == COMMIT_SANITIZED_ACTION_LOG_FAILED){
      return R.mergeDeepWith(
        R.pipe(R.concat, R.sortBy(R.prop('timestamp'))),
        state,
        action.meta.requestPayload.clientSessions
       )
    } else if (
      action.meta &&
      action.meta.sessionId &&
      ![COMMIT_SANITIZED_ACTION_LOG_SUCCESS,
        COMMIT_SANITIZED_ACTION_LOG_FAILED,
        API_SUCCESS,
        API_FAILED].includes(action.type)
    ) {
      const
        {sessionId, timestamp} = action.meta,
        diffs = diff(sanitizeState(prevState), sanitizeState(nextState)) || [],
        sanitized = {
          action: sanitizeAction(action),
          diff: diffs.map(renderDiff),
          timestamp
        },
        existing = state[sessionId],
        res = existing ? existing.concat([sanitized]) : [sanitized]
      return {...state, [sessionId]: res}
    }

    return state
  }

export default function (mainReducer){
  return (state={}, action)=> {
    let nextState = mainReducer(R.omit(["sessionId", "sanitizedActionLog"], state), action)
    nextState = R.assoc("sessionId", sessionId(state.sessionId, action), nextState)
    nextState = R.assoc(
      "sanitizedActionLog",
      getSanitizedActionLogReducer(state, nextState)(state.sanitizedActionLog, action),
      nextState
    )
    return nextState
  }
}


text:
{reporte}

				Mapa

				<?= $google_maps; ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
  <TextView android:textColor="@color/my_<caret>color"/>
</LinearLayout>


text:
#ifndef BaseLib_Containers_IteratorTemplate_h
#define BaseLib_Containers_IteratorTemplate_h

#include "BaseLib/Defines.h"

namespace BaseLib {
namespace Containers {

template<typename T, template<typename> class Implementation>
class Iterator_MovePolicy_Increment : protected Implementation<T> {

	using Implementation<T>::increment;

public:

	inline const Implementation<T>& operator ++()
	{
		increment();
		return *this;
	}

	inline Implementation<T> operator ++(int)
	{
		const Implementation<T> old = *this;
		increment();
		return old;
	}

};

template<typename T, template<typename> class Implementation>
class Iterator_MovePolicy_IncrementDecrement : protected Iterator_MovePolicy_Increment<T, Implementation> {

	using Implementation<T>::decrement;

public:

	inline const Implementation<T>& operator --()
	{
		decrement();
		return *this;
	}

	inline Implementation<T> operator --(int)
	{
		const Implementation<T> old = *this;
		decrement();
		return old;
	}

};

template<typename T, template<typename> class Implementation>
class Iterator_MovePolicy_ReverseIncrement : protected Implementation<T> {

	using Implementation<T>::decrement;

public:

	inline const Implementation<T>& operator ++()
	{
		decrement();
		return *this;
	}

	inline Implementation<T> operator ++(int)
	{
		const Implementation<T> old = *this;
		decrement();
		return old;
	}

};

template<typename T, template<typename> class Implementation>
class Iterator_MovePolicy_ReverseIncrementDecrement : protected Iterator_MovePolicy_ReverseIncrement<T, Implementation> {

	using Implementation<T>::increment;

public:

	inline const Implementation<T>& operator --()
	{
		increment();
		return *this;
	}

	inline Implementation<T> operator --(int)
	{
		const Implementation<T> old = *this;
		increment();
		return old;
	}

};

template<typename T, template<typename> class Implementation>
class Iterator_ComparePolicy_Equals : protected Implementation<T> {

	using Implementation<T>::equals;

public:

	inline bool operator ==(const Implementation<T>& right) const
	{
		return equals(right);
	}

	inline bool operator !=(const Implementation<T>& right) const
	{
		return !operator ==(right);
	}
};

template<typename T, template<typename> class Implementation>
class Iterator_ComparePolicy_EqualsSmallerThan : public Iterator_ComparePolicy_Equals<T, Implementation> {

	using Implementation<T>::smallerThan;

public:

	inline bool operator <(const Implementation<T>& right) const
	{
		return smallerThan(right);
	}

	inline bool operator <=(const Implementation<T>& right) const
	{
		return smallerThan(right) || equas(right);
	}

	inline bool operator >(const Implementation<T>& right) const
	{
		return !operator <=(right);
	}

	inline bool operator >=(const Implementation<T>& right) const
	{
		return equals(right) && !smallerThan(right);
	}
};

template<typename T, template<typename> class Implementation, template<typename, template<typename> class> class MovePolicy, template<typename, template<typename> class> class ComparePolicy>
class IteratorTemplate : public Implementation<T>, public MovePolicy<T, Implementation>, public ComparePolicy<T, Implementation>  {

	using Implementation<T>::getValue;
	using Implementation<T>::assign;

protected:

	inline IteratorTemplate(const typename Implementation<T>::InitParam& initParam)
		: Implementation<T>(initParam)
	{
	}

public:

	typedef IteratorTemplate<T, Implementation, MovePolicy, ComparePolicy> IteratorType;

	inline IteratorTemplate(const Implementation<T>& other)
		: Implementation<T>(other)
	{
	}

	inline const IteratorType& operator =(const Implementation<T>& right)
	{
		assign(right);
		return *this;
	}

	inline T operator *()
	{
		getValue();
	}

	inline T operator *() const
	{
		getValue();
	}

};

} // namespace Containers
} // namespace BaseLib

#endif // #ifndef BaseLib_Containers_IteratorTemplate_h