text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ZD.HanziLookup
{
	/// <summary>
    /// A WrittenStroke holds onto a list of points.
	/// It can use those points analyze itself and build a List of SubStrokes.
	///
	/// Analyzing and building a SubStroke List is a two-stage process.
	/// The Stroke must be analyzed before the List can be built.
	/// The reason analyzing and marking is separate from building the List is mostly
	/// so that we could graphically display the SubStroke segments if we chose to.
    /// </summary>
	public class WrittenStroke
    {

		// pointList contains WrittenPoints
		private List<WrittenPoint> pointList = new List<WrittenPoint>();

		// Flag to see if this stroke has already been analyzed
		private bool isAnalyzed = false;

		public WrittenStroke()
        {
			// noop
		}

        public List<WrittenPoint> PointList
        {
            get { return pointList; }
        }

		public bool IsAnalyzed
        {
            get { return isAnalyzed; }
		}

		public void AddPoint(WrittenPoint point,
            ref double charLeftX, ref double charRightX,
            ref double charTopY, ref double charBottomY)
        {
			int pointX = point.X;
			int pointY = point.Y;

			// Expand the bounding box coordinates for this WrittenCharacter in necessary.
			charLeftX = Math.Min(pointX, charLeftX);
			charRightX = Math.Max(pointX, charRightX);
			charTopY = Math.Min(pointY, charTopY);
			charBottomY = Math.Max(pointY, charBottomY);

			this.pointList.Add(point);
		}

		// Defines the minimum length of a SubStroke segment.
		// If a two pivot points are within this length, the first of the pivots will be unmarked as a pivot.
		private const double MIN_SEGMENT_LENGTH = 12.5;

		// Used to find abrupt corners in a stroke that delimit two SubStrokes.
		private const double MAX_LOCAL_LENGTH_RATIO = 1.1;

		// Used to find a gradual transition between one SubStroke and another at a curve.
        private const double MAX_RUNNING_LENGTH_RATIO = 1.09;

		public List<SubStrokeDescriptor> GetSubStrokes(double charWidth, double charHeight)
        {
			if(!this.isAnalyzed) this.AnalyzeAndMark();

            List<SubStrokeDescriptor> subStrokes = new List<SubStrokeDescriptor>();

			// Any WrittenStroke should have at least two points, (a single point cannot constitute a Stroke).
			// We should therefore be safe calling an iterator without checking for the first point.
			WrittenPoint previousPoint = pointList[0];

            for (int i = 1; i != pointList.Count; ++i)
			{
				WrittenPoint nextPoint = pointList[i];

				if(nextPoint.IsPivot)
                {
					// The direction from each previous point to each successive point, in radians.
					double direction = previousPoint.GetDirection(nextPoint);

					// Use the normalized length, to account for relative character size.
					double normalizedLength = previousPoint.GetDistanceNormalized(nextPoint, charWidth, charHeight);

					SubStrokeDescriptor subStroke = new SubStrokeDescriptor(direction, normalizedLength);
					subStrokes.Add(subStroke);

					previousPoint = nextPoint;
				}
			}

			return subStrokes;
		}

        /// <summary>
		/// Analyzes the given WrittenStroke and marks its constituent WrittenPoints to demarcate the SubStrokes.
		/// Points that demarcate between the SubStroke segments are marked as pivot points.
		/// These pivot points can later be used to build up a List of SubStroke objects.
        /// </summary>
		public void AnalyzeAndMark()
        {
            var pointIter = pointList.GetEnumerator();

			// It should be impossible for a stroke to have < 2 points, so we are safe calling next() twice.
            pointIter.MoveNext();
			WrittenPoint firstPoint = pointIter.Current;
			WrittenPoint previousPoint = firstPoint;
            pointIter.MoveNext();
			WrittenPoint pivotPoint = pointIter.Current;

			// The first point of a Stroke is always a pivot point.
            firstPoint.IsPivot = true;
			int subStrokeIndex = 1;

			// The first point and the next point are always part of the first SubStroke.
			firstPoint.SubStrokeIndex = subStrokeIndex;
			pivotPoint.SubStrokeIndex = subStrokeIndex;

			// localLength keeps track of the immediate distance between the latest three points.
			// We can use the localLength to find an abrupt change in SubStrokes, such as at a corner.
			// We do this by checking localLength against the distance between the first and last
			// of the three points.  If localLength is more than a certain amount longer than the
			// length between the first and last point, then there must have been a corner of some kind.
			double localLength = firstPoint.Distance(pivotPoint);

			// runningLength keeps track of the length between the start of the current SubStroke
			// and the point we are currently examining.  If the runningLength becomes a certain
			// amount longer than the straight distance between the first point and the current
			// point, then there is a new SubStroke.  This accounts for a more gradual change
			// from one SubStroke segment to another, such as at a longish curve.
			double runningLength = localLength;

			// Iterate over the points, marking the appropriate ones as pivots.
			while(pointIter.MoveNext())
            {
				WrittenPoint nextPoint = pointIter.Current;

				// pivotPoint is the point we're currently examining to see if it's a pivot.
				// We get the distance between this point and the next point and add it
				// to the length sums we're using.
				double pivotLength = pivotPoint.Distance(nextPoint);
				localLength += pivotLength;
				runningLength += pivotLength;

				// Check the lengths against the ratios.  If the lengths are a certain among
				// longer than a straight line between the first and last point, then we
				// mark the point as a pivot.
                double distFromPrevious = previousPoint.Distance(nextPoint);
                double distFromFirst = firstPoint.Distance(nextPoint);
				if (localLength > MAX_LOCAL_LENGTH_RATIO * distFromPrevious ||
				   runningLength > MAX_RUNNING_LENGTH_RATIO * distFromFirst)
                {

					if (previousPoint.IsPivot && previousPoint.Distance(pivotPoint) < MIN_SEGMENT_LENGTH)
                    {
						// If the previous point was a pivot and was very close to this point,
						// which we are about to mark as a pivot, then unmark the previous point as a pivot.
						// Also need to decrement the SubStroke that it belongs to since it's not part of
						// the new SubStroke that begins at this pivot.
                        previousPoint.IsPivot = false;
						previousPoint.SubStrokeIndex = subStrokeIndex - 1;
					}
                    else
                    {
						// If we didn't have to unmark a previous pivot, then the we can increment the SubStrokeIndex.
						// If we did unmark a previous pivot, then the old count still applies and we don't need to increment.
						subStrokeIndex++;
					}

					pivotPoint.IsPivot = true;

					// A new SubStroke has begun, so the runningLength gets reset.
                    runningLength = pivotLength;

					firstPoint = pivotPoint;
				}

				localLength = pivotLength;		// Always update the localLength, since it deals with the last three seen points.

				previousPoint = pivotPoint;
				pivotPoint = nextPoint;

				pivotPoint.SubStrokeIndex = subStrokeIndex;
			}

			// last point (currently referenced by pivotPoint) has to be a pivot
			pivotPoint.IsPivot = true;

			// Point before the final point may need to be handled specially.
			// Often mouse action will produce an unintended small segment at the end.
			// We'll want to unmark the previous point if it's also a pivot and very close to the lat point.
			// However if the previous point is the first point of the stroke, then don't unmark it, because then we'd only have one pivot.
			if (previousPoint.IsPivot &&
			    previousPoint.Distance(pivotPoint) < MIN_SEGMENT_LENGTH &&
			    previousPoint != this.pointList[0])
            {
				previousPoint.IsPivot = false;
				pivotPoint.SubStrokeIndex = subStrokeIndex - 1;
			}

			// Mark the stroke as analyzed so that it won't need to be analyzed again.
			this.isAnalyzed = true;
		}
	}
}


text:
package ru.job4j.pattern.proxy;

import ru.job4j.tracker.ITracker;
import ru.job4j.tracker.Item;

import java.util.WeakHashMap;

public class TrackerCache implements ITracker {
    private final WeakHashMap<String, Item> cache = new WeakHashMap<>();

    @Override
    public Item add(Item item) {
        this.cache.put(item.getId(), item);
        return item;
    }

    @Override
    public Item findById(String id) {
        return this.cache.get(id);
    }

    @Override
    public void replace(String id, Item item) {

    }

    @Override
    public void delete(String id) {

    }

    @Override
    public Item[] findAll() {
        return new Item[0];
    }

