text:
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.spectrads3;

import com.spectralogic.ds3client.networking.HttpVerb;
import com.spectralogic.ds3client.commands.interfaces.AbstractPaginationRequest;
import com.google.common.net.UrlEscapers;
import java.util.UUID;
import com.spectralogic.ds3client.models.TargetReadPreferenceType;

public class GetAzureTargetReadPreferencesSpectraS3Request extends AbstractPaginationRequest {

    // Variables

    private String bucketId;

    private boolean lastPage;

    private int pageLength;

    private int pageOffset;

    private String pageStartMarker;

    private TargetReadPreferenceType readPreference;

    private String targetId;

    // Constructor

    public GetAzureTargetReadPreferencesSpectraS3Request() {

    }

    public GetAzureTargetReadPreferencesSpectraS3Request withBucketId(final String bucketId) {
        this.bucketId = bucketId;
        this.updateQueryParam("bucket_id", bucketId);
        return this;
    }

    public GetAzureTargetReadPreferencesSpectraS3Request withLastPage(final boolean lastPage) {
        this.lastPage = lastPage;
        if (this.lastPage) {
            this.getQueryParams().put("last_page", null);
        } else {
            this.getQueryParams().remove("last_page");
        }
        return this;
    }

    public GetAzureTargetReadPreferencesSpectraS3Request withPageLength(final int pageLength) {
        this.pageLength = pageLength;
        this.updateQueryParam("page_length", pageLength);
        return this;
    }

    public GetAzureTargetReadPreferencesSpectraS3Request withPageOffset(final int pageOffset) {
        this.pageOffset = pageOffset;
        this.updateQueryParam("page_offset", pageOffset);
        return this;
    }

    public GetAzureTargetReadPreferencesSpectraS3Request withPageStartMarker(final UUID pageStartMarker) {
        this.pageStartMarker = pageStartMarker.toString();
        this.updateQueryParam("page_start_marker", pageStartMarker);
        return this;
    }

    public GetAzureTargetReadPreferencesSpectraS3Request withPageStartMarker(final String pageStartMarker) {
        this.pageStartMarker = pageStartMarker;
        this.updateQueryParam("page_start_marker", pageStartMarker);
        return this;
    }

    public GetAzureTargetReadPreferencesSpectraS3Request withReadPreference(final TargetReadPreferenceType readPreference) {
        this.readPreference = readPreference;
        this.updateQueryParam("read_preference", readPreference);
        return this;
    }

    public GetAzureTargetReadPreferencesSpectraS3Request withTargetId(final UUID targetId) {
        this.targetId = targetId.toString();
        this.updateQueryParam("target_id", targetId);
        return this;
    }

    public GetAzureTargetReadPreferencesSpectraS3Request withTargetId(final String targetId) {
        this.targetId = targetId;
        this.updateQueryParam("target_id", targetId);
        return this;
    }

    @Override
    public HttpVerb getVerb() {
        return HttpVerb.GET;
    }

    @Override
    public String getPath() {
        return "/_rest_/azure_target_read_preference";
    }

    public String getBucketId() {
        return this.bucketId;
    }

    public boolean getLastPage() {
        return this.lastPage;
    }

    public int getPageLength() {
        return this.pageLength;
    }

    public int getPageOffset() {
        return this.pageOffset;
    }

    public String getPageStartMarker() {
        return this.pageStartMarker;
    }

    public TargetReadPreferenceType getReadPreference() {
        return this.readPreference;
    }

    public String getTargetId() {
        return this.targetId;
    }

}


text:
define([
    'underscore',
    'contrail-view',
    'contrail-list-model',
    'config/networking/loadbalancer/ui/js/views/lbCfgFormatters'
], function (_, ContrailView, ContrailListModel, LbCfgFormatters) {
    var self;
    var lbCfgFormatter = new LbCfgFormatters();
    var lbCfgListView = ContrailView.extend({
        el: $(contentContainer),

        render: function () {
            self = this;
            var viewConfig = this.attributes.viewConfig;
            self.floatingIp = {};
            self.floatingIp.list = [];
            self.lb = {};
            self.lb.list = [];
            var currentProject = viewConfig["projectSelectedValueData"];
            var listModelConfig = {
                    remote: {
                        ajaxConfig: {
                            url: '/api/tenants/config/lbaas/load-balancers-details?tenant_id=' + currentProject.value ,
                            type: "GET"
                        },
                        dataParser: self.parseLoadbalancersData,
                    }
                };
                var contrailListModel = new ContrailListModel(listModelConfig);
                self.renderView4Config(self.$el,
                        contrailListModel, getLbCfgListViewConfig(viewConfig, self.floatingIp, self.lb));
        },
        parseLoadbalancersData : function(response){
             var lbList = getValueByJsonPath(response, "loadbalancers", []),
             vmiList = [], fIpList = [], loadBalancerList = [];
             _.each(lbList, function(obj) {
                 var vmi = getValueByJsonPath(obj, "loadbalancer;virtual_machine_interface_refs", []);
                 var loadBalancer = getValueByJsonPath(obj, "loadbalancer", {});
                 loadBalancerList.push({id: loadBalancer.uuid, text: loadBalancer.display_name, fqName:loadBalancer.fq_name });
                 vmiList = vmiList.concat(vmi);
             });
             _.each(vmiList, function(obj) {
                 var floatingIp = getValueByJsonPath(obj, "floating-ip", {});
                 if(Object.keys(floatingIp).length > 0){
                     fIpList.push(floatingIp.uuid);
                 }
             });
             self.floatingIp.list = fIpList;
             self.lb.list = loadBalancerList;
             return lbList;
        }
    });
    var getLbCfgListViewConfig = function (viewConfig, floatingIp, lb) {
        return {
            elementId: cowu.formatElementId([ctwl.CFG_LB_LIST_ID]),
            view: "SectionView",
            viewConfig: {
                rows: [
                    {
                        columns: [
                            {
                                elementId: ctwl.CFG_LB_LIST_ID,
                                title: ctwl.CFG_LB_TITLE,
                                view: "lbCfgGridView",
                                viewPathPrefix:
                                    "config/networking/loadbalancer/ui/js/views/",
                                app: cowc.APP_CONTRAIL_CONTROLLER,
                                viewConfig: {
                                    selectedProjId:
                                      viewConfig.projectSelectedValueData.value,
                                      floatingIp: floatingIp,
                                      lb: lb
                                }
                            }
                        ]
                    }
                ]
            }
        }
    };

    return lbCfgListView;
});

redpajama_set_name: RedPajamaGithub


text:
This module provides some new functionality:

    ctype.isAlnum()
    ctype.isAlpha()
    ctype.isCntrl()
    ctype.isDigit()
    ctype.isGraph()
    ctype.isLower()
    ctype.isPrint()
    ctype.isPunct()
    ctype.isSpace()
    ctype.isUpper()
    ctype.isHex()

> All function calls will expect a string value and will return a boolean value.

## isAlnum

> Checks for just alphanumeric characters.

Example:

```
local ctype = require("ctype")

if ctype.isAlnum("ABC12345")
then
   print("Yes")
else
   print("No")
end
```

## isAlpha

> Checks for just alphabetic characters.

Example:

```
local ctype = require("ctype")

if ctype.isAlpha("ABCabc")
then
   print("Yes")
else
   print("No")
end
```

## isCntrl

> Checks for just control characters.

Example:

```
local ctype = require("ctype")

if ctype.isCntrl("\n\r\t")
then
   print("Yes")
else
   print("No")
end
```

## isDigit

> Checks for just numerical characters.

Example:

```
local ctype = require("ctype")

if ctype.isDigit("12345")
then
   print("Yes")
else
   print("No")
end
```

## isGraph

> Checks for any printable characters except space.

Example:

```
local ctype = require("ctype")

if ctype.isGraph("ABC")
then
   print("Yes")
else
   print("No")
end
```

## isLower

> Checks for just lowercase characters.

Example:

```
local ctype = require("ctype")

if ctype.isLower("abc")
then
   print("Yes")
else
   print("No")
end
```

## isPrint

> Checks for just printable characters.

Example:

```
local ctype = require("ctype")

if ctype.isPrint("Lee")
then
   print("Yes")
else
   print("No")
end
```

## isPunct

>  Checks for any printable characters which are not whitespace or alphanumeric character.

Example:

```
local ctype = require("ctype")

if ctype.isPunct("@")
then
   print("Yes")
else
   print("No")
end
```

## isSpace

> Checks for just whitespace characters.

Example:

```
local ctype = require("ctype")

if ctype.isSpace(" ")
then
   print("Yes")
else
   print("No")
end
```

## isUpper

> Checks for just uppercase characters.

Example:

```
local ctype = require("ctype")

if ctype.isUpper("ABCDEFGH")
then
   print("Yes")
else
   print("No")
end
```

## isHex

> Checks for just characters representing a hexadecimal digit.

Example:

```
local ctype = require("ctype")

if ctype.isHex("ABCDEF0123456789")
then
   print("Yes")
else
   print("No")
end
```

## Installation

Standard

```
git clone git://github.com/mostvotedplaya/Lua-Ctype.git
cd Lua-Ctype/src
make
make install
```

Luarocks

```
luarocks install --server=http://luarocks.org/dev luactype
```


text:
package net.maizegenetics.trait;

import net.maizegenetics.trait.AbstractPhenotype;
import cern.colt.matrix.DoubleFactory2D;
import cern.colt.matrix.DoubleMatrix2D;
import net.maizegenetics.taxa.TaxaList;
import net.maizegenetics.taxa.Taxon;

import java.util.List;

public class SimplePhenotype extends AbstractPhenotype {
	private DoubleMatrix2D data;

	public SimplePhenotype(TaxaList taxa, List<Trait> traits, DoubleMatrix2D data) {
		super(taxa, traits);
		this.data = data;
	}

	public SimplePhenotype(TaxaList taxa, List<Trait> traits, double[][] data) {
		super(taxa, traits);
		this.data = DoubleFactory2D.dense.make(data);
	}

	public SimplePhenotype(TaxaList taxa, List<Trait> traits) {
		super(taxa, traits);
		this.data = DoubleFactory2D.dense.make(getNumberOfTaxa(), getNumberOfTraits(), Double.NaN);
	}

	public double getData(int taxon, int trait) {
		return data.get(taxon, trait);
	}

	public double getData(Taxon taxon, Trait trait) {
		return getData(whichTaxon(taxon), whichTrait(trait));
	}

	public double[][] getData() {
		return data.toArray();
	}

	public void setData(int taxon, int trait, double value) {
		data.set(taxon, trait, value);
	}

