text:
from pocs.utils import error

def on_enter(event_data):
    """
    In the `scheduling` state we attempt to find a field using our scheduler. If field is found,
    make sure that the field is up right now (the scheduler should have taken care of this). If
    observable, set the mount to the field and calls `start_slewing` to begin slew.

    If no observable targets are available, `park` the unit.
    """
    pocs = event_data.model
    pocs.next_state = 'parking'

    if pocs.run_once and len(pocs.observatory.scheduler.observed_list) > 0:
        pocs.say('Looks like we only wanted to run once, parking now')
    else:

        pocs.say("Ok, I'm finding something good to look at...")

        existing_observation = pocs.observatory.current_observation

        # Get the next observation
        try:
            observation = pocs.observatory.get_observation()
            pocs.logger.info("Observation: {}".format(observation))
        except error.NoObservation as e:
            pocs.say("No valid observations found. Can't schedule. Going to park.")
        except Exception as e:
            pocs.logger.warning("Error in scheduling: {}".format(e))
        else:

            if observation != existing_observation:
                pocs.say("Got it! I'm going to check out: {}".format(observation.name))

                pocs.logger.debug("Setting Observation coords: {}".format(observation.field))
                if pocs.observatory.mount.set_target_coordinates(observation.field):
                    pocs.next_state = 'slewing'
                else:
                    pocs.logger.warning("Field not properly set. Parking.")
            else:
                pocs.say("I'm sticking with {}".format(observation.name))
                pocs.next_state = 'tracking'


text:
<?php

namespace CachetHQ\Tests\Cachet\Bus\Events\User;

use CachetHQ\Cachet\Bus\Events\User\UserWasAddedEvent;
use CachetHQ\Cachet\Models\User;

/**
 * This is the user was added event test class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class UserWasAddedEventTest extends AbstractUserEventTestCase
{
    protected function objectHasHandlers()
    {
        return false;
    }

    protected function getObjectAndParams()
    {
        $params = ['user' => new User()];
        $object = new UserWasAddedEvent($params['user']);

        return compact('params', 'object');
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Powered By wufuwei
 */

package com.osp.biz.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import com.osp.biz.service.IOspCatalogService;
import com.osp.biz.manager.IOspCatalogManager;
import com.osp.biz.model.OspCatalog;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

/**
 * @author David Wu email:oradb(a)163.com
 * @version 1.0
 * @since 1.0
 */

@Service
public class OspCatalogService implements IOspCatalogService{

	private IOspCatalogManager ospCatalogManager;

	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性*/

	@Autowired
	public void setOspCatalogManager(IOspCatalogManager manager) {
		this.ospCatalogManager = manager;
	}

	public IOspCatalogManager getEntityManager() {
		return this.ospCatalogManager;
	}

	public OspCatalog getById(java.lang.Long id) {
		return (OspCatalog)ospCatalogManager.getById(id);
	}

	public void save(OspCatalog entity) {
		ospCatalogManager.save(entity);
	}

	public void removeById(java.lang.Long id) {
		ospCatalogManager.removeById(id);
	}

	public void update(OspCatalog entity) {
		ospCatalogManager.update(entity);
	}

	public boolean isUnique(OspCatalog entity, String uniquePropertyNames) {
		return ospCatalogManager.isUnique(entity, uniquePropertyNames);
	}

	public Long pageSelectCount(OspCatalog entity){
		return ospCatalogManager.pageSelectCount(entity);
	}

	public Page findByPageRequest(PageRequest pr) {
		return ospCatalogManager.findByPageRequest(pr);
	}

	public OspCatalog getByInnercode(java.lang.String v) {
		return ospCatalogManager.getByInnercode(v);
	}

	public List<OspCatalog> findAll() {
		return ospCatalogManager.findAll();
	}

	public void updateDynamic(OspCatalog entity){
		ospCatalogManager.updateDynamic(entity);
	}

	public List<OspCatalog> findByDynamicWhere(OspCatalog entity){
		return ospCatalogManager.findByDynamicWhere(entity);
	}

	public void saveOrUpdate(OspCatalog entity){
		ospCatalogManager.saveOrUpdate(entity);
	}

}


text:
require 'svnx/tc'

module Svnx
  module Options
  end
end

module Svnx::Options
  class TestCase < Svnx::TestCase
    def assert_send optcls, expected, values
      opts = optcls.new values
      expected.each do |methname, expval|
        result = opts.send methname
        assert_equal expval, result
      end
    end
  end
end


text:
<?php
namespace OpenDNS\MES\Trident;

/**
 * Delete a stored credit card
 *
 * If you want to refund an already-processed transaction, use Refund instead.
 */
class DeleteStoredCard extends Request
{
    /** @var string Transaction type to send in the request */
    protected $transactionType = 'X';

    /**
     * Set the card ID to delete
     *
     * This is a 32-character alphanumeric ID returned from a previous 'Store Card'
     * call.
     *
     * @param int|string $cardId
     * @return self The current class instance for chaining
     */
    public function setCardId($cardId)
    {
        return $this->setField('card_id', $cardId);
    }
}


text: Js projects boilerplate seeds


text:
importScripts("../../jschords-src.js")
self.onmessage = function(event)
{
	var timeseries = event.data.timeseries;
	var test_frequencies = event.data.test_frequencies;
	var sample_rate = event.data.sample_rate;
	var data = C.AudioUtil.analyze(timeseries, test_frequencies, sample_rate);
	self.postMessage(data);
};


text:
System.register([], function (_export) {
  'use strict';

  var ScrollHandler;

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

  return {
    setters: [],
    execute: function () {
      ScrollHandler = (function () {
        function ScrollHandler() {
          var _this = this;

          _classCallCheck(this, ScrollHandler);

          this.timeConstant = 325;
          this.firefoxMultitude = 30;
          this.mouseMultitude = 1;
          this.keyStep = 120;
          this.isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
          this.hasKeyDown = 'onkeydown' in document;
          this.hasWheelEvent = 'onwheel' in document;
          this.hasMouseWheelEvent = 'onmousewheel' in document;

          this.wheelListener = function (e) {
            return _this.wheel(e);
          };
          this.mouseWheelListener = function (e) {
            return _this.mouseWheel(e);
          };
          this.touchStartListener = function (e) {
            return _this.touchStart(e);
          };
          this.touchMoveListener = function (e) {
            return _this.touchMove(e);
          };
          this.touchEndListener = function (e) {
            return _this.touchEnd(e);
          };
          this.keyDownListener = function (e) {
            return _this.keyDown(e);
          };
        }

        ScrollHandler.prototype.initialize = function initialize(view, listener) {
          this.listener = listener;
          this.view = view;

          if (this.hasWheelEvent) {
            view.addEventListener('wheel', this.wheelListener);
          }

          if (this.hasMouseWheelEvent) {
            view.addEventListener('mousewheel', this.mouseWheelListener);
          }

          if (typeof window.ontouchstart !== 'undefined') {
            view.addEventListener('touchstart', this.touchStartListener);
            view.addEventListener('touchmove', this.touchMoveListener);
            view.addEventListener('touchend', this.touchEndListener);
          }

          if (this.hasKeyDown) {
            view.addEventListener('keydown', this.keyDownListener, false);
          }

          this.offset = 0;
          this.pressed = false;
        };

        ScrollHandler.prototype.dispose = function dispose() {
          this.view.addEventListener('wheel', this.wheelListener);
          this.view.addEventListener('mousewheel', this.mouseWheelListener);
          this.view.addEventListener('touchstart', this.touchStartListener);
          this.view.addEventListener('touchmove', this.touchMoveListener);
          this.view.addEventListener('touchend', this.touchEndListener);
          this.view.addEventListener('keydown', this.keyDownListener);
        };

        ScrollHandler.prototype.ypos = function ypos(event) {
          if (event.targetTouches && event.targetTouches.length >= 1) {
            return event.targetTouches[0].clientY;
          }

          return event.clientY;
        };

        ScrollHandler.prototype.autoScroll = function autoScroll() {
          var _this2 = this;

          var elapsed, delta;
          if (this.amplitude) {
            elapsed = Date.now() - this.timestamp;
            delta = this.amplitude * Math.exp(-elapsed / this.timeConstant);
            if (delta > 0.5 || delta < -0.5) {
              this.offset = this.listener(delta);
              requestAnimationFrame(function () {
                return _this2.autoScroll();
              });
            }
          }
        };

        ScrollHandler.prototype.track = function track() {
          var now, elapsed, delta, v;

          now = Date.now();
          elapsed = now - this.timestamp;
          this.timestamp = now;
          delta = this.offset - this.frame;
          this.frame = this.offset;

          v = 1000 * delta / (1 + elapsed);
          this.velocity = 0.3 * v + 0.2 * this.velocity;
        };

        ScrollHandler.prototype.touchMove = function touchMove(event) {
          var y, delta;
          if (this.pressed) {
            y = this.ypos(event);
            delta = this.reference - y;
            if (delta > 2 || delta < -2) {
              this.reference = y;
              this.offset = this.listener(-delta);
            }
          }
          event.preventDefault();
          event.stopPropagation();
          return false;
        };

        ScrollHandler.prototype.touchStart = function touchStart(event) {
          var _this3 = this;

          this.pressed = true;
          this.reference = this.ypos(event);

          this.velocity = this.amplitude = 0;
          this.frame = this.offset;
          this.timestamp = Date.now();
          clearInterval(this.ticker);
          this.ticker = setInterval(function () {
            return _this3.track();
          }, 10);

          event.preventDefault();
          event.stopPropagation();
          return false;
        };

        ScrollHandler.prototype.touchEnd = function touchEnd(event) {
          var _this4 = this;

          this.pressed = false;

          clearInterval(this.ticker);
          if (this.velocity > 10 || this.velocity < -10) {
            this.amplitude = 0.2 * this.velocity;
            this.target = Math.round(this.offset + this.amplitude);
            this.timestamp = Date.now();
            requestAnimationFrame(function () {
              return _this4.autoScroll();
            });
          }

          event.preventDefault();
          event.stopPropagation();
          return false;
        };

        ScrollHandler.prototype.mouseWheel = function mouseWheel(event) {
          var delta = event.wheelDeltaY ? event.wheelDeltaY : event.wheelDelta;

          this.offset = this.listener(delta);
        };

        ScrollHandler.prototype.wheel = function wheel(event) {
          var delta = event.wheelDeltaY || event.deltaY;

          if (this.isFirefox && event.deltaMode == 1) {
            delta *= this.firefoxMultitude;
            delta = -delta;
          }

          delta *= this.mouseMultitude;

          this.offset = this.listener(delta, true);
        };

        ScrollHandler.prototype.keyDown = function keyDown(event) {
          var delta = 0;
          switch (event.keyCode) {
            case 38:
              delta = this.keyStep;
              break;
            case 40:
              delta = -this.keyStep;
              break;
          }

          this.offset = this.listener(delta);
        };

        return ScrollHandler;
      })();

      _export('ScrollHandler', ScrollHandler);
    }
  };
});