    @Override
    public Item[] findByName(String key) {
        return new Item[0];
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.codegist.crest.param.forms.jaxrs;

import org.codegist.crest.annotate.EndPoint;
import org.codegist.crest.param.forms.common.IBasicsTest;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

/**
 * @author laurent.gilles@codegist.org
 */
public class BasicsTest extends IBasicsTest<BasicsTest.Basics> {

    public BasicsTest(CRestHolder crest) {
        super(crest, Basics.class);
    }

    @EndPoint("{crest.server.end-point}")
    @Path("params/form/basic")
    public static interface Basics extends IBasicsTest.IBasics {

        @POST
        String send();

        @POST
        String send(
                @FormParam("p1") String p1,
                @FormParam("p2") int p2);

    }
}


text:
title:  "Implementing a Bloom filter - Part 1"
date:   2017-05-22 19:00:00
categories: [bloom-filter]
tags: [bloom filter, bloom, cpp, c++]
---

In this series we will implement a very simple Bloom filter in c++.

But first things first. What's a Bloom filter?

Simply put, a Bloom filter is a data structure used for doing lookups of items in sets.
* If the result of the lookup is `false`, the item is definitely not in the set
* If the result of the lookup is `true`, the item *might* be in the set

Note that the Bloom filter doesn't store the raw data so it's not a replacement for storage. The advantage it offers is a constant time lookup optimized for when items are not present in the set.

Let's take a an example. We'll start by putting some items into the Bloom filter.

```c++
put("A")
put("B")
put("C")
```

Now let's ask the filter if these items are present

```c++
isMaybePresent("D")
false
// the item is definitely not in the set, and we know this is correct

isMaybePresent("A")
true
// the item *might* be present, and we know it is, since we've inserted it

isMaybePresent("E")
true
// the item *might* be present, and we know it's not, since we never inserted it
// but it doesn't matter, because we mostly care about when the answer is false
// and we can afford a few false positives
```

And at this point you might be asking yourself, why would anyone use a Bloom filter when it doesn't actually store any data, and it can only tell you if something is not present or maybe present?

Imagine you are building Medium's recommended articles feature. Your recommendation engine gives you a list of articles which the user might enjoy based on their interests. But the recommendation engine has no state, so in this list you could have articles that the user has already read. In order to filter this list out you could of course make database queries for every article to see if they have been read, but that will be expensive. There must be a better way.

**Enter the Bloom filter!**

What if we kept a Bloom filter for every user with the articles they've read? Querying the Bloom filter is a constant time operation, and we wouldn't need to call the database at all. All we have to do is keep the Bloom filter up to date, so every time a user reads something we insert it into the Bloom filter.

Fun fact, this is actually [what Medium does](https://blog.medium.com/what-are-bloom-filters-1ec2a50c68ff#.xlkqtn1vy).

Bloom filters are widely used for this type of quick filtering when the answer is mostly no. They are also used in [Chrome](http://blog.alexyakunin.com/2010/03/nice-bloom-filter-application.html), [Akamai](https://www.akamai.com/jp/ja/multimedia/documents/technical-publication/algorithmic-nuggets-in-content-delivery-technical-publication.pdf) and [Bitcoin](http://www.newsbtc.com/2016/05/10/developers-introduce-bloom-filters-improve-bitcoin-wallet-security/).

Now that we've seen what Bloom filters can do and why they are useful, we'll look at how they do this in [part 2](/2017/bloom-filter-part-2/).


text:
import * as React from 'react'
import { Provider } from 'react-redux'
import { mount } from 'enzyme'
import noop from 'lodash/noop'

import * as Selectors from '../selectors'
import { useFeatureFlag } from '../hooks'

import type { State } from '../../types'
import type { FeatureFlags } from '../types'

jest.mock('../selectors')

const getFeatureFlags: JestMockFn<[State], FeatureFlags> =
  Selectors.getFeatureFlags

describe('config hooks', () => {
  afterEach(() => {
    jest.resetAllMocks()
  })

  describe('useFeatureFlag', () => {
    let result: boolean
    const TestUseFeatureFlag = (props: {| flag: any |}) => {
      result = useFeatureFlag(props.flag)
      return <></>
    }

    const mockStore = {
      getState: () => ({ mockState: true }: any),
      dispatch: noop,
      subscribe: noop,
    }

    const render = (flag: string) => {
      return mount(<TestUseFeatureFlag flag={flag} />, {
        wrappingComponent: Provider,
        wrappingComponentProps: { store: mockStore },
      })
    }

    it('should return false if the feature flag is not set', () => {
      getFeatureFlags.mockReturnValue({})

      render('someFlag')
      expect(result).toBe(false)
    })

    it('should return false if the feature flag is set to false', () => {
      getFeatureFlags.mockReturnValue(({ someFlag: false }: any))

      render('someFlag')
      expect(result).toBe(false)
    })

    it('should return false if the feature flag is set to falsey', () => {
      getFeatureFlags.mockReturnValue(({ someFlag: (0: any) }: any))

      render('someFlag')
      expect(result).toBe(false)
    })

    it('should return true if the feature flag is set', () => {
      getFeatureFlags.mockReturnValue(({ someFlag: true }: any))

      render('someFlag')
      expect(result).toBe(true)
    })

    it('should return true if the feature flag is set to truthy', () => {
      getFeatureFlags.mockReturnValue(({ someFlag: (1: any) }: any))

      render('someFlag')
      expect(result).toBe(true)
    })
  })
})


text:
@interface MAManifestScanner : NSOperation {
    NSArray *apps;
    NSArray *packages;
}

- (id)initWithURL:(NSURL *)src;

@property (nonatomic, copy) void (^progressCallback) (float);
@property (nonatomic, copy) void (^finishCallback) (void);
@property (strong) NSString *currentJobDescription;
@property (strong) NSString *fileName;
@property (strong) NSURL *sourceURL;
@property (weak) id delegate;
@property (strong) NSDictionary *pkginfoKeyMappings;
@property (strong) NSDictionary *receiptKeyMappings;
@property (strong) NSDictionary *installsKeyMappings;
@property (strong) ManifestMOID *manifestID;
@property BOOL performFullScan;

@end


text:
import {extname} from '../utils/path'

/**
 * Test whether a file name has the given extension
 *
 * @function extMatchesStr
 * @param {String} filePath Input file path
 * @param {String} extension The extension to test. An empty string will match a file with no extension.
 * @returns {Boolean} Whether it matched or not.
 *
 * @example
 * var matches = io.extMatchesStr('path/to/data.tsv', 'tsv')
 * console.log(matches) // `true`
 */
export default function extMatchesStr (filePath, extension) {
  // Chop '.' off extension returned by extname
  var ext = extname(filePath).slice(1)
  return ext === extension
}


text:
.class Landroid/support/v7/widget/DropDownListView;
.super Landroid/support/v7/widget/ListViewCompat;
.source "DropDownListView.java"

# instance fields
.field private mClickAnimation:Landroid/support/v4/view/ViewPropertyAnimatorCompat;

.field private mDrawsInPressedState:Z

.field private mHijackFocus:Z

.field private mListSelectionHidden:Z

.field private mScrollHelper:Landroid/support/v4/widget/ListViewAutoScrollHelper;

# direct methods
.method public constructor <init>(Landroid/content/Context;Z)V
    .registers 5
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "hijackFocus"    # Z

    .prologue
    .line 85
    const/4 v0, 0x0

    sget v1, Landroid/support/v7/appcompat/R$attr;->dropDownListViewStyle:I

    invoke-direct {p0, p1, v0, v1}, Landroid/support/v7/widget/ListViewCompat;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V

    .line 86
    iput-boolean p2, p0, Landroid/support/v7/widget/DropDownListView;->mHijackFocus:Z

    .line 87
    const/4 v0, 0x0

    invoke-virtual {p0, v0}, Landroid/support/v7/widget/DropDownListView;->setCacheColorHint(I)V

    .line 88
    return-void
.end method

.method private clearPressedItem()V
    .registers 5

    .prologue
    const/4 v3, 0x0

    .line 173
    iput-boolean v3, p0, Landroid/support/v7/widget/DropDownListView;->mDrawsInPressedState:Z

    .line 174
    invoke-virtual {p0, v3}, Landroid/support/v7/widget/DropDownListView;->setPressed(Z)V

    .line 176
    invoke-virtual {p0}, Landroid/support/v7/widget/DropDownListView;->drawableStateChanged()V

    .line 178
    iget v1, p0, Landroid/support/v7/widget/DropDownListView;->mMotionPosition:I

    invoke-virtual {p0}, Landroid/support/v7/widget/DropDownListView;->getFirstVisiblePosition()I

    move-result v2

    sub-int/2addr v1, v2

    invoke-virtual {p0, v1}, Landroid/support/v7/widget/DropDownListView;->getChildAt(I)Landroid/view/View;

    move-result-object v0

    .line 179
    .local v0, "motionView":Landroid/view/View;
    if-eqz v0, :cond_19

    .line 180
    invoke-virtual {v0, v3}, Landroid/view/View;->setPressed(Z)V

    .line 183
    :cond_19
    iget-object v1, p0, Landroid/support/v7/widget/DropDownListView;->mClickAnimation:Landroid/support/v4/view/ViewPropertyAnimatorCompat;

    if-eqz v1, :cond_25

    .line 184
    iget-object v1, p0, Landroid/support/v7/widget/DropDownListView;->mClickAnimation:Landroid/support/v4/view/ViewPropertyAnimatorCompat;

    invoke-virtual {v1}, Landroid/support/v4/view/ViewPropertyAnimatorCompat;->cancel()V

    .line 185
    const/4 v1, 0x0

    iput-object v1, p0, Landroid/support/v7/widget/DropDownListView;->mClickAnimation:Landroid/support/v4/view/ViewPropertyAnimatorCompat;

    .line 187
    :cond_25
    return-void
.end method

.method private clickPressedItem(Landroid/view/View;I)V
    .registers 5
    .param p1, "child"    # Landroid/view/View;
    .param p2, "position"    # I

    .prologue
    .line 157
    invoke-virtual {p0, p2}, Landroid/support/v7/widget/DropDownListView;->getItemIdAtPosition(I)J

    move-result-wide v0

    .line 158
    .local v0, "id":J
    invoke-virtual {p0, p1, p2, v0, v1}, Landroid/support/v7/widget/DropDownListView;->performItemClick(Landroid/view/View;IJ)Z

    .line 159
    return-void
.end method

.method private setPressedItem(Landroid/view/View;IFF)V
    .registers 13
    .param p1, "child"    # Landroid/view/View;
    .param p2, "position"    # I
    .param p3, "x"    # F
    .param p4, "y"    # F

    .prologue
    const/16 v7, 0x15

    const/4 v6, 0x0

    const/4 v5, 0x1

    .line 190
    iput-boolean v5, p0, Landroid/support/v7/widget/DropDownListView;->mDrawsInPressedState:Z

    .line 193
    sget v3, Landroid/os/Build$VERSION;->SDK_INT:I

    if-lt v3, v7, :cond_d

    .line 194
    invoke-virtual {p0, p3, p4}, Landroid/support/v7/widget/DropDownListView;->drawableHotspotChanged(FF)V

    .line 196
    :cond_d
    invoke-virtual {p0}, Landroid/support/v7/widget/DropDownListView;->isPressed()Z

    move-result v3

    if-nez v3, :cond_16

    .line 197
    invoke-virtual {p0, v5}, Landroid/support/v7/widget/DropDownListView;->setPressed(Z)V

    .line 201
    :cond_16
    invoke-virtual {p0}, Landroid/support/v7/widget/DropDownListView;->layoutChildren()V

    .line 205
    iget v3, p0, Landroid/support/v7/widget/DropDownListView;->mMotionPosition:I

    const/4 v4, -0x1

    if-eq v3, v4, :cond_36

    .line 206
    iget v3, p0, Landroid/support/v7/widget/DropDownListView;->mMotionPosition:I

    invoke-virtual {p0}, Landroid/support/v7/widget/DropDownListView;->getFirstVisiblePosition()I

    move-result v4

    sub-int/2addr v3, v4

    invoke-virtual {p0, v3}, Landroid/support/v7/widget/DropDownListView;->getChildAt(I)Landroid/view/View;

    move-result-object v2

    .line 207
    .local v2, "motionView":Landroid/view/View;
    if-eqz v2, :cond_36

    if-eq v2, p1, :cond_36

    invoke-virtual {v2}, Landroid/view/View;->isPressed()Z

    move-result v3

    if-eqz v3, :cond_36

    .line 208
    invoke-virtual {v2, v6}, Landroid/view/View;->setPressed(Z)V

    .line 211
    .end local v2    # "motionView":Landroid/view/View;
    :cond_36
    iput p2, p0, Landroid/support/v7/widget/DropDownListView;->mMotionPosition:I

    .line 214
    invoke-virtual {p1}, Landroid/view/View;->getLeft()I

    move-result v3

    int-to-float v3, v3

    sub-float v0, p3, v3

    .line 215
    .local v0, "childX":F
    invoke-virtual {p1}, Landroid/view/View;->getTop()I

    move-result v3

    int-to-float v3, v3

    sub-float v1, p4, v3

    .line 216
    .local v1, "childY":F
    sget v3, Landroid/os/Build$VERSION;->SDK_INT:I

    if-lt v3, v7, :cond_4d

    .line 217
    invoke-virtual {p1, v0, v1}, Landroid/view/View;->drawableHotspotChanged(FF)V

    .line 219
    :cond_4d
    invoke-virtual {p1}, Landroid/view/View;->isPressed()Z

    move-result v3

    if-nez v3, :cond_56

    .line 220
    invoke-virtual {p1, v5}, Landroid/view/View;->setPressed(Z)V

    .line 224
    :cond_56
    invoke-virtual {p0, p2, p1, p3, p4}, Landroid/support/v7/widget/DropDownListView;->positionSelectorLikeTouchCompat(ILandroid/view/View;FF)V

    .line 229
    invoke-virtual {p0, v6}, Landroid/support/v7/widget/DropDownListView;->setSelectorEnabled(Z)V

    .line 233
    invoke-virtual {p0}, Landroid/support/v7/widget/DropDownListView;->refreshDrawableState()V

    .line 234
    return-void
.end method

# virtual methods
.method public hasFocus()Z
    .registers 2

    .prologue
    .line 274
    iget-boolean v0, p0, Landroid/support/v7/widget/DropDownListView;->mHijackFocus:Z

    if-nez v0, :cond_a

    invoke-super {p0}, Landroid/support/v7/widget/ListViewCompat;->hasFocus()Z

    move-result v0

    if-eqz v0, :cond_c

    :cond_a
    const/4 v0, 0x1

    :goto_b
    return v0

    :cond_c
    const/4 v0, 0x0

    goto :goto_b
.end method

.method public hasWindowFocus()Z
    .registers 2

    .prologue
    .line 254
    iget-boolean v0, p0, Landroid/support/v7/widget/DropDownListView;->mHijackFocus:Z

    if-nez v0, :cond_a

    invoke-super {p0}, Landroid/support/v7/widget/ListViewCompat;->hasWindowFocus()Z

    move-result v0

    if-eqz v0, :cond_c

    :cond_a
    const/4 v0, 0x1

    :goto_b
    return v0

    :cond_c
    const/4 v0, 0x0

    goto :goto_b
.end method

.method public isFocused()Z
    .registers 2

    .prologue
    .line 264
    iget-boolean v0, p0, Landroid/support/v7/widget/DropDownListView;->mHijackFocus:Z

    if-nez v0, :cond_a

    invoke-super {p0}, Landroid/support/v7/widget/ListViewCompat;->isFocused()Z

    move-result v0

    if-eqz v0, :cond_c

    :cond_a
    const/4 v0, 0x1

    :goto_b
    return v0

    :cond_c
    const/4 v0, 0x0

    goto :goto_b
.end method

.method public isInTouchMode()Z
    .registers 2

    .prologue
    .line 244
    iget-boolean v0, p0, Landroid/support/v7/widget/DropDownListView;->mHijackFocus:Z

    if-eqz v0, :cond_8

    iget-boolean v0, p0, Landroid/support/v7/widget/DropDownListView;->mListSelectionHidden:Z

    if-nez v0, :cond_e

    :cond_8
    invoke-super {p0}, Landroid/support/v7/widget/ListViewCompat;->isInTouchMode()Z

    move-result v0

    if-eqz v0, :cond_10

    :cond_e
    const/4 v0, 0x1

    :goto_f
    return v0

    :cond_10
    const/4 v0, 0x0

    goto :goto_f
.end method

.method public onForwardedEvent(Landroid/view/MotionEvent;I)Z
    .registers 14
    .param p1, "event"    # Landroid/view/MotionEvent;
    .param p2, "activePointerId"    # I

    .prologue
    const/4 v10, 0x1

    .line 97
    const/4 v4, 0x1

    .line 98
    .local v4, "handledEvent":Z
    const/4 v3, 0x0

    .line 100
    .local v3, "clearPressedItem":Z
    invoke-virtual {p1}, Landroid/view/MotionEvent;->getActionMasked()I

    move-result v0

    .line 101
    .local v0, "actionMasked":I
    packed-switch v0, :pswitch_data_68

    .line 134
    :cond_a
    :goto_a
    if-eqz v4, :cond_e

    if-eqz v3, :cond_11

    .line 135
    :cond_e
    invoke-direct {p0}, Landroid/support/v7/widget/DropDownListView;->clearPressedItem()V

    .line 139
    :cond_11
    if-eqz v4, :cond_5d

    .line 140
    iget-object v8, p0, Landroid/support/v7/widget/DropDownListView;->mScrollHelper:Landroid/support/v4/widget/ListViewAutoScrollHelper;

    if-nez v8, :cond_1e

    .line 141
    new-instance v8, Landroid/support/v4/widget/ListViewAutoScrollHelper;

    invoke-direct {v8, p0}, Landroid/support/v4/widget/ListViewAutoScrollHelper;-><init>(Landroid/widget/ListView;)V

    iput-object v8, p0, Landroid/support/v7/widget/DropDownListView;->mScrollHelper:Landroid/support/v4/widget/ListViewAutoScrollHelper;

    .line 143
    :cond_1e
    iget-object v8, p0, Landroid/support/v7/widget/DropDownListView;->mScrollHelper:Landroid/support/v4/widget/ListViewAutoScrollHelper;

    invoke-virtual {v8, v10}, Landroid/support/v4/widget/ListViewAutoScrollHelper;->setEnabled(Z)Landroid/support/v4/widget/AutoScrollHelper;

    .line 144
    iget-object v8, p0, Landroid/support/v7/widget/DropDownListView;->mScrollHelper:Landroid/support/v4/widget/ListViewAutoScrollHelper;

    invoke-virtual {v8, p0, p1}, Landroid/support/v4/widget/ListViewAutoScrollHelper;->onTouch(Landroid/view/View;Landroid/view/MotionEvent;)Z

    .line 149
    :cond_28
    :goto_28
    return v4

    .line 103
    :pswitch_29
    const/4 v4, 0x0

    .line 104
    goto :goto_a

    .line 106
    :pswitch_2b
    const/4 v4, 0x0

    .line 109
    :pswitch_2c
    invoke-virtual {p1, p2}, Landroid/view/MotionEvent;->findPointerIndex(I)I

    move-result v1

    .line 110
    .local v1, "activeIndex":I
    if-gez v1, :cond_34

    .line 111
    const/4 v4, 0x0

    .line 112
    goto :goto_a

    .line 115
    :cond_34
    invoke-virtual {p1, v1}, Landroid/view/MotionEvent;->getX(I)F

    move-result v8

    float-to-int v6, v8

    .line 116
    .local v6, "x":I
    invoke-virtual {p1, v1}, Landroid/view/MotionEvent;->getY(I)F

    move-result v8

    float-to-int v7, v8

    .line 117
    .local v7, "y":I
    invoke-virtual {p0, v6, v7}, Landroid/support/v7/widget/DropDownListView;->pointToPosition(II)I

    move-result v5

    .line 118
    .local v5, "position":I
    const/4 v8, -0x1

    if-ne v5, v8, :cond_47

    .line 119
    const/4 v3, 0x1

    .line 120
    goto :goto_a

    .line 123
    :cond_47
    invoke-virtual {p0}, Landroid/support/v7/widget/DropDownListView;->getFirstVisiblePosition()I

    move-result v8

    sub-int v8, v5, v8

    invoke-virtual {p0, v8}, Landroid/support/v7/widget/DropDownListView;->getChildAt(I)Landroid/view/View;

    move-result-object v2

    .line 124
    .local v2, "child":Landroid/view/View;
    int-to-float v8, v6

    int-to-float v9, v7

    invoke-direct {p0, v2, v5, v8, v9}, Landroid/support/v7/widget/DropDownListView;->setPressedItem(Landroid/view/View;IFF)V

    .line 125
    const/4 v4, 0x1

    .line 127
    if-ne v0, v10, :cond_a

    .line 128
    invoke-direct {p0, v2, v5}, Landroid/support/v7/widget/DropDownListView;->clickPressedItem(Landroid/view/View;I)V

    goto :goto_a

    .line 145
    .end local v1    # "activeIndex":I
    .end local v2    # "child":Landroid/view/View;
    .end local v5    # "position":I
    .end local v6    # "x":I
    .end local v7    # "y":I
    :cond_5d
    iget-object v8, p0, Landroid/support/v7/widget/DropDownListView;->mScrollHelper:Landroid/support/v4/widget/ListViewAutoScrollHelper;

    if-eqz v8, :cond_28

    .line 146
    iget-object v8, p0, Landroid/support/v7/widget/DropDownListView;->mScrollHelper:Landroid/support/v4/widget/ListViewAutoScrollHelper;

    const/4 v9, 0x0

    invoke-virtual {v8, v9}, Landroid/support/v4/widget/ListViewAutoScrollHelper;->setEnabled(Z)Landroid/support/v4/widget/AutoScrollHelper;

    goto :goto_28

    .line 101
    :pswitch_data_68
    .packed-switch 0x1
        :pswitch_2b
        :pswitch_2c
        :pswitch_29
    .end packed-switch
.end method

.method setListSelectionHidden(Z)V
    .registers 2
    .param p1, "hideListSelection"    # Z

    .prologue
    .line 169
    iput-boolean p1, p0, Landroid/support/v7/widget/DropDownListView;->mListSelectionHidden:Z

    .line 170
    return-void
.end method

.method protected touchModeDrawsInPressedStateCompat()Z
    .registers 2

    .prologue
    .line 238
    iget-boolean v0, p0, Landroid/support/v7/widget/DropDownListView;->mDrawsInPressedState:Z

    if-nez v0, :cond_a

    invoke-super {p0}, Landroid/support/v7/widget/ListViewCompat;->touchModeDrawsInPressedStateCompat()Z

    move-result v0

    if-eqz v0, :cond_c

    :cond_a
    const/4 v0, 0x1

    :goto_b
    return v0

    :cond_c
    const/4 v0, 0x0

    goto :goto_b
.end method


text:
var path = require('path');

var webpack = require('webpack');
var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var path = require('path');
var env = require('yargs').argv.mode;

var libraryName = 'Deslider';

const ExtractTextPlugin = require('extract-text-webpack-plugin');
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

var plugins = [];

var outputFile;

if (env === 'build') {
  plugins.push(new UglifyJsPlugin({ minimize: true }));
  outputFile = libraryName + '.min.js';

  plugins.push(new ExtractTextPlugin("../css/style.min.css"));

  plugins.push(new OptimizeCssAssetsPlugin({
      //assetNameRegExp: /\.min\.css$/,
      // default is /\.css$/g
      cssProcessorOptions: { discardComments: { removeAll: true } }
  }));
} else {
  plugins.push(new ExtractTextPlugin("../css/style.css"));
  outputFile = libraryName + '.js';
}

var config = {
  watch: true,
  entry: [ __dirname + '/src/main.js' ],
  devtool: 'source-map',
  output: {
    path: __dirname + '/lib',
    filename: outputFile,
    library: libraryName,
    libraryTarget: 'umd'
  },
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'jshint-loader'
      }
    ],
    loaders: [
      {
        test: /(\.jsx|\.js)$/,
        loader: "babel!eslint-loader",
        exclude: /(node_modules|bower_components)/
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader")
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader!sass-loader")
      },
    ]
  },
  resolve: {
    // root: path.resolve('./src'),
    extensions: ['', '.js']
  },
  plugins: plugins
};

module.exports = config;

/*
 *  __dirname refers to the diretory where this webpack.config.js lives
 * https://julienrenaux.fr/2015/03/30/introduction-to-webpack-with-practical-examples/
 */
/*

  // https://github.com/webpack/webpack/issues/2764
  // http://stackoverflow.com/questions/29210325/webpack-sass-where-is-the-css-file
  // http://stackoverflow.com/questions/35637184/minify-css-from-webpacks-extracttextplugin-and-style-loader
  // http://stackoverflow.com/questions/40356445/webpack-how-to-compile-scss-into-a-separate-css-file
  // https://blog.madewithenvy.com/getting-started-with-webpack-2-ed2b86c68783#.k9j27f5vs
  // https://robinwieruch.de/react-eslint-webpack-babel/#eslintBabel
  // http://blog.brew.com.hk/getting-started-with-webpack/
  // https://www.sitepoint.com/javascript-modules-bundling-transpiling/
  // https://qconsf.com/system/files/presentation-slides/webpack-_one_build_step_to_rule_them_all.pdf
  // https://www.codementor.io/javascript/tutorial/module-bundler-webpack-getting-started-guide
  // https://www.gitbook.com/book/abhijeetnmishra/webpack-step-by-step/details
  // https://www.bensmithett.com/smarter-css-builds-with-webpack/
  // https://gist.github.com/nkbt/9efd4facb391edbf8048
  // https://robinwieruch.de/react-eslint-webpack-babel/
  // http://krasimirtsonev.com/blog/article/javascript-library-starter-using-webpack-es6
  // https://www.sitepoint.com/transpiling-es6-modules-to-amd-commonjs-using-babel-gulp/
  // http://guybedford.com/practical-workflows-for-es6-modules

*/


text:
namespace WimdioApiProxy.v2.DataTransferObjects.TimeSeries
{
    public enum DataOperation
    {
        Sum,
        Max,
        Min,
        Avg,
        Count
    }