	public void setData(Taxon taxon, Trait trait, double value) {
		data.set(whichTaxon(taxon), whichTrait(trait), value);
	}

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    tools:context="${relativePackage}.${activityClass}" >

	<RelativeLayout
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="1"
	    android:gravity="top">

	    <TextView android:id="@+id/lblStart"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentLeft="true"
	        android:layout_toLeftOf="@+id/valStart"
	        android:textSize="18sp"
	        android:text="@string/started" />

	    <TextView android:id="@+id/valStart"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentRight="true"
	        android:textSize="18sp" />

	</RelativeLayout>

	<RelativeLayout
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="1"
	    android:gravity="top">

	    <TextView android:id="@+id/lblEnd"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentLeft="true"
	        android:layout_toLeftOf="@+id/valEnd"
	        android:textSize="18sp"
	        android:text="@string/ended" />

	    <TextView android:id="@+id/valEnd"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentRight="true"
	        android:textSize="18sp" />

	</RelativeLayout>

	<RelativeLayout
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="1"
	    android:gravity="top">

	    <TextView android:id="@+id/lblElapsed"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentLeft="true"
	        android:layout_toLeftOf="@+id/valElapsed"
	        android:textSize="18sp"
	        android:text="@string/duration" />

	    <TextView android:id="@+id/valElapsed"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentRight="true"
	        android:textSize="18sp" />

	</RelativeLayout>

	<RelativeLayout
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="1"
	    android:gravity="top">

	    <TextView android:id="@+id/lblDistance"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentLeft="true"
	        android:layout_toLeftOf="@+id/valDistance"
	        android:textSize="18sp"
	        android:text="@string/distance" />

	    <TextView android:id="@+id/valDistance"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentRight="true"
	        android:textSize="18sp" />

	</RelativeLayout>

	<View
        android:layout_width="match_parent"
        android:layout_height="2dip"
        android:background="#FF909090" />

	<TableLayout
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="4"
	    android:gravity="fill_vertical"
	    android:stretchColumns="1" >

	    <TableRow>

	       	<TextView
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content" />

	       	<TextView
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:textSize="18sp"
		        android:padding="3dip"
		        android:gravity="right"
		        android:text="@string/avg" />

	       	<TextView
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:textSize="18sp"
		        android:padding="3dip"
		        android:gravity="right"
		        android:text="@string/max" />

	    </TableRow>

	    <TableRow>

	       	<TextView android:id="@+id/lblCardio"
	       	    android:layout_width="wrap_content"
	       	    android:layout_height="wrap_content"
	       	    android:text="@string/cardio_bpm"
	       	    android:textSize="18sp" />

		    <TextView android:id="@+id/valCardioAvg"
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:textSize="18sp"
		        android:padding="3dip"
		        android:gravity="right" />

		    <TextView android:id="@+id/valCardioMax"
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:textSize="18sp"
		        android:padding="3dip"
		        android:gravity="right" />

	    </TableRow>

	    <TableRow>

	       	<TextView android:id="@+id/lblSpeed"
	       	    android:layout_width="wrap_content"
	       	    android:layout_height="wrap_content"
	       	    android:text="@string/speed_kmh"
	       	    android:textSize="18sp" />

		    <TextView android:id="@+id/valSpeedAvg"
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:textSize="18sp"
		        android:padding="3dip"
		        android:gravity="right" />

		    <TextView android:id="@+id/valSpeedMax"
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:textSize="18sp"
		        android:padding="3dip"
		        android:gravity="right" />

	    </TableRow>

	    <TableRow>

	       	<TextView android:id="@+id/lblCadence"
	       	    android:layout_width="wrap_content"
	       	    android:layout_height="wrap_content"
	       	    android:text="@string/cadence_rpm"
	       	    android:textSize="18sp" />

		    <TextView android:id="@+id/valCadenceAvg"
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:textSize="18sp"
		        android:padding="3dip"
		        android:gravity="right" />

		    <TextView android:id="@+id/valCadenceMax"
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:textSize="18sp"
		        android:padding="3dip"
		        android:gravity="right" />

	    </TableRow>

	</TableLayout>

	<View
        android:layout_width="match_parent"
        android:layout_height="2dip"
        android:background="#FF909090" />

	<RelativeLayout
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="1"
	    android:gravity="bottom">

	    <TextView
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentLeft="true"
	        android:layout_toLeftOf="@+id/valGear"
	        android:textSize="18sp"
	        android:text="@string/gear" />

	    <TextView android:id="@+id/valGear"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentRight="true"
	        android:textSize="18sp" />

	</RelativeLayout>

	<RelativeLayout
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="1"
	    android:gravity="bottom">

	    <TextView
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentLeft="true"
	        android:layout_toLeftOf="@+id/valFitness"
	        android:textSize="18sp"
	        android:text="@string/fitness" />

	    <TextView android:id="@+id/valFitness"
	        android:layout_width="wrap_content"
	        android:layout_height="wrap_content"
	        android:layout_alignParentRight="true"
	        android:textSize="18sp" />

	</RelativeLayout>

	<LinearLayout
        android:id="@+id/documento_twopane_buttons"
        style="android:attr/buttonBarStyle"
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="2"
	    android:gravity="bottom"
        android:orientation="horizontal" >

		<Button
		    android:id="@+id/btnOk"
			android:layout_width="0dp"
			android:layout_weight="1"
	        android:layout_height="wrap_content"
		    style="?android:attr/buttonStyleSmall"
	        android:textSize="24sp"
	        android:text="@string/close" />

		<Button
		    android:id="@+id/btnDelete"
			android:layout_width="0dp"
			android:layout_weight="1"
	        android:layout_height="wrap_content"
		    style="?android:attr/buttonStyleSmall"
	        android:textSize="24sp"
	        android:text="@string/delete" />

	</LinearLayout>

</LinearLayout>


text:
/*
 *
 * This file was generated by LLRP Code Generator
 * see http://llrp-toolkit.cvs.sourceforge.net/llrp-toolkit/
 * for more information
 * Generated on: Sun Apr 08 14:14:10 EDT 2012;
 *
 */

/*
 * Copyright 2007 ETH Zurich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 */
package org.llrp.ltk.generated.parameters;

import maximsblog.blogspot.com.llrpexplorer.Logger;

import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;

import org.llrp.ltk.exceptions.InvalidLLRPMessageException;
import org.llrp.ltk.exceptions.MissingParameterException;
import org.llrp.ltk.generated.LLRPConstants;
import org.llrp.ltk.types.LLRPBitList;
import org.llrp.ltk.types.LLRPMessage;
import org.llrp.ltk.types.SignedShort;
import org.llrp.ltk.types.TLVParameter;
import org.llrp.ltk.types.TVParameter;
import org.llrp.ltk.types.UnsignedShort;

import java.util.LinkedList;
import java.util.List;

/**
 * For a particular antenna, this parameter specifies the Reader's valid index range in the Receive Sensitivity Table.  A Reader should report this parameter if the Reader allows control of receive sensitivity (i.e., the Reader reports a Receive Sensitivity Table with more than one entry) and the Reader supports multiple antennas where the antennas can have different receive sensitivity values.If this parameter is omitted, then the Client SHALL assume that for all of the Reader's antennas the index range is the same as in the Receive Sensitivity Table.

See also {@link LLRP Specification Section 9.2.1.2}
 and {@link LLRP Specification Section 16.2.3.1.2}

 */

/**
 * For a particular antenna, this parameter specifies the Reader's valid index range in the Receive Sensitivity Table.  A Reader should report this parameter if the Reader allows control of receive sensitivity (i.e., the Reader reports a Receive Sensitivity Table with more than one entry) and the Reader supports multiple antennas where the antennas can have different receive sensitivity values.If this parameter is omitted, then the Client SHALL assume that for all of the Reader's antennas the index range is the same as in the Receive Sensitivity Table.

See also {@link LLRP Specification Section 9.2.1.2}
 and {@link LLRP Specification Section 16.2.3.1.2}

      .
 */
public class PerAntennaReceiveSensitivityRange extends TLVParameter {
    public static final SignedShort TYPENUM = new SignedShort(149);
    private static final Logger LOGGER = Logger.getLogger(PerAntennaReceiveSensitivityRange.class);
    protected UnsignedShort antennaID;
    protected UnsignedShort receiveSensitivityIndexMin;
    protected UnsignedShort receiveSensitivityIndexMax;

    /**
     * empty constructor to create new parameter.
     */
    public PerAntennaReceiveSensitivityRange() {
    }

    /**
     * Constructor to create parameter from binary encoded parameter
     * calls decodeBinary to decode parameter.
     * @param list to be decoded
     */
    public PerAntennaReceiveSensitivityRange(LLRPBitList list) {
        decodeBinary(list);
    }

    /**
    * Constructor to create parameter from xml encoded parameter
    * calls decodeXML to decode parameter.
    * @param element to be decoded
    */
    public PerAntennaReceiveSensitivityRange(Element element)
        throws InvalidLLRPMessageException {
        decodeXML(element);
    }

    /**
    * {@inheritDoc}
    */
    public LLRPBitList encodeBinarySpecific() {
        LLRPBitList resultBits = new LLRPBitList();

        if (antennaID == null) {
            LOGGER.warn(" antennaID not set");
            throw new MissingParameterException(
                " antennaID not set  for Parameter of Type PerAntennaReceiveSensitivityRange");
        }

        resultBits.append(antennaID.encodeBinary());

        if (receiveSensitivityIndexMin == null) {
            LOGGER.warn(" receiveSensitivityIndexMin not set");
            throw new MissingParameterException(
                " receiveSensitivityIndexMin not set  for Parameter of Type PerAntennaReceiveSensitivityRange");
        }

        resultBits.append(receiveSensitivityIndexMin.encodeBinary());

        if (receiveSensitivityIndexMax == null) {
            LOGGER.warn(" receiveSensitivityIndexMax not set");
            throw new MissingParameterException(
                " receiveSensitivityIndexMax not set  for Parameter of Type PerAntennaReceiveSensitivityRange");
        }

        resultBits.append(receiveSensitivityIndexMax.encodeBinary());

        return resultBits;
    }