text:
package es.uv.etse.bdweb.hotel.DAO;

import java.util.List;

public interface DAO<K, T> {

	public T getById(K id);

	public List<T> findAll();

	public void create(T entity);

	public void update(T entity);

	public void delete(T entity);

	public void deleteById(K entityId);

	public List<T> findByCriteria(String criteria);

	public List<T> findByCriteria(String join, String criteria);

	public List<T> findAllOrderByDesc(String campo);

	public List<Object[]> findObjectsByNativeQuery(String query);

	public Object findByNativeQuery(String query);

	public void updateByNativeQuery(String query);
}


text:
package overlay

import (
	"fmt"
	"syscall"

	"github.com/coreos/rkt/pkg/label"
	"github.com/hashicorp/errwrap"
)

// MountCfg contains the needed data to construct the overlay mount syscall.
// The Lower and Upper fields are paths to the filesystems to be merged. The
// Work field should be an empty directory. Dest is where the mount will be
// located. Lbl is an SELinux label.
type MountCfg struct {
	Lower,
	Upper,
	Work,
	Dest,
	Lbl string
}

// Mount mounts the upper and lower directories to the destination directory.
// The MountCfg struct supplies information required to build the mount system
// call.
func Mount(cfg *MountCfg) error {
	opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", cfg.Lower, cfg.Upper, cfg.Work)
	opts = label.FormatMountLabel(opts, cfg.Lbl)
	if err := syscall.Mount("overlay", cfg.Dest, "overlay", 0, opts); err != nil {
		return errwrap.Wrap(fmt.Errorf("error mounting overlay with options '%s' and dest '%s'", opts, cfg.Dest), err)
	}

	return nil
}


text:
// $Id: SETUP.C 344 2012-12-13 13:10:53Z krasznaa $
/***************************************************************************
 * @Project: SFrame - ROOT-based analysis framework for ATLAS
 * @Package: Plug-ins
 *
 * @author Stefan Ask       <Stefan.Ask@cern.ch>           - Manchester
 * @author David Berge      <David.Berge@cern.ch>          - CERN
 * @author Johannes Haller  <Johannes.Haller@cern.ch>      - Hamburg
 * @author A. Krasznahorkay <Attila.Krasznahorkay@cern.ch> - NYU/Debrecen
 *
 ***************************************************************************/

/**
 * This function loads all the libraries needed for SFramePlugIns (including
 * SFramePlugIns itself) on the PROOF master and worker nodes.
 */
int SETUP() {

   if( gSystem->Load( "libGenVector" ) == -1 ) return -1;
   if( gSystem->Load( "libSFramePlugIns" ) == -1 ) return -1;

   return 0;
}


text:
module Graphics.Pastel.GTK.Test ( testGTK ) where

import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.Events

import Graphics.Pastel
import Graphics.Pastel.GTK.Draw

testGTK :: (Int, Int) -> Drawing -> IO ()
testGTK (w,h) d = do
    initGUI

    window <- windowNew
    set window [windowTitle := "Pastel Gtk Runner"]

    pixbuf <- drawGTK (w,h) $ d
    image <- imageNewFromPixbuf pixbuf
    containerAdd window image

    widgetShowAll window

    onDestroy window mainQuit
    mainGUI


text:
var app = angular.module("app", []);

app.controller('RoomCtrl', function () {
  this.openDoor = function () {
    alert("creak");
  };

  this.buttonTitle = "I'm a button";

  this.foo = "I'm in the room controller!";
});

app.controller('OtherCtrl', function () {
  this.foo = "I'm in the other controller!";
});


text:
<?php
//
// Copyright (c) 2009-2019 Oliver Lehmann <lehmann@ans-netz.de>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
// $Id: moduleEvents.php,v 1.20 2015/02/13 00:03:37 olivleh1 Exp $
//
namespace client\module;

use client\handler\EventControllerHandler;
use client\util\Environment;

class moduleEvents extends module {

	public final function __construct() {
		parent::__construct();
	}

	public final function check_events($request_uri) {
		if (! Environment::getInstance()->getEventsShown()) {
			Environment::getInstance()->setEventsShown( true );
			$events = EventControllerHandler::getInstance()->showEventList();
			if ($events ['mms_missing'] === true && $events ['numberOfAddableSettlements'] > 0) {
				$this->template_assign( 'MONTH', $events ['month'] );
				$this->template_assign( 'YEAR', $events ['year'] );
				$this->template_assign( 'NUM_ADDABLE_SETTLEMENTS', $events ['numberOfAddableSettlements'] );
				$this->template_assign( 'REQUEST_URI', $request_uri );

				$this->parse_header_bootstraped( 0, 'display_event_monthlysettlement.tpl' );
				return $this->fetch_template( 'display_event_monthlysettlement.tpl' );
			}
			if ($events ['numberOfImportedMoneyflows'] > 0) {
				$this->template_assign( 'REQUEST_URI', $request_uri );

				$this->parse_header_bootstraped( 0, 'display_event_imported_moneyflows.tpl' );
				return $this->fetch_template( 'display_event_imported_moneyflows.tpl' );
			}
		}
		return null;
	}
}


text:
package straw.storm.util;

import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

import java.io.IOException;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.json.JSONArray;
import org.json.JSONObject;

public class PercolatorHelper {

	public static String extract_text(String data) {
		// parse input JSON
		JSONObject obj = null;
		String text = null;
		try {
			obj = new JSONObject(data);
			text = obj.getString("text");
		}
		catch (org.json.JSONException e) {
			// TODO: Bad json passed
			// System.out.println("JSON PARSER FAILED TO HANDLE: " + data);
			//e.printStackTrace();
		}

		return text;
	}

	public static QueryBuilder make_query(String data){
		// build a query out of the data JSON string
		QueryBuilder qb = null;
		JSONObject obj = null;
		try {
			obj = new JSONObject(data);
		}
		catch (org.json.JSONException e) {
			System.out.println("JSON PARSER FAILED TO HANDLE: " + data);
			e.printStackTrace();
		}

		String type = obj.getString("type");

		// terms query parser
		if(type.equalsIgnoreCase("terms-query")) {
			Integer minimum_match = obj.getInt("minimum-match");
			JSONArray arr = obj.getJSONArray("terms");

			if (arr!=null){
				String[] string_arry = new String[arr.length()];
				// use length of array if minimum match not provided
				if (minimum_match==null){
					minimum_match=arr.length();
				}
				for(int i=0; i<arr.length(); i++){
					string_arry[i] = arr.getString(i);
				}
				qb = termsQuery("text", string_arry).minimumMatch(minimum_match);
			}
		}
		return qb;
	}
}


text:
package com.acod.play.app.Activities;

import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.acod.play.app.Fragments.ResultsFragment;
import com.acod.play.app.Interfaces.DataTransmission;
import com.acod.play.app.Interfaces.UpdateUI;
import com.acod.play.app.R;
import com.acod.play.app.Searching.RecentSearchSuggestionProvider;
import com.acod.play.app.Searching.SearchAllSites;

/**
 * Created by andrew on 03/07/14.
 */
public class SearchActivity extends ActionBarActivity implements DataTransmission, UpdateUI {
    ProgressDialog pd;
    ResultsFragment resultsFragment;
    String query;
    SearchView sv;
    SearchAllSites search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.searchview);
        resultsFragment = (ResultsFragment) getFragmentManager().findFragmentById(R.id.resultsFrag);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(getString(R.string.resultsactivitytitle));
        handleIntent(getIntent());

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (!HomescreenActivity.checkNetworkState(this))
            Toast.makeText(this, "Check your internet connection", Toast.LENGTH_LONG).show();
        if (!(this.query == null) && !(sv == null))
            sv.setQuery(this.query, false);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        search.cancel(true);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.searchmenu, menu);
        sv = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.search));
        SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        sv.setSearchableInfo(manager.getSearchableInfo(getComponentName()));
        sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                startActivity(new Intent(getApplicationContext(), SearchActivity.class).putExtra(SearchManager.QUERY, s).setAction("android.intent.action.SEARCH"));

                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }
        });
        sv.setIconifiedByDefault(false);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void openPlayer(Bundle data) {
        Intent intent = new Intent(this, PlayerActivity.class);
        intent.putExtra("data", data);
        startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {

        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            this.query = query;
            SearchRecentSuggestions suggestionsProvider = new SearchRecentSuggestions(getApplicationContext(), RecentSearchSuggestionProvider.AUTHORITY, RecentSearchSuggestionProvider.MODE);
            suggestionsProvider.saveRecentQuery(query, null);
            search = new SearchAllSites(query, getApplicationContext(), this);
            search.execute();

        }
    }

    @Override
    public void openResultsFragment(Bundle results) {
        resultsFragment.setResults(results);
    }

    @Override
    public void openProgressDialog() {
        pd = new ProgressDialog(this);
        pd.setMessage("Loading Sources");
        pd.show();
    }

    @Override
    public void closeProgressDialog() {
        pd.dismiss();

    }
}


