text:
typedef pcl::PointXYZRGB PointC;
typedef pcl::PointCloud<PointC> PointCloudC;

namespace rapid {
namespace perception {
PoseEstimationMatch::PoseEstimationMatch()
    : cloud_(new PointCloudC), fitness_(std::numeric_limits<double>::max()) {}

PoseEstimationMatch::PoseEstimationMatch(PointCloudC::Ptr cloud,
                                         const geometry_msgs::Pose& pose,
                                         const geometry_msgs::Vector3& scale,
                                         double fitness)
    : cloud_(new PointCloudC), pose_(pose), scale_(scale), fitness_(fitness) {
  *cloud_ = *cloud;
  Eigen::Vector4f min_pt;
  Eigen::Vector4f max_pt;
  pcl::getMinMax3D(*cloud_, min_pt, max_pt);
  center_.x = min_pt.x() + (max_pt.x() - min_pt.x()) / 2;
  center_.y = min_pt.y() + (max_pt.y() - min_pt.y()) / 2;
  center_.z = min_pt.z() + (max_pt.z() - min_pt.z()) / 2;
}

pcl::PointCloud<pcl::PointXYZRGB>::Ptr PoseEstimationMatch::cloud() const {
  return cloud_;
}

geometry_msgs::Pose PoseEstimationMatch::pose() const { return pose_; }

geometry_msgs::Vector3 PoseEstimationMatch::scale() const { return scale_; }

pcl::PointXYZ PoseEstimationMatch::center() const { return center_; }

double PoseEstimationMatch::fitness() const { return fitness_; }

void PoseEstimationMatch::set_fitness(double fitness) { fitness_ = fitness; }

bool ComparePoseEstimationMatch(const PoseEstimationMatch& a,
                                const PoseEstimationMatch& b) {
  return a.fitness() < b.fitness();
}

void VisualizeMatches(ros::Publisher& pub, ros::Publisher& marker_pub,
                      const std::vector<PoseEstimationMatch>& matches) {
  std::string frame_id = "";
  visualization_msgs::Marker clear;
  clear.ns = "output";
  clear.action = 3;
  if (marker_pub) {
    marker_pub.publish(clear);
  }
  if (pub) {
    PointCloudC::Ptr output_cloud(new PointCloudC);
    for (size_t i = 0; i < matches.size(); ++i) {
      const PoseEstimationMatch& match = matches[i];
      viz::ColorizeRandom(match.cloud());
      *output_cloud += *match.cloud();
      if (frame_id == "" && match.cloud()->header.frame_id != "") {
        frame_id = match.cloud()->header.frame_id;
      }

      if (marker_pub) {
        geometry_msgs::PoseStamped ps;
        ps.header.frame_id = match.cloud()->header.frame_id;
        ps.pose = match.pose();
        visualization_msgs::Marker box = viz::OutlineBox(ps, match.scale());
        box.ns = "output";
        box.id = i;
        box.scale.x = 0.0025;
        marker_pub.publish(box);
      }

      // geometry_msgs::PoseStamped ps;
      // ps.header.frame_id = match.cloud()->header.frame_id;
      // ps.pose = match.pose();
      // viz::Marker output_box =
      //    viz::Marker::OutlineBox(marker_pub, ps, object_roi_dimensions);
      // geometry_msgs::Vector3 scale;
      // scale.x = 0.0025;
      // output_box.SetScale(scale);
      // output_box.SetNamespace("output");
      // output_boxes.push_back(output_box);
      // output_boxes[output_boxes_.size() - 1].Publish();
    }
    if (frame_id == "") {
      frame_id = "base_link";
    }
    ROS_INFO("Visualizing matches in frame: %s", frame_id.c_str());
    output_cloud->header.frame_id = frame_id;
    viz::PublishCloud(pub, *output_cloud);
  }
}
}  // namespace perception
}  // namespace rapid


text:
/*
 * This file can be used for general library features of flow-test-123.
 *
 * The library features can be made available as CommonJS modules that the
 * components in this project utilize.
 */

redpajama_set_name: RedPajamaGithub


text:
---
title: Change the height of the input element
page_title: Change the height of the input element | UI for ASP.NET AJAX Documentation
description: Change the height of the input element
slug: combobox/appearance-and-styling/change-the-height-of-the-input-element
tags: tutorial,change,height,input,element
published: True
position: 4
---

# Change the height of the input element

>caution This page contains information about RadComboBox for ASP.NET Ajax version **2009.1.311 and later.** If you are using any previous version - please check [this article]({%slug combobox/appearance-and-styling/change-the-height-of-the-input-element%}).
>

## Introduction