    public enum TimeInterval
    {
        Day,
        Month,
        Year,
        None
    }
}


text:
#ifndef THEORY_H_
#define THEORY_H_

#include "monosat/mtl/Vec.h"
#include "monosat/mtl/Heap.h"
#include "monosat/mtl/Alg.h"
#include "monosat/utils/Options.h"
#include "monosat/core/SolverTypes.h"
#include "monosat/core/Heuristic.h"
#include <ostream>
#include <string>

namespace Monosat {
/**
 * Abstract interface to SMT theory solvers, as accessed by the SAT solver
 */
class Theory : public virtual Heuristic {

public:
    ~Theory() override{
    }

    int getTheoryIndex() const override = 0;

    virtual void setTheoryIndex(int id) = 0;

    virtual void backtrackUntil(int untilLevel) = 0;

    virtual void newDecisionLevel() = 0;

    virtual void enqueueTheory(Lit p) = 0;

    virtual void enqueueAnyUnqueued(){

    }

    virtual void clearSatisfied(){

    }

    virtual bool propagateTheory(vec<Lit>& conflict) = 0;

    virtual bool solveTheory(vec<Lit>& conflict) = 0;

    virtual bool theoryIsSatisfied(){
        return false;
    }

    //virtual Lit decideTheory(CRef & decision_reason)=0;
    virtual bool supportsDecisions(){
        return false;
    }