text:
class CalendarPresenter
  MIN_YEAR = 1000
  MAX_YEAR = 3000

  attr_reader :year

  def initialize(year)
    if year >= MIN_YEAR and year <= MAX_YEAR
      @year = year
    else
      @year = nil
    end
  end

  def each_month &block
    if valid?
      months = (1..12).collect { |month| MonthPresenter.new(year, month) }
      months.each &block
    end
  end

  def valid?
    not year.nil?
  end
end


text:
package eic.beike.projectx.android.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import eic.beike.projectx.R;
import eic.beike.projectx.android.LocationFinder;
import eic.beike.projectx.util.Constants;

/**
 * This is the first activity to start. It checks if you have chosen a nickname before
 * if not it starts nameSplashActivity else starts menu
 *
 * @author Adam Ingmansson
 */
public class MainActivity extends Activity {

    public static final int NEXT_ACTIVITY = 0;

    private LocationFinder locationFinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_splash);

        SharedPreferences settings = getSharedPreferences(Constants.SETTINGS_FILE, 0);

        String name = settings.getString(Constants.NAME_FIELD, "");

        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationFinder = new LocationFinder(lm);

        // First time running?
        if (name.equals("")) {

            // Start the name picker activity
            startActivityForResult(
                    new Intent(this, NameSplashActivity.class),
                    MainActivity.NEXT_ACTIVITY
            );
        } else {

            // Start the menu
            Intent intent = new Intent(this, MenuActivity.class);

            // Set so there is no history for back button
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Off we go
            startActivityForResult(intent, MainActivity.NEXT_ACTIVITY);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        locationFinder.stop();

        Log.d("LocationFinder", "Removing listener");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * Handles the result from any activity started by this.
     *
     * @param requestCode The code identifying which request
     * @param resultCode The result code of that request
     * @param data The intent
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == MainActivity.RESULT_CANCELED) {
            finish();
        }
    }

}


text:
using System;
using System.Collections.Generic;
using Iced.Intel;
using Xunit;

namespace Iced.UnitTests.Intel.FormatterTests {
	public sealed class MiscTests {
		[Fact]
		void Test_FormatterOperandOptions_properties() {
			FormatterOperandOptions options = default;

			options.MemorySizeOptions = MemorySizeOptions.Always;
			Assert.Equal(MemorySizeOptions.Always, options.MemorySizeOptions);

			options.MemorySizeOptions = MemorySizeOptions.Minimal;
			Assert.Equal(MemorySizeOptions.Minimal, options.MemorySizeOptions);

			options.MemorySizeOptions = MemorySizeOptions.Never;
			Assert.Equal(MemorySizeOptions.Never, options.MemorySizeOptions);

			options.MemorySizeOptions = MemorySizeOptions.Default;
			Assert.Equal(MemorySizeOptions.Default, options.MemorySizeOptions);

			options.BranchSize = true;
			Assert.True(options.BranchSize);
			options.BranchSize = false;
			Assert.False(options.BranchSize);

			options.RipRelativeAddresses = true;
			Assert.True(options.RipRelativeAddresses);
			options.RipRelativeAddresses = false;
			Assert.False(options.RipRelativeAddresses);
		}

		[Fact]
		void NumberFormattingOptions_ctor_throws_if_null_options() {
			Assert.Throws<ArgumentNullException>(() => new NumberFormattingOptions(null, false, false, false));
		}

		public static IEnumerable<object[]> AllFormatters {
			get {
				var result = new List<object[]>();
				foreach (var formatter in Utils.GetAllFormatters())
					result.Add(new object[] { formatter });
				return result.ToArray();
			}
		}

		[Theory]
		[MemberData(nameof(AllFormatters))]
		void Methods_throw_if_null_input(Formatter formatter) {
			Instruction instruction = default;
			instruction.Code = Code.Mov_rm64_r64;
			instruction.Op0Register = Register.RAX;
			instruction.Op1Register = Register.RCX;
			Assert.Throws<ArgumentNullException>(() => formatter.FormatMnemonic(instruction, null));
			Assert.Throws<ArgumentNullException>(() => formatter.FormatMnemonic(instruction, null, FormatMnemonicOptions.None));
			Assert.Throws<ArgumentNullException>(() => formatter.FormatOperand(instruction, null, 0));
			Assert.Throws<ArgumentNullException>(() => formatter.FormatOperandSeparator(instruction, null));
			Assert.Throws<ArgumentNullException>(() => formatter.FormatAllOperands(instruction, null));
			Assert.Throws<ArgumentNullException>(() => formatter.Format(instruction, null));
		}

		[Theory]
		[MemberData(nameof(AllFormatters))]
		void Methods_throw_if_invalid_operand_or_instructionOperand(Formatter formatter) {
			{
				Instruction instruction = default;
				instruction.Code = Code.Mov_rm64_r64;
				instruction.Op0Register = Register.RAX;
				instruction.Op1Register = Register.RCX;
				const int numOps = 2;
				const int numInstrOps = 2;
				Assert.Equal(numOps, formatter.GetOperandCount(instruction));
				Assert.Equal(numInstrOps, instruction.OpCount);
#if INSTR_INFO
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(instruction, -1, out _));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(instruction, numOps, out _));
#endif
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(instruction, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(instruction, numOps));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(instruction, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(instruction, numInstrOps));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(instruction, new StringOutput(), -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(instruction, new StringOutput(), numOps));
			}

			{
				Instruction invalid = default;
#if INSTR_INFO
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(invalid, -1, out _));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(invalid, 0, out _));
#endif
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(invalid, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(invalid, 0));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(invalid, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(invalid, 0));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(invalid, new StringOutput(), -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(invalid, new StringOutput(), 0));
			}

#if ENCODER
			{
				var db = Instruction.CreateDeclareByte(new byte[8]);
#if INSTR_INFO
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(db, -1, out _));
#endif
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(db, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(db, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(db, new StringOutput(), -1));
				Assert.Equal(8, db.DeclareDataCount);
				for (int i = 0; i < db.DeclareDataCount; i++) {
#if INSTR_INFO
					formatter.TryGetOpAccess(db, i, out _);
#endif
					formatter.GetInstructionOperand(db, i);
					formatter.FormatOperand(db, new StringOutput(), i);
				}
				for (int i = db.DeclareDataCount; i < 17; i++) {
#if INSTR_INFO
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(db, i, out _));
#endif
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(db, i));
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(db, new StringOutput(), i));
				}
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(db, 0));
			}
#endif

#if ENCODER
			{
				var dw = Instruction.CreateDeclareWord(new byte[8]);
#if INSTR_INFO
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dw, -1, out _));
#endif
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dw, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dw, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dw, new StringOutput(), -1));
				Assert.Equal(4, dw.DeclareDataCount);
				for (int i = 0; i < dw.DeclareDataCount; i++) {
#if INSTR_INFO
					formatter.TryGetOpAccess(dw, i, out _);
#endif
					formatter.GetInstructionOperand(dw, i);
					formatter.FormatOperand(dw, new StringOutput(), i);
				}
				for (int i = dw.DeclareDataCount; i < 17; i++) {
#if INSTR_INFO
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dw, i, out _));
#endif
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dw, i));
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dw, new StringOutput(), i));
				}
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dw, 0));
			}
#endif

#if ENCODER
			{
				var dd = Instruction.CreateDeclareDword(new byte[8]);
#if INSTR_INFO
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dd, -1, out _));
#endif
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dd, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dd, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dd, new StringOutput(), -1));
				Assert.Equal(2, dd.DeclareDataCount);
				for (int i = 0; i < dd.DeclareDataCount; i++) {
#if INSTR_INFO
					formatter.TryGetOpAccess(dd, i, out _);
#endif
					formatter.GetInstructionOperand(dd, i);
					formatter.FormatOperand(dd, new StringOutput(), i);
				}
				for (int i = dd.DeclareDataCount; i < 17; i++) {
#if INSTR_INFO
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dd, i, out _));
#endif
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dd, i));
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dd, new StringOutput(), i));
				}
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dd, 0));
			}
#endif

#if ENCODER
			{
				var dq = Instruction.CreateDeclareQword(new byte[8]);
#if INSTR_INFO
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dq, -1, out _));
#endif
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dq, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dq, -1));
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dq, new StringOutput(), -1));
				Assert.Equal(1, dq.DeclareDataCount);
				for (int i = 0; i < dq.DeclareDataCount; i++) {
#if INSTR_INFO
					formatter.TryGetOpAccess(dq, i, out _);
#endif
					formatter.GetInstructionOperand(dq, i);
					formatter.FormatOperand(dq, new StringOutput(), i);
				}
				for (int i = dq.DeclareDataCount; i < 17; i++) {
#if INSTR_INFO
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dq, i, out _));
#endif
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dq, i));
					Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dq, new StringOutput(), i));
				}
				Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dq, 0));
			}