    /**
    * {@inheritDoc}
    */
    public Content encodeXML(String name, Namespace ns) {
        // element in namespace defined by parent element
        Element element = new Element(name, ns);
        // child element are always in default LLRP namespace
        ns = Namespace.getNamespace("llrp", LLRPConstants.LLRPNAMESPACE);

        if (antennaID == null) {
            LOGGER.warn(" antennaID not set");
            throw new MissingParameterException(" antennaID not set");
        } else {
            element.addContent(antennaID.encodeXML("AntennaID", ns));
        }

        if (receiveSensitivityIndexMin == null) {
            LOGGER.warn(" receiveSensitivityIndexMin not set");
            throw new MissingParameterException(
                " receiveSensitivityIndexMin not set");
        } else {
            element.addContent(receiveSensitivityIndexMin.encodeXML(
                    "ReceiveSensitivityIndexMin", ns));
        }

        if (receiveSensitivityIndexMax == null) {
            LOGGER.warn(" receiveSensitivityIndexMax not set");
            throw new MissingParameterException(
                " receiveSensitivityIndexMax not set");
        } else {
            element.addContent(receiveSensitivityIndexMax.encodeXML(
                    "ReceiveSensitivityIndexMax", ns));
        }

        //parameters
        return element;
    }

    /**
    * {@inheritDoc}
    */
    protected void decodeBinarySpecific(LLRPBitList binary) {
        int position = 0;
        int tempByteLength;
        int tempLength = 0;
        int count;
        SignedShort type;
        int fieldCount;
        Custom custom;
        antennaID = new UnsignedShort(binary.subList(position,
                    UnsignedShort.length()));
        position += UnsignedShort.length();
        receiveSensitivityIndexMin = new UnsignedShort(binary.subList(
                    position, UnsignedShort.length()));
        position += UnsignedShort.length();
        receiveSensitivityIndexMax = new UnsignedShort(binary.subList(
                    position, UnsignedShort.length()));
        position += UnsignedShort.length();
    }

    /**
    * {@inheritDoc}
    */
    public void decodeXML(Element element) throws InvalidLLRPMessageException {
        List<Element> tempList = null;
        boolean atLeastOnce = false;
        Custom custom;

        Element temp = null;

        // child element are always in default LLRP namespace
        Namespace ns = Namespace.getNamespace(LLRPConstants.LLRPNAMESPACE);

        temp = element.getChild("AntennaID", ns);

        if (temp != null) {
            antennaID = new UnsignedShort(temp);
        }

        element.removeChild("AntennaID", ns);
        temp = element.getChild("ReceiveSensitivityIndexMin", ns);

        if (temp != null) {
            receiveSensitivityIndexMin = new UnsignedShort(temp);
        }

        element.removeChild("ReceiveSensitivityIndexMin", ns);
        temp = element.getChild("ReceiveSensitivityIndexMax", ns);

        if (temp != null) {
            receiveSensitivityIndexMax = new UnsignedShort(temp);
        }

        element.removeChild("ReceiveSensitivityIndexMax", ns);

        if (element.getChildren().size() > 0) {
            String message = "PerAntennaReceiveSensitivityRange has unknown element " +
                ((Element) element.getChildren().get(0)).getName();
            throw new InvalidLLRPMessageException(message);
        }
    }

    //setters
    /**
    * set   antennaID of type UnsignedShort .
    * @param   antennaID to be set
    */
    public void setAntennaID(final UnsignedShort antennaID) {
        this.antennaID = antennaID;
    }

    /**
    * set   receiveSensitivityIndexMin of type UnsignedShort .
    * @param   receiveSensitivityIndexMin to be set
    */
    public void setReceiveSensitivityIndexMin(
        final UnsignedShort receiveSensitivityIndexMin) {
        this.receiveSensitivityIndexMin = receiveSensitivityIndexMin;
    }

    /**
    * set   receiveSensitivityIndexMax of type UnsignedShort .
    * @param   receiveSensitivityIndexMax to be set
    */
    public void setReceiveSensitivityIndexMax(
        final UnsignedShort receiveSensitivityIndexMax) {
        this.receiveSensitivityIndexMax = receiveSensitivityIndexMax;
    }

    // end setter

    //getters
    /**
    * get   antennaID of type UnsignedShort.
    * @return   type UnsignedShort to be set
    */
    public UnsignedShort getAntennaID() {
        return this.antennaID;
    }

    /**
    * get   receiveSensitivityIndexMin of type UnsignedShort.
    * @return   type UnsignedShort to be set
    */
    public UnsignedShort getReceiveSensitivityIndexMin() {
        return this.receiveSensitivityIndexMin;
    }

    /**
    * get   receiveSensitivityIndexMax of type UnsignedShort.
    * @return   type UnsignedShort to be set
    */
    public UnsignedShort getReceiveSensitivityIndexMax() {
        return this.receiveSensitivityIndexMax;
    }

    // end getters

    //add methods

    // end add

    /**
    * For TLV Parameter length can not be determined at compile time. This method therefore always returns 0.
    * @return Integer always zero
    */
    public static Integer length() {
        return 0;
    }

    /**
    * {@inheritDoc}
    */
    public SignedShort getTypeNum() {
        return TYPENUM;
    }

    /**
    * {@inheritDoc}
    */
    public String getName() {
        return "PerAntennaReceiveSensitivityRange";
    }