    virtual void undecideTheory(Lit l){

    }

    //Some theory solvers do not have data structures that allow them to skip theory propagation.
    //This function should be overridden to return 'true' if the theory cannot be skipped.
    virtual bool unskipable() const{
        return false;
    }

    virtual Heuristic* getConflictingHeuristic(){
        if(this->supportsDecisions()){
            return this;
        }else{
            return nullptr;
        }
    }

    //Lazily construct the reason clause explaining this propagation
    virtual void buildReason(Lit p, vec<Lit>& reason, CRef reason_marker){
        return buildReason(p, reason);
    }

    virtual bool supportsLazyBacktracking(){
        return false;
    }

    //Not all theories have a name; if they do not, they can just return the empty string.
    virtual const std::string& getName(){
        static const std::string empty("");
        return empty;
    }

    virtual const char* getTheoryType() = 0;

protected:
    virtual void buildReason(Lit p, vec<Lit>& reason){

    }

public:
    //Informs the theory solver about whether this literal (with this polarity!) ever occurs in its parent solver
    virtual void setLiteralOccurs(Lit l, bool occurs){

    }

    virtual void printStats(int detailLevel = 0){

    }

    virtual bool check_propagated(){
        return true;
    }

    virtual bool check_solved(){
        return true;
    }

    virtual void printSolution(){

    }

    virtual void writeTheoryWitness(std::ostream& write_to){
        //do nothing
    }

    virtual void preprocess(){

    }
};

}

#endif /* THEORY_H_ */


text:
class IncomeFixture < MagiFixture
  attr_accessor :magi, :test_sets

  def initialize
    super
    @magi = 'Income'
    @test_sets = [
      # ensure that medicaid threshold is making its way down properly
      {
        test_name: "Income - Set Percentage Used",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "Y",
          "Applicant Pregnancy Category Indicator" => "N",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 0,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "N",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "Percentage for Medicaid Category Used" => {"percentage" => "Y", "method" => "standard", "threshold" => 100},
          "Percentage for CHIP Category Used" => {"percentage" => "Y", "method" => "standard", "threshold" => 133},
        }
      },
      {
        test_name: "Income - Set FPL Percentage",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "Y",
          "Applicant Pregnancy Category Indicator" => "Y",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 0,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "N",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "FPL" => 20090,
          "FPL * Percentage Medicaid" => 21094.5,
          "FPL * Percentage CHIP" => 27724.2,
          "Category Used to Calculate Medicaid Income" => 'Adult Group Category',
          "Category Used to Calculate CHIP Income" => 'Pregnancy Category'
        }
      },
      {
        test_name: "Income - Set Calculated Income as Percentage of FPL",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "Y",
          "Applicant Pregnancy Category Indicator" => "Y",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 24042,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "N",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "FPL" => 20090,
          "Calculated Income as Percentage of FPL" => 119
        }
      },
      {
        test_name: "Income - Calculate 2016 FPL Correctly",
        inputs: {
          "Application Year" => 2016,
          "Applicant Adult Group Category Indicator" => "Y",
          "Applicant Pregnancy Category Indicator" => "Y",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 25000,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2016" => { "FPL By Household Size" => [11880,16020,20160,24300,28440,32580,36730,40890], "FPL Per Extra Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "N",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "FPL" => 20160,
          "Calculated Income as Percentage of FPL" => 124
        }
      },

      # determine income eligibility rule - Medicaid
      {
        test_name: "Determine Medicaid Income Eligibility - Max Eligible Medicaid None",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "N",
          "Applicant Pregnancy Category Indicator" => "N",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 0,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "N",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "Applicant Income Medicaid Eligible Indicator" => "N",
          "Income Medicaid Eligible Ineligibility Reason" => 401
        }
      },
      {
        test_name: "Determine Medicaid Income Eligibility - Calculated Income Greater Than Max Eligible",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "Y",
          "Applicant Pregnancy Category Indicator" => "N",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 22090, # slightly higher than fpl * percentage medicaid from above
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "N",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "Applicant Income Medicaid Eligible Indicator" => "N",
          "Income Medicaid Eligible Ineligibility Reason" => 402
        }
      },
      {
        test_name: "Determine Medicaid Income Eligibility - Calculated Income Lower Than Max Eligible",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "Y",
          "Applicant Pregnancy Category Indicator" => "N",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 20000,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "N",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "Applicant Income Medicaid Eligible Indicator" => "Y",
          "Income Medicaid Eligible Ineligibility Reason" => 999
        }
      },

      # determine income eligibility rule - CHIP - 27724.2
      {
        test_name: "Determine CHIP Income Eligibility - No CHIP Eligibility",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "N",
          "Applicant Pregnancy Category Indicator" => "N",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 20000,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "Y",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "Applicant Income CHIP Eligible Indicator" => "N",
          "Income CHIP Eligible Ineligibility Reason" => 401
        }
      },
      {
        test_name: "Determine CHIP Income Eligibility - Calculated Income Greater than Max Eligible Income",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "Y",
          "Applicant Pregnancy Category Indicator" => "Y",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 30000,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "Y",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "Applicant Income CHIP Eligible Indicator" => "N",
          "Income CHIP Eligible Ineligibility Reason" => 402
        }
      },
      {
        test_name: "Determine CHIP Income Eligibility - Calculated Income Lower than Max Eligible Income",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "Y",
          "Applicant Pregnancy Category Indicator" => "Y",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "Y",
          "Applicant CHIP Targeted Low Income Child Indicator" => "Y",
          "Calculated Income" => 20000,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "Y",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
          "Applicant Income CHIP Eligible Indicator" => "Y",
          "Income CHIP Eligible Ineligibility Reason" => 999
        }
      },

      {
        test_name: "Bad Info - Inputs",
        inputs: {
          "Applicant Age" => 20
        },
        configs: {
          "FPL" => { "2015" => { "Base FPL" => 11770, "FPL Per Person" => 4160 } },
          "Option CHIP Pregnancy Category" => "N",
          "Medicaid Thresholds" => { "Adult Group Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 100 } },
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
        }
      },
      {
        test_name: "Bad Info - Configs",
        inputs: {
          "Application Year" => 2015,
          "Applicant Adult Group Category Indicator" => "Y",
          "Applicant Pregnancy Category Indicator" => "N",
          "Applicant Parent Caretaker Category Indicator" => "N",
          "Applicant Child Category Indicator" => "N",
          "Applicant Optional Targeted Low Income Child Indicator" => "N",
          "Applicant CHIP Targeted Low Income Child Indicator" => "N",
          "Calculated Income" => 0,
          "Medicaid Household" => MedicaidHousehold.new("house", '', '', '', 3),
          "Applicant Age" => 20
        },
        configs: {
          "CHIP Thresholds" => { "Pregnancy Category" => { "percentage" => "Y", "method" => "standard", "threshold" => 133 } }
        },
        expected_outputs: {
        }
      }
    ]
  end