#endif
		}

		[Fact]
		void StringOutput_throws_if_invalid_input() {
			Assert.Throws<ArgumentNullException>(() => new StringOutput(null));
		}

		[Fact]
		void StringOutput_uses_input_sb() {
			var sb = new System.Text.StringBuilder();
			sb.Append("Text");
			var output = new StringOutput(sb);
			output.Write("hello", FormatterTextKind.Text);
			Assert.Equal("Texthello", sb.ToString());
			Assert.Equal("Texthello", output.ToString());
		}

		[Fact]
		void Verify_default_formatter_options() {
			var options = new FormatterOptions();
			Assert.False(options.UppercasePrefixes);
			Assert.False(options.UppercaseMnemonics);
			Assert.False(options.UppercaseRegisters);
			Assert.False(options.UppercaseKeywords);
			Assert.False(options.UppercaseDecorators);
			Assert.False(options.UppercaseAll);
			Assert.Equal(0, options.FirstOperandCharIndex);
			Assert.Equal(0, options.TabSize);
			Assert.False(options.SpaceAfterOperandSeparator);
			Assert.False(options.SpaceAfterMemoryBracket);
			Assert.False(options.SpaceBetweenMemoryAddOperators);
			Assert.False(options.SpaceBetweenMemoryMulOperators);
			Assert.False(options.ScaleBeforeIndex);
			Assert.False(options.AlwaysShowScale);
			Assert.False(options.AlwaysShowSegmentRegister);
			Assert.False(options.ShowZeroDisplacements);
			Assert.Null(options.HexPrefix);
			Assert.Null(options.HexSuffix);
			Assert.Equal(4, options.HexDigitGroupSize);
			Assert.Null(options.DecimalPrefix);
			Assert.Null(options.DecimalSuffix);
			Assert.Equal(3, options.DecimalDigitGroupSize);
			Assert.Null(options.OctalPrefix);
			Assert.Null(options.OctalSuffix);
			Assert.Equal(4, options.OctalDigitGroupSize);
			Assert.Null(options.BinaryPrefix);
			Assert.Null(options.BinarySuffix);
			Assert.Equal(4, options.BinaryDigitGroupSize);
			Assert.Null(options.DigitSeparator);
			Assert.False(options.LeadingZeros);
			Assert.False(options.LeadingZeroes);
			Assert.True(options.UppercaseHex);
			Assert.True(options.SmallHexNumbersInDecimal);
			Assert.True(options.AddLeadingZeroToHexNumbers);
			Assert.Equal(NumberBase.Hexadecimal, options.NumberBase);
			Assert.True(options.BranchLeadingZeros);
			Assert.True(options.BranchLeadingZeroes);
			Assert.False(options.SignedImmediateOperands);
			Assert.True(options.SignedMemoryDisplacements);
			Assert.False(options.DisplacementLeadingZeros);
			Assert.False(options.DisplacementLeadingZeroes);
			Assert.Equal(MemorySizeOptions.Default, options.MemorySizeOptions);
			Assert.False(options.RipRelativeAddresses);
			Assert.True(options.ShowBranchSize);
			Assert.True(options.UsePseudoOps);
			Assert.False(options.ShowSymbolAddress);
			Assert.False(options.PreferST0);
			Assert.Equal(CC_b.b, options.CC_b);
			Assert.Equal(CC_ae.ae, options.CC_ae);
			Assert.Equal(CC_e.e, options.CC_e);
			Assert.Equal(CC_ne.ne, options.CC_ne);
			Assert.Equal(CC_be.be, options.CC_be);
			Assert.Equal(CC_a.a, options.CC_a);
			Assert.Equal(CC_p.p, options.CC_p);
			Assert.Equal(CC_np.np, options.CC_np);
			Assert.Equal(CC_l.l, options.CC_l);
			Assert.Equal(CC_ge.ge, options.CC_ge);
			Assert.Equal(CC_le.le, options.CC_le);
			Assert.Equal(CC_g.g, options.CC_g);
			Assert.False(options.ShowUselessPrefixes);
			Assert.False(options.GasNakedRegisters);
			Assert.False(options.GasShowMnemonicSizeSuffix);
			Assert.False(options.GasSpaceAfterMemoryOperandComma);
			Assert.True(options.MasmAddDsPrefix32);
			Assert.True(options.MasmSymbolDisplInBrackets);
			Assert.True(options.MasmDisplInBrackets);
			Assert.False(options.NasmShowSignExtendedImmediateSize);
		}

		[Fact]
		void Throws_if_invalid_CC_value() {
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_b = (CC_b)IcedConstants.CC_b_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_ae = (CC_ae)IcedConstants.CC_ae_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_e = (CC_e)IcedConstants.CC_e_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_ne = (CC_ne)IcedConstants.CC_ne_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_be = (CC_be)IcedConstants.CC_be_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_a = (CC_a)IcedConstants.CC_a_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_p = (CC_p)IcedConstants.CC_p_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_np = (CC_np)IcedConstants.CC_np_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_l = (CC_l)IcedConstants.CC_l_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_ge = (CC_ge)IcedConstants.CC_ge_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_le = (CC_le)IcedConstants.CC_le_EnumCount);
			Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_g = (CC_g)IcedConstants.CC_g_EnumCount);
		}
	}
}
#endif


text:
require 'rails_helper'

RSpec.describe Assignment, type: :model do
  it 'has a valid factory' do
    expect(FactoryBot.build(:valid_assignment)).to be_valid
  end

  # test validations

  it 'is invalid without a deadline' do
    assignment = FactoryBot.build(:valid_assignment, deadline: nil)
    expect(assignment).to be_invalid
  end

  it 'is invalid without a title' do
    assignment = FactoryBot.build(:valid_assignment, title: nil)
    expect(assignment).to be_invalid
  end

  it 'is invalid with duplicate title in same lecture' do
    assignment = FactoryBot.create(:valid_assignment, title: 'usual BS')
    lecture = assignment.lecture
    new_assignment = FactoryBot.build(:valid_assignment, lecture: lecture,
                                                         title: 'usual BS')
    expect(new_assignment).to be_invalid
  end

  it 'is invalid with inadmissible accepted filetype' do
    assignment = FactoryBot.build(:valid_assignment, accepted_file_type: '.jpg')
    expect(assignment).to be_invalid
  end

  # test traits
  describe 'with lecture' do
    it 'has a lecture' do
      assignment = FactoryBot.build(:assignment, :with_lecture)
      expect(assignment.lecture).to be_kind_of(Lecture)
    end
  end

  # test method - NEEDS TO BE DONE
end


text:
const name = 'date-picker';

describe("Metro 4 :: Date picker", () => {
    it('Component Initialization', ()=>{
        cy.visit("cypress/"+name+".html");
    })
})


text:
/* global $ */
var generatorsTable = {};
var generatorsContent = {};
var contentVariables = {};
var fetchedURIs = [];
var exlusivePools = {};

//Load a table type generator
function loadGenerator(filePath,loadingMessageCallback, rootNameCallBack) {
	$.getJSON( filePath, function(Generator) {
		if(Generator.Type)
		{
			if(Generator.Type == "Table")
			{
				if(Generator.Name in generatorsTable == false)
				{
					generatorsTable[Generator.Name] = Generator.Data;
					console.log(Generator.Name + " loaded");
				}
			}else
			{
				if(Generator.Name in generatorsContent == false)
				{
					generatorsContent[Generator.Name] = Generator;
					console.log(Generator.Name + " loaded");
				}
			}
		}else
		{
			console.error("Missing type in " + filePath + " file, can't load.");
		}

		//Load listed dependencies, if any
		if("Dependencies" in Generator)
		{
			if( Generator.Dependencies != "")
            {
                var dependencies = Generator.Dependencies.split(";");
                $.each(dependencies, function(_,dependency)
                {
                    if(dependency && $.inArray(dependency,fetchedURIs) == -1)
                    {
                        loadGenerator(dependency,loadingMessageCallback);
                        fetchedURIs.push(dependency);
                    }

                });
            }
		}

		if(rootNameCallBack)
		{
			rootNameCallBack(Generator.Name);
		}

        if(loadingMessageCallback)
		{
			loadingMessageCallback(Generator.Name);
		}
	}).fail(function( jqxhr, textStatus, error ) {
    	var err = textStatus + ", " + error;
    	console.log( "Request Failed: " + err );
	});
}

//Get the title and description of a Content Generator
function getContentPageInformation(contentName)
{
	var Information = {};

	if(contentName in generatorsContent)
	{
		var contentGenerator = generatorsContent[contentName];

		if("Title" in contentGenerator)
		{
			Information["Title"] = contentGenerator["Title"];
		}

		if("Description" in contentGenerator)
		{
			Information["Description"] = contentGenerator["Description"];
		}

		if("ButtonText" in contentGenerator)
		{
			Information["ButtonText"] = contentGenerator["ButtonText"];
		}else
		{
			Information["ButtonText"] = "Again";
		}

	}else{
		console.error("Content Generator " + contentName + " is not loaded.");
	}

	return Information;
}

//Generate the text entries from a Content Generator
function generateFromContent(contentName, clearData)
{
	if(contentName in generatorsContent)
	{
		var content = "";
		var poolName = "None";
		var contentGenerator = generatorsContent[contentName];

        if(clearData)
        {
            contentVariables = {};
            exlusivePools = {}
        }

        //Process Variables, for use in markup.
        if("Variables" in contentGenerator)
        {
            $.each(contentGenerator.Variables, function(name,value){
                if(name in contentVariables == false)
                {
                    contentVariables[name] = processNestedEntries(value,"None");
                }
            });
        }

		$.each(contentGenerator.Data, function(key,section){
			var sectionContent = "";

            //Check if this is going into an exlusivity pool
            if("Exclusive" in section)
            {
                poolName = section.Exclusive;
            }

			//Select one of the options in a -Choice sections, by weight.
			if("TextTable" in section)
			{
				var totalWeight = totalWeightTableSection(section.TextTable);
				section.Text = getRandomTableSectionEntryByWeight(section.TextTable, totalWeight);
			}else if("TextIndex" in section)
			{
				var doubleIndex= false;
                if(section.ParagraphType == "DoubleIndex")
                    doubleIndex = true;

                section.Text = generateIndex(section.TextIndex,doubleIndex);

			}

			//set properties not specified in json to default
			if("Chance" in section == false)
				section.Chance = 100;

			if("MinAmount" in section == false)
				section.MinAmount = 1;

			if("MaxAmount" in section == false)
				section.MaxAmount = section.MinAmount;

			if("ParagraphType" in section == false)
				section.ParagraphType = "Paragraph";

			//Dispatch to specific paragraph type methods
			if(section.ParagraphType == "Paragraph" || section.ParagraphType == "Paragraph-Start"
			|| section.ParagraphType == "Paragraph-End")
			{
				sectionContent += generateContentParagraph(section,poolName);
			}else if(section.ParagraphType == "DoubleList" || section.ParagraphType == "DoubleList-Start"){
                sectionContent += generateContentList(section,true,poolName);
            }else if (section.ParagraphType == "List" || section.ParagraphType == "List-Continues" || section.ParagraphType == "List-Start"
			|| section.ParagraphType == "List-End") {
				sectionContent += generateContentList(section,false,poolName);
			}else if(section.ParagraphType == "CommaSeperatedList"){
                sectionContent += generateContentCommaSeperated(section,poolName);
            }else{
				//Fallback to no decorations on unspecified type.
				sectionContent += generateContentUndecorated(section,poolName);
			}

            if("SentenceCase" in section == true)
            {

                if(section.SentenceCase == "Title-Case")
                {
                    sectionContent = sectionContent.toLowerCase().toTitleCase();
                }else if(section.SentenceCase == "Sentence")
				{
					sectionContent = sectionContent.toSentenceCase();
				}
            }

            content += sectionContent;
		});

		return content;
	}else{
		console.error("Content Generator " + contentName + " is not loaded.");
	}
}