**Vertical dimensions** [Telerik Visual Style Builder](http://stylebuilder.telerik.com/)

## Gather your tools

````ASPNET
<telerik:RadComboBox runat="server" id="RadComboBox1">
	<Items>
		<telerik:RadComboBoxItem Text="Alpha" />
		<telerik:RadComboBoxItem Text="Vita" />
		<telerik:RadComboBoxItem Text="Ghamma" />
		<telerik:RadComboBoxItem Text="Epsilon" />
		<telerik:RadComboBoxItem Text="Zeta" />
		<telerik:RadComboBoxItem Text="Eta" />
		<telerik:RadComboBoxItem Text="Theta" />
		<telerik:RadComboBoxItem Text="Iota" />
		<telerik:RadComboBoxItem Text="Kappa" />
		<telerik:RadComboBoxItem Text="Lambda" />
	</Items>
</telerik:RadComboBox>
````

Now that we have a test project, we will need to take one Office2007 skin from this folder: `<RadControls install folder>`\Skins\Office2007\Copy the file **ComboBox.Office2007.css** and the folder ComboBox, create a Skins folder in your project, create a sub-folder named **50pxOffice2007** and Paste them in it. Modify your RadComboBox declaration like this to disable the embedded skin:

````ASPNET
<telerik:radcombobox
    runat="server"
    skin="Office2007"
    enableembeddedskins="false"
    id="RadComboBox">
````

Add a link to the CSS file in the head tag:

````ASPNET
<link href="Skins/50pxOffice2007/ComboBox.Office2007.css" rel="stylesheet" type="text/css" />
````

Check if everything renders properly - the combobox skin should look like the Office2007 skin now.

## Claim your skin

To really make the skin your own you will need to give it a name. As you probably already guessed, mine will be called **50pxOffice2007**, but you can be more creative. First rename your skin CSS file to ComboBox.50pxOffice2007.css:

![ComboBox Rename](images/combobox_renameshot.png)

and change the link in the test file to:

````ASPNET
<link href="Skins/50pxOffice2007/ComboBox.50pxOffice2007.css" rel="stylesheet" type="text/css" />
````

The actual name of the CSS file does not really matter but it's a good practice to name your assets with meaningful names that will help you find them easier. Now open the file and invoke the Find&Replace tool with Ctrl+H or Edit `->` Find and Replace `->` Quick Replace. Pay attention to what you are replacing and replace all occurrences of **_Office2007** with **_50pxOffice2007** in the CSS file:

![ComboBox Replace](images/combobox_replaceshot.png)

Save the file. Open Default.aspx and change RadComboBox skin name accordingly:

````ASPNET
<telerik:radcombobox
runat="server"
skin="50pxOffice2007"
enableembeddedskins="false">
````

Check if the skin renders okay.

## Getting Your Hands Dirty

Now that we have an external skin of our own, we can start changing it to fit our needs. First launch your Photoshop and open the **rcbSprite.png** (not the IE6 one – It is 8bit indexed alpha). Are you confused? Let's fix that:

![ComboBox Combo Explained](images/combobox_comboexplained.png)

As you can see, the top four rows are for the four RadComboBox state backgrounds, while the fifth row contains only the drop down arrow backgrounds. The rest of the sprite is used for styling the drop down header and footer.So, now that we know how the sprite is constructed, we need to resize the state and the arrow backgrounds to 50px height. To be able to do that, first we will need to resize the RadComboBox sprite image canvas to fit the expanding contents. Use Image `->` Canvas Size or Ctrl+Alt+C and enter 300px for height (5x50+what remains for the header). Align the contents to the top. Next, drag some guides from the top ruler and place them in 50px intervals starting from the first 50px. Then one by one cut the different states and the header (select one state with the Selection tool, create new Layer via Cut with the context menu and drag it to its new place) and place them under every guide until you get this:

![ComboBox Distributed Sprites](images/combobox_distributedsprites.png)

Now we are ready to resize the state sprites.

## Running with Scissors

After placing the states at their proper places, we'll need to resize them carefully in order to preserve the gradients as much as possible. To do that we will need scaling algorithm different than Nearest Neighbor – go to Edit `->` Preferences `->` General `->` Image Interpolation and choose Bicubic or Bicubic Smoother. Hit OK. Now use the Selection tool to select the bottom half of the Normal state then hold Ctrl and drag it until you reach the bottom guide with the bottom edge of the selection. You should get something like this in the end:

![ComboBox Resize Step1](images/combobox_resize1ststep.png)

Now select one or several pixels high line closer to the inner edges, change to the Move tool (with V) and scale the selection upwards (or downwards depending on where you selected) until you get this:

![ComboBox Resize Step2](images/combobox_resize2ndstep.png)

Split the second sprite right in the middle – select from the half to the bottom edge, separating the light from the dark colors, hold Ctrl and drag to the bottom guide.

![ComboBox Resize Step3](images/combobox_resize3rdstep.png)

Drag a new guide in the middle of the empty space (at exactly 75px), like this:

![ComboBox Resize Step4](images/combobox_resize4thstep.png)

Next, carefully select the bottom part of the sprite from the top edge to 3px above the bottom one. We want to leave the bottom edge and the corner transparency intact. Your selection should look like this:

![ComboBox Resize Step5](images/combobox_resize5thstep.png)

Scale it to the middle:

![ComboBox Resize Step6](images/combobox_resize6thstep.png)

And do the same to the top part of the sprite:

![ComboBox Resize Step7](images/combobox_resize7thstep.png)

Now repeat for the rest of the states until you get to the arrows.

## Pixel Art

Now that we have all the states ready, we should also resize the arrow ends. This task is more complicated since the arrow is part of the background. So, in order to resize them, we will need first to separate the arrows from the background. To do so we will use a Magic Wand (tool – activated with W). Adjust some of the tool properties – set the Tolerance to 110, switch off Anti-alias, but leave Contiguous on. Now select the arrows one by one, excluding the disabled two – we'll need to change the tolerance to 20 before doing so. Also add to the selection the white arrow pixels in the hover and selected states. Most skins probably won't require using tolerance and additional pixels, but we chose one of the hardest so you can get the idea. After you finish selecting, get the context menu up and do a Layer via Cut:

![ComboBox Resize Step8](images/combobox_resize8thstep.png)

After cutting the arrows, hide the new layer and you can resize the states as before. There's one little detail though – every state now will have a hole in the middle. Fill it up before you start resizing – either with copy and paste, with the Stamp tool (be careful with the source of the stamp though) or by using select and duplicate (Ctrl + Alt + drag selection). Show the hidden arrows in the end and move their layer to the middle. You should get something like this in the end:

![ComboBox Resize Step9](images/combobox_resize9thstep.png)

We are ready with the sprite now.

## Saving your work

Now that we have the sprite image ready, we should replace the existing ones in the external skin we prepared. Open Save for Web and Devices dialog and use the following options to save **rcbSprite.png**:

![ComboBox Resize Step9](images/combobox_saveforweb.png)

Note that we are using **24bit PNG with alpha transparency** here. Replace the rcbSprite.png file which you've opened in the beginning. Since IE6 doesn't support the alpha transparency of 24bit PNGs (rendering it completely opaque), we will need a second sprite image only for this browser. Bring up again Save for Web and Devices but use these options this time:

![ComboBox Resize Step9](images/combobox_saveforwebie6.png)

Make sure **Matte** is set to **None**, otherwise you won't get index transparency on the state corners. Hit Save and replace the **rcbSpriteIE6.png** file in the same folder.

## Specificity Wars

Now that we are done with the sprite images, a relatively easy part remains – fixing the skin CSS to support the new sprite height we have made. Switch to your editor and open the CSS file. First thing to do is to override the default height and line-height of the Office2007 RadComboBox. Add this CSS rule somewhere in your CSS file, let's say at the end:

````CSS
div.RadComboBox_50pxOffice2007 table td.rcbInputCell
{
    height: 50px;
    line-height:50px;
}
````

Note the element type in front of the first class – it is used to **raise the specificity** so that we can override the base stylesheet selectors (the baseStyleSheet was added in Q3 2009 release). If you want to learn more about specificity, there's an excellent article in the [Smashing Magazine](http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/). Now that we have RadComboBox height, we should change the background-positions of the four states. Find the lines below in the file (**note that the line numbers below can change in next releases,** these are based on the Q2 2009 Office2007 skin) and change them accordingly to the sprite image background positions - from divisible by 22, to divisible by 50:

Around lines 40-44:

````CSS
.RadComboBox_50pxOffice2007 .rcbHovered .rcbReadOnly td.rcbInputCellLeft
{
    background-position: 0 -50px;
}

.RadComboBox_50pxOffice2007 .rcbHovered .rcbReadOnly td.rcbInputCellRight
{
    background-position: 100% -50px;
}

.RadComboBox_50pxOffice2007 .rcbFocused .rcbReadOnly td.rcbInputCellLeft
{
    background-position: 0 -100px;
}

.RadComboBox_50pxOffice2007 .rcbFocused .rcbReadOnly td.rcbInputCellRight
{
    background-position: 100% -100px;
}
````

Around lines 56-85:

````CSS
.RadComboBox_50pxOffice2007 td.rcbArrowCellLeft { background-position: -18px -200px; }
.RadComboBox_50pxOffice2007 td.rcbArrowCellRight { background-position: 0 -200px; }
.RadComboBox_50pxOffice2007 .rcbHovered .rcbArrowCellLeft { background-position: -54px -200px; }
.RadComboBox_50pxOffice2007 .rcbHovered .rcbArrowCellRight { background-position: -36px -200px; }
.RadComboBox_50pxOffice2007 .rcbFocused .rcbArrowCellLeft { background-position: -90px -200px; }
.RadComboBox_50pxOffice2007 .rcbFocused .rcbArrowCellRight { background-position: -72px -200px; }
.RadComboBox_50pxOffice2007 td.rcbArrowCellHidden,
.RadComboBox_50pxOffice2007 .rcbHovered td.rcbArrowCellHidden,
.RadComboBox_50pxOffice2007 .rcbFocused td.rcbArrowCellHidden { background-position: -15px -200px; }
/* Read-only styles */
.RadComboBox_50pxOffice2007 .rcbHovered .rcbReadOnly td.rcbArrowCellHidden { background-position: -51px -200px; }
.RadComboBox_50pxOffice2007 .rcbFocused .rcbReadOnly td.rcbArrowCellHidden { background-position: -87px -200px; }
.RadComboBox_50pxOffice2007 .rcbReadOnly td.rcbArrowCellLeft { background-position: -18px -200px; }
.RadComboBox_50pxOffice2007 .rcbReadOnly td.rcbArrowCellRight { background-position: -2px -200px; }
.RadComboBox_50pxOffice2007 .rcbHovered .rcbReadOnly .rcbArrowCellLeft { background-position: -54px -200px; }
.RadComboBox_50pxOffice2007 .rcbHovered .rcbReadOnly .rcbArrowCellRight { background-position: -38px -200px; }
.RadComboBox_50pxOffice2007 .rcbFocused .rcbReadOnly .rcbArrowCellLeft { background-position: -90px -200px; }
.RadComboBox_50pxOffice2007 .rcbFocused .rcbReadOnly .rcbArrowCellRight { background-position: -74px -200px; }
.RadComboBox_50pxOffice2007 .rcbReadOnly td.rcbArrowCellHidden { background-position: -15px -200px; }
.RadComboBox_50pxOffice2007 .rcbHovered .rcbReadOnly td.rcbArrowCellHidden { background-position: -51px -200px; }
.RadComboBox_50pxOffice2007 .rcbFocused .rcbReadOnly td.rcbArrowCellHidden { background-position: -87px -200px; }
Around line 114:
.RadComboBoxDropDown_50pxOffice2007 .rcbHeader,
.RadComboBoxDropDown_50pxOffice2007 .rcbFooter
{
background-color: #f1f2f4;
background-position: 0 -250px;
}
````

Around lines 150-156:

````CSS
.RadComboBox_50pxOffice2007 .rcbDisabled td.rcbInputCellLeft { background-position: 0 -150px; }
.RadComboBox_50pxOffice2007 .rcbDisabled td.rcbInputCellRight { background-position: 100% -150px; }
.RadComboBox_50pxOffice2007 .rcbDisabled td.rcbArrowCellLeft { background-position: -126px -200px; }
.RadComboBox_50pxOffice2007 .rcbDisabled td.rcbArrowCellRight { background-position: -108px -200px; }
.RadComboBox_50pxOffice2007 .rcbDisabled .rcbReadOnly td.rcbArrowCellRight { background-position: -110px -200px; }
.RadComboBox_50pxOffice2007 table.rcbDisabled td.rcbArrowCellHidden,
.RadComboBox_50pxOffice2007 .rcbDisabled .rcbReadOnly td.rcbArrowCellHidden { background-position: -123px -200px; }
````

Around line 172:

````CSS
.RadComboBoxDropDown_50pxOffice2007 .rcbMoreResults a
{
    background-position: -157px-220px;
}
````

Refresh your page – your 50px RadComboBox looks great! One finishing touch – if you want to change the font family and size – use the style on line 9 to do it:

````CSS
.RadComboBox_50pxOffice2007,.RadComboBox_50pxOffice2007 .rcbInput,.RadComboBoxDropDown_50pxOffice2007
{
    font: bold 18px "Segoe UI", Arial, sans-serif;
    color: #333;
}
````

That's all. I hope this tutorial was helpful to you. Have fun designing new and exciting skins for RadComboBox.

You can download a sample project from [here](http://blogs.telerik.com/Files/ComboResizeTutorial.zip).


text:
package com.opengamma.bbg.loader;

import static com.opengamma.bbg.BloombergConstants.BBG_WEEKLY_INDEX_OPTIONS_TYPE;
import static com.opengamma.bbg.BloombergConstants.BLOOMBERG_EQUITY_INDEX_TYPE;
import static com.opengamma.bbg.BloombergConstants.FIELD_CRNCY;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUTURES_CATEGORY;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_LAST_TRADE_DT;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_LONG_NAME;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_TRADING_HRS;
import static com.opengamma.bbg.BloombergConstants.FIELD_FUT_VAL_PT;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_BBG_UNIQUE;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_CUSIP;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_ISIN;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_MIC_PRIM_EXCH;
import static com.opengamma.bbg.BloombergConstants.FIELD_ID_SEDOL1;
import static com.opengamma.bbg.BloombergConstants.FIELD_MARKET_SECTOR_DES;
import static com.opengamma.bbg.BloombergConstants.FIELD_PARSEKYABLE_DES;
import static com.opengamma.bbg.BloombergConstants.FIELD_UNDL_SPOT_TICKER;
import static com.opengamma.bbg.util.BloombergDataUtils.isValidField;

import java.util.Collections;
import java.util.Set;

import org.fudgemsg.FudgeMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.ZonedDateTime;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.opengamma.bbg.referencedata.ReferenceDataProvider;
import com.opengamma.bbg.util.BloombergDataUtils;
import com.opengamma.core.id.ExternalSchemes;
import com.opengamma.financial.security.future.EquityFutureSecurity;
import com.opengamma.id.ExternalId;
import com.opengamma.master.security.ManageableSecurity;
import com.opengamma.util.money.Currency;
import com.opengamma.util.time.Expiry;

/** Creates EquityFutureSecurity from fields loaded from Bloomberg */
public class EquityFutureLoader extends SecurityLoader {

  /** Logger. */
  private static final Logger s_logger = LoggerFactory.getLogger(EquityFutureLoader.class);

  /** The fields to load from Bloomberg */
  private static final Set<String> BLOOMBERG_EQUITY_FUTURE_FIELDS = Collections.unmodifiableSet(Sets.newHashSet(
      FIELD_FUT_LONG_NAME,
      FIELD_FUT_LAST_TRADE_DT,
      FIELD_FUT_TRADING_HRS,
      FIELD_ID_MIC_PRIM_EXCH,
      FIELD_CRNCY,
      FIELD_MARKET_SECTOR_DES,
      FIELD_PARSEKYABLE_DES,
      FIELD_UNDL_SPOT_TICKER,
      FIELD_ID_BBG_UNIQUE,
      FIELD_ID_CUSIP,
      FIELD_ID_ISIN,
      FIELD_ID_SEDOL1,
      FIELD_FUT_VAL_PT,
      FIELD_FUTURES_CATEGORY));

  /** The set of valid Bloomberg 'Futures Category Types' that will map to EquityFutureSecurity */
  public static final Set<String> VALID_SECURITY_TYPES = ImmutableSet.of(
      BLOOMBERG_EQUITY_INDEX_TYPE,
      BBG_WEEKLY_INDEX_OPTIONS_TYPE); // THIS IS IFFY - 2EH3 INDEX, FOR EXAMPLE, HAS A FUTURE CATEGORY OF WEEKLY INDEX OPTIONS, THOUGH IT JUST AN ALIAS FOR ESH3 INDEX WHICH IS EQUITY INDEX);
                                      //TODO: Answer this: Are Equity Index Futures EquityFutureSecurity or IndexFutureSecurity? - See EquityFutureLoader, too
  /**
   * Creates an instance.
   * @param referenceDataProvider  the provider, not null
   */
  public EquityFutureLoader(ReferenceDataProvider referenceDataProvider) {
    super(s_logger, referenceDataProvider, SecurityType.EQUITY_FUTURE);
  }

  //-------------------------------------------------------------------------
  @Override
  protected ManageableSecurity createSecurity(FudgeMsg fieldData) {
    String expiryDate = fieldData.getString(FIELD_FUT_LAST_TRADE_DT);
    String futureTradingHours = fieldData.getString(FIELD_FUT_TRADING_HRS);
    String micExchangeCode = fieldData.getString(FIELD_ID_MIC_PRIM_EXCH);
    String currencyStr = fieldData.getString(FIELD_CRNCY);
    String underlyingTicker = fieldData.getString(FIELD_UNDL_SPOT_TICKER);
    String name = BloombergDataUtils.removeDuplicateWhiteSpace(fieldData.getString(FIELD_FUT_LONG_NAME), " ");
    String category = BloombergDataUtils.removeDuplicateWhiteSpace(fieldData.getString(FIELD_FUTURES_CATEGORY), " ");
    String bbgUnique = fieldData.getString(FIELD_ID_BBG_UNIQUE);
    String marketSector = fieldData.getString(FIELD_MARKET_SECTOR_DES);
    String unitAmount = fieldData.getString(FIELD_FUT_VAL_PT);

    if (!isValidField(bbgUnique)) {
      s_logger.warn("bbgUnique is null, cannot construct EquityFutureSecurity");
      return null;
    }
    if (!isValidField(expiryDate)) {
      s_logger.warn("expiry date is null, cannot construct EquityFutureSecurity");
      return null;
    }
    if (!isValidField(futureTradingHours)) {
      s_logger.warn("futures trading hours is null, cannot construct EquityFutureSecurity");
      return null;
    }
    if (!isValidField(micExchangeCode)) {
      s_logger.warn("settlement exchange is null, cannot construct EquityFutureSecurity");
      return null;
    }
    if (!isValidField(currencyStr)) {
      s_logger.info("currency is null, cannot construct EquityFutureSecurity");
      return null;
    }
    if (!isValidField(category)) {
      s_logger.info("category is null, cannot construct EquityFutureSecurity");
      return null;
    }
    ExternalId underlying = null;
    if (underlyingTicker != null) {
      underlying = ExternalSchemes.bloombergTickerSecurityId(underlyingTicker + " " + marketSector);
    }

    Currency currency = Currency.parse(currencyStr);

    Expiry expiry = decodeExpiry(expiryDate, futureTradingHours);
    if (expiry == null) {
      return null;
    }

    // FIXME: Case - treatment of Settlement Date
    s_logger.warn("Creating EquityFutureSecurity - settlementDate set equal to expiryDate. Missing lag.");
    ZonedDateTime settlementDate = expiry.getExpiry();

    EquityFutureSecurity security = new EquityFutureSecurity(expiry, micExchangeCode, micExchangeCode, currency, Double.valueOf(unitAmount), settlementDate, underlying, category);
    security.setName(name);
    // set identifiers
    parseIdentifiers(fieldData, security);
    return security;
  }

  @Override
  protected Set<String> getBloombergFields() {
    return BLOOMBERG_EQUITY_FUTURE_FIELDS;
  }

}


text:
package cogroo.uima;

import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;

public class FakeAE extends JCasAnnotator_ImplBase {

  @Override
  public void process(JCas aJCas) throws AnalysisEngineProcessException {
    // TODO Auto-generated method stub

  }

}


text:
package hbase

import (
	"math"
	"time"

	pb "github.com/golang/protobuf/proto"
	"github.com/lazyshot/go-hbase/proto"

	"bytes"
	"fmt"
	"strings"
)

type Scan struct {
	client *Client

	id    uint64
	table []byte

	StartRow []byte
	StopRow  []byte

	families   [][]byte
	qualifiers [][][]byte

	nextStartRow []byte

	numCached int
	closed    bool

	//for filters
	timeRange *TimeRange

	location *regionInfo
	server   *connection
}

const (
	// copy from golang source code time/time.go
	// since it is private in time package, just copy it
	secondsPerHour       = 60 * 60
	secondsPerDay        = 24 * secondsPerHour
	unixToInternal int64 = (1969*365 + 1969/4 - 1969/100 + 1969/400) * secondsPerDay
)

var maxTimestamp time.Time

func init() {
	// because golang's internal time represent is from Jan 1st, 1
	// so if we want the max timestamp, we have to minus time.unixToInternal
	// and as hbase accept a microsecond based timestamp, we divided it by 1000
	maxTimestamp = time.Unix((math.MaxInt64-unixToInternal)/1e9, 0)
}

func newScan(table []byte, client *Client) *Scan {
	return &Scan{
		client:       client,
		table:        table,
		nextStartRow: nil,

		families:   make([][]byte, 0),
		qualifiers: make([][][]byte, 0),

		numCached: 100,
		closed:    false,

		timeRange: nil,
	}
}

// set scan time range
func (s *Scan) SetTimeRange(from time.Time, to time.Time) {
	if s.timeRange == nil {
		s.timeRange = &TimeRange{
			From: from,
			To:   to,
		}
	} else {
		s.timeRange.From = from
		s.timeRange.To = to
	}
}

// set scan time start only.
// if set start only, use a max timestamp as end automaticly.
// but since max timestamp is not a precise value,
// you'd better use `SetTimeRange()` set start and end yourself.
func (s *Scan) SetTimeRangeFrom(from time.Time) {
	s.SetTimeRange(from, maxTimestamp)
}

// set scan time end only.
//if only set end, use time.Unix(0, 0)(Jan 1st, 1970) as start automaticly
func (s *Scan) SetTimeRangeTo(to time.Time) {
	s.SetTimeRange(time.Unix(0, 0), to)
}

func (s *Scan) SetCached(n int) {
	s.numCached = n
}

func (s *Scan) Map(f func(*ResultRow)) {
	for {
		results := s.next()

		if results == nil {
			break
		}

		for _, v := range results {
			f(v)

			if s.closed {
				return
			}
		}
	}
}

func (s *Scan) Close() {
	if s.closed == false {
		log.Debug("Closing scan: %d", s.id)
		s.closeScan(s.server, s.location, s.id)
		s.closed = true
	}
}

func (s *Scan) AddString(famqual string) error {
	parts := strings.Split(famqual, ":")

	if len(parts) > 2 {
		return fmt.Errorf("Too many colons were found in the family:qualifier string. '%s'", famqual)
	} else if len(parts) == 2 {
		s.AddStringColumn(parts[0], parts[1])
	} else {
		s.AddStringFamily(famqual)
	}

	return nil
}

func (s *Scan) AddStringColumn(family, qual string) {
	s.AddColumn([]byte(family), []byte(qual))
}

func (s *Scan) AddStringFamily(family string) {
	s.AddFamily([]byte(family))
}

func (s *Scan) AddColumn(family, qual []byte) {
	s.AddFamily(family)

	pos := s.posOfFamily(family)

	s.qualifiers[pos] = append(s.qualifiers[pos], qual)
}

func (s *Scan) AddFamily(family []byte) {
	pos := s.posOfFamily(family)

	if pos == -1 {
		s.families = append(s.families, family)
		s.qualifiers = append(s.qualifiers, make([][]byte, 0))
	}
}

func (s *Scan) posOfFamily(family []byte) int {
	for p, v := range s.families {
		if bytes.Equal(family, v) {
			return p
		}
	}
	return -1
}

func (s *Scan) getData(nextStart []byte) []*ResultRow {
	if s.closed {
		return nil
	}

	server, location := s.getServerAndLocation(s.table, nextStart)

	req := &proto.ScanRequest{
		Region: &proto.RegionSpecifier{
			Type:  proto.RegionSpecifier_REGION_NAME.Enum(),
			Value: []byte(location.name),
		},
		NumberOfRows: pb.Uint32(uint32(s.numCached)),
		Scan:         &proto.Scan{},
	}

	if s.id > 0 {
		req.ScannerId = pb.Uint64(s.id)
	} else {
		if s.StartRow != nil {
			req.Scan.StartRow = s.StartRow
		}
		if s.StopRow != nil {
			req.Scan.StopRow = s.StopRow
		}
		if s.timeRange != nil {
			req.Scan.TimeRange = &proto.TimeRange{
				From: pb.Uint64(uint64(s.timeRange.From.UnixNano() / 1e6)),
				To:   pb.Uint64(uint64(s.timeRange.To.UnixNano() / 1e6)),
			}
		}
	}

	for i, v := range s.families {
		req.Scan.Column = append(req.Scan.Column, &proto.Column{
			Family:    v,
			Qualifier: s.qualifiers[i],
		})
	}

	log.Debug("sending scan request: [server=%s] [id=%d]", server.name, s.id)

	cl := newCall(req)
	server.call(cl)

	log.Debug("sent scan request: [server=%s] [id=%d]", server.name, s.id)

	select {
	case msg := <-cl.responseCh:
		return s.processResponse(msg)
	}
}

var lastRegionRows int = 0

func (s *Scan) processResponse(response pb.Message) []*ResultRow {
	var res *proto.ScanResponse
	switch r := response.(type) {
	case *proto.ScanResponse:
		res = r
	default:
		log.Error("Invalid response returned: %T", response)
		return nil
	}

	nextRegion := true
	s.nextStartRow = nil
	s.id = res.GetScannerId()

	results := res.GetResults()
	n := len(results)

	lastRegionRows += n

	if (n == s.numCached) ||
		len(s.location.endKey) == 0 ||
		(s.StopRow != nil && bytes.Compare(s.location.endKey, s.StopRow) > 0 && n < s.numCached) ||
		(res.GetMoreResults() && n > 0) {
		nextRegion = false
	}

	if n < s.numCached {
		s.nextStartRow = incrementByteString(s.location.endKey, len(s.location.endKey)-1)
	}

	if nextRegion {
		log.Debug("Finished %s. Num results from region: %d. On to the next one.", s.location.name, lastRegionRows)
		s.closeScan(s.server, s.location, s.id)
		s.server = nil
		s.location = nil
		s.id = 0
		lastRegionRows = 0
	}

	if n == 0 && !nextRegion {
		log.Debug("N == 0 and !nextRegion")
		s.Close()
	}

	tbr := make([]*ResultRow, n)
	for i, v := range results {
		tbr[i] = newResultRow(v)
	}

	return tbr
}

func (s *Scan) next() []*ResultRow {
	startRow := s.nextStartRow
	if startRow == nil {
		startRow = s.StartRow
	}

	return s.getData(startRow)
}

func (s *Scan) closeScan(server *connection, location *regionInfo, id uint64) {

	req := &proto.ScanRequest{
		Region: &proto.RegionSpecifier{
			Type:  proto.RegionSpecifier_REGION_NAME.Enum(),
			Value: []byte(location.name),
		},
		ScannerId:    pb.Uint64(id),
		CloseScanner: pb.Bool(true),
	}
	cl := newCall(req)
	server.call(cl)
	<-cl.responseCh
}

func (s *Scan) getServerAndLocation(table, startRow []byte) (server *connection, location *regionInfo) {
	if s.server != nil && s.location != nil {
		server = s.server
		location = s.location
		return
	}
	log.Debug("Get next region to scan [table=%s] [startRow=%s]", table, startRow)

	location = s.client.locateRegion(table, startRow, true)
	server = s.client.getRegionConnection(location.server)

	log.Debug("Got the next region to scan [table=%s] [regionName=%s] [conn=%s]", table, location.name, server.name)

	s.server = server
	s.location = location
	return
}


text:
package com.hazelcast.map.impl.querycache;

import com.hazelcast.config.Config;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.QueryCacheConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import com.hazelcast.map.QueryCache;
import com.hazelcast.map.impl.querycache.utils.Employee;
import com.hazelcast.query.Predicates;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.Collection;

import static java.lang.String.format;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class QueryCacheDataSyncWithMapTest extends HazelcastTestSupport {

    protected String mapName = randomString();
    protected String cacheName = randomString();
    protected TestHazelcastInstanceFactory factory = createHazelcastInstanceFactory();

    protected IMap<Integer, Employee> map;
    protected QueryCache<Integer, Employee> queryCache;

    @Before
    public void setUp() throws Exception {
        QueryCacheConfig queryCacheConfig = new QueryCacheConfig(cacheName);
        queryCacheConfig.getPredicateConfig().setImplementation(Predicates.alwaysTrue());

        MapConfig mapConfig = new MapConfig(mapName).addQueryCacheConfig(queryCacheConfig);

        Config config = getConfig();
        config.addMapConfig(mapConfig);

        HazelcastInstance instance = factory.newHazelcastInstance(config);
        map = instance.getMap(mapName);
        queryCache = map.getQueryCache(cacheName);
    }

    @Test
    public void map_and_queryCache_data_sync_after_map_clear() {
        test_map_wide_event(MethodName.CLEAR);
    }

    @Test
    public void map_and_queryCache_data_sync_after_map_evictAll() {
        test_map_wide_event(MethodName.EVICT_ALL);
    }

    private void test_map_wide_event(MethodName methodName) {
        for (int i = 0; i < 3; i++) {

            callMethod(methodName);

            int start = i * 10;
            for (int j = start; j < start + 10; j++) {
                map.put(j, new Employee(j));
            }
        }

        assertTrueEventually(new AssertTask() {
            @Override
            public void run() {
                int mapSize = map.size();
                int queryCacheSize = queryCache.size();

                String msg = "query cache should have same size with underlying imap but"
                        + " its size found %d while map size is %d";

                assertEquals(format(msg, queryCacheSize, mapSize), mapSize, queryCacheSize);

                Collection<Employee> valuesInMap = map.values();
                Collection<Employee> valuesInQueryCache = queryCache.values();

                String msg2 = "valuesInMap %s but valuesInQueryCache %s";
                assertTrue(format(msg2, valuesInMap, valuesInQueryCache),
                        valuesInMap.containsAll(valuesInQueryCache));
            }
        });
    }

    private void callMethod(MethodName methodName) {
        switch (methodName) {
            case CLEAR:
                map.clear();
                break;
            case EVICT_ALL:
                map.evictAll();
                break;
        }
    }

    enum MethodName {
        CLEAR,
        EVICT_ALL
    }
}


text:
[![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/yoon-gu/mozart/blob/master/LICENSE)
[![Documentation Status](https://readthedocs.org/projects/mozart/badge/?version=latest)](http://mozart.readthedocs.io/en/latest/?badge=latest)
[![Build Status](https://travis-ci.org/yoon-gu/Mozart.svg?branch=master)](https://travis-ci.org/yoon-gu/Mozart)
[![Build status](https://ci.appveyor.com/api/projects/status/55et5ffdm46eyi2y?svg=true)](https://ci.appveyor.com/project/yoon-gu/mozart)
[![codecov](https://codecov.io/gh/yoon-gu/Mozart/branch/master/graph/badge.svg)](https://codecov.io/gh/yoon-gu/Mozart)
[![Coverage Status](https://coveralls.io/repos/github/yoon-gu/Mozart/badge.svg?branch=master)](https://coveralls.io/github/yoon-gu/Mozart?branch=master)

# Mozart
## Intallation
- run `pip install git+https://github.com/yoon-gu/Mozart.git`
- document : http://mozart.readthedocs.io/en/latest/

## Contribution
1. Fork
1. Write code

	for each element there are three key functions
	1. function to have `matrices` corresponding the `element` and `degree` : `getMatrices(...)`
	1. function to solve `pde` : `solve(...)`
	1. function to compute `error` : `computeError(...)`

1. Add `docstring` for documentation. It should contain the following four things:
	1. Description of a function
	1. `Parameters`
	1. `Returns`
	1. `Example`
	1. For example
		```python
		def one_dim(c4n, n4e, n4Db, f, u_D, degree = 1):
		"""
		Computes the coordinates of nodes and elements.

		Parameters
			- ``c4n`` (``float64 array``) : coordinates
			- ``n4e`` (``int32 array``) : nodes for elements
			- ``n4Db`` (``int32 array``) : Dirichlet boundary nodes
			- ``f`` (``lambda``) : source term
			- ``u_D`` (``lambda``) : Dirichlet boundary condition
			- ``degree`` (``int32``) : Polynomial degree

		Returns
			- ``x`` (``float64 array``) : solution

		Example
			>>> N = 3
			>>> c4n, n4e = unit_interval(N)
			>>> n4Db = [0, N-1]
			>>> f = lambda x: np.ones_like(x)
			>>> u_D = lambda x: np.zeros_like(x)
			>>> from mozart.poisson.solve import one_dim
			>>> x = one_dim(c4n, n4e, n4Db, f, u_D)
			>>> print(x)
			array([ 0.   ,  0.125,  0.   ])
		"""
		```
1. Add test code for your code.
	- Without this, you will have failure for automation test system(`codecov`).
	- run `cd /path/to/Mozart/`
	- run `nosetests`
1. Check documentation by running
	1. `cd /path/to/Mozart/`
	1. `pip uninstall mozart`
	1. `python setup.py install`
	1. `cd /path/to/Mozart/docs`
	1. `make html`(UNIX) or `./make.bat html`(Windows)
	1. Open `Mozart/docs/_build/index.html`


text:
void memory_init();
void memory_refresh(int fd);
void memory_exit();

#endif


text:
layout: post
title: Key features of Swift 2.1
---

# Key features of Swift 2.1

## Introduction
Swift, the programming language Apple designed to replace Objective-C, has split the opinions of many people during it's existence.
For hardcore Objective-C developers it's the incarnation of Lucifer himself, unleashed by demons in Apple to destroy their beloved language.
But for me, and others like me, it's a gift from the good developers in Apple to us common-folk.

It simplifies the development, it's almost infinitely extensible, it's modern and developing in it is fast. And by fast - I mean very,very fast. Since Swift approaches programming from a pragmatic rather than idealistic standpoint, once you get a hang of it - you can develop loads of functionality in only a few lines of code. Being an iOS and Android developer, I can't help myself but compare it to using Java in Android. And in that regard, it leaves Java behind in it's tracks. It has all the features Java has (only the language, not the library) and then some.

It's verbose enough when it needs to be (with named external parameters for example) and very concise when you perform common tasks (filtering lists, unwrapping nils, initialising structures etc...). So now, in no particular order, here is a list of my favourite features of the Swift Programming Language

## Functions as first-class citizens
Functions in Swift are objects. Just like Ints, just like Strings and all the rest. Their type is defined by their signature. So for example `func refactorCode(codeBase : String, refactorer : Refactorer) -> String` would have a type `(String,Refactorer)->String` . Since functions are objects, you can do a lot of interesting things with them:

- Store them in variables and constants
- Pass them as arguments to a function
- Return them from a function
- Store them in Arrays and Dictionaries

This is one of those things that don't seem to be such a big deal when you read about it in the language spec, but it's extremely useful in day to day development. For example you can create a service that loads code Asynchronously and request the function as a parameter

```swift
func performAsyncCall(params : RequestParams, onCompleteHandler : (String)->Void)
```

And then in the calling code you can make a function that handles the request

```swift
func handleRequest(result : String){ ... }
```

And pass it as the function parameter

```swift
...
performAsyncCall(params: requestParams, handleRequest)
...
```
It works asynchronously and it looks concise. I prefer a different way of achieving this behaviour which I will show later in this post

## Tuple data type
Before going further, I must mention the Tuple data type. It's embedded in the language and it enables easy creation of objects without an accompanying class. The usefulness of tuples can't be overstated as they are, in my opinion, one of the strongest features of the language.

A tuple is an ordered pair of values of different types. In Swift we declare tuples by listing them within parentheses and separating them by commas.

```swift
let someTuple = ("Hello", 2, 3.15, new DBContext("db_conn_string"))
```

By default you can access the values of the tuple by their position in the tuple

```swift
someTuple.0 //returns "Hello"
someTuple.1 //returns 2
someTuple.3 //returns an instance of DBContext
```

I use this method rarely since it obscures too much information for my taste. But fortunately, in Swift we are able to name the tuples

```swift
let person = (name: "Tyler Durden", age: 33, mentalState: MentalStateEnum.Schizophrenic)
```

And then access them by their name

```swift
print("Patient name: \(person.name), patient age: \(person.age), patient mental state: \(person.mentalState)")
```

This makes writing some code very short and concise and it enables us to have a function return multiple values - extremely useful for HTTP responses

```swift
func makeHttpRequest(request : HttpRequest) -> (httpResponse: Response, error : NSError?){
	...
	return (response, error)
}
```

We declared a very useful data classification by splitting the data to response and error since now we can check if there is an error and act accordingly. This significantly increases the readability of our code.

You can also use tuples as a quickhand way of initialising multiple variables or constants:

```swift
var (x,y,z) = (2, 7, 3.554)
```

x , y  and z are set to the respective values of corresponding indices

One more cool use of tuples if for exposing the index value of an element in an array while iterating over it - courtesy of the `.enumerate()`function

```swift
	for (index, value) in someArray.enumerate(){
		...
	}
```

## Optionals

Checking for nils (Swift equivalent of null) is a tedious task which should be, if at all possible, avoided. Swift has a syntax shaped in a way that, by default, you **must** pay attention to what each variable or constant can be. If you declare a variable like this

```swift
var someValue : String
```

You cannot set it to nil in any part of your code. Any attempt of setting it to nil will result in a compile time error. Even not initialising it in the constructor of the class will be a compile time error. This variable must, at every point during it's lifecycle, have a value.
If you want to declare a variable that **can** be nil, then you must **explicitly** specify it like this

```swift
var someValue : String?
```

Since swift compiler has the ability to infer types, it will always assume that the type of your variable is not optional. So this code

```swift
var someValue = "This is a value"
someValue = nil
```

**will not work**. The compiler defaults to a non-nil type by default. A behaviour that is complementary to that of Java for example - which defaults to a nullable type.

In order to access values of optionals, we must unwrap them first. You can't just say `let someConst = someOptional` and hope for the best at runtime. You should't be doing this in any other languages as well, but you still do. Because you don't care.
Swift makes doing this very **explicit** and very **ugly**. In order to force unwrap a value, you must but an (!) exclamation mark after it like so

```swift
let someConst = someOptional!
```

this looks bad. And making bad practices explicit rather than default is always a good decision when designing a programming language.
Now, the *right* way of unwrapping in Swift is

```swift
if let unwrappedValue = someOptional{
	//perform success code
} else{
	//value someOptional was nil -> handle accordingly
}
```

or

```swift
guard let unwrappedValue = someOptional else{
	//unwrapping failed, handle accordingly
}
unwrappedValue.performAction() //use unwrappedValue safely, knowing it was unwrapped
```

This way makes it abundantly clear what you're trying to do. And you can always use the good-old nil coalescing operator `let unwrapped = optionalValue ?? defaultValue`which sets the unwrapped to `optionalValue` if it's not nil or sets it to `defaultValue` if `optionalValue` is nil

## Closures

Closures are anonymously defined bits of code that perform an action. They are, like functions, first-class citizens and can be dealt with as we please. Basic closure syntax is

```swift
{
	(param_1, param_2,...,param_n-1, param_n)->ReturnType in
		//perform some action
}
```

This type of invoking closures is most verbose, but I don't use it very often since I like my code to be concise. An example, referring to the function from the first chapter would be

```swift
performAsyncCall(params, {
	(result->String)->Void in
		//Do some work
})
```

Another way of writing the same code would be

```swift
performAsyncCall(params, {
	(result) in
		//Do some work
})
```

This takes advantage of swifts inbuilt type inference capabilities.
Yet another way of writing this would be

```swift
performAsyncCall(params, {
	$0 //Do some work with $0
})
```

If you don't name the parameter, and Swift is able to infer their type - the compiler automatically exposes them as variables with a dollar($) sign and their position index in the function definition

Now yet *another* way of writing the same code would be

```swift
performAsyncCall(params){
	$0 //Do some work with $0
}
```

This leverages the fact that the function onComplete is the **last** parameter of the `performAsyncCall`function. If a function has a function as it's last parameter, you can call it via a **trailing closure** - a block of code encapsulated by curly braces.

You can use all three types of closure calls in trailing closures

## Super powerful enums
In most languages enums tend to be boring. Not in Swift.
You declare enums pretty conventionally

```swift
enum Compass{
	case North
	case West
	case East
	case South
}
```

but very quickly things get very interesting. You can make certain types of enums receive parameters. Define an enum...

```swift
enum Barcode{
	case QR(String)
	case Regular2D([Int])
}
```

...and then simply initialise it and expose it's properties to the underlying code

```swift
var currentBarcode = Barcode.QR("someQrString")
...
...
switch currentBarcode{
	case .QR(let qrCodeString):
		print(qrCodeString) //Prints someQrString
}
```

And just like that you've categorised your data in a simple and intuitive way.
And not just this - Swift enums can have properties. The properties must be computed in some way - most often based on the type of the enum

```swift
enum Compass{
	case West,East,North,South

	var coordinateBase : [Int : Int] {
		switch self{
			case .North :
				return [0 : 1]
			case .South :
				return [0 : -1]
			case .East :
				return [1 : 0]
			case .West :
				return [-1 : 0]
		}
	}
}
```

Then just use this enum in the following way

```swift
let position = Compass.East
print(position.coordinateBase) // returns [1 : 0]
```

This is particularly useful in creating enum routers - a concept widely used in Swift. Enum routers enable type safe and easy generation of request strings for API calls.

Note that the `switch` in Swift must be exhaustive

## Property observers

In Swift you can declare an *observer* for every class propery. There are four kinds of observers:

- `didSet`
- `willSet`
- `didGet`
- `willGet`

the syntax is like so

```swift
var someProperty : Type? {
	didSet{

	}
	willSet{

	}
	didGet{

	}
	willGet{

	}
}
```

Not only is this extremely useful in asynchronous programming (throw some exceptions maybe?), it's a very powerful synchronisation tool. I've used it in the past for exposing variables that get written in the database.

```swift
class DBLayer{
	public static let dbExpose = DBContext("conn_string")

	var someVariable : String {
		didSet{
			dbExpose.update(forKey: "SOME_VARIABLE", someVariable)
			dbExpose.save()
		}
		didGet{
			//Increment counter maybe??
		}
	}
}
```

This snippet, as useless as it is (don't write it like this!) - demonstrates a very intuitive way to synchronise the database every time a variable gets set.

## Extensions

Swift has a simple way of extending the functionality of types. It should be used with caution because if you're not careful you could have the names of your functions collide with the names of other functions - leading to a compiler error

One thing I did using it is extend the inbuilt `String` and extend it with a generic function for parsing the `String` to JSON

```swift
extension String{
	func mapToObject<TType : Mappable>()->TType?{
        return Mapper<TType>().map(self)
    }
}
```

Which can than be called like so

```swift
var someObjectInstance : ObjectType = stringJson.mapToObject()
```

## Do whatever you want with operators

In languages like `Java`, operators are set in stone. If you wanted to implement the addition of two instances of some type, you could only implement something like `.add(Type first, Type second)` and return an instance of the `Type` . In Swift you can

- Overload existing operators
- Implemet the operators as
	- `prefix`
	- `infix`
	- `postfix`
- Adjust the operator precedence
- Implement custom operators

I'll demonstrate this on the example of the `ComplexNumber` class

```swift
struct ComplexNumber{
	public real : Double
	public complex : Double
}

func + (left : ComplexNumber, right: ComplexNumber) -> ComplexNumber{
		return ComplexNumber(left.real + right.real, left.complex + right.complex)
}

//Invert the number
prefix func - (number : ComplexNumber)->ComplexNumber{
	return ComplexNumber(-number.real, -number.real)
}

postfix func ++ (number: ComplexNumber)->ComplexNumber{
	return ComplexNumber(number.real + 1, number.complex + 1)
}

//Modulus of the complex number
prefix func /\ (number: ComplexNumber)->ComplexNumber{
	//sqrt(x*x + y*y) implement
	return ComplexNumber(...,...)//TODO
}
```

This is just some of the most interesting functionality. If you liked the article, follow me on [Twitter](http://twitter.com/mislavjavor) for updates


text:
<?php

declare(strict_types=1);

namespace Windwalker\Stream;

/**
 * The ArrayStream class.
 *
 * @since  2.1
 */
class StringStream extends Stream
{
    /**
     * Stream resource.
     *
     * @var string
     */
    protected $resource;

    /**
     * Property position.
     *
     * @var  integer
     */
    protected $pointer = 0;

    /**
     * Property pointer.
     *
     * @var  integer
     */
    protected $readPosition = 0;

    /**
     * Property metadata.
     *
     * @var  array
     */
    private $metadata = [
        'wrapper_type' => 'string',
        'stream_type' => 'STDIO',
        'mode' => 'r+b',
        'unread_bytes' => 0,
        'seekable' => true,
        'uri' => '',
        'timed_out' => false,
        'blocked' => true,
        'eof' => false,
    ];

    /**
     * Property seekable.
     *
     * @var  boolean
     */
    protected $seekable = true;

    /**
     * Property writable.
     *
     * @var  boolean
     */
    protected $writable = true;

    /**
     * Class init.
     *
     * @param  string  $stream  The stream resource cursor.
     * @param  string  $mode    Mode with which to open stream
     */
    public function __construct($stream = '', $mode = 'rb+')
    {
        $this->attach($stream, $mode);
    }

    /**
     * Closes the stream and any underlying resources.
     *
     * @return void
     */
    public function close()
    {
        $this->detach();
    }

    /**
     * Method to attach resource into object.
     *
     * @param  string|resource  $stream  The stream resource cursor.
     * @param  string           $mode    Mode with which to open stream
     *
     * @return  static Return self to support chaining.
     */
    public function attach($stream, $mode = 'rb+')
    {
        $this->stream = $stream;

        if (is_resource($stream)) {
            throw new \InvalidArgumentException('StringStream do not support resource.');
        }

        if (is_array($stream) || (is_object($stream) && !is_callable([$stream, '__toString']))) {
            throw new \InvalidArgumentException('StringStream only support string as resource.');
        }

        if (!str_contains('+', $mode)) {
            $this->writable = false;
        }

        $this->resource = (string) $stream;

        return $this;
    }

    /**
     * Separates any underlying resources from the stream.
     *
     * After the stream has been detached, the stream is in an unusable state.
     *
     * @return resource|null Underlying PHP stream, if any
     */
    public function detach()
    {
        $resource = $this->resource;

        $this->resource = null;
        $this->stream   = null;
        $this->pointer  = 0;
        $this->seekable = true;
        $this->writable = true;

        return $resource;
    }

    /**
     * Get the size of the stream if known.
     *
     * @return int|null Returns the size in bytes if known, or null if unknown.
     */
    public function getSize()
    {
        if ($this->resource === null) {
            return null;
        }

        return strlen($this->resource);
    }

    /**
     * Returns the current position of the file read/write pointer
     *
     * @return int Position of the file pointer
     * @throws \RuntimeException on error.
     */
    public function tell()
    {
        if ($this->resource === null) {
            throw new \RuntimeException('No resource set.');
        }

        return $this->pointer;
    }

    /**
     * Returns true if the stream is at the end of the stream.
     *
     * @return bool
     */
    public function eof()
    {
        return $this->readPosition > $this->getSize();
    }

    /**
     * Returns whether or not the stream is seekable.
     *
     * @return bool
     */
    public function isSeekable()
    {
        return $this->seekable;
    }

    /**
     * Seek to a position in the stream.
     *
     * @link http://www.php.net/manual/en/function.fseek.php
     *
     * @param  int  $offset  Stream offset
     * @param  int  $whence  Specifies how the cursor position will be calculated
     *                       based on the seek offset. Valid values are identical to the built-in
     *                       PHP $whence values for `fseek()`.  SEEK_SET: Set position equal to
     *                       offset bytes SEEK_CUR: Set position to current location plus offset
     *                       SEEK_END: Set position to end-of-stream plus offset.
     *
     * @return boolean
     *
     * @throws \RuntimeException on failure.
     */
    public function seek($offset, $whence = SEEK_SET)
    {
        if (!$this->isSeekable()) {
            throw new \RuntimeException('Stream is not seekable');
        }

        if ($whence == SEEK_SET) {
            $this->pointer = $offset;
        } elseif ($whence == SEEK_CUR) {
            $this->pointer += $offset;
        } elseif ($whence == SEEK_END) {
            $this->pointer = $this->getSize();
            $this->pointer += $offset;
        }

        if ($this->pointer < 0) {
            throw new \RuntimeException('Position should not less than 0.');
        }

        return true;
    }

    /**
     * Seek to the beginning of the stream.
     *
     * If the stream is not seekable, this method will raise an exception;
     * otherwise, it will perform a seek(0).
     *
     * @throws \RuntimeException on failure.
     * @link http://www.php.net/manual/en/function.fseek.php
     * @see  seek()
     */
    public function rewind()
    {
        $this->readPosition = 0;

        return $this->seek(0);
    }

    /**
     * Returns whether or not the stream is writable.
     *
     * @return bool
     */
    public function isWritable()
    {
        return $this->writable;
    }

    /**
     * Write data to the stream.
     *
     * @param  string  $string  The string that is to be written.
     *
     * @return int Returns the number of bytes written to the stream.
     * @throws \RuntimeException on failure.
     */
    public function write($string)
    {
        $length = strlen($string);

        $start = substr($this->resource, 0, $this->pointer);
        $end   = substr($this->resource, $this->pointer + $length);

        $this->resource = $start . $string . $end;

        $this->pointer = strlen($start . $string);

        return $string;
    }

    /**
     * Returns whether or not the stream is readable.
     *
     * @return bool
     */
    public function isReadable(): bool
    {
        return true;
    }

    /**
     * Read data from the stream.
     *
     * @param  int  $length  Read up to $length bytes from the object and return
     *                       them. Fewer than $length bytes may be returned if underlying stream
     *                       call returns fewer bytes.
     *
     * @return string Returns the data read from the stream, or an empty string
     *     if no bytes are available.
     * @throws \RuntimeException if an error occurs.
     */
    public function read($length)
    {
        $this->readPosition = $this->pointer;

        $result = substr($this->resource, $this->readPosition, $length);

        $this->pointer      += $length;
        $this->readPosition = $this->pointer;

        return $result;
    }

    /**
     * Returns the remaining contents in a string
     *
     * @return string
     * @throws \RuntimeException if unable to read or an error occurs while
     *     reading.
     */
    public function getContents()
    {
        if ($this->resource === null) {
            return '';
        }

        $result = substr($this->resource, $this->pointer);

        if ($result === false) {
            return '';
        }

        return $result;
    }

    /**
     * Get stream metadata as an associative array or retrieve a specific key.
     *
     * The keys returned are identical to the keys returned from PHP's
     * stream_get_meta_data() function.
     *
     * @link http://php.net/manual/en/function.stream-get-meta-data.php
     *
     * @param  string  $key  Specific metadata to retrieve.
     *
     * @return array|mixed|null Returns an associative array if no key is
     *     provided. Returns a specific key value if a key is provided and the
     *     value is found, or null if the key is not found.
     */
    public function getMetadata($key = null)
    {
        $metadata = $this->metadata;

        $metadata['eof']          = $this->eof();
        $metadata['seekable']     = $this->isSeekable();
        $metadata['unread_bytes'] = $this->getSize() - $this->pointer;
        $metadata['mode']         = 'rb';

        if ($this->isWritable()) {
            $metadata['mode'] = 'r+b';
        }

        if ($key === null) {
            return $metadata;
        }

        if (!array_key_exists($key, $metadata)) {
            return null;
        }

        return $metadata[$key];
    }

    /**
     * Method to get property Resource
     *
     * @return  resource
     */
    public function getResource()
    {
        return $this->resource;
    }

    /**
     * Method to set property seekable
     *
     * @param  boolean  $seekable
     *
     * @return  static  Return self to support chaining.
     */
    public function seekable($seekable)
    {
        $this->seekable = (bool) $seekable;

        return $this;
    }

    /**
     * Method to set property writable
     *
     * @param  boolean  $writable
     *
     * @return  static  Return self to support chaining.
     */
    public function writable($writable)
    {
        $this->writable = (bool) $writable;

        return $this;
    }
}


text:
module Azure::Web::Mgmt::V2018_02_01
  module Models
    #
    # Defines values for SolutionType
    #
    module SolutionType
      QuickSolution = "QuickSolution"
      DeepInvestigation = "DeepInvestigation"
      BestPractices = "BestPractices"
    end
  end
end


text:
import Tag from './shared/Tag';

export default class RawMustacheTag extends Tag {
	type: 'RawMustacheTag';
}


text:
title:  La legge e il vangelo
date:   05/04/2018
---

Avventisti del settimo giorno: nel nostro nome è già implicito ciò per cui ci battiamo. Il settimo giorno è il sabato, che sottolinea la nostra assoluta convinzione non tanto nello specifico comandamento, ma anche in tutti gli altri nove. L'attributo «avventista» rimanda invece alla nostra certezza nel ritorno di Cristo, una verità possibile solo perché Gesù, la prima volta che è sceso su questa terra, ha accettato di morire espiando al nostro posto. Tirando le somme, avventisti del settimo giorno comunica due componenti cruciali e inseparabili della verità presente: la legge e il vangelo.

`Perché i testi di seguito indicati dimostrano lo stretto legame tra la legge e il vangelo?`

`Geremia 44:23; Romani 3:20-26; Romani 7:7.`

Vangelo significa buona notizia, quella secondo cui malgrado il nostro peccato e la violazione della legge divina, possiamo essere perdonati per merito di quello che Gesù ha ottenuto alla croce. Abbiamo inoltre ricevuto tutti gli strumenti indispensabili per ubbidire alla legge, pienamente e fino in fondo.

Non stupisce quindi se, nel contesto dei tempi finali e della contingente ferocità del gran conflitto, al popolo di Dio viene ritagliata una descrizione del tutto specifica.

`Leggere Apocalisse 14:12. Perché questo passo svela il collegamento tra legge e vangelo?`

`In che modo noi avventisti possiamo mostrare al prossimo che ubbidire alla legge non significa essere legalisti, ma è una naturale maturazione motivata dall'amore di Dio e dalla consapevolezza di essere salvati? Perché passi come Deuteronomio 11:1 e 1 Giovanni 5:3 avvalorano questa tesi?`


text:
'use strict';

var gulp = require('gulp');
(function() {
    var includeAll = require('include-all');
    /**
     * Loads task modules from a relative path.
     */
    function loadTasks(relPath) {
        return includeAll({
            dirname: require('path').resolve(__dirname, relPath),
            filter: /(.+)\.js$/
        }) || {};
    }
    // *
    //  * Invokes the function from a Gulp configuration module with
    //  * a single argument - the `gulp` object.

    function addTasks(tasks) {
        for (var taskName in tasks) {
            if (tasks.hasOwnProperty(taskName)) {
                tasks[taskName](gulp);
            }
        }
    }
    /**
     * Add all Gulp tasks to the gulpfile.
     * Tasks are in `tasks/`
     */
    addTasks(loadTasks('tasks/'));
}());

// require('gulp-load-tasks')(__dirname + '/tasks');
gulp.task('default', ['init']);


text:
#include <activemq/wireformat/openwire/marshal/generated/JournalQueueAckMarshaller.h>

#include <activemq/commands/JournalQueueAck.h>
#include <activemq/exceptions/ActiveMQException.h>
#include <decaf/lang/Pointer.h>

//
//     NOTE!: This file is autogenerated - do not modify!
//            if you need to make a change, please see the Java Classes in the
//            activemq-core module
//

using namespace std;
using namespace activemq;
using namespace activemq::exceptions;
using namespace activemq::commands;
using namespace activemq::wireformat;
using namespace activemq::wireformat::openwire;
using namespace activemq::wireformat::openwire::marshal;
using namespace activemq::wireformat::openwire::utils;
using namespace activemq::wireformat::openwire::marshal::generated;
using namespace decaf;
using namespace decaf::io;
using namespace decaf::lang;

///////////////////////////////////////////////////////////////////////////////
DataStructure* JournalQueueAckMarshaller::createObject() const {
    return new JournalQueueAck();
}

///////////////////////////////////////////////////////////////////////////////
unsigned char JournalQueueAckMarshaller::getDataStructureType() const {
    return JournalQueueAck::ID_JOURNALQUEUEACK;
}

///////////////////////////////////////////////////////////////////////////////
void JournalQueueAckMarshaller::tightUnmarshal(OpenWireFormat* wireFormat, DataStructure* dataStructure, DataInputStream* dataIn, BooleanStream* bs) {

    try {

        BaseDataStreamMarshaller::tightUnmarshal(wireFormat, dataStructure, dataIn, bs);

        JournalQueueAck* info =
            dynamic_cast<JournalQueueAck*>(dataStructure);
        info->setDestination(Pointer<ActiveMQDestination>(dynamic_cast<ActiveMQDestination* >(
            tightUnmarshalNestedObject(wireFormat, dataIn, bs))));
        info->setMessageAck(Pointer<MessageAck>(dynamic_cast<MessageAck* >(
            tightUnmarshalNestedObject(wireFormat, dataIn, bs))));
    }
    AMQ_CATCH_RETHROW(decaf::io::IOException)
    AMQ_CATCH_EXCEPTION_CONVERT(exceptions::ActiveMQException, decaf::io::IOException)
    AMQ_CATCHALL_THROW(decaf::io::IOException)
}

///////////////////////////////////////////////////////////////////////////////
int JournalQueueAckMarshaller::tightMarshal1(OpenWireFormat* wireFormat, DataStructure* dataStructure, BooleanStream* bs) {

    try {

        JournalQueueAck* info =
            dynamic_cast<JournalQueueAck*>(dataStructure);

        int rc = BaseDataStreamMarshaller::tightMarshal1(wireFormat, dataStructure, bs);
        rc += tightMarshalNestedObject1(wireFormat, info->getDestination().get(), bs);
        rc += tightMarshalNestedObject1(wireFormat, info->getMessageAck().get(), bs);

        return rc + 0;
    }
    AMQ_CATCH_RETHROW(decaf::io::IOException)
    AMQ_CATCH_EXCEPTION_CONVERT(exceptions::ActiveMQException, decaf::io::IOException)
    AMQ_CATCHALL_THROW(decaf::io::IOException)
}

///////////////////////////////////////////////////////////////////////////////
void JournalQueueAckMarshaller::tightMarshal2(OpenWireFormat* wireFormat, DataStructure* dataStructure, DataOutputStream* dataOut, BooleanStream* bs) {

    try {

        BaseDataStreamMarshaller::tightMarshal2(wireFormat, dataStructure, dataOut, bs );

        JournalQueueAck* info =
            dynamic_cast<JournalQueueAck*>(dataStructure);
        tightMarshalNestedObject2(wireFormat, info->getDestination().get(), dataOut, bs);
        tightMarshalNestedObject2(wireFormat, info->getMessageAck().get(), dataOut, bs);
    }
    AMQ_CATCH_RETHROW(decaf::io::IOException)
    AMQ_CATCH_EXCEPTION_CONVERT( exceptions::ActiveMQException, decaf::io::IOException)
    AMQ_CATCHALL_THROW(decaf::io::IOException)
}

///////////////////////////////////////////////////////////////////////////////
void JournalQueueAckMarshaller::looseUnmarshal(OpenWireFormat* wireFormat, DataStructure* dataStructure, DataInputStream* dataIn) {

    try {

        BaseDataStreamMarshaller::looseUnmarshal(wireFormat, dataStructure, dataIn);
        JournalQueueAck* info =
            dynamic_cast<JournalQueueAck*>(dataStructure);
        info->setDestination(Pointer<ActiveMQDestination>(dynamic_cast<ActiveMQDestination*>(
            looseUnmarshalNestedObject(wireFormat, dataIn))));
        info->setMessageAck(Pointer<MessageAck>(dynamic_cast<MessageAck*>(
            looseUnmarshalNestedObject(wireFormat, dataIn))));
    }
    AMQ_CATCH_RETHROW(decaf::io::IOException)
    AMQ_CATCH_EXCEPTION_CONVERT(exceptions::ActiveMQException, decaf::io::IOException)
    AMQ_CATCHALL_THROW(decaf::io::IOException)
}

///////////////////////////////////////////////////////////////////////////////
void JournalQueueAckMarshaller::looseMarshal(OpenWireFormat* wireFormat, DataStructure* dataStructure, DataOutputStream* dataOut) {

    try {

        JournalQueueAck* info =
            dynamic_cast<JournalQueueAck*>(dataStructure);
        BaseDataStreamMarshaller::looseMarshal(wireFormat, dataStructure, dataOut);
        looseMarshalNestedObject(wireFormat, info->getDestination().get(), dataOut);
        looseMarshalNestedObject(wireFormat, info->getMessageAck().get(), dataOut);
    }
    AMQ_CATCH_RETHROW(decaf::io::IOException)
    AMQ_CATCH_EXCEPTION_CONVERT(exceptions::ActiveMQException, decaf::io::IOException)
    AMQ_CATCHALL_THROW(decaf::io::IOException)
}


text:
@interface VKFriend : _VKFriend {}
// Custom logic goes here.

- (void)initWithDictionary:(NSDictionary *)dictionary;
@end


text:
package nri.startup.inshort.utils;

/**
 * Created by Krushnakant on 06-07-2016.
 */
public class Constant {

    public static final String PLATFORM = "android";

    //SharedPreference Data
    //public static final int PRIVATE_MODE = 0;
    public static final String PREF_NAME = "NRIinshort";
    public static final String PREF_FIRST_TIME = "firsttime";
    public static final String PREF_TOTAL = "total";
    public static final String PREF_CURRENT_PAGE = "currentpage";
    public static final String PREF_NEWS_COUNT = "newscount";

}