end


text:
package uk.ac.ed.ph.snuggletex.tokens;

import uk.ac.ed.ph.snuggletex.definitions.LaTeXMode;
import uk.ac.ed.ph.snuggletex.definitions.MathCharacter;
import uk.ac.ed.ph.snuggletex.internal.FrozenSlice;

/**
 * Represents a character in math mode.
 *
 * @see TokenType
 *
 * @author  David McKain
 * @version $Revision: 742 $
 */
public final class MathCharacterToken extends FlowToken {

    private final MathCharacter mathCharacter;

    public MathCharacterToken(final FrozenSlice slice, final MathCharacter mathCharacter) {
        super(slice, TokenType.MATH_CHARACTER, LaTeXMode.MATH, null, mathCharacter.getInterpretationMap());
        this.mathCharacter = mathCharacter;
    }

    @Override
    public MathCharacter getMathCharacter() {
        return mathCharacter;
    }
}


text:
package br.edu.ladoss.nutrif.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

/**
 * Created by juan on 19/03/16.
 */
public class PreferencesUtils {
    private static String ACCESS_KEY_INDEX = "chave";

    public static void setAccessKeyOnSharedPreferences(Context context, String chave) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putString(ACCESS_KEY_INDEX, chave).apply();
    }

    public static String getAccessKeyOnSharedPreferences(Context context) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        String accesskey = sharedPreferences.getString(ACCESS_KEY_INDEX, "");

        return accesskey;
    }
}


text:
package com.fsck.k9.preferences;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

import com.fsck.k9.Account;
import com.imaeses.squeaky.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.Store;
import com.fsck.k9.mail.ServerSettings;
import com.fsck.k9.mail.Transport;
import com.fsck.k9.preferences.Settings.InvalidSettingValueException;
import com.fsck.k9.preferences.Settings.SettingsDescription;

public class SettingsExporter {
    private static final String EXPORT_FILENAME = "settings.k9s";

    /**
     * File format version number.
     *
     * <p>
     * Increment this if you need to change the structure of the settings file. When you do this
     * remember that we also have to be able to handle old file formats. So have fun adding support
     * for that to {@link SettingsImporter} :)
     * </p>
     */
    public static final int FILE_FORMAT_VERSION = 1;

    public static final String ROOT_ELEMENT = "k9settings";
    public static final String VERSION_ATTRIBUTE = "version";
    public static final String FILE_FORMAT_ATTRIBUTE = "format";
    public static final String GLOBAL_ELEMENT = "global";
    public static final String SETTINGS_ELEMENT = "settings";
    public static final String ACCOUNTS_ELEMENT = "accounts";
    public static final String ACCOUNT_ELEMENT = "account";
    public static final String UUID_ATTRIBUTE = "uuid";
    public static final String INCOMING_SERVER_ELEMENT = "incoming-server";
    public static final String OUTGOING_SERVER_ELEMENT = "outgoing-server";
    public static final String TYPE_ATTRIBUTE = "type";
    public static final String HOST_ELEMENT = "host";
    public static final String PORT_ELEMENT = "port";
    public static final String CONNECTION_SECURITY_ELEMENT = "connection-security";
    public static final String AUTHENTICATION_TYPE_ELEMENT = "authentication-type";
    public static final String USERNAME_ELEMENT = "username";
    public static final String CLIENT_CERTIFICATE_ALIAS_ELEMENT = "client-cert-alias";
    public static final String PASSWORD_ELEMENT = "password";
    public static final String EXTRA_ELEMENT = "extra";
    public static final String IDENTITIES_ELEMENT = "identities";
    public static final String IDENTITY_ELEMENT = "identity";
    public static final String FOLDERS_ELEMENT = "folders";
    public static final String FOLDER_ELEMENT = "folder";
    public static final String NAME_ATTRIBUTE = "name";
    public static final String VALUE_ELEMENT = "value";
    public static final String KEY_ATTRIBUTE = "key";
    public static final String NAME_ELEMENT = "name";
    public static final String EMAIL_ELEMENT = "email";
    public static final String DESCRIPTION_ELEMENT = "description";