function generateOptionalInlineContent(filePath,idNumber)
{
    var rootGeneratorName;
    var button = document.getElementById("OptionalInclusive" + idNumber);
    var div = document.createElement("div");

    div.className = "OptionalInlineContent";

    loadGenerator(filePath,function(generatorName){},function(generatorName)
    {
        rootGeneratorName = generatorName;
    });

    $( document ).ajaxStop(function() {
         $(this).unbind("ajaxStop");
        div.innerHTML = generateFromContent(rootGeneratorName, true);
        button.parentNode.insertBefore(div, button.nextSibling);

        button.style.display = 'none';
    });
}

//generate a Content Generator section with Paragraph decoration
function generateContentParagraph(section, poolName)
{
	var content = "";
	var chanceR = Math.floor((Math.random() * 100) +1);

	if( chanceR <= section.Chance)
	{
		if(section.ParagraphType != "Paragraph-End")
			content+="
";

		var amountR = Math.floor((Math.random() * section.MaxAmount) + section.MinAmount);
		for(var i = 0;  i<amountR; i++)
		{
			content += processNestedEntries(section.Text,poolName);
		}

		if(section.ParagraphType != "Paragraph-Start")
			content+="
";
	}

	return content;
}

//generate a Content Generator section with List decorations
function generateContentList(section, doubleColumn, poolName)
{
	var content = "";
	var chanceR = Math.floor((Math.random() * 100) +1);

	if( chanceR <= section.Chance)
	{
		if(section.ParagraphType != "List-End" && section.ParagraphType != "List-Continues")
        {
            if(doubleColumn)
            {
                content+="
";
            }
            else
            {
                content+="
";
            }
        }

		var amountR = getRandomNumberInclusive(section.MinAmount,section.MaxAmount);

        for(var i = 0;  i<amountR; i++)
		{
			content += "
" + processNestedEntries(section.Text,poolName) + "
";
		}

        if(section.ParagraphType != "List-Start"  && section.ParagraphType != "DoubleList-Start" && section.ParagraphType != "List-Continues")
			content+="
";
	}

	return content;
}

function generateContentCommaSeperated(section, poolName)
{
    var content = [];
	var chanceR = Math.floor((Math.random() * 100) +1);

	if( chanceR <= section.Chance)
	{
		var amountR = getRandomNumberInclusive(section.MinAmount,section.MaxAmount);
		for(var i = 0;  i<amountR; i++)
		{
			content.push(processNestedEntries(section.Text,poolName));
		}
	}

	return content.join(", ");
}

//generate a Content Generator section without any decorations.
function generateContentUndecorated(section, poolName)
{
	var content = "";
	var chanceR = Math.floor((Math.random() * 100) +1);

	if( chanceR <= section.Chance)
	{
		var amountR = getRandomNumberInclusive(section.MinAmount,section.MaxAmount);
		for(var i = 0;  i<amountR; i++)
		{
			content += processNestedEntries(section.Text,poolName);
		}
	}

	return content;
}

//Generate the text entries from a Table
function generateFromTable(tableName, poolName)
{
		if(tableName in generatorsTable)
		{
			var content="";

			var table = generatorsTable[tableName];
			$.each(table, function(_, section)
			{
				if((typeof section ) === 'string')
				{
					content+= processNestedEntries(section,poolName);
				}else
				{
					//Grab a random entry from the section
					var totalWeight = totalWeightTableSection(section);
					var randomEntry = getRandomTableSectionEntryByWeight(section, totalWeight);

					//Find any nested references to generators and process those.
					randomEntry = processNestedEntries(randomEntry,poolName);

					//Add to content
					content += randomEntry;
				}
			});

			return content;
		}else{
			console.error("Table Generator " + tableName + " is not loaded.");
		}

}

function generateIndex(indexTable,doubleColumn)
{
	var text = "";
	if(doubleColumn)
    {
        text +="
";
    }
    else
    {
        text += "
";
    }

	$.each(indexTable, function(_, value){
		$.each(value, function(k,v){
			text += "
 "+ k +"
";
		});

	});

	text += "
";
	return text;
}

//Find references to generators in a string and replace them with the generators content
function processNestedEntries(entry, poolName)
{
	var regex = /\$(\w)-([\w\.\/]+)\$/g;
	var match;
	//Modifying the original string during regex.exec resets the progress.
	//So copy it and regex over the copy while modifying the original
	var regexString = entry;

	//Recurse for nested entries.
	while ((match = regex.exec(regexString)) !== null) {
		var insertValue = processEntryMarkup(match);

        //If a poolname is set, ensure the value is exclusive before allowing it in.
        if(poolName && poolName != "None")
        {
            //console.log("Pool: " + poolName)
            if( poolName in exlusivePools )
            {
                var i = 100 ; // Max Retry attempts.
                while($.inArray(insertValue, exlusivePools[poolName]) != -1)
                {
                    insertValue = processEntryMarkup(match);
                    i--;

                    //Abort if no new values found after to many attempts, throw an error on the log
                    if( i < 0)
                    {
                        console.log("Duplicate: " + insertValue + " vs " + exlusivePools[poolName])
                        return entry;
                    }
                }

                exlusivePools[poolName].push(insertValue);
                //console.log(exlusivePools[poolName]);
            }
            else
            {
                exlusivePools[poolName] = [];
                exlusivePools[poolName].push(insertValue);
            }
        }

        //finally replace value
        entry = entry.replace(match[0],insertValue);
	}
	return entry;
}

//Given a regex match for markup, returns a valid replacement value.
function processEntryMarkup(match)
{
    var text = "Markup Replacement Error for: " + match[0];

    if(match[1] == "T") //Table Entry
    {
        text = generateFromTable(match[2]);
    }else if(match[1] == "C") //Content Entry
    {
        text = generateFromContent(match[2]);
    }
    else if(match[1] == "R") //Random Number
    {
        var numbers = match[2].split("_");
        var r = getRandomNumberInclusive(numbers[0],numbers[1]);
        text = "" + r;
    }else if(match[1] == "V") //Variable
    {
        text = contentVariables[match[2]];
    }else if(match[1] == "O") //Optional Inline Content
    {
        var e = match[2].split("_");
        rId = getRandomNumberInclusive(1,10000);
        text = "<button id='OptionalInclusive{1}' onclick=generateOptionalInlineContent('{2}',{1})>{0}</button>".format(e[1],rId,e[0])
    }

    return text;
}

//Add up all the weight in a Sections
function totalWeightTableSection(section)
{
	var weight = 0;

	$.each(section, function(_, entry)
	{
		$.each(entry, function(_,w){
			weight+=w;
		});
	});

	return weight;
}

//Return an entry from a Table Section randomly but modified by weight.
function getRandomTableSectionEntryByWeight(section, totalweight)
{

	var r = Math.floor((Math.random() * totalweight));
	var returnText = "";
	var finished = false; //Can't neatly break out of a jquery .each so use a manual termination.

	$.each(section, function(_, entry)
	{
		$.each(entry, function(text,weight){

			if( r < weight && 1 && !finished)
			{
				returnText = text;
				finished = true;
			}else if(!finished)
			{
				r-= weight;
			}
		});
	});

	return returnText;
}

function doesStringProbablyIncludeHTML(str)
{
	if (str.match("[<>=]")) {
		return true;
	}
	return false;
}

function getRandomNumberInclusive(min, max) {
    min = Number(min);
    max = Number(max);

    var r   =  Math.floor(Math.random() * (max - min + 1)) + min;
    return r;
}

String.prototype.format = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

//Source: http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript
String.prototype.toTitleCase = function() {
	// Certain minor words should be left lowercase unless
  	// they are the first or last words in the string
  	lowers = ['a', 'an', 'the', 'and', 'but', 'or', 'for', 'nor', 'as', 'at',
  	'by', 'for', 'from', 'in', 'into', 'near', 'of', 'on', 'onto', 'to', 'with'];

	var correctedStr = this.trim();
	correctedStr = correctedStr.replace(/</g, " <" );
	correctedStr = correctedStr.replace(/>/g, "> " );

	var words=correctedStr.split(" ");
	var str = "";

	for(i=0;i<words.length;i++)
	{
		if(words[i] &&  !doesStringProbablyIncludeHTML(words[i]) )
		{
			if($.inArray(words[i].toLowerCase(), lowers ) == -1)
			{
				console.log(words[i])
				words[i] = words[i][0].toUpperCase() + words[i].substring(1)
			}

		}

		str = str + words[i] + " "
	}

	return str;
}

String.prototype.toSentenceCase = function() {
	var correctedStr = this.trim();
	correctedStr = correctedStr.replace(/</g, " <" );
	correctedStr = correctedStr.replace(/>/g, "> " );

	var sentences=correctedStr.split(".");
	var str = "";

	for(i=0;i<sentences.length;i++)
	{
		var setFirstwordCapital = false;
		var words = sentences[i].split(" ");
		var lastWord;
		for(j=0;j<words.length;j++)
		{
			if(!setFirstwordCapital && !doesStringProbablyIncludeHTML(words[j]))
			{
				if(words[j][0])
				{
					words[j] = words[j][0].toUpperCase() + words[j].substr(1);
					setFirstwordCapital = true
				}
			}

			if(words[j] && !doesStringProbablyIncludeHTML(words[j]))
			{
				lastWord = words[j]
			}

			str = str + words[j] + " "
		}

		if(lastWord)
		{
			lastWordIndex = str.lastIndexOf(lastWord);
			str = str.substring(0,lastWordIndex) + lastWord + "." + str.substring(lastWordIndex + lastWord.length);
			lastWord = "";
		}
	}
	return str
}