    /**
    * return string representation. All field values but no parameters are included
    * @return String
    */
    public String toString() {
        String result = "PerAntennaReceiveSensitivityRange: ";
        result += ", antennaID: ";
        result += antennaID;
        result += ", receiveSensitivityIndexMin: ";
        result += receiveSensitivityIndexMin;
        result += ", receiveSensitivityIndexMax: ";
        result += receiveSensitivityIndexMax;
        result = result.replaceFirst(", ", "");

        return result;
    }
}


text:
This directory contains a dependency-free, header-only library of templates
providing well-defined semantics for safely and performantly handling a variety
of numeric operations, including most common arithmetic operations and
conversions.

The public API is broken out into the following header files:

*   `checked_math.h` contains the `CheckedNumeric` template class and helper
    functions for performing arithmetic and conversion operations that detect
    errors and boundary conditions (e.g. overflow, truncation, etc.).
*   `clamped_math.h` contains the `ClampedNumeric` template class and
    helper functions for performing fast, clamped (i.e. [non-sticky](#notsticky)
    saturating) arithmetic operations and conversions.
*   `safe_conversions.h` contains the `StrictNumeric` template class and
    a collection of custom casting templates and helper functions for safely
    converting between a range of numeric types.
*   `safe_math.h` includes all of the previously mentioned headers.

*** aside
**Note:** The `Numeric` template types implicitly convert from C numeric types
and `Numeric` templates that are convertable to an underlying C numeric type.
The conversion priority for `Numeric` type coercions is:

*   `StrictNumeric` coerces to `ClampedNumeric` and `CheckedNumeric`
*   `ClampedNumeric` coerces to `CheckedNumeric`
***

[TOC]

## Common patterns and use-cases

The following covers the preferred style for the most common uses of this
library. Please don't cargo-cult from anywhere else. 😉

### Performing checked arithmetic type conversions

The `checked_cast` template converts between arbitrary arithmetic types, and is
used for cases where a conversion failure should result in program termination:

```cpp
// Crash if signed_value is out of range for buff_size.
size_t buff_size = checked_cast<size_t>(signed_value);
```

### Performing saturated (clamped) arithmetic type conversions

The `saturated_cast` template converts between arbitrary arithmetic types, and
is used in cases where an out-of-bounds source value should be saturated to the
corresponding maximum or minimum of the destination type:

```cpp
// Cast to a smaller type, saturating as needed.
int8_t eight_bit_value = saturated_cast<int8_t>(int_value);

// Convert from float with saturation to INT_MAX, INT_MIN, or 0 for NaN.
int int_value = saturated_cast<int>(floating_point_value);
```

`ClampCeil`, `ClampFloor`, and `ClampRound` provide similar functionality to the
versions in `std::`, but saturate and return an integral type.  An optional
template parameter specifies the desired destination type (`int` if
unspecified).  These should be used for most floating-to-integral conversions.

```cpp
// Basically saturated_cast<int>(std::round(floating_point_value)).
int int_value = ClampRound(floating_point_value);

// A destination type can be explicitly specified.
uint8_t byte_value = ClampFloor<uint8_t>(floating_point_value);
```

### Enforcing arithmetic type conversions at compile-time

The `strict_cast` emits code that is identical to `static_cast`. However,
provides static checks that will cause a compilation failure if the
destination type cannot represent the full range of the source type:

```cpp
// Throw a compiler error if byte_value is changed to an out-of-range-type.
int int_value = strict_cast<int>(byte_value);
```

You can also enforce these compile-time restrictions on function parameters by
using the `StrictNumeric` template:

```cpp
// Throw a compiler error if the size argument cannot be represented by a
// size_t (e.g. passing an int will fail to compile).
bool AllocateBuffer(void** buffer, StrictCast<size_t> size);
```

### Comparing values between arbitrary arithmetic types

Both the `StrictNumeric` and `ClampedNumeric` types provide well defined
comparisons between arbitrary arithmetic types. This allows you to perform
comparisons that are not legal or would trigger compiler warnings or errors
under the normal arithmetic promotion rules:

```cpp
bool foo(unsigned value, int upper_bound) {
  // Converting to StrictNumeric allows this comparison to work correctly.
  if (MakeStrictNum(value) >= upper_bound)
    return false;
```

*** note
**Warning:** Do not perform manual conversions using the comparison operators.
Instead, use the cast templates described in the previous sections, or the
constexpr template functions `IsValueInRangeForNumericType` and
`IsTypeInRangeForNumericType`, as these templates properly handle the full range
of corner cases and employ various optimizations.
***

### Calculating a buffer size (checked arithmetic)

When making exact calculations—such as for buffer lengths—it's often necessary
to know when those calculations trigger an overflow, undefined behavior, or
other boundary conditions. The `CheckedNumeric` template does this by storing
a bit determining whether or not some arithmetic operation has occurred that
would put the variable in an "invalid" state. Attempting to extract the value
from a variable in an invalid state will trigger a check/trap condition, that
by default will result in process termination.

Here's an example of a buffer calculation using a `CheckedNumeric` type (note:
the AssignIfValid method will trigger a compile error if the result is ignored).

```cpp
// Calculate the buffer size and detect if an overflow occurs.
size_t size;
if (!CheckAdd(kHeaderSize, CheckMul(count, kItemSize)).AssignIfValid(&size)) {
  // Handle an overflow error...
}
```

### Calculating clamped coordinates (non-sticky saturating arithmetic)

Certain classes of calculations—such as coordinate calculations—require
well-defined semantics that always produce a valid result on boundary
conditions. The `ClampedNumeric` template addresses this by providing
performant, non-sticky saturating arithmetic operations.

Here's an example of using a `ClampedNumeric` to calculate an operation
insetting a rectangle.

```cpp
// Use clamped arithmetic since inset calculations might overflow.
void Rect::Inset(int left, int top, int right, int bottom) {
  origin_ += Vector2d(left, top);
  set_width(ClampSub(width(), ClampAdd(left, right)));
  set_height(ClampSub(height(), ClampAdd(top, bottom)));
}
```

*** note

The `ClampedNumeric` type is not "sticky", which means the saturation is not
retained across individual operations. As such, one arithmetic operation may
result in a saturated value, while the next operation may then "desaturate"
the value. Here's an example:

```cpp
ClampedNumeric<int> value = INT_MAX;
++value;  // value is still INT_MAX, due to saturation.
--value;  // value is now (INT_MAX - 1), because saturation is not sticky.
```

***

## Conversion functions and StrictNumeric<> in safe_conversions.h

This header includes a collection of helper `constexpr` templates for safely
performing a range of conversions, assignments, and tests.

### Safe casting templates

*   `as_signed()` - Returns the supplied integral value as a signed type of
    the same width.
*   `as_unsigned()` - Returns the supplied integral value as an unsigned type
    of the same width.
*   `checked_cast<>()` - Analogous to `static_cast<>` for numeric types, except
    that by default it will trigger a crash on an out-of-bounds conversion (e.g.
    overflow, underflow, NaN to integral) or a compile error if the conversion
    error can be detected at compile time. The crash handler can be overridden
    to perform a behavior other than crashing.
*   `saturated_cast<>()` - Analogous to `static_cast` for numeric types, except
    that it returns a saturated result when the specified numeric conversion
    would otherwise overflow or underflow. An NaN source returns 0 by
    default, but can be overridden to return a different result.
*   `strict_cast<>()` - Analogous to `static_cast` for numeric types, except
    this causes a compile failure if the destination type is not large
    enough to contain any value in the source type. It performs no runtime
    checking and thus introduces no runtime overhead.

### Other helper and conversion functions

*   `ClampCeil<>()` - A convenience function that computes the ceil of its floating-
    point arg, then saturates to the destination type (template parameter,
    defaults to `int`).
*   `ClampFloor<>()` - A convenience function that computes the floor of its
    floating-point arg, then saturates to the destination type (template
    parameter, defaults to `int`).
*   `IsTypeInRangeForNumericType<>()` - A convenience function that evaluates
    entirely at compile-time and returns true if the destination type (first
    template parameter) can represent the full range of the source type
    (second template parameter).
*   `IsValueInRangeForNumericType<>()` - A convenience function that returns
    true if the type supplied as the template parameter can represent the value
    passed as an argument to the function.
*   `IsValueNegative()` - A convenience function that will accept any
    arithmetic type as an argument and will return whether the value is less
    than zero. Unsigned types always return false.
*   `ClampRound<>()` - A convenience function that rounds its floating-point arg,
    then saturates to the destination type (template parameter, defaults to
    `int`).
*   `SafeUnsignedAbs()` - Returns the absolute value of the supplied integer
    parameter as an unsigned result (thus avoiding an overflow if the value
    is the signed, two's complement minimum).

### StrictNumeric<>

`StrictNumeric<>` is a wrapper type that performs assignments and copies via
the `strict_cast` template, and can perform valid arithmetic comparisons
across any range of arithmetic types. `StrictNumeric` is the return type for
values extracted from a `CheckedNumeric` class instance. The raw numeric value
is extracted via `static_cast` to the underlying type or any type with
sufficient range to represent the underlying type.

*   `MakeStrictNum()` - Creates a new `StrictNumeric` from the underlying type
    of the supplied arithmetic or StrictNumeric type.
*   `SizeT` - Alias for `StrictNumeric<size_t>`.

## CheckedNumeric<> in checked_math.h

`CheckedNumeric<>` implements all the logic and operators for detecting integer
boundary conditions such as overflow, underflow, and invalid conversions.
The `CheckedNumeric` type implicitly converts from floating point and integer
data types, and contains overloads for basic arithmetic operations (i.e.: `+`,
`-`, `*`, `/` for all types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers).
However, *the [variadic template functions
](#CheckedNumeric_in-checked_math_h-Non_member-helper-functions)
are the preferred API,* as they remove type ambiguities and help prevent a number
of common errors. The variadic functions can also be more performant, as they
eliminate redundant expressions that are unavoidable with the with the operator
overloads. (Ideally the compiler should optimize those away, but better to avoid
them in the first place.)

Type promotions are a slightly modified version of the [standard C/C++ numeric
promotions
](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions)
with the two differences being that *there is no default promotion to int*
and *bitwise logical operations always return an unsigned of the wider type.*

### Example

```
#include "base/numerics/checked_math.h"
...
CheckedNumeric<uint32_t> variable = 0;
variable++;
variable--;
if (variable.ValueOrDie() == 0)
  // Fine, |variable| still within valid range.

variable--;
variable++;
if (variable.ValueOrDie() == 0)  // Breakpoint or configured CheckHandler
  // Does not happen as variable underflowed.
```

### Members

The unary negation, increment, and decrement operators are supported, along
with the following unary arithmetic methods, which return a new
`CheckedNumeric` as a result of the operation:

*   `Abs()` - Absolute value.
*   `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type
    (valid for only integral types).
*   `Max()` - Returns whichever is greater of the current instance or argument.
    The underlying return type is whichever has the greatest magnitude.
*   `Min()` - Returns whichever is lowest of the current instance or argument.
    The underlying return type is whichever has can represent the lowest
    number in the smallest width (e.g. int8_t over unsigned, int over
    int8_t, and float over int).

The following are for converting `CheckedNumeric` instances:

*   `type` - The underlying numeric type.
*   `AssignIfValid()` - Assigns the underlying value to the supplied
    destination pointer if the value is currently valid and within the
    range supported by the destination type. Returns true on success.
*   `Cast<>()` - Instance method returning a `CheckedNumeric` derived from
    casting the current instance to a `CheckedNumeric` of the supplied
    destination type.

*** aside
The following member functions return a `StrictNumeric`, which is valid for
comparison and assignment operations, but will trigger a compile failure on
attempts to assign to a type of insufficient range. The underlying value can
be extracted by an explicit `static_cast` to the underlying type or any type
with sufficient range to represent the underlying type.
***

*   `IsValid()` - Returns true if the underlying numeric value is valid (i.e.
    has not wrapped or saturated and is not the result of an invalid
    conversion).
*   `ValueOrDie()` - Returns the underlying value. If the state is not valid
    this call will trigger a crash by default (but may be overridden by
    supplying an alternate handler to the template).
*   `ValueOrDefault()` - Returns the current value, or the supplied default if
    the state is not valid (but will not crash).

**Comparison operators are explicitly not provided** for `CheckedNumeric`
types because they could result in a crash if the type is not in a valid state.
Patterns like the following should be used instead:

```cpp
// Either input or padding (or both) may be arbitrary sizes.
size_t buff_size;
if (!CheckAdd(input, padding, kHeaderLength).AssignIfValid(&buff_size) ||
     buff_size >= kMaxBuffer) {
  // Handle an error...
} else {
  // Do stuff on success...
}
```

### Non-member helper functions

The following variadic convenience functions, which accept standard arithmetic
or `CheckedNumeric` types, perform arithmetic operations, and return a
`CheckedNumeric` result. The supported functions are:

*   `CheckAdd()` - Addition.
*   `CheckSub()` - Subtraction.
*   `CheckMul()` - Multiplication.
*   `CheckDiv()` - Division.
*   `CheckMod()` - Modulus (integer only).
*   `CheckLsh()` - Left integer shift (integer only).
*   `CheckRsh()` - Right integer shift (integer only).
*   `CheckAnd()` - Bitwise AND (integer only with unsigned result).
*   `CheckOr()`  - Bitwise OR (integer only with unsigned result).
*   `CheckXor()` - Bitwise XOR (integer only with unsigned result).
*   `CheckMax()` - Maximum of supplied arguments.
*   `CheckMin()` - Minimum of supplied arguments.

The following wrapper functions can be used to avoid the template
disambiguator syntax when converting a destination type.

*   `IsValidForType<>()` in place of: `a.template IsValid<>()`
*   `ValueOrDieForType<>()` in place of: `a.template ValueOrDie<>()`
*   `ValueOrDefaultForType<>()` in place of: `a.template ValueOrDefault<>()`

The following general utility methods is are useful for converting from
arithmetic types to `CheckedNumeric` types:

*   `MakeCheckedNum()` - Creates a new `CheckedNumeric` from the underlying type
    of the supplied arithmetic or directly convertible type.

## ClampedNumeric<> in clamped_math.h

`ClampedNumeric<>` implements all the logic and operators for clamped
(non-sticky saturating) arithmetic operations and conversions. The
`ClampedNumeric` type implicitly converts back and forth between floating point
and integer data types, saturating on assignment as appropriate. It contains
overloads for basic arithmetic operations (i.e.: `+`, `-`, `*`, `/` for
all types and `%`, `<<`, `>>`, `&`, `|`, `^` for integers) along with comparison
operators for arithmetic types of any size. However, *the [variadic template
functions
](#ClampedNumeric_in-clamped_math_h-Non_member-helper-functions)
are the preferred API,* as they remove type ambiguities and help prevent
a number of common errors. The variadic functions can also be more performant,
as they eliminate redundant expressions that are unavoidable with the operator
overloads. (Ideally the compiler should optimize those away, but better to avoid
them in the first place.)

Type promotions are a slightly modified version of the [standard C/C++ numeric
promotions
](http://en.cppreference.com/w/cpp/language/implicit_conversion#Numeric_promotions)
with the two differences being that *there is no default promotion to int*
and *bitwise logical operations always return an unsigned of the wider type.*

*** aside
Most arithmetic operations saturate normally, to the numeric limit in the
direction of the sign. The potentially unusual cases are:

*   **Division:** Division by zero returns the saturated limit in the direction
    of sign of the dividend (first argument). The one exception is 0/0, which
	returns zero (although logically is NaN).
*   **Modulus:** Division by zero returns the dividend (first argument).
*   **Left shift:** Non-zero values saturate in the direction of the signed
    limit (max/min), even for shifts larger than the bit width. 0 shifted any
    amount results in 0.
*   **Right shift:** Negative values saturate to -1. Positive or 0 saturates
    to 0. (Effectively just an unbounded arithmetic-right-shift.)
*   **Bitwise operations:** No saturation; bit pattern is identical to
    non-saturated bitwise operations.
***

### Members

The unary negation, increment, and decrement operators are supported, along
with the following unary arithmetic methods, which return a new
`ClampedNumeric` as a result of the operation:

*   `Abs()` - Absolute value.
*   `UnsignedAbs()` - Absolute value as an equal-width unsigned underlying type
    (valid for only integral types).
*   `Max()` - Returns whichever is greater of the current instance or argument.
    The underlying return type is whichever has the greatest magnitude.
*   `Min()` - Returns whichever is lowest of the current instance or argument.
    The underlying return type is whichever has can represent the lowest
    number in the smallest width (e.g. int8_t over unsigned, int over
    int8_t, and float over int).

The following are for converting `ClampedNumeric` instances:

*   `type` - The underlying numeric type.
*   `RawValue()` - Returns the raw value as the underlying arithmetic type. This
    is useful when e.g. assigning to an auto type or passing as a deduced
    template parameter.
*   `Cast<>()` - Instance method returning a `ClampedNumeric` derived from
    casting the current instance to a `ClampedNumeric` of the supplied
    destination type.

### Non-member helper functions

The following variadic convenience functions, which accept standard arithmetic
or `ClampedNumeric` types, perform arithmetic operations, and return a
`ClampedNumeric` result. The supported functions are:

*   `ClampAdd()` - Addition.
*   `ClampSub()` - Subtraction.
*   `ClampMul()` - Multiplication.
*   `ClampDiv()` - Division.
*   `ClampMod()` - Modulus (integer only).
*   `ClampLsh()` - Left integer shift (integer only).
*   `ClampRsh()` - Right integer shift (integer only).
*   `ClampAnd()` - Bitwise AND (integer only with unsigned result).
*   `ClampOr()`  - Bitwise OR (integer only with unsigned result).
*   `ClampXor()` - Bitwise XOR (integer only with unsigned result).
*   `ClampMax()` - Maximum of supplied arguments.
*   `ClampMin()` - Minimum of supplied arguments.

The following is a general utility method that is useful for converting
to a `ClampedNumeric` type:

*   `MakeClampedNum()` - Creates a new `ClampedNumeric` from the underlying type
    of the supplied arithmetic or directly convertible type.


text:
<!DOCTYPE html>

    <title>2015 計算機程式 作業二 - 2015FALL KMOL 課程</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="canonical" href="./2015cp_hw_w4.html">

        <meta name="author" content="40323213" />
        <meta name="keywords" content="pelican,publishing" />
        <meta name="description" content="作業二摘要" />

        <meta property="og:site_name" content="2015FALL KMOL 課程" />
        <meta property="og:type" content="article"/>
        <meta property="og:title" content="2015 計算機程式 作業二"/>
        <meta property="og:url" content="./2015cp_hw_w4.html"/>
        <meta property="og:description" content="作業二摘要"/>
        <meta property="article:published_time" content="2015-11-01" />
            <meta property="article:section" content="Python" />
            <meta property="article:tag" content="pelican" />
            <meta property="article:tag" content="publishing" />
            <meta property="article:author" content="40323213" />

        <link rel="stylesheet" href="./theme/css/bootstrap.min.css" type="text/css"/>
    <link href="./theme/css/font-awesome.min.css" rel="stylesheet">

    <link href="./theme/css/pygments/native.css" rel="stylesheet">
    <link rel="stylesheet" href="./theme/css/style.css" type="text/css"/>

        <link href="./feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
              title="2015FALL KMOL 課程 ATOM Feed"/>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                Toggle navigation

            </button>

2015FALL KMOL 課程

                            Python

Archives

                        2015 計算機程式 作業二

    Date

        <time datetime="2015-11-01T12:41:00+08:00"> 週日 01 十一月 2015</time>

Tags
	pelican
        /
	publishing

以下為作業二內容

利用 iframe 嵌入投影片:

作業二投影片

作業二錄影 from nash on Vimeo.

Comments

        Please enable JavaScript to view the comments powered by
            Disqus.
        comments powered by Disqus

Social

 You can add links in your config file

 Another social link

Tags

Links

                2015課程網頁

                Python

                You can modify those links in your config file

© 2015 KMOL
            · Powered by pelican-bootstrap3,
            Pelican,
            Bootstrap

 Back to top


text:
#include "OgreStableHeaders.h"
#include "OfsFileSystem.h"
#include "OgreLogManager.h"
#include "OgreException.h"
#include "OgreStringVector.h"
#include "OgreRoot.h"

#include <boost/regex.hpp>

namespace Ogre {

	bool OFSArchive::ms_IgnoreHidden = true;

    //-----------------------------------------------------------------------
    OFSArchive::OFSArchive(const String& name, const String& archType)
        : Archive(name, archType)
    {
        int pos = name.find("::");
        mName = name;
        mFileSystemName = name.substr(0, pos);
        mDir = name;
        mDir.erase(0, pos + 2);
        if(!mDir.empty() && mDir[mDir.length() - 1] == '/')
            mDir.erase(mDir.length() - 1, 1);
    }
    //-----------------------------------------------------------------------
    bool OFSArchive::isCaseSensitive(void) const
    {
        return true;
    }
    //-----------------------------------------------------------------------
    static bool is_absolute_path(const char* path)
    {
        return path[0] == '/' || path[0] == '\\';
    }
    //-----------------------------------------------------------------------
    static String concatenate_path(const String& base, const String& name)
    {
        if (base.empty() || is_absolute_path(name.c_str()))
            return name;
        else
            return base + '/' + name;
    }
    //-----------------------------------------------------------------------
    void OFSArchive::findFiles(const String& pattern, bool recursive,
        bool dirs, StringVector* simpleList, FileInfoList* detailList) const
    {
        // pattern can contain a directory name, separate it from mask
        size_t pos1 = pattern.rfind ('/');
        size_t pos2 = pattern.rfind ('\\');
        if (pos1 == pattern.npos || ((pos2 != pattern.npos) && (pos1 < pos2)))
            pos1 = pos2;
        String directory;
        if (pos1 != pattern.npos)
            directory = pattern.substr (0, pos1 + 1);

        String full_pattern = concatenate_path(mDir, pattern);
        String mod_pattern = pattern;

        OFS::FileList retList = mOfs->listFiles(mDir.c_str(), OFS::OFS_FILE);

        if(pattern == "*")
        {
            for(unsigned int i = 0;i < retList.size();i++)
            {
                if (simpleList)
                {
                    simpleList->push_back(directory + retList[i].name);
                }
                else if (detailList)
                {
                    FileInfo fi;
                    fi.archive = (Archive*)this;
                    fi.filename = directory + retList[i].name;
                    fi.basename = retList[i].name;
                    fi.path = directory;
                    fi.compressedSize = retList[i].file_size;
                    fi.uncompressedSize = retList[i].file_size;
                    detailList->push_back(fi);
                }
            }
        }
        else
        {
            if(mod_pattern[0] == '*')
                mod_pattern = "." + mod_pattern;

            try
            {
                const boost::regex e(mod_pattern.c_str());

                for(unsigned int i = 0;i < retList.size();i++)
                {
                    if(regex_match(retList[i].name.c_str(), e))
                    {
                        if (simpleList)
                        {
                            simpleList->push_back(directory + retList[i].name);
                        }
                        else if (detailList)
                        {
                            FileInfo fi;
                            fi.archive = (Archive*)this;
                            fi.filename = directory + retList[i].name;
                            fi.basename = retList[i].name;
                            fi.path = directory;
                            fi.compressedSize = retList[i].file_size;
                            fi.uncompressedSize = retList[i].file_size;
                            detailList->push_back(fi);
                        }
                    }
                }
            }
            catch(...)
            {
            }
        }
/*
        lHandle = _findfirst(full_pattern.c_str(), &tagData);
        res = 0;
        while (lHandle != -1 && res != -1)
        {
            if ((dirs == ((tagData.attrib & _A_SUBDIR) != 0)) &&
				( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
                (!dirs || !is_reserved_dir (tagData.name)))
            {
                if (simpleList)
                {
                    simpleList->push_back(directory + tagData.name);
                }
                else if (detailList)
                {
                    FileInfo fi;
                    fi.archive = this;
                    fi.filename = directory + tagData.name;
                    fi.basename = tagData.name;
                    fi.path = directory;
                    fi.compressedSize = tagData.size;
                    fi.uncompressedSize = tagData.size;
                    detailList->push_back(fi);
                }
            }
            res = _findnext( lHandle, &tagData );
        }
        // Close if we found any files
        if(lHandle != -1)
            _findclose(lHandle);

        // Now find directories
        if (recursive)
        {
            String base_dir = mName;
            if (!directory.empty ())
            {
                base_dir = concatenate_path(mName, directory);
                // Remove the last '/'
                base_dir.erase (base_dir.length () - 1);
            }
            base_dir.append ("/*");

            // Remove directory name from pattern
            String mask ("/");
            if (pos1 != pattern.npos)
                mask.append (pattern.substr (pos1 + 1));
            else
                mask.append (pattern);

            lHandle = _findfirst(base_dir.c_str (), &tagData);
            res = 0;
            while (lHandle != -1 && res != -1)
            {
                if ((tagData.attrib & _A_SUBDIR) &&
					( !ms_IgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) &&
                    !is_reserved_dir (tagData.name))
                {
                    // recurse
                    base_dir = directory;
                    base_dir.append (tagData.name).append (mask);
                    findFiles(base_dir, recursive, dirs, simpleList, detailList);
                }
                res = _findnext( lHandle, &tagData );
            }
            // Close if we found any files
            if(lHandle != -1)
                _findclose(lHandle);
        }
*/
    }
    //-----------------------------------------------------------------------
    OFSArchive::~OFSArchive()
    {
        unload();
    }
    //-----------------------------------------------------------------------
    void OFSArchive::load()
    {
		OGRE_LOCK_AUTO_MUTEX;

        // test to see if this folder is writeable
		String testPath = mFileSystemName + "__testwrite.ogre";
		std::ofstream writeStream;
		writeStream.open(testPath.c_str());
		if (writeStream.fail())
			mReadOnly = true;
		else
		{
			mReadOnly = false;
			writeStream.close();
			::remove(testPath.c_str());
		}

        mOfs.mount(mFileSystemName.c_str(), OFS::OFS_MOUNT_OPEN);
    }
    //-----------------------------------------------------------------------
    void OFSArchive::unload()
    {
        OGRE_LOCK_AUTO_MUTEX;

        mOfs.unmount();
    }
    //-----------------------------------------------------------------------
    DataStreamPtr OFSArchive::open(const String& filename, bool readOnly) const
    {
        String name = concatenate_path(mDir, filename);

        std::replace(name.begin(), name.end(), '\\', '/');

        unsigned int mode = OFS::OFS_READ;

		if (!readOnly && !isReadOnly())
            mode |= OFS::OFS_WRITE;

        OFS::OFSHANDLE *handle = new OFS::OFSHANDLE();
        OFS::OfsResult ret = mOfs->openFile(*handle, name.c_str(), mode);

        if(ret != OFS::OFS_OK)
        {
			delete handle;

            OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND,
				"Cannot open file: " + name,
				"OFSArchive::open");
        }

		/// Construct return stream, tell it to delete on destroy
		OfsDataStream* stream = OGRE_NEW OfsDataStream(mOfs, handle);

        return DataStreamPtr(stream);
    }
	//---------------------------------------------------------------------
	DataStreamPtr OFSArchive::create(const String& filename)
	{
		if (isReadOnly())
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
				"Cannot create a file in a read-only archive",
				"OFSArchive::create");
		}

        String name = concatenate_path(mDir, filename);

        std::replace(name.begin(), name.end(), '\\', '/');

        OFS::OFSHANDLE *handle = new OFS::OFSHANDLE();
        OFS::OfsResult ret = mOfs->createFile(*handle, name.c_str());

        if(ret != OFS::OFS_OK)
        {
			delete handle;

            OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND,
				"Cannot create file: " + name,
				"OFSArchive::create");
        }

		/// Construct return stream, tell it to delete on destroy
		OfsDataStream* stream = OGRE_NEW OfsDataStream(mOfs, handle);

        return DataStreamPtr(stream);
	}
	//---------------------------------------------------------------------
	void OFSArchive::remove(const String& filename)
	{
		if (isReadOnly())
		{
			OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
				"Cannot remove a file from a read-only archive",
				"OFSArchive::remove");
		}

		String name = concatenate_path(mDir, filename);

        std::replace(name.begin(), name.end(), '\\', '/');

        mOfs->deleteFile(name.c_str());
	}
    //-----------------------------------------------------------------------
    StringVectorPtr OFSArchive::list(bool recursive, bool dirs) const
    {
		// directory change requires locking due to saved returns
		// Note that we have to tell the SharedPtr to use OGRE_DELETE_T not OGRE_DELETE by passing category
		StringVectorPtr ret(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);

        findFiles("*", recursive, dirs, ret.getPointer(), 0);

        return ret;
    }
    //-----------------------------------------------------------------------
    FileInfoListPtr OFSArchive::listFileInfo(bool recursive, bool dirs) const
    {
		// Note that we have to tell the SharedPtr to use OGRE_DELETE_T not OGRE_DELETE by passing category
        FileInfoListPtr ret(OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);

        findFiles("*", recursive, dirs, 0, ret.getPointer());

        return ret;
    }
    //-----------------------------------------------------------------------
    StringVectorPtr OFSArchive::find(const String& pattern,
                                            bool recursive, bool dirs) const
    {
		// Note that we have to tell the SharedPtr to use OGRE_DELETE_T not OGRE_DELETE by passing category
		StringVectorPtr ret(OGRE_NEW_T(StringVector, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);

        findFiles(pattern, recursive, dirs, ret.getPointer(), 0);

        return ret;

    }
    //-----------------------------------------------------------------------
    FileInfoListPtr OFSArchive::findFileInfo(const String& pattern,
        bool recursive, bool dirs) const
    {
		// Note that we have to tell the SharedPtr to use OGRE_DELETE_T not OGRE_DELETE by passing category
		FileInfoListPtr ret(OGRE_NEW_T(FileInfoList, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T);

        findFiles(pattern, recursive, dirs, 0, ret.getPointer());

        return ret;
    }
    //-----------------------------------------------------------------------
	bool OFSArchive::exists(const String& filename) const
	{
		String name = concatenate_path(mDir, filename);

        std::replace(name.begin(), name.end(), '\\', '/');

        return mOfs->exists(name.c_str());
	}
	//---------------------------------------------------------------------
	time_t OFSArchive::getModifiedTime(const String& filename) const
	{
		String name = concatenate_path(mDir, filename);

        std::replace(name.begin(), name.end(), '\\', '/');

        time_t mod_time = 0;

        mOfs->getModificationTime(name.c_str(), mod_time);

	    return mod_time;
	}
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    //-----------------------------------------------------------------------
    OfsDataStream::OfsDataStream(OFS::OfsPtr _ofsptr, OFS::OFSHANDLE *_handle)
        : mOfs(_ofsptr), mFileHandle(_handle)
    {
        assert(_handle != NULL);
        OFS::ofs64 sz = 0;

        _ofsptr->getFileSize(*_handle, sz);
        _ofsptr->getFileName(*_handle, mName);

        mSize = sz;

        mAccess = 0;

        if(_handle->getAcessFlags() & OFS::OFS_READ)
            mAccess |= DataStream::READ;

        if(_handle->getAcessFlags() & OFS::OFS_WRITE)
            mAccess |= DataStream::WRITE;
    }
    //-----------------------------------------------------------------------
	OfsDataStream::~OfsDataStream()
	{
		close();
	}
    //-----------------------------------------------------------------------
    size_t OfsDataStream::read(void* buf, size_t count)
    {
        unsigned int read_amount = 0;

        mOfs->read(*mFileHandle, (char*)buf, count, &read_amount);

        return read_amount;
    }
	//---------------------------------------------------------------------
	size_t OfsDataStream::write(const void* buf, size_t count)
	{
        if(mOfs->write(*mFileHandle, (const char*)buf, (unsigned int)count) == OFS::OFS_OK)
            return count;
        else
            return 0;
	}
    //-----------------------------------------------------------------------
    void OfsDataStream::skip(long count)
    {
        mOfs->seek(*mFileHandle, count, OFS::OFS_SEEK_CURRENT);
    }
    //-----------------------------------------------------------------------
    void OfsDataStream::seek(size_t pos)
    {
        mOfs->seek(*mFileHandle, pos, OFS::OFS_SEEK_BEGIN);
    }
    //-----------------------------------------------------------------------
    size_t OfsDataStream::tell(void) const
    {
        return mOfs->tell(*mFileHandle);
    }
    //-----------------------------------------------------------------------
    bool OfsDataStream::eof(void) const
    {
        return mOfs->eof(*mFileHandle);
    }
    //-----------------------------------------------------------------------
    void OfsDataStream::close(void)
    {
        if (mFileHandle != 0)
		{
            mOfs->closeFile(*mFileHandle);

            delete mFileHandle;
            mFileHandle = 0;
		}

        mOfs.unmount();
    }
    //-----------------------------------------------------------------------
    const String& OFSArchiveFactory::getType(void) const
    {
        static String name = "Ofs";
        return name;
    }
    //-----------------------------------------------------------------------
}


text:
package com.jiahaoliuliu.unittestingwithandroidstudio;

import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowApplication;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Created by jiahao on 3/9/15.
 */
@RunWith(RobolectricGradleTestRunner.class)
public class MainActivityTest {

    private MainActivity mMainActivity;

    @Before
    public void setup() {
        Intent startMainActivityIntent = new Intent(
                ShadowApplication.getInstance().getApplicationContext(), MainActivity.class);
        // Here you can add any data to the intent

        mMainActivity = Robolectric.buildActivity(MainActivity.class)
                .withIntent(startMainActivityIntent).create().get();
    }

    @Test
    public void linkedViewsTest() {
        assertThat(mMainActivity).isNotNull();

        EditText firstNumberET = (EditText)mMainActivity.findViewById(R.id.first_number_et);
        assertThat(firstNumberET).isNotNull();

        TextView addSymbolTV = (TextView)mMainActivity.findViewById(R.id.add_symbol_tv);
        assertThat(addSymbolTV).isNotNull();

        EditText secondNumberET = (EditText)mMainActivity.findViewById(R.id.second_number_et);
        assertThat(secondNumberET).isNotNull();

        Button calculateBtn = (Button)mMainActivity.findViewById(R.id.calculate_btn);
        assertThat(calculateBtn).isNotNull();

        TextView resultTV = (TextView)mMainActivity.findViewById(R.id.result_tv);
        assertThat(resultTV).isNotNull();

    }

    @Test
    public void valuesInitializedTest() {
        EditText firstNumberET = (EditText)mMainActivity.findViewById(R.id.first_number_et);
        assertThat(firstNumberET.getText()).isEqualTo("0");

        TextView addSymbolTV = (TextView)mMainActivity.findViewById(R.id.add_symbol_tv);
        assertThat(addSymbolTV.getText()).isEqualTo("+");

        EditText secondNumberET = (EditText)mMainActivity.findViewById(R.id.second_number_et);
        assertThat(secondNumberET.getText()).isEqualTo("0");

        Button calculateBtn = (Button)mMainActivity.findViewById(R.id.calculate_btn);
        assertThat(calculateBtn.getText()).isEqualTo("=");

        TextView resultTV = (TextView)mMainActivity.findViewById(R.id.result_tv);
        assertThat(resultTV.getText()).isEmpty();
    }

    /**
     * This test check if the calculator could do the follow operation:
     *     1 + 2 = 3
     */
    @Test
    public void simpleSumTest() {
        int firstNumber = 1;
        int secondNumber = 2;

        Calculator calculator = new Calculator(firstNumber, secondNumber);
        int result = calculator.sum();

        EditText firstNumberET = (EditText)mMainActivity.findViewById(R.id.first_number_et);
        firstNumberET.setText(String.valueOf(firstNumber));

        EditText secondNumberET = (EditText)mMainActivity.findViewById(R.id.second_number_et);
        secondNumberET.setText(String.valueOf(secondNumber));

        Button calculateBtn = (Button)mMainActivity.findViewById(R.id.calculate_btn);
        calculateBtn.performClick();

        TextView resultTV = (TextView)mMainActivity.findViewById(R.id.result_tv);
        assertThat(resultTV.getText()).isEqualTo(String.valueOf(result));
    }

    @After
    public void tearDown() {
        mMainActivity = null;
    }
}


text:
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
 * Print Recursive
 *
 * Simply wraps a print_r() in pre tags for debugging.
 *
 * @param mixed
 * @return string
 */
if (!function_exists('_pr')) {
    function _pr($a)
    {
        echo "
";
        print_r($a);
        echo "
";
    }
}

// ------------------------------------------------------------------------

/*
 * Variable Dump
 *
 * Simply wraps a var_dump() in pre tags for debugging.
 *
 * @param mixed
 * @return string
 */
if (!function_exists('_vd')) {
    function _vd($a)
    {
        echo "
";
        var_dump($a);
        echo "
";
    }
}

// ------------------------------------------------------------------------

/*
 * Array to Object
 *
 * Converts an array to an object
 *
 * @param array
 * @return object
 */
if (!function_exists('array_to_object')) {
    function array_to_object($array)
    {
        $Object = new stdClass();
        foreach ($array as $key => $value) {
            $Object->$key = $value;
        }

        return $Object;
    }
}

// ------------------------------------------------------------------------

/*
 * Object to Array
 *
 * Converts an object to an array
 *
 * @param object
 * @return array
 */
if (!function_exists('object_to_array')) {
    function object_to_array($Object)
    {
        $array = get_object_vars($Object);

        return $array;
    }
}

// ------------------------------------------------------------------------

/*
 * Is Ajax
 *
 * Returns true if request is ajax protocol
 *
 * @return bool
 */
if (!function_exists('is_ajax')) {
    function is_ajax()
    {
        return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
    }
}

// ------------------------------------------------------------------------

/*
 * Image Thumb
 *
 * Creates an image thumbnail and caches the image
 *
 * @param string
 * @param int
 * @param int
 * @param bool
 * @param array
 * @return string
 */
if (!function_exists('image_thumb')) {
    function image_thumb($source_image, $width = 0, $height = 0, $crop = FALSE, $props = array())
    {
        $CI =& get_instance();
        $CI->load->library('image_cache');

        $props['source_image'] = '/' . str_replace(base_url(), '', $source_image);
        $props['width'] = $width;
        $props['height'] = $height;
        $props['crop'] = $crop;

        $CI->image_cache->initialize($props);
        $image = $CI->image_cache->image_cache();
        $CI->image_cache->clear();

        return $image;
    }
}

// ------------------------------------------------------------------------

/*
 * BR 2 NL
 *
 * Converts html
 to new line \n
 *
 * @param string
 * @return string
 */
if (!function_exists('br2nl')) {
    function br2nl($text)
    {
        return preg_replace('/
/i', '', $text);
    }
}

// ------------------------------------------------------------------------

/*
 * Option Array Value
 *
 * Returns single dimension array from an Array of objects with the key and value defined
 *
 * @param array
 * @param string
 * @param string
 * @param array
 * @return array
 */
if (!function_exists('option_array_value')) {
    function option_array_value($object_array, $key, $value, $default = array())
    {
        $option_array = array();

        if (!empty($default)) {
            $option_array = $default;
        }

        foreach ($object_array as $Object) {
            $option_array[$Object->$key] = $Object->$value;
        }

        return $option_array;
    }
}

// ------------------------------------------------------------------------

/*
 * In URI
 *
 * Checks if current uri segments exist in array of uri strings
 *
 * @param string or array
 * @param string
 * @param bool
 * @return bool
 */
if (!function_exists('in_uri')) {
    function in_uri($uri_array, $uri = null, $array_keys = FALSE)
    {
        if (!is_array($uri_array)) {
            $uri_array = array($segments);
        }

        $CI =& get_instance();

        if (!empty($uri)) {
            $uri_string = '/' . trim($uri, '/');
        } else {
            $uri_string = '/' . trim($CI->uri->uri_string(), '/');
        }

        $uri_array = ($array_keys) ? array_keys($uri_array) : $uri_array;

        foreach ($uri_array as $string) {
            if (strpos($uri_string, ($string != '') ? '/' . trim($string, '/') : ' ') === 0) {
                $exp = explode($string, $uri_string);
                if ($exp[1] == "") {
                    return true;
                }
            }
        }

        return false;
    }
}

// ------------------------------------------------------------------------

/*
 * Theme Partial
 *
 * Load a theme partial
 *
 * @param string
 * @param array
 * @param bool
 * @return string
 */
if (!function_exists('theme_partial')) {
    function theme_partial($view, $vars = array(), $return = TRUE)
    {
        $CI =& get_instance();
        $CI->load->library('parser');

        return $CI->parser->parse_string($CI->load->theme($CI->template->theme . '/views/partials/' . trim($view, '/'), $vars, $return, $CI->template->theme_path), $vars, $return);
    }
}

// ------------------------------------------------------------------------

/*
 * Theme Url
 *
 * Create a url to the current theme
 *
 * @param string
 * @return string
 */
if (!function_exists('theme_url')) {
    function theme_url($uri = '')
    {
        $CI =& get_instance();
        return base_url($CI->template->theme_path . '/' . $CI->template->theme . '/' . trim($uri, '/'));
    }
}

// ------------------------------------------------------------------------

/*
 * Domain Name
 *
 * Returns the site domain name and tld
 *
 * @return string
 */
if (!function_exists('domain_name')) {
    function domain_name()
    {
        $CI =& get_instance();

        $info = parse_url($CI->config->item('base_url'));
        $host = $info['host'];
        $host_names = explode(".", $host);
        return $host_names[count($host_names) - 2] . "." . $host_names[count($host_names) - 1];
    }
}

// ------------------------------------------------------------------------

/*
 * Glob Recursive
 *
 * Run glob function recursivley on a directory
 *
 * @param string
 * @return array
 */
if (!function_exists('glob_recursive')) {
    // Does not support flag GLOB_BRACE

    function glob_recursive($pattern, $flags = 0)
    {
        $files = glob($pattern, $flags);

        foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
            $files = array_merge($files, glob_recursive($dir . '/' . basename($pattern), $flags));
        }

        return $files;
    }
}

// ------------------------------------------------------------------------

/*
 * URL Base64 Encode
 *
 * Encodes a string as base64, and sanitizes it for use in a CI URI.
 *
 * @param string
 * @return string
 */
if (!function_exists('url_base64_encode')) {
    function url_base64_encode(&$str = "")
    {
        return strtr(
            base64_encode($str),
            array(
                '+' => '.',
                '=' => '-',
                '/' => '~'
            )
        );
    }
}

// ------------------------------------------------------------------------

/*
 * URL Base64 Decode
 *
 * Decodes a base64 string that was encoded by ci_base64_encode.
 *
 * @param string
 * @return string
 */
if (!function_exists('url_base64_decode')) {
    function url_base64_decode(&$str = "")
    {
        return base64_decode(strtr(
            $str,
            array(
                '.' => '+',
                '-' => '=',
                '~' => '/'
            )
        ));
    }
}

// ------------------------------------------------------------------------

/*
 * Output XML
 *
 * Sets the header content type to XML and
 * outputs the <?php xml tag
 *
 * @param string
 * @return string
 */
if (!function_exists('xml_output')) {
    function xml_output()
    {
        $CI =& get_instance();
        $CI->output->set_content_type('text/xml');
        $CI->output->set_output("<?phpxml version=\"1.0\"?>\r\n");
    }
}

// ------------------------------------------------------------------------

/*
 * JS Head Start
 *
 * Starts output buffering to place javascript in the  of the template
 *
 * @return void
 */
if (!function_exists('js_start')) {
    function js_start()
    {
        ob_start();
    }
}

// ------------------------------------------------------------------------

/*
 * JS Head End
 *
 * Ends output buffering to place javascript in the  of the template
 *
 * @return void
 */
if (!function_exists('js_end')) {
    function js_end()
    {
        $CI =& get_instance();
        $CI->template->add_script(ob_get_contents());
        ob_end_clean();
    }
}

// ------------------------------------------------------------------------

/*
 * String to Boolean
 *
 * This function analyzes a string and returns false if the string is empty, false, or 0
 * and true for everything else
 *
 * @param string
 * @return bool
 */
if (!function_exists('str_to_bool')) {
    function str_to_bool($str)
    {
        if (is_bool($str)) {
            return $str;
        }

        $str = (string)$str;

        if (in_array(strtolower($str), array('false', '0', ''))) {
            return false;
        } else {
            return true;
        }
    }
}

// ------------------------------------------------------------------------

/*
 * Is Inline Editable
 *
 * Returns true if inline editing is enabled, admin toolbar is enabled, and user is an administrator
 *
 * @return bool
 */
if (!function_exists('is_inline_editable')) {
    function is_inline_editable($content_type_id = null)
    {
        $CI =& get_instance();
        $CI->load->model('content_types_model');

        if ($CI->settings->enable_inline_editing && $CI->settings->enable_admin_toolbar && $CI->secure->group_types(array(ADMINISTRATOR))->is_auth()) {
            if (empty($content_type_id)) {
                return TRUE;
            }

            if ($CI->Group_session->type != SUPER_ADMIN) {
                // Check if we have already cached permissions for this content type
                if (!isset($CI->content_types_model->has_permission_cache[$content_type_id])) {
                    $Content_types_model = new Content_types_model();

                    // No permission for this content type has been cached yet.
                    // Query to see if current user has permission to this content type
                    $Content_type = $Content_types_model->group_start()
                        ->where('restrict_admin_access', 0)
                        ->or_where_related('admin_groups', 'group_id', $CI->Group_session->id)
                        ->group_end()
                        ->get_by_id($content_type_id);

                    $CI->content_types_model->has_permission_cache[$content_type_id] = ($Content_type->exists()) ? TRUE : FALSE;
                }

                return $CI->content_types_model->has_permission_cache[$content_type_id];
            } else {
                return TRUE;
            }
        } else {
            return FALSE;
        }
    }
}


text:
package com.squeezer.designpatterns.prototype;

public abstract class Prototype implements Cloneable {

    protected String mText;

    public Prototype(String text) {
        mText = text;
    }

    @Override
    public Prototype clone() throws CloneNotSupportedException {
        return (Prototype) super.clone();
    }

    public void setText(String text) {
        mText = text;
    }

    public abstract void display();
}


text:
typedef enum {
    UPStackMenuStackPosition_up = 0,
    UPStackMenuStackPosition_down
} UPStackMenuStackPosition_e;

typedef enum {
    UPStackMenuAnimationType_linear = 0,
    UPStackMenuAnimationType_progressive,
    UPStackMenuAnimationType_progressiveInverse
} UPStackMenuAnimationType_e;

@protocol UPStackMenuDelegate;

@interface UPStackMenu : UIView <UPStackMenuItemDelegate>

// Vertical spacing between each stack menu item
@property (nonatomic, readwrite)            CGFloat                     itemsSpacing;
// Whether the items should bounce at the end of the opening animation, or a the beginning of the closing animaton
@property (nonatomic, readwrite)            BOOL                        bouncingAnimation;
// Opening animation total duration (in seconds)
@property (nonatomic, readwrite)            NSTimeInterval              openAnimationDuration;
// Closing animation total duration (in seconds)
@property (nonatomic, readwrite)            NSTimeInterval              closeAnimationDuration;
// Delay between each item animation start during opening (in seconds)
@property (nonatomic, readwrite)            NSTimeInterval              openAnimationDurationOffset;
// Delay between each item animation start during closing (in seconds)
@property (nonatomic, readwrite)            NSTimeInterval              closeAnimationDurationOffset;
@property (nonatomic, readwrite)            UPStackMenuStackPosition_e  stackPosition;
@property (nonatomic, readwrite)            UPStackMenuAnimationType_e  animationType;
@property (nonatomic, readonly)             BOOL                        isOpen;
@property (nonatomic, unsafe_unretained)    id<UPStackMenuDelegate>     delegate;

- (id)initWithContentView:(UIView*)contentView;

- (void)addItem:(UPStackMenuItem*)item;
- (void)addItems:(NSArray*)items;
- (void)removeItem:(UPStackMenuItem*)item;
- (void)removeItemAtIndex:(NSUInteger)index;
- (void)removeAllItems;

- (NSArray*)items;

- (void)openStack;
- (void)closeStack;

@end

@protocol UPStackMenuDelegate <NSObject>

@optional
- (void)stackMenuWillOpen:(UPStackMenu*)menu;
- (void)stackMenuDidOpen:(UPStackMenu*)menu;
- (void)stackMenuWillClose:(UPStackMenu*)menu;
- (void)stackMenuDidClose:(UPStackMenu*)menu;
- (void)stackMenu:(UPStackMenu*)menu didTouchItem:(UPStackMenuItem*)item atIndex:(NSUInteger)index;

@end


text:
package com.svbio.cloudkeeper.model.beans.element.serialization;

import com.svbio.cloudkeeper.model.bare.element.serialization.BareByteSequence;
import com.svbio.cloudkeeper.model.bare.element.serialization.BareSerializationNodeVisitor;
import com.svbio.cloudkeeper.model.bare.element.serialization.BareSerializationRoot;
import com.svbio.cloudkeeper.model.bare.element.serialization.BareSerializedString;
import com.svbio.cloudkeeper.model.beans.element.MutableQualifiedNamable;
import com.svbio.cloudkeeper.model.immutable.element.Key;
import com.svbio.cloudkeeper.model.immutable.element.NoKey;

import javax.annotation.Nullable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.util.List;

final class JAXBAdapters {
    private JAXBAdapters() {
        throw new AssertionError(String.format("No %s instances for you!", getClass().getName()));
    }

    private interface JAXBSerializationNode {
        MutableSerializationNode<?> toMutableSerializationNode();
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    static final class JAXBByteSequence implements JAXBSerializationNode {
        @XmlAttribute
        @Nullable
        private Key id;

        @XmlValue
        @Nullable
        private byte[] byteSequence;

        @Override
        public MutableByteSequence toMutableSerializationNode() {
            return new MutableByteSequence()
                .setKey(id)
                .setArray(byteSequence);
        }
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    static final class JAXBSerializedString implements JAXBSerializationNode {
        @XmlAttribute
        @Nullable
        private Key id;

        @XmlValue
        @Nullable
        private String string;

        @Override
        public MutableSerializedString toMutableSerializationNode() {
            return new MutableSerializedString()
                .setKey(id)
                .setString(string);
        }
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    static final class JAXBSerializationRoot implements JAXBSerializationNode {
        @XmlAttribute
        @Nullable
        private Key id;

        @XmlAttribute
        @Nullable
        private MutableQualifiedNamable ref;

        @XmlElements({
            @XmlElement(type = JAXBByteSequence.class, name = "serialized-as-byte-stream"),
            @XmlElement(type = JAXBSerializedString.class, name = "serialized-as-string"),
            @XmlElement(type = JAXBSerializationRoot.class, name = "serialized-as-tree")
        })
        @Nullable
        private List<MutableSerializationNode<?>> entries;

        @Override
        public MutableSerializationRoot toMutableSerializationNode() {
            MutableSerializationRoot serializationRoot = new MutableSerializationRoot()
                .setKey(
                    id == null
                        ? NoKey.instance()
                        : id
                )
                .setDeclaration(ref);
            if (entries != null) {
                serializationRoot.setEntries(entries);
            }
            return serializationRoot;
        }
    }

    enum ToJAXBVisitor implements BareSerializationNodeVisitor<Object, Void> {
        INSTANCE;

        @Override
        public JAXBSerializationRoot visitRoot(BareSerializationRoot node, @Nullable Void parameter) {
            MutableSerializationRoot mutableNode = (MutableSerializationRoot) node;
            JAXBSerializationRoot jaxbSerializationRoot = new JAXBSerializationRoot();
            jaxbSerializationRoot.id = mutableNode.getKey();
            jaxbSerializationRoot.ref = mutableNode.getDeclaration();
            jaxbSerializationRoot.entries = mutableNode.getEntries();
            return jaxbSerializationRoot;
        }

        @Override
        public JAXBByteSequence visitByteSequence(BareByteSequence node, @Nullable Void parameter) {
            JAXBByteSequence jaxbByteSequence = new JAXBByteSequence();
            jaxbByteSequence.id = node.getKey();
            jaxbByteSequence.byteSequence = node.getArray();
            return jaxbByteSequence;
        }

        @Override
        public JAXBSerializedString visitText(BareSerializedString node, @Nullable Void parameter) {
            JAXBSerializedString jaxbSerializedString = new JAXBSerializedString();
            jaxbSerializedString.id = node.getKey();
            jaxbSerializedString.string = node.getString();
            return jaxbSerializedString;
        }
    }

    static final class SerializationNodeAdapter extends XmlAdapter<Object, MutableSerializationNode<?>> {
        @Override
        @Nullable
        public MutableSerializationNode<?> unmarshal(@Nullable Object original) {
            return original == null
                ? null
                : ((JAXBSerializationNode) original).toMutableSerializationNode();
        }

        @Override
        @Nullable
        public Object marshal(@Nullable MutableSerializationNode<?> original) {
            return original == null
                ? null
                : original.accept(ToJAXBVisitor.INSTANCE, null);
        }
    }

    static final class SerializationRootAdapter extends XmlAdapter<JAXBSerializationRoot, MutableSerializationRoot> {
        @Override
        @Nullable
        public MutableSerializationRoot unmarshal(@Nullable JAXBSerializationRoot original) {
            return original == null
                ? null
                : original.toMutableSerializationNode();
        }

        @Override
        @Nullable
        public JAXBSerializationRoot marshal(@Nullable MutableSerializationRoot original) {
            return original == null
                ? null
                : ToJAXBVisitor.INSTANCE.visitRoot(original, null);
        }
    }
}


text:
package com.jetbrains.python.testing.doctest;

import com.intellij.execution.Executor;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.RunProfileState;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.WriteExternalException;
import com.jetbrains.python.testing.AbstractPythonLegacyTestRunConfiguration;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;

public class PythonDocTestRunConfiguration extends AbstractPythonLegacyTestRunConfiguration<PythonDocTestRunConfiguration>
                                          implements PythonDocTestRunConfigurationParams {
  protected @NlsSafe String myPluralTitle = "Doctests";
  protected @NlsSafe String myTitle = "Doctest";
  public PythonDocTestRunConfiguration(Project project,
                                       ConfigurationFactory configurationFactory) {
    super(project, configurationFactory);
  }

  @Override
  protected SettingsEditor<PythonDocTestRunConfiguration> createConfigurationEditor() {
    return new PythonDocTestRunConfigurationEditor(getProject(), this);
  }

  @Override
  public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) {
    return new PythonDocTestCommandLineState(this, env);
  }

  @Override
  public void readExternal(@NotNull Element element) throws InvalidDataException {
    super.readExternal(element);
  }

  @Override
  public void writeExternal(@NotNull Element element) throws WriteExternalException {
    super.writeExternal(element);
  }

  @Override
  protected String getTitle() {
    return myTitle;
  }

  @Override
  protected String getPluralTitle() {
    return myPluralTitle;
  }

  public static void copyParams(PythonDocTestRunConfigurationParams source, PythonDocTestRunConfigurationParams target) {
    copyParams(source.getTestRunConfigurationParams(), target.getTestRunConfigurationParams());
  }
}


text:
<?php

declare(strict_types = 1);

namespace Unicity\MappingService\Data {

	use \Unicity\Core;
	use \Unicity\MappingService;

	/**
	 * This class enumerates the different types of data format used by the mapping service
	 * via the data translation.
	 *
	 * @access public
	 * @class
	 * @final
	 * @package MappingService
	 */
	final class FormatType extends Core\Enum {

		/**
		 * This variable stores the enumerations.
		 *
		 * @access protected
		 * @static
		 * @var array                                               an indexed array of the enumerations
		 */
		protected static $__enums;

		/**
		 * This method returns the token at the specified ordinal index.
		 *
		 * @access protected
		 * @static
		 * @param integer $ordinal                                  the ordinal index of the token
		 * @return MappingService\Data\FormatType                   the token
		 */
		protected static function __enum(int $ordinal) : MappingService\Data\FormatType {
			if (!is_array(static::$__enums)) {
				static::$__enums = array();
				static::$__enums[] = new static('canonical', 'Canonical');
				static::$__enums[] = new static('model', 'Model');
			}
			return static::$__enums[$ordinal];
		}

		/**
		 * This constructor initializes the enumeration.
		 *
		 * @access protected
		 * @param string $name                                      the name of the enumeration
		 * @param mixed $value                                      the value to be assigned to the
		 *                                                          enumeration
		 */
		protected function __construct(string $name, $value) {
			$this->__name = $name;
			$this->__value = $value;
			$this->__ordinal = count(static::$__enums);
		}

		/**
		 * This method returns the "canonical" token.
		 *
		 * @access public
		 * @static
		 * @return MappingService\Data\FormatType                   the format type token
		 */
		public static function canonical() : \Unicity\MappingService\Data\FormatType {
			return static::__enum(0);
		}

		/**
		 * This method returns the "model" token.
		 *
		 * @access public
		 * @static
		 * @return MappingService\Data\FormatType                   the format type token
		 */
		public static function model() : \Unicity\MappingService\Data\FormatType {
			return static::__enum(1);
		}

	}

}


text:
package command_parser

import (
	"strings"

	"code.cloudfoundry.org/cli/command/translatableerror"
)

func preventExtraArgs(args []string) error {
	if len(args) > 0 {
		return translatableerror.TooManyArgumentsError{
			ExtraArgument: strings.Join(args, " "),
		}
	}
	return nil
}