    public static String exportToFile(Context context, boolean includeGlobals,
            Set<String> accountUuids)
            throws SettingsImportExportException {

        OutputStream os = null;
        String filename = null;
        try
        {
            File dir = new File(Environment.getExternalStorageDirectory() + File.separator
                                + context.getPackageName());
            dir.mkdirs();
            File file = Utility.createUniqueFile(dir, EXPORT_FILENAME);
            filename = file.getAbsolutePath();
            os = new FileOutputStream(filename);

            exportPreferences(context, os, includeGlobals, accountUuids);

            // If all went well, we return the name of the file just written.
            return filename;
        } catch (Exception e) {
            throw new SettingsImportExportException(e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ioe) {
                    Log.w(K9.LOG_TAG, "Couldn't close exported settings file: " + filename);
                }
            }
        }
    }

    public static void exportPreferences(Context context, OutputStream os, boolean includeGlobals,
            Set<String> accountUuids) throws SettingsImportExportException  {

        try {
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(os, "UTF-8");

            serializer.startDocument(null, Boolean.TRUE);

            // Output with indentation
            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

            serializer.startTag(null, ROOT_ELEMENT);
            serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION));
            serializer.attribute(null, FILE_FORMAT_ATTRIBUTE,
                    Integer.toString(FILE_FORMAT_VERSION));

            Log.i(K9.LOG_TAG, "Exporting preferences");

            Preferences preferences = Preferences.getPreferences(context);
            SharedPreferences storage = preferences.getPreferences();

            Set<String> exportAccounts;
            if (accountUuids == null) {
                Account[] accounts = preferences.getAccounts();
                exportAccounts = new HashSet<String>();
                for (Account account : accounts) {
                    exportAccounts.add(account.getUuid());
                }
            } else {
                exportAccounts = accountUuids;
            }

            Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll());

            if (includeGlobals) {
                serializer.startTag(null, GLOBAL_ELEMENT);
                writeSettings(serializer, prefs);
                serializer.endTag(null, GLOBAL_ELEMENT);
            }

            serializer.startTag(null, ACCOUNTS_ELEMENT);
            for (String accountUuid : exportAccounts) {
                Account account = preferences.getAccount(accountUuid);
                writeAccount(serializer, account, prefs);
            }
            serializer.endTag(null, ACCOUNTS_ELEMENT);

            serializer.endTag(null, ROOT_ELEMENT);
            serializer.endDocument();
            serializer.flush();

        } catch (Exception e) {
            throw new SettingsImportExportException(e.getLocalizedMessage(), e);
        }
    }

    private static void writeSettings(XmlSerializer serializer,
            Map<String, Object> prefs) throws IOException {

        for (Entry<String, TreeMap<Integer, SettingsDescription>> versionedSetting :
                GlobalSettings.SETTINGS.entrySet()) {

            String key = versionedSetting.getKey();
            String valueString = (String) prefs.get(key);
            TreeMap<Integer, SettingsDescription> versions = versionedSetting.getValue();
            Integer highestVersion = versions.lastKey();
            SettingsDescription setting = versions.get(highestVersion);
            if (setting == null) {
                // Setting was removed.
                continue;
            }

            if (valueString != null) {
                try {
                    Object value = setting.fromString(valueString);
                    String outputValue = setting.toPrettyString(value);
                    writeKeyValue(serializer, key, outputValue);
                } catch (InvalidSettingValueException e) {
                    Log.w(K9.LOG_TAG, "Global setting \"" + key  + "\" has invalid value \"" +
                            valueString + "\" in preference storage. This shouldn't happen!");
                }
            } else {
                if (K9.DEBUG) {
                    Log.d(K9.LOG_TAG, "Couldn't find key \"" + key + "\" in preference storage." +
                            "Using default value.");
                }

                Object value = setting.getDefaultValue();
                String outputValue = setting.toPrettyString(value);
                writeKeyValue(serializer, key, outputValue);
            }
        }
    }

    private static void writeAccount(XmlSerializer serializer, Account account,
            Map<String, Object> prefs) throws IOException {

        Set<Integer> identities = new HashSet<Integer>();
        Set<String> folders = new HashSet<String>();
        String accountUuid = account.getUuid();

        serializer.startTag(null, ACCOUNT_ELEMENT);
        serializer.attribute(null, UUID_ATTRIBUTE, accountUuid);

        String name = (String) prefs.get(accountUuid + "." + Account.ACCOUNT_DESCRIPTION_KEY);
        if (name != null) {
            serializer.startTag(null, NAME_ELEMENT);
            serializer.text(name);
            serializer.endTag(null, NAME_ELEMENT);
        }

        // Write incoming server settings
        ServerSettings incoming = Store.decodeStoreUri(account.getStoreUri());
        serializer.startTag(null, INCOMING_SERVER_ELEMENT);
        serializer.attribute(null, TYPE_ATTRIBUTE, incoming.type);

        writeElement(serializer, HOST_ELEMENT, incoming.host);
        if (incoming.port != -1) {
            writeElement(serializer, PORT_ELEMENT, Integer.toString(incoming.port));
        }
        if (incoming.connectionSecurity != null) {
            writeElement(serializer, CONNECTION_SECURITY_ELEMENT, incoming.connectionSecurity.name());
        }
        if (incoming.authenticationType != null) {
            writeElement(serializer, AUTHENTICATION_TYPE_ELEMENT, incoming.authenticationType.name());
        }
        writeElement(serializer, USERNAME_ELEMENT, incoming.username);
        writeElement(serializer, CLIENT_CERTIFICATE_ALIAS_ELEMENT, incoming.clientCertificateAlias);
        // XXX For now we don't export the password
        //writeElement(serializer, PASSWORD_ELEMENT, incoming.password);

        Map<String, String> extras = incoming.getExtra();
        if (extras != null && extras.size() > 0) {
            serializer.startTag(null, EXTRA_ELEMENT);
            for (Entry<String, String> extra : extras.entrySet()) {
                writeKeyValue(serializer, extra.getKey(), extra.getValue());
            }
            serializer.endTag(null, EXTRA_ELEMENT);
        }

        serializer.endTag(null, INCOMING_SERVER_ELEMENT);

        // Write outgoing server settings
        ServerSettings outgoing = Transport.decodeTransportUri(account.getTransportUri());
        serializer.startTag(null, OUTGOING_SERVER_ELEMENT);
        serializer.attribute(null, TYPE_ATTRIBUTE, outgoing.type);

        writeElement(serializer, HOST_ELEMENT, outgoing.host);
        if (outgoing.port != -1) {
            writeElement(serializer, PORT_ELEMENT, Integer.toString(outgoing.port));
        }
        if (outgoing.connectionSecurity != null) {
            writeElement(serializer, CONNECTION_SECURITY_ELEMENT, outgoing.connectionSecurity.name());
        }
        if (outgoing.authenticationType != null) {
            writeElement(serializer, AUTHENTICATION_TYPE_ELEMENT, outgoing.authenticationType.name());
        }
        writeElement(serializer, USERNAME_ELEMENT, outgoing.username);
        writeElement(serializer, CLIENT_CERTIFICATE_ALIAS_ELEMENT, outgoing.clientCertificateAlias);
        // XXX For now we don't export the password
        //writeElement(serializer, PASSWORD_ELEMENT, outgoing.password);

        extras = outgoing.getExtra();
        if (extras != null && extras.size() > 0) {
            serializer.startTag(null, EXTRA_ELEMENT);
            for (Entry<String, String> extra : extras.entrySet()) {
                writeKeyValue(serializer, extra.getKey(), extra.getValue());
            }
            serializer.endTag(null, EXTRA_ELEMENT);
        }

        serializer.endTag(null, OUTGOING_SERVER_ELEMENT);

        // Write account settings
        serializer.startTag(null, SETTINGS_ELEMENT);
        for (Map.Entry<String, Object> entry : prefs.entrySet()) {
            String key = entry.getKey();
            String valueString = entry.getValue().toString();
            String[] comps = key.split("\\.");

            if (comps.length < 2) {
                // Skip global settings
                continue;
            }

            String keyUuid = comps[0];
            String secondPart = comps[1];

            if (!keyUuid.equals(accountUuid)) {
                // Setting doesn't belong to the account we're currently writing.
                continue;
            }

            String keyPart;
            if (comps.length >= 3) {
                String thirdPart = comps[2];

                if (Account.IDENTITY_DESCRIPTION_KEY.equals(secondPart)) {
                    // This is an identity key. Save identity index for later...
                    try {
                        identities.add(Integer.parseInt(thirdPart));
                    } catch (NumberFormatException e) { /* ignore */ }
                    // ... but don't write it now.
                    continue;
                }

                if (FolderSettings.SETTINGS.containsKey(thirdPart)) {
                    // This is a folder key. Save folder name for later...
                    folders.add(secondPart);
                    // ... but don't write it now.
                    continue;
                }

                // Strip account UUID from key
                keyPart = key.substring(comps[0].length() + 1);
            } else {
                keyPart = secondPart;
            }

            TreeMap<Integer, SettingsDescription> versionedSetting =
                AccountSettings.SETTINGS.get(keyPart);

            if (versionedSetting != null) {
                Integer highestVersion = versionedSetting.lastKey();
                SettingsDescription setting = versionedSetting.get(highestVersion);

                if (setting != null) {
                    // Only export account settings that can be found in AccountSettings.SETTINGS
                    try {
                        Object value = setting.fromString(valueString);
                        String pretty = setting.toPrettyString(value);
                        writeKeyValue(serializer, keyPart, pretty);
                    } catch (InvalidSettingValueException e) {
                        Log.w(K9.LOG_TAG, "Account setting \"" + keyPart  + "\" (" +
                                account.getDescription() + ") has invalid value \"" + valueString +
                                "\" in preference storage. This shouldn't happen!");
                    }
                }
            }
        }
        serializer.endTag(null, SETTINGS_ELEMENT);

        if (identities.size() > 0) {
            serializer.startTag(null, IDENTITIES_ELEMENT);

            // Sort identity indices (that's why we store them as Integers)
            List<Integer> sortedIdentities = new ArrayList<Integer>(identities);
            Collections.sort(sortedIdentities);

            for (Integer identityIndex : sortedIdentities) {
                writeIdentity(serializer, accountUuid, identityIndex.toString(), prefs);
            }
            serializer.endTag(null, IDENTITIES_ELEMENT);
        }

        if (folders.size() > 0) {
            serializer.startTag(null, FOLDERS_ELEMENT);
            for (String folder : folders) {
                writeFolder(serializer, accountUuid, folder, prefs);
            }
            serializer.endTag(null, FOLDERS_ELEMENT);
        }

        serializer.endTag(null, ACCOUNT_ELEMENT);
    }

    private static void writeIdentity(XmlSerializer serializer, String accountUuid,
            String identity, Map<String, Object> prefs) throws IOException {

        serializer.startTag(null, IDENTITY_ELEMENT);

        String prefix = accountUuid + ".";
        String suffix = "." + identity;

        // Write name belonging to the identity
        String name = (String) prefs.get(prefix + Account.IDENTITY_NAME_KEY + suffix);
        serializer.startTag(null, NAME_ELEMENT);
        serializer.text(name);
        serializer.endTag(null, NAME_ELEMENT);

        // Write email address belonging to the identity
        String email = (String) prefs.get(prefix + Account.IDENTITY_EMAIL_KEY + suffix);
        serializer.startTag(null, EMAIL_ELEMENT);
        serializer.text(email);
        serializer.endTag(null, EMAIL_ELEMENT);

        // Write identity description
        String description = (String) prefs.get(prefix + Account.IDENTITY_DESCRIPTION_KEY + suffix);
        if (description != null) {
            serializer.startTag(null, DESCRIPTION_ELEMENT);
            serializer.text(description);
            serializer.endTag(null, DESCRIPTION_ELEMENT);
        }

        // Write identity settings
        serializer.startTag(null, SETTINGS_ELEMENT);
        for (Map.Entry<String, Object> entry : prefs.entrySet()) {
            String key = entry.getKey();
            String valueString = entry.getValue().toString();
            String[] comps = key.split("\\.");

            if (comps.length < 3) {
                // Skip non-identity config entries
                continue;
            }

            String keyUuid = comps[0];
            String identityKey = comps[1];
            String identityIndex = comps[2];
            if (!keyUuid.equals(accountUuid) || !identityIndex.equals(identity)) {
                // Skip entries that belong to another identity
                continue;
            }

            TreeMap<Integer, SettingsDescription> versionedSetting =
                IdentitySettings.SETTINGS.get(identityKey);

            if (versionedSetting != null) {
                Integer highestVersion = versionedSetting.lastKey();
                SettingsDescription setting = versionedSetting.get(highestVersion);

                if (setting != null) {
                    // Only write settings that have an entry in IdentitySettings.SETTINGS
                    try {
                        Object value = setting.fromString(valueString);
                        String outputValue = setting.toPrettyString(value);
                        writeKeyValue(serializer, identityKey, outputValue);
                    } catch (InvalidSettingValueException e) {
                        Log.w(K9.LOG_TAG, "Identity setting \"" + identityKey +
                                "\" has invalid value \"" + valueString +
                                "\" in preference storage. This shouldn't happen!");
                    }
                }
            }
        }
        serializer.endTag(null, SETTINGS_ELEMENT);

        serializer.endTag(null, IDENTITY_ELEMENT);
    }

    private static void writeFolder(XmlSerializer serializer, String accountUuid,
            String folder, Map<String, Object> prefs) throws IOException {

        serializer.startTag(null, FOLDER_ELEMENT);
        serializer.attribute(null, NAME_ATTRIBUTE, folder);

        // Write folder settings
        for (Map.Entry<String, Object> entry : prefs.entrySet()) {
            String key = entry.getKey();
            String valueString = entry.getValue().toString();
            String[] comps = key.split("\\.");

            if (comps.length < 3) {
                // Skip non-folder config entries
                continue;
            }

            String keyUuid = comps[0];
            String folderName = comps[1];
            String folderKey = comps[2];

            if (!keyUuid.equals(accountUuid) || !folderName.equals(folder)) {
                // Skip entries that belong to another folder
                continue;
            }

            TreeMap<Integer, SettingsDescription> versionedSetting =
                FolderSettings.SETTINGS.get(folderKey);

            if (versionedSetting != null) {
                Integer highestVersion = versionedSetting.lastKey();
                SettingsDescription setting = versionedSetting.get(highestVersion);

                if (setting != null) {
                    // Only write settings that have an entry in FolderSettings.SETTINGS
                    try {
                        Object value = setting.fromString(valueString);
                        String outputValue = setting.toPrettyString(value);
                        writeKeyValue(serializer, folderKey, outputValue);
                    } catch (InvalidSettingValueException e) {
                        Log.w(K9.LOG_TAG, "Folder setting \"" + folderKey +
                                "\" has invalid value \"" + valueString +
                                "\" in preference storage. This shouldn't happen!");
                    }
                }
            }
        }

        serializer.endTag(null, FOLDER_ELEMENT);
    }

    private static void writeElement(XmlSerializer serializer, String elementName, String value)
            throws IllegalArgumentException, IllegalStateException, IOException {
        if (value != null) {
            serializer.startTag(null, elementName);
            serializer.text(value);
            serializer.endTag(null, elementName);
        }
    }

    private static void writeKeyValue(XmlSerializer serializer, String key, String value)
            throws IllegalArgumentException, IllegalStateException, IOException {
        serializer.startTag(null, VALUE_ELEMENT);
        serializer.attribute(null, KEY_ATTRIBUTE, key);
        if (value != null) {
            serializer.text(value);
        }
        serializer.endTag(null, VALUE_ELEMENT);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>OculusMobileSDKHeadTracking (Oculus Mobile SDK Head Tracking)</title>
<meta name="date" content="2016-05-18">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.judax.oculusmobilesdkheadtracking

Class OculusMobileSDKHeadTracking

java.lang.Object

com.judax.oculusmobilesdkheadtracking.OculusMobileSDKHeadTracking

public class OculusMobileSDKHeadTracking
extends java.lang.Object

This class allows to acquire just the head tracking information (orientation) from the Oculus mobile SDK.
 An activity life cycle events are passed along to instances of this class.
 Any class can register to listen to head tracking events. Instances of this class also internally store the
 state of the head tracking values. These values can be retrieved any time calling the corresponding get methods.
 At least for now, the view that instances of this class provide needs to be added to the view hierarchy
 in order for the head tracking acquisition mechanism to work. This view won't be used to render anything
 so there are several recommendations on how to add the view inside your applications:
 1) Use a FrameLayout to add the view and then add your app's views on top of it. Recommended. FrameLayout-s stack views
 one on top of the other. The view required for the head tracking to work can be occluded by the view of your app.
 2) Add the view as a 1x1 pixel size view using the corresponding layout parameters. Not recommended as at least one
 pixel of you application will be used by this view. Not a perfect solution but works