text:
FactoryBot.define do
  factory :navigation_item, class: AmaLayout::NavigationItem do
    text { 'Gotham Overview' }
    icon { 'fa-tachometer' }
    link { 'http://waffleemporium.ca/gotica' }
    alt { 'Back to my dashboard' }
  end
end


text:
namespace Components {

	export class TestComponent extends polymer.Base {

		public field: string = 'foo';
		public is: string;

		constructor() {
			super();
			this.is = 'test-test';
		}

        public ready(): void {
			console.log('ready');
			this.async(() => {
				console.log('delayed');
			}, 500);
        }
	}

	polymer.createElement(TestComponent);
}


text:
webpackJsonp([0xdd4892ef81a],{564:function(t,e){t.exports={pathContext:{}}}});
//# sourceMappingURL=path---blog-fixing-jquery-click-a0e39f21c11f6a62c5ab.js.map


text:
Changelog
=========

## v3.1.4

- [#414](https://github.com/offirgolan/ember-cp-validations/pull/414) Dependency upgrades

## v3.1.3

- [#405](https://github.com/offirgolan/ember-cp-validations/pull/405) Add support for ember-source NPM package [@rwjblue](https://github.com/rwjblue))

## v3.1.2

- [#389](https://github.com/offirgolan/ember-cp-validations/pull/389) [BUGFIX] Resolve \_type conflicts with EmberValidator classes

## v3.1.1

- [#383](https://github.com/offirgolan/ember-cp-validations/pull/383) [BUGFIX] Use ember-require-module

## v3.1.0

- [#363](https://github.com/offirgolan/ember-cp-validations/pull/363) Use ember-validators
- [#364](https://github.com/offirgolan/ember-cp-validations/pull/364) [FEATURE] Volatile option

## v3.0.1

- [#344](https://github.com/offirgolan/ember-cp-validations/pull/344) [BUGFIX] DEPRECATION: Ember.Handlebars.SafeString [@kepek](https://github.com/kepek)

## v3.0.0

- [#226](https://github.com/offirgolan/ember-cp-validations/pull/226) Warning Validators
- [#232](https://github.com/offirgolan/ember-cp-validations/pull/232) Computed Options (special thanks to [@xcambar](https://github.com/xcambar))
- [#239](https://github.com/offirgolan/ember-cp-validations/pull/239) Use Require for Checking Ember Data
- [#240](https://github.com/offirgolan/ember-cp-validations/pull/240) DS Error Validator + Nested Keys
- [#241](https://github.com/offirgolan/ember-cp-validations/pull/241) Fix blueprint warning
- [#245](https://github.com/offirgolan/ember-cp-validations/pull/245) Utilize \_\_root\_\_ in validator blueprint
- [#249](https://github.com/offirgolan/ember-cp-validations/pull/249) Fixed email regex of format validator [@simonihmig](https://github.com/simonihmig)
- [#252](https://github.com/offirgolan/ember-cp-validations/pull/252) Fix require module
- [#262](https://github.com/offirgolan/ember-cp-validations/pull/262) Use `model` instead of `_model` when declaring custom dependents
- [#266](https://github.com/offirgolan/ember-cp-validations/pull/266) Check for null in extractOptionsDependentKeys [@xcambar](https://github.com/xcambar)
- [#272](https://github.com/offirgolan/ember-cp-validations/pull/272) Fix ember-cli deprecation warning
- [#294](https://github.com/offirgolan/ember-cp-validations/pull/294) [BUGFIX] Validate promise resolves even when validations are still validating
- [#305](https://github.com/offirgolan/ember-cp-validations/pull/305) [BUGFIX] Provide `baseDir` to allow for proper caching
- [#311](https://github.com/offirgolan/ember-cp-validations/pull/311) [FEATURE] Place mixin under a named scope for Ember Inspector
- [#312](https://github.com/offirgolan/ember-cp-validations/pull/312) [BUGFIX] Deleted DS.Model records should be suppressed
- [#321](https://github.com/offirgolan/ember-cp-validations/pull/321) [FEATURE] Lazily run validations
- [#330](https://github.com/offirgolan/ember-cp-validations/pull/330) [FEATURE] Add option `allowNonTld` for email format validator [@indr](https://github.com/indr)
- [#333](https://github.com/offirgolan/ember-cp-validations/pull/333) [BUGFIX] Define CPs and nested CPs in attrs object once per class
- [#338](https://github.com/offirgolan/ember-cp-validations/pull/338) [FEATURE] Add validator type to error messages [@kepek](https://github.com/kepek)
- [#339](https://github.com/offirgolan/ember-cp-validations/pull/339) [BUGFIX] Allow for requirejs.has to not be available [@jasonmit](https://github.com/jasonmit)

## v3.0.0-beta.7

- [#330](https://github.com/offirgolan/ember-cp-validations/pull/330) [FEATURE] Add option `allowNonTld` for email format validator [@indr](https://github.com/indr)
- [#333](https://github.com/offirgolan/ember-cp-validations/pull/333) [BUGFIX] Define CPs and nested CPs in attrs object once per class

## v3.0.0-beta.6

- [#305](https://github.com/offirgolan/ember-cp-validations/pull/305) [BUGFIX] Provide `baseDir` to allow for proper caching
- [#311](https://github.com/offirgolan/ember-cp-validations/pull/311) [FEATURE] Place mixin under a named scope for Ember Inspector
- [#312](https://github.com/offirgolan/ember-cp-validations/pull/312) [BUGFIX] Deleted DS.Model records should be suppressed
- [#321](https://github.com/offirgolan/ember-cp-validations/pull/321) [FEATURE] Lazily run validations

## v3.0.0-beta.5

- [#294](https://github.com/offirgolan/ember-cp-validations/pull/294) [BUGFIX] Validate promise resolves even when validations are still validating

## v3.0.0-beta.4

- [#266](https://github.com/offirgolan/ember-cp-validations/pull/266) Check for null in extractOptionsDependentKeys [@xcambar](https://github.com/xcambar)
- [#272](https://github.com/offirgolan/ember-cp-validations/pull/272) Fix ember-cli deprecation warning

## v3.0.0-beta.3

- [#262](https://github.com/offirgolan/ember-cp-validations/pull/262) Use `model` instead of `_model` when declaring custom dependents

## v3.0.0-beta.2

- [#252](https://github.com/offirgolan/ember-cp-validations/pull/252) Fix require module

## v3.0.0-beta.1

- [#241](https://github.com/offirgolan/ember-cp-validations/pull/241) Fix blueprint warning
- [#245](https://github.com/offirgolan/ember-cp-validations/pull/245) Utilize \_\_root\_\_ in validator blueprint
- [#249](https://github.com/offirgolan/ember-cp-validations/pull/249) Fixed email regex of format validator [@simonihmig](https://github.com/simonihmig)

## v3.0.0-beta.0

- [#226](https://github.com/offirgolan/ember-cp-validations/pull/226) Warning Validators
- [#232](https://github.com/offirgolan/ember-cp-validations/pull/232) Computed Options (special thanks to [@xcambar](https://github.com/xcambar))
- [#239](https://github.com/offirgolan/ember-cp-validations/pull/239) Use Require for Checking Ember Data
- [#240](https://github.com/offirgolan/ember-cp-validations/pull/240) DS Error Validator + Nested Keys

## v2.9.3
- [#211](https://github.com/offirgolan/ember-cp-validations/pull/211) Fix regression from last patch by exposing `allowNone` which defaults to __true__ in length validator

## v2.9.2
- [#208](https://github.com/offirgolan/ember-cp-validations/pull/208) Null or undefined value in length should return invalid not blank

## v2.9.1
- [#203](https://github.com/offirgolan/ember-cp-validations/pull/203) Ember.String.htmlSafe throws exception
- [#207](https://github.com/offirgolan/ember-cp-validations/pull/207) Minor bug fixes
  - Null or undefined value in `length` validator should be invalid
  - Added `parentAttribute` to error object to better understand where an error is coming from
  - Added `.[]` to has-many dependent keys
  - Extend all dependents from Base

## v2.9.0
- [#177](https://github.com/offirgolan/ember-cp-validations/pull/177) Expose dependent keys API to validators

#### Upgrade Notes

Since the CPs now require container/owner access to get all the dependent keys, you will need to add all validators that your unit tests depend on to the `needs` array in your test module declaration.

```js
moduleForModel('user', {
  needs: ['validator:presence', 'validator:length']
});
```

## v2.8.0
- [#161](https://github.com/offirgolan/ember-cp-validations/pull/161) Alias validator
- [#168](https://github.com/offirgolan/ember-cp-validations/pull/168) Add `onOrBefore`, `onOrAfter`, and `precision` options to date validator [@aaronbhansen](https://github.com/aaronbhansen)
- [#170](https://github.com/offirgolan/ember-cp-validations/pull/170) Only call super on validations class if it exists via shouldCallSuper
- [#171](https://github.com/offirgolan/ember-cp-validations/pull/171) Value option
- [#171](https://github.com/offirgolan/ember-cp-validations/pull/171) All _Options as Functions_ methods are now provided with `model` and `attribute`
- [#173](https://github.com/offirgolan/ember-cp-validations/pull/173) Add `ignoreBlank` option to presence validator [@krasnoukhov](https://github.com/krasnoukhov)

## v2.7.2
- [#163](https://github.com/offirgolan/ember-cp-validations/pull/163) Fix leaky state with nested objects
- [#167](https://github.com/offirgolan/ember-cp-validations/pull/167) Add null safe checks for relational validators after promise resolves

## v2.7.1
- [#159](https://github.com/offirgolan/ember-cp-validations/pull/159) Fix deprecation warning Ember.merge > Ember.assign for Ember >= 2.5.0 [@urbany](https://github.com/urbany)

## v2.7.0
- [#146](https://github.com/offirgolan/ember-cp-validations/pull/146) Global options
- [#152](https://github.com/offirgolan/ember-cp-validations/pull/152) Export validators from addon namespace [@luxferresum](https://github.com/luxferresum)

## v2.6.1
- [#140](https://github.com/offirgolan/ember-cp-validations/pull/140) Fixed moment date parsing deprecations [@danielspaniel](https://github.com/danielspaniel)

## v2.6.0
- [#132](https://github.com/offirgolan/ember-cp-validations/pull/132) Add support for nested keys in validation rules.
- [#132](https://github.com/offirgolan/ember-cp-validations/pull/132) Create validations object once per class instead of every instance

## v2.5.0
- [#122](https://github.com/offirgolan/ember-cp-validations/pull/122) Blueprints/validator-test: Fix typo in `_filesPath()` method [@Turbo87](https://github.com/Turbo87)
- [#127](https://github.com/offirgolan/ember-cp-validations/pull/127) DS Error validator. See docs [here](http://offirgolan.github.io/ember-cp-validations/docs/classes/DS%20Error.html)

## v2.4.1
- [#119](https://github.com/offirgolan/ember-cp-validations/issues/119) Fix for `Dependent keys containing @each only work one level deep` warnings in Ember Canary - 2.5
- [#124](https://github.com/offirgolan/ember-cp-validations/issues/124) Validate `on` runs validation on all attributes [@kat3kasper](https://github.com/kat3kasper)

## v2.4.0
- [#112](https://github.com/offirgolan/ember-cp-validations/pull/112) Support validations via inheritance
- [#116](https://github.com/offirgolan/ember-cp-validations/pull/116) Support relational validators (`has-many` and `belongs-to`) in plain Ember Objects
- [#117](https://github.com/offirgolan/ember-cp-validations/pull/117) Move caches out of the prototype and into the instance

## v2.3.0
- [#106](https://github.com/offirgolan/ember-cp-validations/pull/106) Ability to enable/disable validations. See documentation [here](http://offirgolan.github.io/ember-cp-validations/docs/modules/Validators.html)

## v2.2.1
- [#103](https://github.com/offirgolan/ember-cp-validations/pull/103) Fixed debounced validation issue

## v2.2.0
- [#92](https://github.com/offirgolan/ember-cp-validations/pull/92) Debounced Validation
- [#96](https://github.com/offirgolan/ember-cp-validations/pull/96) Expose `options` property for attribute validations which contains a hash of built options grouped by validator type

## v2.1.2
- [#78](https://github.com/offirgolan/ember-cp-validations/pull/78) Migrate to owners over container for Ember >= 2.3.0-beta.1 support

## v2.1.1
- [#64](https://github.com/offirgolan/ember-cp-validations/pull/64) Allow blank in number validator
- [#65](https://github.com/offirgolan/ember-cp-validations/pull/65) Handle ember-data promise proxy based instances in presence

## v2.1.0
- [#59](https://github.com/offirgolan/ember-cp-validations/pull/59) Add enumerable list of all error objects
- [#62](https://github.com/offirgolan/ember-cp-validations/pull/62) Number validator

## v2.0.1
- [#53](https://github.com/offirgolan/ember-cp-validations/issues/53) Support v-get inside element note attribute strings

## v2.0.0
- Renamed `attributeDescription` to `description`
- I18n support (currently Ember-Intl & Ember-I18n)
- Added hooks in both Message base and validator base
- Validation options can also be function that are called before validate
- [#27](https://github.com/offirgolan/ember-cp-validations/issues/38) Declare custom dependent keys in validators (both custom and predefined)
- [#30](https://github.com/offirgolan/ember-cp-validations/issues/30) MomentJS is now only required if you want to use the date validator and is no longer a forced dependency
- [#33](https://github.com/offirgolan/ember-cp-validations/issues/33) Removed Ember.String.fmt dependency
- [#38](https://github.com/offirgolan/ember-cp-validations/issues/38) Default options in validation declarations

#### Upgrade Notes
Please checkout the [upgrading documentation](UPGRADING.md) for more details.

## v1.1.0
- `v-get` helper

#### Upgrade Notes
When upgrading, you will need to run `ember install ember-cp-validations` again or run the generator `ember g ember-cp-validations` after upping the version in `package.json`.

## v1.0.2
- Fixed an issue where if a result was undefined or null, it would update the validation result to false but would continue to go down the chain on get

## v1.0.1
- **BREAKING CHANGE** - confirmation rework - [issue](https://github.com/offirgolan/ember-cp-validations/issues/4)
- isInvalid helper - [issue](https://github.com/offirgolan/ember-cp-validations/issues/2)
- fixed lodash error - [issue](https://github.com/offirgolan/ember-cp-validations/issues/3)

## v1.0.0
- Initial Release


text:
<!-- saved from url=(0013)about:internet -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Intentalodenuevo</title>
</head>
<body bgcolor="#ffffff">
<script language="JavaScript">
<!--
var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
// Gestionar todos los mensajes de FSCommand de una película Flash
function Intentalodenuevo_DoFSCommand(command, args) {
	var IntentalodenuevoObj = isInternetExplorer ? document.all.Intentalodenuevo : document.Intentalodenuevo;
	//
	// Introduzca su código aquí.
	//
}
// Ancla para Internet Explorer
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) {
	document.write('<script language=\"VBScript\"\>\n');
	document.write('On Error Resume Next\n');
	document.write('Sub Intentalodenuevo_FSCommand(ByVal command, ByVal args)\n');
	document.write('	Call Intentalodenuevo_DoFSCommand(command, args)\n');
	document.write('End Sub\n');
	document.write('</script\>\n');
}
//-->
</script>
<!--URL utilizadas en la película-->
<!--Texto utilizado en la película-->
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="Intentalodenuevo" width="80%" height="100%" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="Intentalodenuevo.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><embed src="Intentalodenuevo.swf" quality="high" bgcolor="#ffffff" width="80%" height="100%" swLiveConnect=true id="Intentalodenuevo" name="Intentalodenuevo" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer_es" />
</object>
</body>
</html>


text:
//
//  WMLogfileViewController.m
//  WhaleMeter
//
//  Created by Reinoud Elhorst on 21/04/2014.
//  Copyright (c) 2014 Reinoud Elhorst. All rights reserved.
//

#import "WMLogfileViewController.h"
#import "WMFileManager.h"
#import <MessageUI/MFMailComposeViewController.h>

#define SOUND_FIELD_INDEX 13
#define MANUAL_LIGHT_FIELD_INDEX 14
#define COMMENT_FIELD_INDEX 15

@interface WMLogfileViewController () <UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate, MFMailComposeViewControllerDelegate>

@end

@implementation WMLogfileViewController
NSMutableArray* lines;
UIActionSheet* clickActionSheet;
UIActionSheet* deleteFileActionSheet;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    clickActionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                   delegate:self
                                          cancelButtonTitle:@"Cancel"
                                     destructiveButtonTitle:@"Delete"
                                          otherButtonTitles:@"Edit comment",nil];
    deleteFileActionSheet= [[UIActionSheet alloc] initWithTitle:nil
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                         destructiveButtonTitle:@"Delete File"
                                              otherButtonTitles:nil];

}

-(void) viewWillAppear:(BOOL)animated
{
    self.navigationItem.title = self.fileName;
    NSString* fileContent = [[WMFileManager sharedInstance] getLogfileContent:self.fileName];
    lines = [NSMutableArray arrayWithObject:[fileContent componentsSeparatedByString:@"\n"]];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[lines lastObject] count] - 2; // remove header, remove last empty line
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"LoglineCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    @try {
        NSString* line = [[lines lastObject] objectAtIndex:indexPath.row + 1]; // ignore header
        NSArray* parts = [line componentsSeparatedByString:@","];
        NSString* time = [parts[0] componentsSeparatedByString:@" "][1];
        double_t lux = [parts[1] doubleValue];
        NSString* sound = parts[SOUND_FIELD_INDEX];
        NSString* manualLight = parts[MANUAL_LIGHT_FIELD_INDEX];
        NSString* comments = parts[COMMENT_FIELD_INDEX];
        cell.textLabel.text = [NSString stringWithFormat:@"%@ %.3g lx %@ %@ %@", time, lux, sound, manualLight, comments];
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        cell.textLabel.text=@"#ERROR#";
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [clickActionSheet showInView:self.view];
}

- (void)checkEnableUndoButton
{
    self.undoButton.enabled = ([lines count] > 1);
}

-(IBAction)undo:(id)sender
{
    if ([lines count] > 1) {
        [lines removeLastObject];
    }
    [self.tableView reloadData];
    [self writeFile];
    [self checkEnableUndoButton];
}

-(IBAction)deleteFileButtonPress:(id)sender
{
    [deleteFileActionSheet showInView:self.view];
}

-(void) writeFile
{
    [[WMFileManager sharedInstance] writeFile:self.fileName withData:[[lines lastObject] componentsJoinedByString:@"\n"]];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet == clickActionSheet) {
        NSInteger indexInArray = self.tableView.indexPathForSelectedRow.row + 1; //ignore header
        switch(buttonIndex) {
            case 0: /*delete*/
            {
                NSArray* startLines = [[lines lastObject] subarrayWithRange:NSMakeRange(0, indexInArray)];
                NSArray* endLines =   [[lines lastObject]
                                       subarrayWithRange:NSMakeRange(
                                                                     indexInArray+1,
                                                                     [[lines lastObject] count] - (indexInArray + 1))];
                [lines addObject:[startLines arrayByAddingObjectsFromArray:endLines]];
                [self.tableView reloadData];
                [self writeFile];
                [self checkEnableUndoButton];
                [self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:NO];
                break;
            }
            case 1: /* edit */
            {
                self.modalMaker.hidden = NO;
                self.commentBox.hidden = NO;
                NSString* line = [lines lastObject][indexInArray];
                NSArray* parts = [line componentsSeparatedByString:@","];
                NSString* sound = parts[SOUND_FIELD_INDEX];
                NSString* manualLight = parts[MANUAL_LIGHT_FIELD_INDEX];
                NSString* comments = parts[COMMENT_FIELD_INDEX];
                self.soundField.text = sound;
                self.manualLightField.text = manualLight;
                self.commentField.text = comments;
                [self.soundField becomeFirstResponder];
                break;
            }
            case 3: /*cancel*/
            {
                [self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:NO];
                break;
            }
        }
    } else {
        if (buttonIndex == 0) {
            [[WMFileManager sharedInstance] deleteFile:self.fileName];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

-(IBAction)editCommentCancel:(id)sender
{
    self.modalMaker.hidden = YES;
    self.commentBox.hidden = YES;
    [self.soundField resignFirstResponder];
    [self.manualLightField resignFirstResponder];
    [self.commentField resignFirstResponder];
    [self.tableView deselectRowAtIndexPath:self.tableView.indexPathForSelectedRow animated:NO];
}

-(IBAction)editCommentSubmit:(id)sender
{
    NSInteger indexInArray = self.tableView.indexPathForSelectedRow.row + 1; //ignore header
    NSString* line = [lines lastObject][indexInArray]; //ignore header
    NSArray* parts = [line componentsSeparatedByString:@","];
    NSArray* partsWeKeep = [parts subarrayWithRange:NSMakeRange(0, SOUND_FIELD_INDEX)];
    NSArray* toAdd = @[
                    [self.soundField.text stringByReplacingOccurrencesOfString:@"," withString:@"."],
                    [self.manualLightField.text stringByReplacingOccurrencesOfString:@"," withString:@"."],
                    [self.commentField.text stringByReplacingOccurrencesOfString:@"," withString:@"."]];
    NSArray* newparts = [partsWeKeep arrayByAddingObjectsFromArray: toAdd];
    NSString* newline = [newparts componentsJoinedByString:@","];

    NSMutableArray* newlines = [[lines lastObject] mutableCopy];
    [newlines replaceObjectAtIndex:indexInArray withObject:newline];
    [lines addObject:[NSArray arrayWithArray:newlines]];
    [self.tableView reloadData];
    [self writeFile];
    [self checkEnableUndoButton];
    [self editCommentCancel:sender];
}

-(IBAction)sendByEmail:(id)sender
{
    MFMailComposeViewController* mailViewController = [MFMailComposeViewController new];
    mailViewController.mailComposeDelegate = self;
    NSString* to = [[NSUserDefaults standardUserDefaults] stringForKey:@"Default Email"];
    [mailViewController setToRecipients:[to componentsSeparatedByString:@","]];
    [mailViewController setSubject:[NSString stringWithFormat:@"Whalemeter: %@", self.fileName]];
    NSData* data = [[[WMFileManager sharedInstance] getLogfileContent:self.fileName]
                    dataUsingEncoding:NSUTF8StringEncoding];
    [mailViewController addAttachmentData:data mimeType:@"text/csv" fileName:self.fileName];
    [self presentViewController:mailViewController animated:YES completion:NULL];
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}

@end


text:
import six
from funcy import memoize, merge

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

CACHEOPS_REDIS = getattr(settings, 'CACHEOPS_REDIS', None)
CACHEOPS_DEFAULTS = getattr(settings, 'CACHEOPS_DEFAULTS', {})
CACHEOPS = getattr(settings, 'CACHEOPS', {})
CACHEOPS_LRU = getattr(settings, 'CACHEOPS_LRU', False)
CACHEOPS_DEGRADE_ON_FAILURE = getattr(settings, 'CACHEOPS_DEGRADE_ON_FAILURE', False)

FILE_CACHE_DIR = getattr(settings, 'FILE_CACHE_DIR', '/tmp/cacheops_file_cache')
FILE_CACHE_TIMEOUT = getattr(settings, 'FILE_CACHE_TIMEOUT', 60*60*24*30)

ALL_OPS = {'get', 'fetch', 'count', 'exists'}

@memoize
def prepare_profiles():
    """
    Prepares a dict 'app.model' -> profile, for use in model_profile()
    """
    profile_defaults = {
        'ops': (),
        'local_get': False,
        'db_agnostic': True,
    }
    profile_defaults.update(CACHEOPS_DEFAULTS)

    model_profiles = {}
    for app_model, profile in CACHEOPS.items():
        if profile is None:
            model_profiles[app_model] = None
            continue

        model_profiles[app_model] = mp = merge(profile_defaults, profile)
        if mp['ops'] == 'all':
            mp['ops'] = ALL_OPS
        # People will do that anyway :)
        if isinstance(mp['ops'], six.string_types):
            mp['ops'] = {mp['ops']}
        mp['ops'] = set(mp['ops'])

        if 'timeout' not in mp:
            raise ImproperlyConfigured(
                'You must specify "timeout" option in "%s" CACHEOPS profile' % app_model)

    return model_profiles

@memoize
def model_profile(model):
    """
    Returns cacheops profile for a model
    """
    model_profiles = prepare_profiles()

    app = model._meta.app_label
    model_name = model._meta.model_name
    for guess in ('%s.%s' % (app, model_name), '%s.*' % app, '*.*'):
        if guess in model_profiles:
            return model_profiles[guess]
    else:
        return None


text:
@interface NSObject(FIGAlbumReaderDelegate)

- (void)whenReaderFailture:(NSError *)error;

- (void)whenReaderSuccess;

@end

@interface FIGAlbumReader : NSObject

// 相册
@property (nonatomic, strong) NSMutableArray *albums;

- (void)setDelegate:(id)delegate;

-(id)initWithAlbumTypes: (NSInteger) groupTypes;

//读取所有相册信息, 该方法为异步方法
-(void)readAlbums;

// 删除所有相册
-(void)removeAllAlbums;

//获取相册数量
-(NSInteger)getAlbumCount;

//获取相册信息
-(FIGAlbumInfo *)getAlbumInfoAtIndex:(NSInteger) index;

@end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bulletin Acad. Polonaise Sci. , Math. et Nat. , Sér. B 12: 404 (1964)

#### Original name
Entomophthora virulenta I.M. Hall & P.H. Dunn, 1957

### Remarks
null


text:
package com.amatkivskiy.gitter.sdk.rx.client;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import com.amatkivskiy.gitter.sdk.Constants;
import com.amatkivskiy.gitter.sdk.api.builder.GitterApiBuilder;
import com.amatkivskiy.gitter.sdk.converter.UserJsonDeserializer;
import com.amatkivskiy.gitter.sdk.model.response.UserResponse;
import com.amatkivskiy.gitter.sdk.model.response.message.MessageResponse;
import com.amatkivskiy.gitter.sdk.rx.api.RxGitterStreamingApi;
import com.amatkivskiy.gitter.sdk.rx.streaming.OnSubscribeBufferedReader;
import com.amatkivskiy.gitter.sdk.rx.streaming.model.RoomEvent;
import com.amatkivskiy.gitter.sdk.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import retrofit.client.Response;
import retrofit.converter.GsonConverter;
import rx.Observable;
import rx.functions.Func1;

public class RxGitterStreamingApiClient {
  private RxGitterStreamingApi api;
  private Gson gson;

  public RxGitterStreamingApiClient(RxGitterStreamingApi api, Gson gson) {
    this.api = api;
    this.gson = gson;
  }

  public Observable<MessageResponse> getRoomMessagesStream(String roomId) {
    return api.getRoomMessagesStream(roomId).flatMap(new Func1<Response, Observable<String>>() {
      @Override
      public Observable<String> call(Response response) {
        try {
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody().in()));
          return Observable.create(new OnSubscribeBufferedReader(bufferedReader));
        } catch (IOException e) {
          return Observable.error(e);
        }
      }
    }).filter(new Func1<String, Boolean>() {
      @Override
      public Boolean call(String s) {
//        This check is required because server sometimes return empty string or string with newline character.
        return StringUtils.checkIfValidMessageJson(s);
      }
    }).map(new Func1<String, MessageResponse>() {
      @Override
      public MessageResponse call(String s) {
        return gson.fromJson(s, MessageResponse.class);
      }
    });
  }

  public Observable<RoomEvent> getRoomEventsStream(String roomId) {
    return api.getRoomEventsStream(roomId).flatMap(new Func1<Response, Observable<String>>() {
      @Override
      public Observable<String> call(Response response) {
        try {
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody().in()));
          return Observable.create(new OnSubscribeBufferedReader(bufferedReader));
        } catch (IOException e) {
          return Observable.error(e);
        }
      }
    }).filter(new Func1<String, Boolean>() {
      @Override
      public Boolean call(String s) {
//        This check is required because server sometimes return empty string or string with newline character.
        return StringUtils.checkIfValidMessageJson(s);
      }
    }).map(new Func1<String, RoomEvent>() {
      @Override
      public RoomEvent call(String s) {
        return gson.fromJson(s, RoomEvent.class);
      }
    });
  }

  public static class Builder extends GitterApiBuilder<Builder, RxGitterStreamingApiClient> {

    protected String getFullEndpointUrl() {
      return Constants.GitterEndpoints.GITTER_STREAMING_API_ENDPOINT + "/" + apiVersion + "/";
    }

    @Override
    public RxGitterStreamingApiClient build() {
      prepareDefaultBuilderConfig();

      Gson gson = new GsonBuilder()
          .registerTypeAdapter(UserResponse.class, new UserJsonDeserializer())
          .create();
      restAdapterBuilder.setConverter(new GsonConverter(gson));

      RxGitterStreamingApi api = restAdapterBuilder.build().create(RxGitterStreamingApi.class);
      return new RxGitterStreamingApiClient(api, gson);
    }
  }
}


text:
package org.broad.igv.feature.genome.load;

import org.broad.igv.feature.Chromosome;
import org.broad.igv.feature.genome.Genome;

import java.io.IOException;
import java.util.List;

public class ChromsizesLoader extends GenomeLoader {

    private String genomePath;

    public ChromsizesLoader(String genomePath) {
        this.genomePath = genomePath;
    }

    /**
     * Define a minimal genome from a chrom.sizes file.  It is assumed (required) that the file follow the
     * UCSC naming convention  =>  [id].chrom.sizes
     * @return
     * @throws IOException
     */
    @Override
    public Genome loadGenome() throws IOException {
        int firstPeriodIdx = genomePath.indexOf('.');
        String genomeId = genomePath.substring(0, firstPeriodIdx);
        List<Chromosome> chromosomes = ChromSizesParser.parse(genomePath);
        Genome newGenome = new Genome(genomeId, chromosomes);
        return newGenome;

    }
}