Author:

JudaX

Constructor Summary

Constructors

Constructor and Description

OculusMobileSDKHeadTracking()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
addOculusMobileSDKHeadTrackingListener(OculusMobileSDKHeadTrackingListener listener)

Register a listener that will be notified when head tracking changes occur.

OculusMobileSDKHeadTrackingData
getData()

java.lang.String
getErrorMessage()

View
getView()

Returns a view that needs to be added at some point to the application view hierarchy in order to make the
 head tracking acquisition to work.

boolean
hasStarted()

void
pause()

Call this method on the Activity onPause life cycle event.

void
removeAllOculusMobileSDKHeadTrackingListeners()

Remove all the registered listeners for head tracking event changes.

void
removeOculusMobileSDKHeadTrackingListener(OculusMobileSDKHeadTrackingListener listener)

Unregister a listener of head tracking changes.

void
resume()

Call this method on the Activity onResume life cycle event.

void
start(Activity activity)

Call this method to initialize the Oculus mobile head tracking.

void
stop()

Call this method on the Activity onDestroy life cycle event.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

OculusMobileSDKHeadTracking

public OculusMobileSDKHeadTracking()

Method Detail

start

public void start(Activity activity)

Call this method to initialize the Oculus mobile head tracking.

Parameters:

activity - The activity where the head tracking will be executed on.

Throws:

java.lang.IllegalStateException - if the Oculus mobile SDK could not be initialized.

getView

public View getView()

Returns a view that needs to be added at some point to the application view hierarchy in order to make the
 head tracking acquisition to work.

Returns:

the view to be added to the application view hierarchy in order to fully initialize the head tracking.

resume

public void resume()

Call this method on the Activity onResume life cycle event. It can also be called at any time to resume
 a head tracking that is paused.

pause

public void pause()

Call this method on the Activity onPause life cycle event. It can also be called at any time to
 pause the head tracking.

stop

public void stop()

Call this method on the Activity onDestroy life cycle event. It fully finalizes the
 head tracking mechanism.

hasStarted

public boolean hasStarted()

Returns:

if the head tracking has started (true) or not (false)

getErrorMessage

public java.lang.String getErrorMessage()

Returns:

the errorMessage

getData

public OculusMobileSDKHeadTrackingData getData()

Returns:

the current head tracking data.

addOculusMobileSDKHeadTrackingListener

public void addOculusMobileSDKHeadTrackingListener(OculusMobileSDKHeadTrackingListener listener)

Register a listener that will be notified when head tracking changes occur.

Parameters:

listener - The instance to be registered to listen to head tracking changes.

removeOculusMobileSDKHeadTrackingListener

public void removeOculusMobileSDKHeadTrackingListener(OculusMobileSDKHeadTrackingListener listener)

Unregister a listener of head tracking changes.

Parameters:

listener - The listener to be unregistered from listening to head tracking updates.

removeAllOculusMobileSDKHeadTrackingListeners

public void removeAllOculusMobileSDKHeadTrackingListeners()

Remove all the registered listeners for head tracking event changes.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
/* eslint-disable */
import React from 'react';
import VideoPreview from '../../src/components/Fields/video/videoPreview';
import { shallow, mount } from 'enzyme';
import sinon from 'sinon';
/* eslint-enable */

const fakeProps = {
  thumbnailUrl: 'image.jpg',
  url: 'https://www.youtube.com/',
  title: 'Video title',
  authorName: 'First Last',
};

describe('VideoPreview field', () => {
  it('should render the input field', () => {
    const elem = shallow(<VideoPreview {...fakeProps} />);

    const thumb = elem.find('.PyramidVideoPreview__Thumbnail');

    // Expect a single label to be rendered
    expect(thumb).to.have.length(1);

    // Render text field
    expect(elem.find('.PyramidVideoPreview__Content')).to.have.length(1);

    expect(thumb.prop('href')).to.equal(fakeProps.url);

    expect(thumb.find('img').prop('src')).to.equal('image.jpg');

    expect(elem.find('.PyramidVideoPreview__ContentTitle').text()).to.equal(fakeProps.title);

    expect(elem.find('.PyramidVideoPreview__ContentAuthor').text()).to.equal(fakeProps.authorName);
  });
});


text:
void SSUIImageWriteToSavedPhotosAlbumWithAlbumAssetsGroup(UIImage *image,
                                                          SSUIAssetsGroup *albumAssetsGroup,
                                                          SSUIWriteAssetCompletionBlock completionBlock) {
  [[SSUIAssetsManager sharedInstance] saveImageWithImageRef:image.CGImage
                                           albumAssetsGroup:albumAssetsGroup
                                                orientation:image.imageOrientation
                                            completionBlock:completionBlock];
}

void SSUISaveImageAtPathToSavedPhotosAlbumWithAlbumAssetsGroup(NSString *imagePath,
                                                               SSUIAssetsGroup *albumAssetsGroup,
                                                               SSUIWriteAssetCompletionBlock completionBlock) {
  [[SSUIAssetsManager sharedInstance] saveImageWithImagePathURL:[NSURL fileURLWithPath:imagePath]
                                               albumAssetsGroup:albumAssetsGroup
                                                completionBlock:completionBlock];
}

void SSUISaveVideoAtPathToSavedPhotosAlbumWithAlbumAssetsGroup(NSString *videoPath,
                                                               SSUIAssetsGroup *albumAssetsGroup,
                                                               SSUIWriteAssetCompletionBlock completionBlock) {
  [[SSUIAssetsManager sharedInstance] saveVideoWithVideoPathURL:[NSURL fileURLWithPath:videoPath]
                                               albumAssetsGroup:albumAssetsGroup
                                                completionBlock:completionBlock];
}

@implementation SSUIAssetsManager{
  PHCachingImageManager *_cachingImageManager;
}

+ (SSUIAssetsManager *)sharedInstance {
  static dispatch_once_t onceToken;
  static SSUIAssetsManager *instance = nil;
  dispatch_once(&onceToken,^{
    instance = [[super allocWithZone:NULL] init];
  });
  return instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone {
  return [self sharedInstance];
}

+ (SSUIAssetAuthorizationStatus)authorizationStatus {
  SSUIAssetAuthorizationStatus status;
  PHAuthorizationStatus authorizationStatus = [PHPhotoLibrary authorizationStatus];
  if (authorizationStatus == PHAuthorizationStatusRestricted || authorizationStatus == PHAuthorizationStatusDenied) {
    status = SSUIAssetAuthorizationStatusNotAuthorized;
  } else if (authorizationStatus == PHAuthorizationStatusNotDetermined) {
    status = SSUIAssetAuthorizationStatusNotDetermined;
  } else {
    status = SSUIAssetAuthorizationStatusAuthorized;
  }
  return status;
}

+ (void)requestAuthorization:(void(^)(SSUIAssetAuthorizationStatus status))handler {
  [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus phStatus) {
    SSUIAssetAuthorizationStatus status;
    if (phStatus == PHAuthorizationStatusRestricted || phStatus == PHAuthorizationStatusDenied) {
      status = SSUIAssetAuthorizationStatusNotAuthorized;
    } else if (phStatus == PHAuthorizationStatusNotDetermined) {
      status = SSUIAssetAuthorizationStatusNotDetermined;
    } else {
      status = SSUIAssetAuthorizationStatusAuthorized;
    }
    if (handler) {
      handler(status);
    }
  }];
}

- (void)enumerateAllAlbumsWithAlbumContentType:(SSUIAlbumContentType)contentType showEmptyAlbum:(BOOL)showEmptyAlbum showSmartAlbumIfSupported:(BOOL)showSmartAlbumIfSupported usingBlock:(void (^)(SSUIAssetsGroup *resultAssetsGroup))enumerationBlock {
  NSArray *tempAlbumsArray = [PHPhotoLibrary fetchAllAlbumsWithAlbumContentType:contentType
                                                                 showEmptyAlbum:showEmptyAlbum
                                                                 showSmartAlbum:showSmartAlbumIfSupported];
  PHFetchOptions *fetchOptions = [PHPhotoLibrary createFetchOptionsWithAlbumContentType:contentType];

  for (NSUInteger i = 0; i < [tempAlbumsArray count]; i++) {
    PHAssetCollection *assetCollection = [tempAlbumsArray objectAtIndex:i];
    SSUIAssetsGroup *assetsGroup = [[SSUIAssetsGroup alloc] initWithCollection:assetCollection
                                                            fetchAssetsOptions:fetchOptions];
    if (enumerationBlock) {
      enumerationBlock(assetsGroup);
    }
  }

  if (enumerationBlock) {
    enumerationBlock(nil);
  }
}

- (void)enumerateAllAlbumsWithAlbumContentType:(SSUIAlbumContentType)contentType usingBlock:(void (^)(SSUIAssetsGroup *resultAssetsGroup))enumerationBlock {
  [self enumerateAllAlbumsWithAlbumContentType:contentType
                                showEmptyAlbum:NO
                     showSmartAlbumIfSupported:YES
                                    usingBlock:enumerationBlock];
}

- (void)saveImageWithImageRef:(CGImageRef)imageRef albumAssetsGroup:(SSUIAssetsGroup *)albumAssetsGroup orientation:(UIImageOrientation)orientation completionBlock:(SSUIWriteAssetCompletionBlock)completionBlock {
  PHAssetCollection *albumPhAssetCollection = albumAssetsGroup.assetCollection;
  [[PHPhotoLibrary sharedPhotoLibrary] addImageToAlbum:imageRef
                                  albumAssetCollection:albumPhAssetCollection
                                           orientation:orientation
                                     completionHandler:^(BOOL success, NSDate *creationDate, NSError *error) {
                                       if (success) {
                                         PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
                                         fetchOptions.predicate = [NSPredicate predicateWithFormat:@"creationDate = %@", creationDate];
                                         PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:albumPhAssetCollection
                                                                                options:fetchOptions];
                                         SSUIAsset *asset = [[SSUIAsset alloc] initWithAsset:fetchResult.lastObject];
                                         completionBlock(asset, error);
                                       } else {
                                         SSUIKitLog(@"Get PHAsset of image error: %@", error);
                                         completionBlock(nil, error);
                                       }
                                     }];
}

- (void)saveImageWithImagePathURL:(NSURL *)imagePathURL albumAssetsGroup:(SSUIAssetsGroup *)albumAssetsGroup completionBlock:(SSUIWriteAssetCompletionBlock)completionBlock {
  PHAssetCollection *albumPhAssetCollection = albumAssetsGroup.assetCollection;
  [[PHPhotoLibrary sharedPhotoLibrary] addImageToAlbum:imagePathURL
                                  albumAssetCollection:albumPhAssetCollection
                                     completionHandler:^(BOOL success, NSDate *creationDate, NSError *error) {
                                       if (success) {
                                         PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
                                         fetchOptions.predicate = [NSPredicate predicateWithFormat:@"creationDate = %@", creationDate];
                                         PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:albumPhAssetCollection
                                                                                options:fetchOptions];
                                         SSUIAsset *asset = [[SSUIAsset alloc] initWithAsset:fetchResult.lastObject];
                                         completionBlock(asset, error);
                                       } else {
                                         SSUIKitLog(@"Get PHAsset of image error: %@", error);
                                         completionBlock(nil, error);
                                       }
                                     }];
}

- (void)saveVideoWithVideoPathURL:(NSURL *)videoPathURL albumAssetsGroup:(SSUIAssetsGroup *)albumAssetsGroup completionBlock:(SSUIWriteAssetCompletionBlock)completionBlock {
  PHAssetCollection *albumPhAssetCollection = albumAssetsGroup.assetCollection;
  [[PHPhotoLibrary sharedPhotoLibrary] addVideoToAlbum:videoPathURL
                                  albumAssetCollection:albumPhAssetCollection
                                     completionHandler:^(BOOL success, NSDate *creationDate, NSError *error) {
                                       if (success) {
                                         PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
                                         fetchOptions.predicate = [NSPredicate predicateWithFormat:@"creationDate = %@", creationDate];
                                         PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:albumPhAssetCollection
                                                                                options:fetchOptions];
                                         SSUIAsset *asset = [[SSUIAsset alloc] initWithAsset:fetchResult.lastObject];
                                         completionBlock(asset, error);
                                       } else {
                                         SSUIKitLog(@"Get PHAsset of video Error: %@", error);
                                         completionBlock(nil, error);
                                       }
                                     }];
}

#pragma mark - getter

- (PHCachingImageManager *)cachingImageManager {
  if (!_cachingImageManager) {
    _cachingImageManager = [[PHCachingImageManager alloc] init];
  }
  return _cachingImageManager;
}
@end

@implementation PHPhotoLibrary (UI)

+ (PHFetchOptions *)createFetchOptionsWithAlbumContentType:(SSUIAlbumContentType)contentType {
  PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
  switch (contentType) {
    case SSUIAlbumContentTypeOnlyPhoto:
      fetchOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i", PHAssetMediaTypeImage];
      break;

    case SSUIAlbumContentTypeOnlyVideo:
      fetchOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i",PHAssetMediaTypeVideo];
      break;

    case SSUIAlbumContentTypeOnlyAudio:
      fetchOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i",PHAssetMediaTypeAudio];
      break;

    default:
      break;
  }
  return fetchOptions;
}

+ (NSArray *)fetchAllAlbumsWithAlbumContentType:(SSUIAlbumContentType)contentType showEmptyAlbum:(BOOL)showEmptyAlbum showSmartAlbum:(BOOL)showSmartAlbum {
  NSMutableArray *tempAlbumsArray = [[NSMutableArray alloc] init];
  PHFetchOptions *fetchOptions = [PHPhotoLibrary createFetchOptionsWithAlbumContentType:contentType];
  PHFetchResult *fetchResult;
  if (showSmartAlbum) {
    fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum
                                                           subtype:PHAssetCollectionSubtypeAny
                                                           options:nil];
  } else {
    fetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum
                                                           subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary
                                                           options:nil];
  }
  for (NSInteger i = 0; i < fetchResult.count; i++) {
    PHCollection *collection = fetchResult[i];
    if ([collection isKindOfClass:[PHAssetCollection class]]) {
      PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
      PHFetchResult *currentFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:fetchOptions];
      if (currentFetchResult.count > 0 || showEmptyAlbum) {
        if (assetCollection.assetCollectionSubtype == PHAssetCollectionSubtypeSmartAlbumUserLibrary) {
          [tempAlbumsArray insertObject:assetCollection atIndex:0];
        } else {
          [tempAlbumsArray addObject:assetCollection];
        }
      }
    } else {
      NSAssert(NO, @"Fetch collection not PHCollection: %@", collection);
    }
  }
  PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
  for (NSInteger i = 0; i < topLevelUserCollections.count; i++) {
    PHCollection *collection = topLevelUserCollections[i];
    if ([collection isKindOfClass:[PHAssetCollection class]]) {
      PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
      if (showEmptyAlbum) {
        [tempAlbumsArray addObject:assetCollection];
      } else {
        PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:fetchOptions];
        if (fetchResult.count > 0) {
          [tempAlbumsArray addObject:assetCollection];
        }
      }
    }
  }

  PHFetchResult *macCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
                                                                           subtype:PHAssetCollectionSubtypeAlbumSyncedAlbum
                                                                           options:nil];
  for (NSInteger i = 0; i < macCollections.count; i++) {
    PHCollection *collection = macCollections[i];
    if ([collection isKindOfClass:[PHAssetCollection class]]) {
      PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
      [tempAlbumsArray addObject:assetCollection];
    }
  }
  NSArray *resultAlbumsArray = [tempAlbumsArray copy];

  return resultAlbumsArray;
}

+ (PHAsset *)fetchLatestAssetWithAssetCollection:(PHAssetCollection *)assetCollection {
  PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
  fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
  PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:fetchOptions];
  PHAsset *latestAsset = fetchResult.lastObject;
  return latestAsset;
}

- (void)addImageToAlbum:(CGImageRef)imageRef albumAssetCollection:(PHAssetCollection *)albumAssetCollection orientation:(UIImageOrientation)orientation completionHandler:(void(^)(BOOL success, NSDate *creationDate, NSError *error))completionHandler {
  UIImage *targetImage = [UIImage imageWithCGImage:imageRef scale:ScreenScale orientation:orientation];
  [[PHPhotoLibrary sharedPhotoLibrary] addImageToAlbum:targetImage
                                          imagePathURL:nil
                                  albumAssetCollection:albumAssetCollection
                                     completionHandler:completionHandler];
}

- (void)addImageToAlbum:(NSURL *)imagePathURL albumAssetCollection:(PHAssetCollection *)albumAssetCollection completionHandler:(void (^)(BOOL success, NSDate *creationDate, NSError *error))completionHandler {
  [[PHPhotoLibrary sharedPhotoLibrary] addImageToAlbum:nil
                                          imagePathURL:imagePathURL
                                  albumAssetCollection:albumAssetCollection
                                     completionHandler:completionHandler];
}

- (void)addImageToAlbum:(UIImage *)image imagePathURL:(NSURL *)imagePathURL albumAssetCollection:(PHAssetCollection *)albumAssetCollection completionHandler:(void(^)(BOOL success, NSDate *creationDate, NSError *error))completionHandler {
  __block NSDate *creationDate = nil;
  [self performChanges:^{
    PHAssetChangeRequest *assetChangeRequest;
    if (image) {
      assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
    } else if (imagePathURL) {
      assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:imagePathURL];
    } else {
      SSUIKitLog(@"Creating asset with empty data");
      return;
    }
    assetChangeRequest.creationDate = [NSDate date];
    creationDate = assetChangeRequest.creationDate;
    if (albumAssetCollection.assetCollectionType == PHAssetCollectionTypeAlbum) {
      PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:albumAssetCollection];
      [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
    }
  } completionHandler:^(BOOL success, NSError *error) {
    if (!success) {
      SSUIKitLog(@"Creating asset of image error : %@", error);
    }
    if (completionHandler) {
      dispatch_async(dispatch_get_main_queue(), ^{
        BOOL creatingSuccess = success && creationDate;
        completionHandler(creatingSuccess, creationDate, error);
      });
    }
  }];
}

- (void)addVideoToAlbum:(NSURL *)videoPathURL albumAssetCollection:(PHAssetCollection *)albumAssetCollection completionHandler:(void(^)(BOOL success, NSDate *creationDate, NSError *error))completionHandler {
  __block NSDate *creationDate = nil;
  [self performChanges:^{
    PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoPathURL];
    assetChangeRequest.creationDate = [NSDate date];
    creationDate = assetChangeRequest.creationDate;
    if (albumAssetCollection.assetCollectionType == PHAssetCollectionTypeAlbum) {
      PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:albumAssetCollection];
      [assetCollectionChangeRequest addAssets:@[[assetChangeRequest placeholderForCreatedAsset]]];
    }
  } completionHandler:^(BOOL success, NSError *error) {
    if (!success) {
      SSUIKitLog(@"Creating asset of video error: %@", error);
    }
    if (completionHandler) {
      dispatch_async(dispatch_get_main_queue(), ^{
        BOOL creatingSuccess = success && creationDate;
        completionHandler(creatingSuccess, creationDate, error);
      });
    }
  }];
}
@end