text:
package org.apache.harmony.text.tests.java.text;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InvalidObjectException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.text.DateFormat;
import java.text.DateFormat.Field;
import java.util.Calendar;

import junit.framework.TestCase;

public class DataFormatFieldTest extends TestCase{

	public void test_ConstructorLjava_lang_StringLjava_lang_String() {
		// Regression for HARMONY-178
		MyField field = new MyField("day of month", Calendar.ERA);

		assertEquals("field has wrong name", "day of month", field.getName());
		assertEquals("field has wrong Calendar field number", Calendar.ERA,
				field.getCalendarField());

		DateFormat.Field realField = DateFormat.Field
				.ofCalendarField(Calendar.ERA);
		assertSame("Modified calendar field with the same field number",
				DateFormat.Field.ERA, realField);

		DateFormat.Field realField2 = DateFormat.Field
				.ofCalendarField(Calendar.DAY_OF_MONTH);
		assertSame("Modified calendar field with the same field number",
				DateFormat.Field.DAY_OF_MONTH, realField2);
	}

    static class MyField extends DateFormat.Field {
        private static final long serialVersionUID = 1L;

        protected MyField(String fieldName, int calendarField) {
            super(fieldName, calendarField);
        }

        protected String getName() {
            return super.getName();
        }
    }

    /**
     * @tests java.text.DateFormat$Field#Field(java.lang.String, int)
     */
    public void test_ConstructorLjava_lang_StringI() {
        MyField field = new MyField("a field", Calendar.DAY_OF_WEEK);

        assertEquals("field has wrong name", "a field", field.getName());
        assertEquals("field has wrong Calendar field number",
                Calendar.DAY_OF_WEEK, field.getCalendarField());

        DateFormat.Field realField = DateFormat.Field
                .ofCalendarField(Calendar.DAY_OF_WEEK);
        assertSame("Modified calendar field with the same field number",
                DateFormat.Field.DAY_OF_WEEK, realField);
    }

    /**
     * @tests java.text.DateFormat$Field#Field(java.lang.String, int)
     */
    public void test_Constructor2() {
        MyField field = new MyField("day of month", Calendar.ERA);

        assertEquals("field has wrong name", "day of month", field.getName());
        assertEquals("field has wrong Calendar field number", Calendar.ERA,
                field.getCalendarField());

        DateFormat.Field realField = DateFormat.Field
                .ofCalendarField(Calendar.ERA);
        assertSame("Modified calendar field with the same field number",
                DateFormat.Field.ERA, realField);

        DateFormat.Field realField2 = DateFormat.Field
                .ofCalendarField(Calendar.DAY_OF_MONTH);
        assertSame("Modified calendar field with the same field number",
                DateFormat.Field.DAY_OF_MONTH, realField2);
    }

    /**
     * @tests java.text.DateFormat$Field#getCalendarField()
     */
    public void test_getCalendarField() {
        // Test for method int getCalendarField()
        assertEquals("Field.AM_PM.getCalendarField() returned the wrong value",
                Calendar.AM_PM, Field.AM_PM.getCalendarField());

        // test special cases
        assertEquals(
                "Field.TIME_ZONE.getCalendarField() returned the wrong value",
                -1, Field.TIME_ZONE.getCalendarField());
        assertEquals("Field.HOUR0.getCalendarField() returned the wrong value",
                Calendar.HOUR, Field.HOUR0.getCalendarField());
        assertEquals("Field.HOUR1.getCalendarField() returned the wrong value",
                -1, Field.HOUR1.getCalendarField());
        assertEquals(
                "Field.HOUR_OF_DAY0.getCalendarField() returned the wrong value",
                Calendar.HOUR_OF_DAY, Field.HOUR_OF_DAY0.getCalendarField());
        assertEquals(
                "Field.HOUR_OF_DAY1.getCalendarField() returned the wrong value",
                -1, Field.HOUR_OF_DAY1.getCalendarField());
    }

    /**
     * @tests java.text.DateFormat$Field#ofCalendarField(int)
     */
    public void test_ofCalendarFieldI() {
        // Test for method static java.text.DateFormat.Field
        // ofCalendarField(int)
        assertSame("ofCalendarField(Calendar.AM_PM) returned the wrong value",
                Field.AM_PM, Field.ofCalendarField(Calendar.AM_PM));

        // test special cases
        assertSame("ofCalendarField(Calendar.HOUR) returned the wrong value",
                Field.HOUR0, Field.ofCalendarField(Calendar.HOUR));
        assertSame(
                "ofCalendarField(Calendar.HOUR_OF_DAY) returned the wrong value",
                Field.HOUR_OF_DAY0, Field.ofCalendarField(Calendar.HOUR_OF_DAY));

        // test illegal args
        try {
            DateFormat.Field.ofCalendarField(-1);
            fail("Expected IllegalArgumentException for ofCalendarField(-1)");
        } catch (IllegalArgumentException e) {
        }

        try {
            DateFormat.Field.ofCalendarField(Calendar.FIELD_COUNT);
            fail("Expected IllegalArgumentException for ofCalendarField(Calendar.FIELD_COUNT)");
        } catch (IllegalArgumentException e) {
        }

        // test Calendar fields that do not have corresponding DateFormat Fields
        assertNull(
                "ofCalendarField(Calendar.DST_OFFSET) returned the wrong value",
                DateFormat.Field.ofCalendarField(Calendar.DST_OFFSET));
        assertNull(
                "ofCalendarField(Calendar.ZONE_OFFSET) returned the wrong value",
                DateFormat.Field.ofCalendarField(Calendar.ZONE_OFFSET));
    }

    /**
     * @tests java.text.DateFormat$Field#readResolve()
     */
    public void test_readResolve() {
        // test for method java.lang.Object readResolve()

        // see serialization stress tests:
        // implemented in
        // SerializationStressTest4.test_writeObject_NumberFormat_Field()

        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            out = new ObjectOutputStream(bytes);

            DateFormat.Field dfield, dfield2;
            MyField field;

            // a regular instance of DateFormat.Field
            dfield = DateFormat.Field.MILLISECOND;

            // a subclass instance with null name
            field = new MyField(null, Calendar.AM_PM);

            out.writeObject(dfield);
            out.writeObject(field);

            in = new ObjectInputStream(new ByteArrayInputStream(bytes
                    .toByteArray()));

            try {
                dfield2 = (Field) in.readObject();
                assertSame("resolved incorrectly", dfield, dfield2);
            } catch (IllegalArgumentException e) {
                fail("Unexpected IllegalArgumentException: " + e);
            }

            try {
                in.readObject();
                fail("Expected InvalidObjectException for subclass instance with null name");
            } catch (InvalidObjectException e) {
            }

        } catch (IOException e) {
            fail("unexpected IOException" + e);
        } catch (ClassNotFoundException e) {
            fail("unexpected ClassNotFoundException" + e);
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
            }
        }
    }
}


text:
/**
 * Scripts communs à toutes les pages
 */

if(typeof Gosyl === 'undefined') Gosyl = {};

Gosyl.Common = (function() {
	/**
	 * Réglages pour le datepicker
	 */
	var dateMini = new Date('1900', '1' , '1');
	var dateNow = new Date();

	/*
	 * réglage pour le sessionStorage
	 */
	var expire = 86400;//24 heures

	function init() {
		initSessionStorage();
        evtAjaxLoading();
        unFocusBtnAfterClick();
	}

	function evtAjaxLoading() {
	    $(document).on('ajaxSend', loadingAjax)
            .on('ajaxComplete', ajaxLoaded);
    }

	function getIdItem(item) {
		var aItem = item.split('_');

		return aItem[1];
	}

	/*********************************************
	 * SessionStorage
	 *********************************************/

	/*
	 * Initialisation d'une durée de vie du sessionStorage
	 */
	function initSessionStorage() {
		if(typeof sessionStorage != 'undefined') {
			var dtNow = new Date();

			if(!('expire' in sessionStorage)) {
				sessionStorage.setItem('expire', dtNow.getTime());
			} else {
				// On évalue la date d'expiration
				var dtExpire = new Date();

				dtExpire.setTime(sessionStorage.getItem('expire'));

				// On retranche une durée de vie du cache
				dtNow.setTime(dtNow.getTime() - this.expire);

				if(dtExpire.getTime() < dtNow.getTime()) {
					var dtNewExpire = new Date();

					clearSessionStorage();
					sessionStorage.setItem('expire', dtNewExpire.getTime());
				}
			}
		}
	}

	/**
	 * On efface le sessionStorage
	 */
	function clearSessionStorage(reInit) {
		if(typeof reInit == 'undefined') {
			reInit = false;
		}

		sessionStorage.clear();
		if(reInit) {
			initSessionStorage();
		}
	}

	/*********************************************
	 * Fonctions date
	**********************************************/

	function getFrDateTime(date) {
	    if(typeof date == 'undefined') {
	        date = new Date();
        }

		var jour = date.getUTCDate();
		var mois = date.getMonth();
		var annee = date.getFullYear();

		var heure = date.getHours();
		var minute = date.getMinutes();
		var seconde = date.getSeconds();

		function ajout0(prop) {
			if(prop.toString().length == 1) {
				return '0' + prop;
			}
			return prop;
		}

		jour = ajout0(jour);
		mois = ajout0(mois + 1);

		return jour + '/' + mois + '/' + annee + ' ' + heure + ':' + minute + ':' + seconde;
	}

	/**
	 * Retourne l'objet Date avec en parèmetre un dateTime prédéfini (jj/mm/aaaa hh:MM:ss)
	 * @param sDateHeure string
	 * @returns {Date}
	 */
	function decomposeDate(sDateHeure) {
		var aDateHeure = sDateHeure.split(' ');
		var sDate = aDateHeure[0];
		var sHeure = aDateHeure[1];

		var aDate = sDate.split('/');
		var jour = aDate[0];
		var mois = aDate[1];
		var annee = aDate[2];

		var aHeure = sHeure.split(':');
		var heure = aHeure[0];
		var minute = aHeure[1];
		var seconde = aHeure[2];

		return new Date(annee, mois, jour, heure, minute, seconde);
	}

	/*********************************************
	 * Fonctions chaîne de caractères
	**********************************************/

	/**
	 * Met en majuscule la première lettre de chaque mot d'une chaîne de caractères
	 * @param str
	 * @returns string
	 */
	function STR_ucwords(str) {
		str = str.toLowerCase().replace(/^[\u00C0-\u1FFF\u2C00-\uD7FF\w]|\s[\u00C0-\u1FFF\u2C00-\uD7FF\w]/g, function(letter) {
		    return letter.toUpperCase();
		});

		return str;
	}

	function loadDatePicker(element) {
		$('#' + element).datepicker({
			autoSize: true,
			onClose: function(dateText, instance) {
				$(this).datepicker('setDate', dateText);
			}
		});
	}

	function loadingAjax(e) {
	    e.stopPropagation();
		$('#ajaxLoading').show();
	}

	function ajaxLoaded(e) {
	    e.stopPropagation();
		$('#ajaxLoading').hide();
	}

	function getDimensionElement(elem) {
		function internal(elem) {
			if($('#' + elem).length == 0) {
				throw new MonException(elem + ' : is undefined !');
			} else {
				var oElem = $('#' + elem);

				var borderLeftWidth = parseInt(oElem.css('border-left-width'));
				var borderRightWidth = parseInt(oElem.css('border-right-width'));
				var paddingLeft = parseInt(oElem.css('padding-left'));
				var paddingRight = parseInt(oElem.css('padding-right'));
				var width = parseInt(oElem.css('width'));

				var borderTopWidth  = parseInt(oElem.css('border-top-width'));
				var paddingTop = parseInt(oElem.css('padding-top'));
				var height = parseInt(oElem.css('height'));
				var paddingBottom = parseInt(oElem.css('padding-bottom'));
				var borderBottomWidth = parseInt(oElem.css('border-bottom-width'));

				return {
                    x: borderLeftWidth + paddingLeft + width + paddingRight + borderRightWidth,
                    y: borderTopWidth + paddingTop + height + paddingBottom + borderBottomWidth
                };
			}
		}
		var dim = {};
		try {
			dim = internal(elem);
		} catch (e) {
			dim = {
				x: 0,
				y: 0
			}

		}
		return dim;
	}

	function MonException(message) {
		this.message = message;
		this.name = "MonException";
	}

	function getMsgRetourForm(messages) {
		var contenu = "";

		$.each(messages, function(i, msg) {
			contenu += msg;
			if(i < messages.length) {
				contenu += '<br />';
			}
		});

		return contenu;
	}

	function unFocusBtnAfterClick() {
        $('button.btn').on('click', function(e) {
            e.stopPropagation();
            $(this).blur();
        });
    }

	return {
		init: init,
		getIdItem: getIdItem,
		getFrDateTime: getFrDateTime,
		decomposeDate: decomposeDate,
		STR_ucwords: STR_ucwords,
		loadDatePicker: loadDatePicker,
		loadingAjax: loadingAjax,
		ajaxLoaded: ajaxLoaded,
		getDimensionElement: getDimensionElement,
		getMsgRetourForm: getMsgRetourForm,
		dateMini: dateMini,
		dateNow: dateNow,
		clearSessionStorage: clearSessionStorage
	};
})();

$(document).ready(function() {
	$('#ajaxLoading')
	.width($(document).width())
	.height($(document).height());

	Gosyl.Common.init();
});

$.datepicker.setDefaults({
	changeMonth: true,
	changeYear: true,
	dateFormat: 'dd/mm/yy',
	dayNames: [ "Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi" ],
	dayNamesMin: [ "Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa" ],
	dayNamesShort: [ "Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam" ],
	firstDay: 1,
	minDate: Gosyl.Common.dateMini,
	maxDate: Gosyl.Common.dateNow,
	monthName: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre' , 'Octobre', 'Novembre', 'Décembre'],
	monthNamesShort: [ "Jan", "Fev", "Mar", "Avr", "Mai", "Jui", "Juil", "Aoû", "Sep", "Oct", "Nov", "Déc" ],
	yearRange: Gosyl.Common.dateMini.getFullYear() + ':' + Gosyl.Common.dateNow.getFullYear(),
	showButtonPanel: true,
	currentText: "Aujourd'hui",
	closeText: "Fermer",

});

redpajama_set_name: RedPajamaGithub


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

<TITLE>
Segmenter (FreeTTS 1.2)
</TITLE>

<META NAME="keywords" CONTENT="com.sun.speech.freetts.Segmenter class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.sun.speech.freetts

Class Segmenter

java.lang.Object
  com.sun.speech.freetts.Segmenter

All Implemented Interfaces:
UtteranceProcessor

public class Segmenter
extends java.lang.Object
implements UtteranceProcessor

Annotates an utterance with Relation.SYLLABLE,
 Relation.SYLLABLE_STRUCTURE, and
 Relation.SEGMENT.
 To determine stress, the isStressed method relies upon
 a phone ending in the number "1".  Subclasses should override
 isStressed and deStress if stresses are
 determined in other ways.

See Also:
Relation.SEGMENT,
Relation.SYLLABLE,
Relation.SYLLABLE_STRUCTURE

Constructor Summary

Segmenter()

Method Summary

protected  java.lang.String
deStress(java.lang.String phone)

          Converts stressed phoneme to regular phoneme.

protected  boolean
isStressed(java.lang.String phone)

          Determines if the given phonemene is stressed.

 void
processUtterance(Utterance utterance)

          Annotates an utterance with Relation.SYLLABLE,
 Relation.SYLLABLE_STRUCTURE, and
 Relation.SEGMENT.

 java.lang.String
toString()

          Returns the simple name of this class.

Methods inherited from class java.lang.Object

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

Constructor Detail

Segmenter

public Segmenter()

Method Detail

processUtterance

public void processUtterance(Utterance utterance)
                      throws ProcessException

Annotates an utterance with Relation.SYLLABLE,
 Relation.SYLLABLE_STRUCTURE, and
 Relation.SEGMENT.

Specified by:
processUtterance in interface UtteranceProcessor

Parameters:
utterance - the utterance to process/tokenize

Throws:

ProcessException - if an IOException is thrown during the
   processing of the utterance
See Also:
Relation.SEGMENT,
Relation.SYLLABLE,
Relation.SYLLABLE_STRUCTURE

isStressed

protected boolean isStressed(java.lang.String phone)

Determines if the given phonemene is stressed.
 To determine stress, this method relies upon
 a phone ending in the number "1".  Subclasses should override this
 method if stresses are determined in other ways.

Parameters:
phone - the phone to check

Returns:
true if the phone is stressed, otherwise false

deStress

protected java.lang.String deStress(java.lang.String phone)

Converts stressed phoneme to regular phoneme.  This method
 merely removes the last character of the phone.  Subclasses
 should override this if another method is to be used.

Parameters:
phone - the phone to convert

Returns:
de-stressed phone

toString

public java.lang.String toString()

Returns the simple name of this class.

Returns:
the simple name of this class

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
layout: event
categories: eventolocale
title: "Visita LASA"
CL: Milano
locandina: /img/eventilocali/2016_VisitaLASA/locandina.pdf
gallery:
articolo: "visita-al-lasa"
report:
facebook:
link:
---

Per maggiori informazioni si prega di contattare il [presidente](/comitatilocali/) del comitato locale che ha organizzato l'evento.


text:
class wxModule;

typedef wxVector<wxModule*> wxModuleList;

// declaring a class derived from wxModule will automatically create an
// instance of this class on program startup, call its OnInit() method and call
// OnExit() on program termination (but only if OnInit() succeeded)
class WXDLLIMPEXP_BASE wxModule : public wxObject
{
public:
    wxModule() {}
    virtual ~wxModule() {}

    // if module init routine returns false the application
    // will fail to startup

    bool Init() { return OnInit(); }
    void Exit() { OnExit(); }

    // Override both of these

        // called on program startup

    virtual bool OnInit() = 0;

        // called just before program termination, but only if OnInit()
        // succeeded

    virtual void OnExit() = 0;

    static void RegisterModule(wxModule *module);
    static void RegisterModules();
    static bool InitializeModules();
    static void CleanUpModules();
    static bool AreInitialized() { return ms_areInitialized; }

    // used by wxObjectLoader when unloading shared libs's

    static void UnregisterModule(wxModule *module);

protected:
    static wxModuleList ms_modules;

    static bool ms_areInitialized;

    // the function to call from constructor of a deriving class add module
    // dependency which will be initialized before the module and unloaded
    // after that
    void AddDependency(wxClassInfo *dep)
    {
        wxCHECK_RET( dep, wxT("NULL module dependency") );

        m_dependencies.push_back(dep);
    }

    // same as the version above except it will look up wxClassInfo by name on
    // its own. Note that className must be ASCII
    void AddDependency(const char *className)
    {
        m_namedDependencies.push_back(wxASCII_STR(className));
    }

private:
    // initialize module and Append it to initializedModules list recursively
    // calling itself to satisfy module dependencies if needed
    static bool
    DoInitializeModule(wxModule *module, wxModuleList &initializedModules);

    // cleanup the modules in the specified list (which may not contain all
    // modules if we're called during initialization because not all modules
    // could be initialized) and also empty ms_modules itself
    static void DoCleanUpModules(const wxModuleList& modules);

    // resolve all named dependencies and add them to the normal m_dependencies
    bool ResolveNamedDependencies();

    // module dependencies: contains wxClassInfo pointers for all modules which
    // must be initialized before this one
    typedef wxVector<wxClassInfo*> wxArrayClassInfo;
    wxArrayClassInfo m_dependencies;

    // and the named dependencies: those will be resolved during run-time and
    // added to m_dependencies
    wxVector<wxString> m_namedDependencies;

    // used internally while initializing/cleaning up modules
    enum
    {
        State_Registered,   // module registered but not initialized yet
        State_Initializing, // we're initializing this module but not done yet
        State_Initialized   // module initialized successfully
    } m_state;

    wxDECLARE_CLASS(wxModule);
};

#endif // _WX_MODULE_H_


text:
import users from '../../../src/webserver/handlers/users' // eslint-disable-line

describe('webserver/handlers/users', () => {
  it('should work')
})


text:
const gulp = require('gulp')
const plugins = require('gulp-load-plugins')
const config = require('../config')
const $ = plugins()

gulp.task('images', () => {
  return gulp.src(config.images.src)
  .pipe($.if(config.env === 'prod', $.cache($.imagemin(config.images.opts))))
  .pipe(gulp.dest(config.images.dest))
  .pipe($.size({'title': 'images'}))
})


text:
package com.twitter.summingbird.graph

import org.scalacheck.Prop._
import org.scalacheck.{ Gen, Properties }

object ExpressionDagTests extends Properties("ExpressionDag") {
  /*
   * Here we test with a simple algebra optimizer
   */

  sealed trait Formula[T] { // we actually will ignore T
    def evaluate: Int
    def closure: Set[Formula[T]]
  }
  case class Constant[T](override val evaluate: Int) extends Formula[T] {
    def closure = Set(this)
  }
  case class Inc[T](in: Formula[T], by: Int) extends Formula[T] {
    def evaluate = in.evaluate + by
    def closure = in.closure + this
  }
  case class Sum[T](left: Formula[T], right: Formula[T]) extends Formula[T] {
    def evaluate = left.evaluate + right.evaluate
    def closure = (left.closure ++ right.closure) + this
  }
  case class Product[T](left: Formula[T], right: Formula[T]) extends Formula[T] {
    def evaluate = left.evaluate * right.evaluate
    def closure = (left.closure ++ right.closure) + this
  }

  def genForm: Gen[Formula[Int]] = Gen.frequency((1, genProd),
    (1, genSum),
    (4, genInc),
    (4, genConst))

  def genConst: Gen[Formula[Int]] = Gen.chooseNum(Int.MinValue, Int.MaxValue).map(Constant(_))
  def genInc: Gen[Formula[Int]] = for {
    by <- Gen.chooseNum(Int.MinValue, Int.MaxValue)
    f <- Gen.lzy(genForm)
  } yield Inc(f, by)

  def genSum: Gen[Formula[Int]] = for {
    left <- Gen.lzy(genForm)
    // We have to make dags, so select from the closure of left sometimes
    right <- Gen.oneOf(genForm, Gen.oneOf(left.closure.toSeq))
  } yield Sum(left, right)
  def genProd: Gen[Formula[Int]] = for {
    left <- Gen.lzy(genForm)
    // We have to make dags, so select from the closure of left sometimes
    right <- Gen.oneOf(genForm, Gen.oneOf(left.closure.toSeq))
  } yield Product(left, right)

  type L[T] = Literal[T, Formula]

  /**
   * Here we convert our dag nodes into Literal[Formula, T]
   */
  def toLiteral = new GenFunction[Formula, L] {
    def apply[T] = { (form: Formula[T]) =>
      def recurse[T2](memo: HMap[Formula, L], f: Formula[T2]): (HMap[Formula, L], L[T2]) = memo.get(f) match {
        case Some(l) => (memo, l)
        case None => f match {
          case c @ Constant(_) =>
            def makeLit[T1](c: Constant[T1]) = {
              val lit: L[T1] = ConstLit(c)
              (memo + (c -> lit), lit)
            }
            makeLit(c)
          case inc @ Inc(_, _) =>
            def makeLit[T1](i: Inc[T1]) = {
              val (m1, f1) = recurse(memo, i.in)
              val lit = UnaryLit(f1, { f: Formula[T1] => Inc(f, i.by) })
              (m1 + (i -> lit), lit)
            }
            makeLit(inc)
          case sum @ Sum(_, _) =>
            def makeLit[T1](s: Sum[T1]) = {
              val (m1, fl) = recurse(memo, s.left)
              val (m2, fr) = recurse(m1, s.right)
              val lit = BinaryLit(fl, fr, { (f: Formula[T1], g: Formula[T1]) => Sum(f, g) })
              (m2 + (s -> lit), lit)
            }
            makeLit(sum)
          case prod @ Product(_, _) =>
            def makeLit[T1](p: Product[T1]) = {
              val (m1, fl) = recurse(memo, p.left)
              val (m2, fr) = recurse(m1, p.right)
              val lit = BinaryLit(fl, fr, { (f: Formula[T1], g: Formula[T1]) => Product(f, g) })
              (m2 + (p -> lit), lit)
            }
            makeLit(prod)
        }
      }
      recurse(HMap.empty[Formula, L], form)._2
    }
  }

  /**
   * Inc(Inc(a, b), c) = Inc(a, b + c)
   */
  object CombineInc extends Rule[Formula] {
    def apply[T](on: ExpressionDag[Formula]) = {
      case Inc(i @ Inc(a, b), c) if on.fanOut(i) == 1 => Some(Inc(a, b + c))
      case _ => None
    }
  }

  object RemoveInc extends PartialRule[Formula] {
    def applyWhere[T](on: ExpressionDag[Formula]) = {
      case Inc(f, by) => Sum(f, Constant(by))
    }
  }

  //Check the Node[T] <=> Id[T] is an Injection for all nodes reachable from the root

  property("toLiteral/Literal.evaluate is a bijection") = forAll(genForm) { form =>
    toLiteral.apply(form).evaluate == form
  }

  property("Going to ExpressionDag round trips") = forAll(genForm) { form =>
    val (dag, id) = ExpressionDag(form, toLiteral)
    dag.evaluate(id) == form
  }

  property("CombineInc does not change results") = forAll(genForm) { form =>
    val simplified = ExpressionDag.applyRule(form, toLiteral, CombineInc)
    form.evaluate == simplified.evaluate
  }

  property("RemoveInc removes all Inc") = forAll(genForm) { form =>
    val noIncForm = ExpressionDag.applyRule(form, toLiteral, RemoveInc)
    def noInc(f: Formula[Int]): Boolean = f match {
      case Constant(_) => true
      case Inc(_, _) => false
      case Sum(l, r) => noInc(l) && noInc(r)
      case Product(l, r) => noInc(l) && noInc(r)
    }
    noInc(noIncForm) && (noIncForm.evaluate == form.evaluate)
  }

  /**
   * This law is important for the rules to work as expected, and not have equivalent
   * nodes appearing more than once in the Dag
   */
  property("Node structural equality implies Id equality") = forAll(genForm) { form =>
    val (dag, id) = ExpressionDag(form, toLiteral)
    type BoolT[T] = Boolean // constant type function
    dag.idToExp.collect(new GenPartial[HMap[Id, ExpressionDag[Formula]#E]#Pair, BoolT] {
      def apply[T] = {
        case (id, expr) =>
          val node = expr.evaluate(dag.idToExp)
          dag.idOf(node) == id
      }
    }).forall(identity)
  }

  // The normal Inc gen recursively calls the general dag Generator
  def genChainInc: Gen[Formula[Int]] = for {
    by <- Gen.chooseNum(Int.MinValue, Int.MaxValue)
    chain <- genChain
  } yield Inc(chain, by)

  def genChain: Gen[Formula[Int]] = Gen.frequency((1, genConst), (3, genChainInc))
  property("CombineInc compresses linear Inc chains") = forAll(genChain) { chain =>
    ExpressionDag.applyRule(chain, toLiteral, CombineInc) match {
      case Constant(n) => true
      case Inc(Constant(n), b) => true
      case _ => false // All others should have been compressed
    }
  }

  /**
   * We should be able to totally evaluate these formulas
   */
  object EvaluationRule extends Rule[Formula] {
    def apply[T](on: ExpressionDag[Formula]) = {
      case Sum(Constant(a), Constant(b)) => Some(Constant(a + b))
      case Product(Constant(a), Constant(b)) => Some(Constant(a * b))
      case Inc(Constant(a), b) => Some(Constant(a + b))
      case _ => None
    }
  }
  property("EvaluationRule totally evaluates") = forAll(genForm) { form =>
    ExpressionDag.applyRule(form, toLiteral, EvaluationRule) match {
      case Constant(x) if x == form.evaluate => true
      case _ => false
    }
  }
}


text:
layout: page
title: Castaneda King Trade Conference
date: 2016-05-24
author: Andrea Short
tags: weekly links, java
status: published
summary: Morbi iaculis ullamcorper mattis. Proin in est.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 05/30/2016
  endDate: 06/02/2016
  ctyhocn: AMAWEHX
  groupCode: CKTC
published: true
---
Etiam eget tempus orci. Ut felis libero, vehicula vitae efficitur eu, commodo non orci. Curabitur urna ex, tristique et sagittis at, mattis non purus. Nulla facilisi. Fusce eu accumsan elit. Integer enim libero, tincidunt ac lacus et, ornare faucibus nunc. Fusce nibh leo, vehicula ut vehicula a, pulvinar sed ex. Fusce eget leo at ipsum fringilla laoreet et ut mauris. Curabitur vitae arcu hendrerit, pellentesque diam at, aliquet erat. Proin elementum turpis mauris. In dui mi, dictum non tortor eget, cursus lobortis risus.
Aenean eget tellus eleifend neque maximus dapibus. Proin a facilisis purus. Morbi nisi tortor, vulputate ac facilisis ut, vehicula eu elit. Nunc dignissim turpis sed sapien convallis, ut ultricies ipsum commodo. Maecenas quis molestie purus. Fusce ullamcorper nec magna sed interdum. Morbi eleifend ipsum et sapien ullamcorper maximus. In ullamcorper metus arcu, in auctor quam pretium quis. Etiam egestas eu eros ut viverra. Maecenas ultrices mauris dui, eu pulvinar urna dictum non. In scelerisque lobortis felis vitae laoreet. Pellentesque maximus ut risus in blandit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

* Maecenas et nibh sit amet libero condimentum blandit
* Vestibulum eget nunc sit amet massa porttitor pretium non id leo.

Donec sagittis neque ut luctus gravida. Donec faucibus, ex et tempus volutpat, quam velit lobortis urna, ut suscipit massa orci eget dui. Donec eu lacus metus. In ut sagittis turpis. Donec egestas lacus sed tellus accumsan, vitae malesuada lorem egestas. Sed nisi nunc, suscipit et augue et, maximus maximus felis. Etiam eu diam sit amet risus tempor auctor. Nam faucibus lectus sed metus aliquet, posuere mattis sapien pellentesque. Sed a ex velit.


text:
<?xml version="1.0" ?>
<CIM CIMVERSION="2.0" DTDVERSION="2.0">
  <MESSAGE ID="39002" PROTOCOLVERSION="1.0">
    <SIMPLEREQ>
      <IMETHODCALL NAME="DeleteQualifier">
        <LOCALNAMESPACEPATH>
          <NAMESPACE NAME="test"/>
          <NAMESPACE NAME="test_notanamespace"/>
        </LOCALNAMESPACEPATH>
        <IPARAMVALUE NAME="QualifierName">
          <VALUE>TestQualifier003</VALUE>
        </IPARAMVALUE>
      </IMETHODCALL>
    </SIMPLEREQ>
  </MESSAGE>
</CIM>


text:
"""
Tests for module nocexec.drivers.extreme
"""

import unittest
try:
    from unittest import mock
except ImportError:  # pragma: no cover
    import mock
from nocexec.drivers.extreme import XOS, XOSError, XOSCommandError
from nocexec.exception import SSHClientError, SSHClientExecuteCmdError

# pylint: disable=invalid-name,missing-docstring,protected-access
invalid_input = [' asdasdasd', '', '\x07        ^',
                 '', "%% Invalid input detected at '^' marker.", '']
error_input = [' create vlan Test tag 11', '',
               'Error: 802.1Q Tag 11 is assigned to VLAN test.']
normal = [' show vlan', '', 'test']

class TestXOS(unittest.TestCase):

    def setUp(self):
        self.c = XOS(device="d")
        self.c.cli = mock.MagicMock()

    @mock.patch('nocexec.drivers.base.NOCExecDriver.init_client')
    def test_connect(self, mock_init_client):
        mock_sendline = self.c.cli.connection.sendline
        mock_expect = self.c.cli.connection.expect
        self.c.cli.connection.before.splitlines.return_value = ["", "hostname"]
        self.c.connect()
        mock_init_client.assert_called_with()
        self.c.cli.connect.assert_called_with()
        mock_sendline.assert_called_with("disable clipaging")
        mock_expect.assert_called_with('.2 #')
        self.assertEqual(self.c._hostname, "hostname")

    # Test connection error
    @mock.patch('nocexec.drivers.base.NOCExecDriver.init_client')
    def test_error_connect(self, mock_init_client):
        self.c.cli.connect.side_effect = SSHClientError("error")
        with self.assertRaises(XOSError):
            self.c.connect()
        mock_init_client.assert_called_with()

    def test_is_error(self):
        self.assertTrue(self.c._is_error(invalid_input))
        self.assertTrue(self.c._is_error(error_input))
        self.assertFalse(self.c._is_error(normal))

    def _command_function_test(self, funct):
        self.c.cli.execute.return_value = ["l1", "l2"]
        # If the command is repeated then the counter self._cmd_num does
        # not increase
        for _ in range(3):
            self.assertEqual(funct("test"), ["l1", "l2"])
            self.c.cli.execute.assert_called_with(
                command='test', wait=['d.3 #'])
        # but if run new command, counter self._cmd_num does increase
        self.assertEqual(funct("test2"), ["l1", "l2"])
        self.c.cli.execute.assert_called_with(command='test2', wait=['d.4 #'])
        # check errors in result
        for err in [invalid_input, error_input]:
            self.c.cli.execute.return_value = err
            with self.assertRaises(XOSCommandError):
                funct("test2")
            self.c.cli.execute.assert_called_with(
                command='test2', wait=['d.4 #'])
        # execute error
        self.c.cli.execute.side_effect = SSHClientExecuteCmdError("error")
        with self.assertRaises(XOSCommandError):
            self.assertFalse(funct("test"))
        # client not initilized
        self.c.cli = None
        with self.assertRaises(XOSError):
            self.assertFalse(funct("test"))

    def test_view(self):
        self._command_function_test(self.c.view)

    def test_edit(self):
        self._command_function_test(self.c.edit)

    def test_save(self):
        call1 = mock.call(command="save configuration primary",
                          wait=["Do you want to save configuration to primary."
                                "cfg and overwrite it?"])
        call2 = mock.call(command='Yes',
                          wait=["Configuration saved to primary.cfg "
                                "successfully."])
        self.assertTrue(self.c.save())
        self.assertEqual(self.c.cli.execute.mock_calls, [call1, call2])
        # error command
        self.c.cli.execute.side_effect = SSHClientExecuteCmdError("error")
        self.assertFalse(self.c.save())
        # client is None
        self.c.cli = None
        self.assertFalse(self.c.save())


text:
<?php

declare(strict_types=1);

namespace ArrayType;

use InvalidArgumentException;
use WsdlToPhp\PackageBase\AbstractStructArrayBase;

/**
 * This class stands for ArrayOfBookingService ArrayType
 * @package Ews
 * @subpackage Arrays
 * @author WsdlToPhp <contact@wsdltophp.com>
 */
class EwsArrayOfBookingService extends AbstractStructArrayBase
{
    /**
     * The Service
     * Meta information extracted from the WSDL
     * - maxOccurs: unbounded
     * - minOccurs: 0
     * @var \StructType\EwsBookingServiceType[]
     */
    protected array $Service = [];
    /**
     * Constructor method for ArrayOfBookingService
     * @uses EwsArrayOfBookingService::setService()
     * @param \StructType\EwsBookingServiceType[] $service
     */
    public function __construct(array $service = [])
    {
        $this
            ->setService($service);
    }
    /**
     * Get Service value
     * @return \StructType\EwsBookingServiceType[]
     */
    public function getService(): array
    {
        return $this->Service;
    }
    /**
     * This method is responsible for validating the values passed to the setService method
     * This method is willingly generated in order to preserve the one-line inline validation within the setService method
     * @param array $values
     * @return string A non-empty message if the values does not match the validation rules
     */
    public static function validateServiceForArrayConstraintsFromSetService(array $values = []): string
    {
        $message = '';
        $invalidValues = [];
        foreach ($values as $arrayOfBookingServiceServiceItem) {
            // validation for constraint: itemType
            if (!$arrayOfBookingServiceServiceItem instanceof \StructType\EwsBookingServiceType) {
                $invalidValues[] = is_object($arrayOfBookingServiceServiceItem) ? get_class($arrayOfBookingServiceServiceItem) : sprintf('%s(%s)', gettype($arrayOfBookingServiceServiceItem), var_export($arrayOfBookingServiceServiceItem, true));
            }
        }
        if (!empty($invalidValues)) {
            $message = sprintf('The Service property can only contain items of type \StructType\EwsBookingServiceType, %s given', is_object($invalidValues) ? get_class($invalidValues) : (is_array($invalidValues) ? implode(', ', $invalidValues) : gettype($invalidValues)));
        }
        unset($invalidValues);

        return $message;
    }
    /**
     * Set Service value
     * @throws InvalidArgumentException
     * @param \StructType\EwsBookingServiceType[] $service
     * @return \ArrayType\EwsArrayOfBookingService
     */
    public function setService(array $service = []): self
    {
        // validation for constraint: array
        if ('' !== ($serviceArrayErrorMessage = self::validateServiceForArrayConstraintsFromSetService($service))) {
            throw new InvalidArgumentException($serviceArrayErrorMessage, __LINE__);
        }
        $this->Service = $service;

        return $this;
    }
    /**
     * Returns the current element
     * @see AbstractStructArrayBase::current()
     * @return \StructType\EwsBookingServiceType|null
     */
    public function current(): ?\StructType\EwsBookingServiceType
    {
        return parent::current();
    }
    /**
     * Returns the indexed element
     * @see AbstractStructArrayBase::item()
     * @param int $index
     * @return \StructType\EwsBookingServiceType|null
     */
    public function item($index): ?\StructType\EwsBookingServiceType
    {
        return parent::item($index);
    }
    /**
     * Returns the first element
     * @see AbstractStructArrayBase::first()
     * @return \StructType\EwsBookingServiceType|null
     */
    public function first(): ?\StructType\EwsBookingServiceType
    {
        return parent::first();
    }
    /**
     * Returns the last element
     * @see AbstractStructArrayBase::last()
     * @return \StructType\EwsBookingServiceType|null
     */
    public function last(): ?\StructType\EwsBookingServiceType
    {
        return parent::last();
    }
    /**
     * Returns the element at the offset
     * @see AbstractStructArrayBase::offsetGet()
     * @param int $offset
     * @return \StructType\EwsBookingServiceType|null
     */
    public function offsetGet($offset): ?\StructType\EwsBookingServiceType
    {
        return parent::offsetGet($offset);
    }
    /**
     * Add element to array
     * @see AbstractStructArrayBase::add()
     * @throws InvalidArgumentException
     * @param \StructType\EwsBookingServiceType $item
     * @return \ArrayType\EwsArrayOfBookingService
     */
    public function add($item): self
    {
        // validation for constraint: itemType
        if (!$item instanceof \StructType\EwsBookingServiceType) {
            throw new InvalidArgumentException(sprintf('The Service property can only contain items of type \StructType\EwsBookingServiceType, %s given', is_object($item) ? get_class($item) : (is_array($item) ? implode(', ', $item) : gettype($item))), __LINE__);
        }
        return parent::add($item);
    }
    /**
     * Returns the attribute name
     * @see AbstractStructArrayBase::getAttributeName()
     * @return string Service
     */
    public function getAttributeName(): string
    {
        return 'Service';
    }
}


text:
@interface NSArray (RiotAPI)

- (NSArray*)arrayOfObjectsWithClass:(Class)objectClass;

@end


text:
use std::fmt;
use rustc::hir;
use rustc::mir::*;
use rustc::middle::lang_items;
use rustc::traits::Reveal;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::layout::VariantIdx;
use rustc::ty::subst::Substs;
use rustc::ty::util::IntTypeExt;
use rustc_data_structures::indexed_vec::Idx;
use util::patch::MirPatch;

use std::u32;

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum DropFlagState {
    Present, // i.e., initialized
    Absent, // i.e., deinitialized or "moved"
}

impl DropFlagState {
    pub fn value(self) -> bool {
        match self {
            DropFlagState::Present => true,
            DropFlagState::Absent => false
        }
    }
}

#[derive(Debug)]
pub enum DropStyle {
    Dead,
    Static,
    Conditional,
    Open,
}

#[derive(Debug)]
pub enum DropFlagMode {
    Shallow,
    Deep
}

#[derive(Copy, Clone, Debug)]
pub enum Unwind {
    To(BasicBlock),
    InCleanup
}

impl Unwind {
    fn is_cleanup(self) -> bool {
        match self {
            Unwind::To(..) => false,
            Unwind::InCleanup => true
        }
    }

    fn into_option(self) -> Option<BasicBlock> {
        match self {
            Unwind::To(bb) => Some(bb),
            Unwind::InCleanup => None,
        }
    }

    fn map<F>(self, f: F) -> Self where F: FnOnce(BasicBlock) -> BasicBlock {
        match self {
            Unwind::To(bb) => Unwind::To(f(bb)),
            Unwind::InCleanup => Unwind::InCleanup
        }
    }
}

pub trait DropElaborator<'a, 'tcx: 'a> : fmt::Debug {
    type Path : Copy + fmt::Debug;

    fn patch(&mut self) -> &mut MirPatch<'tcx>;
    fn mir(&self) -> &'a Mir<'tcx>;
    fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx>;
    fn param_env(&self) -> ty::ParamEnv<'tcx>;

    fn drop_style(&self, path: Self::Path, mode: DropFlagMode) -> DropStyle;
    fn get_drop_flag(&mut self, path: Self::Path) -> Option<Operand<'tcx>>;
    fn clear_drop_flag(&mut self, location: Location, path: Self::Path, mode: DropFlagMode);

    fn field_subpath(&self, path: Self::Path, field: Field) -> Option<Self::Path>;
    fn deref_subpath(&self, path: Self::Path) -> Option<Self::Path>;
    fn downcast_subpath(&self, path: Self::Path, variant: VariantIdx) -> Option<Self::Path>;
    fn array_subpath(&self, path: Self::Path, index: u32, size: u32) -> Option<Self::Path>;
}

#[derive(Debug)]
struct DropCtxt<'l, 'b: 'l, 'tcx: 'b, D>
    where D : DropElaborator<'b, 'tcx> + 'l
{
    elaborator: &'l mut D,

    source_info: SourceInfo,

    place: &'l Place<'tcx>,
    path: D::Path,
    succ: BasicBlock,
    unwind: Unwind,
}

pub fn elaborate_drop<'b, 'tcx, D>(
    elaborator: &mut D,
    source_info: SourceInfo,
    place: &Place<'tcx>,
    path: D::Path,
    succ: BasicBlock,
    unwind: Unwind,
    bb: BasicBlock)
    where D: DropElaborator<'b, 'tcx>
{
    DropCtxt {
        elaborator, source_info, place, path, succ, unwind
    }.elaborate_drop(bb)
}

impl<'l, 'b, 'tcx, D> DropCtxt<'l, 'b, 'tcx, D>
    where D: DropElaborator<'b, 'tcx>
{
    fn place_ty(&self, place: &Place<'tcx>) -> Ty<'tcx> {
        place.ty(self.elaborator.mir(), self.tcx()).to_ty(self.tcx())
    }

    fn tcx(&self) -> TyCtxt<'b, 'tcx, 'tcx> {
        self.elaborator.tcx()
    }

    /// This elaborates a single drop instruction, located at `bb`, and
    /// patches over it.
    ///
    /// The elaborated drop checks the drop flags to only drop what
    /// is initialized.
    ///
    /// In addition, the relevant drop flags also need to be cleared
    /// to avoid double-drops. However, in the middle of a complex
    /// drop, one must avoid clearing some of the flags before they
    /// are read, as that would cause a memory leak.
    ///
    /// In particular, when dropping an ADT, multiple fields may be
    /// joined together under the `rest` subpath. They are all controlled
    /// by the primary drop flag, but only the last rest-field dropped
    /// should clear it (and it must also not clear anything else).
    ///
    /// FIXME: I think we should just control the flags externally
    /// and then we do not need this machinery.
    pub fn elaborate_drop<'a>(&mut self, bb: BasicBlock) {
        debug!("elaborate_drop({:?})", self);
        let style = self.elaborator.drop_style(self.path, DropFlagMode::Deep);
        debug!("elaborate_drop({:?}): live - {:?}", self, style);
        match style {
            DropStyle::Dead => {
                self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
                    target: self.succ
                });
            }
            DropStyle::Static => {
                let loc = self.terminator_loc(bb);
                self.elaborator.clear_drop_flag(loc, self.path, DropFlagMode::Deep);
                self.elaborator.patch().patch_terminator(bb, TerminatorKind::Drop {
                    location: self.place.clone(),
                    target: self.succ,
                    unwind: self.unwind.into_option(),
                });
            }
            DropStyle::Conditional => {
                let unwind = self.unwind; // FIXME(#43234)
                let succ = self.succ;
                let drop_bb = self.complete_drop(Some(DropFlagMode::Deep), succ, unwind);
                self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
                    target: drop_bb
                });
            }
            DropStyle::Open => {
                let drop_bb = self.open_drop();
                self.elaborator.patch().patch_terminator(bb, TerminatorKind::Goto {
                    target: drop_bb
                });
            }
        }
    }

    /// Return the place and move path for each field of `variant`,
    /// (the move path is `None` if the field is a rest field).
    fn move_paths_for_fields(&self,
                             base_place: &Place<'tcx>,
                             variant_path: D::Path,
                             variant: &'tcx ty::VariantDef,
                             substs: &'tcx Substs<'tcx>)
                             -> Vec<(Place<'tcx>, Option<D::Path>)>
    {
        variant.fields.iter().enumerate().map(|(i, f)| {
            let field = Field::new(i);
            let subpath = self.elaborator.field_subpath(variant_path, field);

            assert_eq!(self.elaborator.param_env().reveal, Reveal::All);
            let field_ty = self.tcx().normalize_erasing_regions(
                self.elaborator.param_env(),
                f.ty(self.tcx(), substs),
            );
            (base_place.clone().field(field, field_ty), subpath)
        }).collect()
    }

    fn drop_subpath(&mut self,
                    place: &Place<'tcx>,
                    path: Option<D::Path>,
                    succ: BasicBlock,
                    unwind: Unwind)
                    -> BasicBlock
    {
        if let Some(path) = path {
            debug!("drop_subpath: for std field {:?}", place);

            DropCtxt {
                elaborator: self.elaborator,
                source_info: self.source_info,
                path, place, succ, unwind,
            }.elaborated_drop_block()
        } else {
            debug!("drop_subpath: for rest field {:?}", place);

            DropCtxt {
                elaborator: self.elaborator,
                source_info: self.source_info,
                place, succ, unwind,
                // Using `self.path` here to condition the drop on
                // our own drop flag.
                path: self.path
            }.complete_drop(None, succ, unwind)
        }
    }

    /// Create one-half of the drop ladder for a list of fields, and return
    /// the list of steps in it in reverse order, with the first step
    /// dropping 0 fields and so on.
    ///
    /// `unwind_ladder` is such a list of steps in reverse order,
    /// which is called if the matching step of the drop glue panics.
    fn drop_halfladder(&mut self,
                       unwind_ladder: &[Unwind],
                       mut succ: BasicBlock,
                       fields: &[(Place<'tcx>, Option<D::Path>)])
                       -> Vec<BasicBlock>
    {
        Some(succ).into_iter().chain(
            fields.iter().rev().zip(unwind_ladder)
                .map(|(&(ref place, path), &unwind_succ)| {
                    succ = self.drop_subpath(place, path, succ, unwind_succ);
                    succ
                })
        ).collect()
    }

    fn drop_ladder_bottom(&mut self) -> (BasicBlock, Unwind) {
        // Clear the "master" drop flag at the end. This is needed
        // because the "master" drop protects the ADT's discriminant,
        // which is invalidated after the ADT is dropped.
        let (succ, unwind) = (self.succ, self.unwind); // FIXME(#43234)
        (
            self.drop_flag_reset_block(DropFlagMode::Shallow, succ, unwind),
            unwind.map(|unwind| {
                self.drop_flag_reset_block(DropFlagMode::Shallow, unwind, Unwind::InCleanup)
            })
        )
    }

    /// Create a full drop ladder, consisting of 2 connected half-drop-ladders
    ///
    /// For example, with 3 fields, the drop ladder is
    ///
    /// .d0:
    ///     ELAB(drop location.0 [target=.d1, unwind=.c1])
    /// .d1:
    ///     ELAB(drop location.1 [target=.d2, unwind=.c2])
    /// .d2:
    ///     ELAB(drop location.2 [target=`self.succ`, unwind=`self.unwind`])
    /// .c1:
    ///     ELAB(drop location.1 [target=.c2])
    /// .c2:
    ///     ELAB(drop location.2 [target=`self.unwind`])
    ///
    /// NOTE: this does not clear the master drop flag, so you need
    /// to point succ/unwind on a `drop_ladder_bottom`.
    fn drop_ladder<'a>(&mut self,
                       fields: Vec<(Place<'tcx>, Option<D::Path>)>,
                       succ: BasicBlock,
                       unwind: Unwind)
                       -> (BasicBlock, Unwind)
    {
        debug!("drop_ladder({:?}, {:?})", self, fields);

        let mut fields = fields;
        fields.retain(|&(ref place, _)| {
            self.place_ty(place).needs_drop(self.tcx(), self.elaborator.param_env())
        });

        debug!("drop_ladder - fields needing drop: {:?}", fields);

        let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
        let unwind_ladder: Vec<_> = if let Unwind::To(target) = unwind {
            let halfladder = self.drop_halfladder(&unwind_ladder, target, &fields);
            halfladder.into_iter().map(Unwind::To).collect()
        } else {
            unwind_ladder
        };

        let normal_ladder =
            self.drop_halfladder(&unwind_ladder, succ, &fields);

        (*normal_ladder.last().unwrap(), *unwind_ladder.last().unwrap())
    }

    fn open_drop_for_tuple<'a>(&mut self, tys: &[Ty<'tcx>])
                               -> BasicBlock
    {
        debug!("open_drop_for_tuple({:?}, {:?})", self, tys);

        let fields = tys.iter().enumerate().map(|(i, &ty)| {
            (self.place.clone().field(Field::new(i), ty),
             self.elaborator.field_subpath(self.path, Field::new(i)))
        }).collect();

        let (succ, unwind) = self.drop_ladder_bottom();
        self.drop_ladder(fields, succ, unwind).0
    }

    fn open_drop_for_box<'a>(&mut self, adt: &'tcx ty::AdtDef, substs: &'tcx Substs<'tcx>)
                             -> BasicBlock
    {
        debug!("open_drop_for_box({:?}, {:?}, {:?})", self, adt, substs);

        let interior = self.place.clone().deref();
        let interior_path = self.elaborator.deref_subpath(self.path);

        let succ = self.succ; // FIXME(#43234)
        let unwind = self.unwind;
        let succ = self.box_free_block(adt, substs, succ, unwind);
        let unwind_succ = self.unwind.map(|unwind| {
            self.box_free_block(adt, substs, unwind, Unwind::InCleanup)
        });

        self.drop_subpath(&interior, interior_path, succ, unwind_succ)
    }

    fn open_drop_for_adt<'a>(&mut self, adt: &'tcx ty::AdtDef, substs: &'tcx Substs<'tcx>)
                             -> BasicBlock {
        debug!("open_drop_for_adt({:?}, {:?}, {:?})", self, adt, substs);
        if adt.variants.len() == 0 {
            return self.elaborator.patch().new_block(BasicBlockData {
                statements: vec![],
                terminator: Some(Terminator {
                    source_info: self.source_info,
                    kind: TerminatorKind::Unreachable
                }),
                is_cleanup: self.unwind.is_cleanup()
            });
        }

        let skip_contents =
            adt.is_union() || Some(adt.did) == self.tcx().lang_items().manually_drop();
        let contents_drop = if skip_contents {
            (self.succ, self.unwind)
        } else {
            self.open_drop_for_adt_contents(adt, substs)
        };

        if adt.has_dtor(self.tcx()) {
            self.destructor_call_block(contents_drop)
        } else {
            contents_drop.0
        }
    }

    fn open_drop_for_adt_contents(&mut self, adt: &'tcx ty::AdtDef,
                                  substs: &'tcx Substs<'tcx>)
                                  -> (BasicBlock, Unwind) {
        let (succ, unwind) = self.drop_ladder_bottom();
        if !adt.is_enum() {
            let fields = self.move_paths_for_fields(
                self.place,
                self.path,
                &adt.variants[VariantIdx::new(0)],
                substs
            );
            self.drop_ladder(fields, succ, unwind)
        } else {
            self.open_drop_for_multivariant(adt, substs, succ, unwind)
        }
    }

    fn open_drop_for_multivariant(&mut self, adt: &'tcx ty::AdtDef,
                                  substs: &'tcx Substs<'tcx>,
                                  succ: BasicBlock,
                                  unwind: Unwind)
                                  -> (BasicBlock, Unwind) {
        let mut values = Vec::with_capacity(adt.variants.len());
        let mut normal_blocks = Vec::with_capacity(adt.variants.len());
        let mut unwind_blocks = if unwind.is_cleanup() {
            None
        } else {
            Some(Vec::with_capacity(adt.variants.len()))
        };

        let mut have_otherwise = false;

        for (variant_index, discr) in adt.discriminants(self.tcx()) {
            let subpath = self.elaborator.downcast_subpath(
                self.path, variant_index);
            if let Some(variant_path) = subpath {
                let base_place = self.place.clone().elem(
                    ProjectionElem::Downcast(adt, variant_index)
                        );
                let fields = self.move_paths_for_fields(
                    &base_place,
                    variant_path,
                    &adt.variants[variant_index],
                    substs);
                values.push(discr.val);
                if let Unwind::To(unwind) = unwind {
                    // We can't use the half-ladder from the original
                    // drop ladder, because this breaks the
                    // "funclet can't have 2 successor funclets"
                    // requirement from MSVC:
                    //
                    //           switch       unwind-switch
                    //          /      \         /        \
                    //         v1.0    v2.0  v2.0-unwind  v1.0-unwind
                    //         |        |      /             |
                    //    v1.1-unwind  v2.1-unwind           |
                    //      ^                                |
                    //       \-------------------------------/
                    //
                    // Create a duplicate half-ladder to avoid that. We
                    // could technically only do this on MSVC, but I
                    // I want to minimize the divergence between MSVC
                    // and non-MSVC.

                    let unwind_blocks = unwind_blocks.as_mut().unwrap();
                    let unwind_ladder = vec![Unwind::InCleanup; fields.len() + 1];
                    let halfladder =
                        self.drop_halfladder(&unwind_ladder, unwind, &fields);
                    unwind_blocks.push(halfladder.last().cloned().unwrap());
                }
                let (normal, _) = self.drop_ladder(fields, succ, unwind);
                normal_blocks.push(normal);
            } else {
                have_otherwise = true;
            }
        }

        if have_otherwise {
            normal_blocks.push(self.drop_block(succ, unwind));
            if let Unwind::To(unwind) = unwind {
                unwind_blocks.as_mut().unwrap().push(
                    self.drop_block(unwind, Unwind::InCleanup)
                        );
            }
        } else {
            values.pop();
        }

        (self.adt_switch_block(adt, normal_blocks, &values, succ, unwind),
         unwind.map(|unwind| {
             self.adt_switch_block(
                 adt, unwind_blocks.unwrap(), &values, unwind, Unwind::InCleanup
             )
         }))
    }

    fn adt_switch_block(&mut self,
                        adt: &'tcx ty::AdtDef,
                        blocks: Vec<BasicBlock>,
                        values: &[u128],
                        succ: BasicBlock,
                        unwind: Unwind)
                        -> BasicBlock {
        // If there are multiple variants, then if something
        // is present within the enum the discriminant, tracked
        // by the rest path, must be initialized.
        //
        // Additionally, we do not want to switch on the
        // discriminant after it is free-ed, because that
        // way lies only trouble.
        let discr_ty = adt.repr.discr_type().to_ty(self.tcx());
        let discr = Place::Local(self.new_temp(discr_ty));
        let discr_rv = Rvalue::Discriminant(self.place.clone());
        let switch_block = BasicBlockData {
            statements: vec![self.assign(&discr, discr_rv)],
            terminator: Some(Terminator {
                source_info: self.source_info,
                kind: TerminatorKind::SwitchInt {
                    discr: Operand::Move(discr),
                    switch_ty: discr_ty,
                    values: From::from(values.to_owned()),
                    targets: blocks,
                }
            }),
            is_cleanup: unwind.is_cleanup(),
        };
        let switch_block = self.elaborator.patch().new_block(switch_block);
        self.drop_flag_test_block(switch_block, succ, unwind)
    }

    fn destructor_call_block<'a>(&mut self, (succ, unwind): (BasicBlock, Unwind))
                                 -> BasicBlock
    {
        debug!("destructor_call_block({:?}, {:?})", self, succ);
        let tcx = self.tcx();
        let drop_trait = tcx.lang_items().drop_trait().unwrap();
        let drop_fn = tcx.associated_items(drop_trait).next().unwrap();
        let ty = self.place_ty(self.place);
        let substs = tcx.mk_substs_trait(ty, &[]);

        let ref_ty = tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
            ty,
            mutbl: hir::Mutability::MutMutable
        });
        let ref_place = self.new_temp(ref_ty);
        let unit_temp = Place::Local(self.new_temp(tcx.mk_unit()));

        let result = BasicBlockData {
            statements: vec![self.assign(
                &Place::Local(ref_place),
                Rvalue::Ref(tcx.types.re_erased,
                            BorrowKind::Mut { allow_two_phase_borrow: false },
                            self.place.clone())
            )],
            terminator: Some(Terminator {
                kind: TerminatorKind::Call {
                    func: Operand::function_handle(tcx, drop_fn.def_id, substs,
                                                   self.source_info.span),
                    args: vec![Operand::Move(Place::Local(ref_place))],
                    destination: Some((unit_temp, succ)),
                    cleanup: unwind.into_option(),
                    from_hir_call: true,
                },
                source_info: self.source_info,
            }),
            is_cleanup: unwind.is_cleanup(),
        };
        self.elaborator.patch().new_block(result)
    }

    /// create a loop that drops an array:
    ///

    ///
    /// loop-block:
    ///    can_go = cur == length_or_end
    ///    if can_go then succ else drop-block
    /// drop-block:
    ///    if ptr_based {
    ///        ptr = &mut *cur
    ///        cur = cur.offset(1)
    ///    } else {
    ///        ptr = &mut P[cur]
    ///        cur = cur + 1
    ///    }
    ///    drop(ptr)
    fn drop_loop(&mut self,
                 succ: BasicBlock,
                 cur: Local,
                 length_or_end: &Place<'tcx>,
                 ety: Ty<'tcx>,
                 unwind: Unwind,
                 ptr_based: bool)
                 -> BasicBlock
    {
        let copy = |place: &Place<'tcx>| Operand::Copy(place.clone());
        let move_ = |place: &Place<'tcx>| Operand::Move(place.clone());
        let tcx = self.tcx();

        let ref_ty = tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
            ty: ety,
            mutbl: hir::Mutability::MutMutable
        });
        let ptr = &Place::Local(self.new_temp(ref_ty));
        let can_go = &Place::Local(self.new_temp(tcx.types.bool));

        let one = self.constant_usize(1);
        let (ptr_next, cur_next) = if ptr_based {
            (Rvalue::Ref(
                tcx.types.re_erased,
                BorrowKind::Mut { allow_two_phase_borrow: false },
                Place::Projection(Box::new(Projection {
                    base: Place::Local(cur),
                    elem: ProjectionElem::Deref,
                }))
             ),
             Rvalue::BinaryOp(BinOp::Offset, copy(&Place::Local(cur)), one))
        } else {
            (Rvalue::Ref(
                 tcx.types.re_erased,
                 BorrowKind::Mut { allow_two_phase_borrow: false },
                 self.place.clone().index(cur)),
             Rvalue::BinaryOp(BinOp::Add, copy(&Place::Local(cur)), one))
        };

        let drop_block = BasicBlockData {
            statements: vec![
                self.assign(ptr, ptr_next),
                self.assign(&Place::Local(cur), cur_next)
            ],
            is_cleanup: unwind.is_cleanup(),
            terminator: Some(Terminator {
                source_info: self.source_info,
                // this gets overwritten by drop elaboration.
                kind: TerminatorKind::Unreachable,
            })
        };
        let drop_block = self.elaborator.patch().new_block(drop_block);

        let loop_block = BasicBlockData {
            statements: vec![
                self.assign(can_go, Rvalue::BinaryOp(BinOp::Eq,
                                                     copy(&Place::Local(cur)),
                                                     copy(length_or_end)))
            ],
            is_cleanup: unwind.is_cleanup(),
            terminator: Some(Terminator {
                source_info: self.source_info,
                kind: TerminatorKind::if_(tcx, move_(can_go), succ, drop_block)
            })
        };
        let loop_block = self.elaborator.patch().new_block(loop_block);

        self.elaborator.patch().patch_terminator(drop_block, TerminatorKind::Drop {
            location: ptr.clone().deref(),
            target: loop_block,
            unwind: unwind.into_option()
        });

        loop_block
    }

    fn open_drop_for_array(&mut self, ety: Ty<'tcx>, opt_size: Option<u64>) -> BasicBlock {
        debug!("open_drop_for_array({:?}, {:?})", ety, opt_size);

        // if size_of::<ety>() == 0 {
        //     index_based_loop
        // } else {
        //     ptr_based_loop
        // }

        if let Some(size) = opt_size {
            assert!(size <= (u32::MAX as u64),
                    "move out check doesn't implemented for array bigger then u32");
            let size = size as u32;
            let fields: Vec<(Place<'tcx>, Option<D::Path>)> = (0..size).map(|i| {
                (self.place.clone().elem(ProjectionElem::ConstantIndex{
                    offset: i,
                    min_length: size,
                    from_end: false
                }),
                 self.elaborator.array_subpath(self.path, i, size))
            }).collect();

            if fields.iter().any(|(_,path)| path.is_some()) {
                let (succ, unwind) = self.drop_ladder_bottom();
                return self.drop_ladder(fields, succ, unwind).0
            }
        }

        let move_ = |place: &Place<'tcx>| Operand::Move(place.clone());
        let tcx = self.tcx();
        let size = &Place::Local(self.new_temp(tcx.types.usize));
        let size_is_zero = &Place::Local(self.new_temp(tcx.types.bool));
        let base_block = BasicBlockData {
            statements: vec![
                self.assign(size, Rvalue::NullaryOp(NullOp::SizeOf, ety)),
                self.assign(size_is_zero, Rvalue::BinaryOp(BinOp::Eq,
                                                           move_(size),
                                                           self.constant_usize(0)))
            ],
            is_cleanup: self.unwind.is_cleanup(),
            terminator: Some(Terminator {
                source_info: self.source_info,
                kind: TerminatorKind::if_(
                    tcx,
                    move_(size_is_zero),
                    self.drop_loop_pair(ety, false),
                    self.drop_loop_pair(ety, true)
                )
            })
        };
        self.elaborator.patch().new_block(base_block)
    }

    // create a pair of drop-loops of `place`, which drops its contents
    // even in the case of 1 panic. If `ptr_based`, create a pointer loop,
    // otherwise create an index loop.
    fn drop_loop_pair(&mut self, ety: Ty<'tcx>, ptr_based: bool) -> BasicBlock {
        debug!("drop_loop_pair({:?}, {:?})", ety, ptr_based);
        let tcx = self.tcx();
        let iter_ty = if ptr_based {
            tcx.mk_mut_ptr(ety)
        } else {
            tcx.types.usize
        };

        let cur = self.new_temp(iter_ty);
        let length = Place::Local(self.new_temp(tcx.types.usize));
        let length_or_end = if ptr_based {
            Place::Local(self.new_temp(iter_ty))
        } else {
            length.clone()
        };

        let unwind = self.unwind.map(|unwind| {
            self.drop_loop(unwind,
                           cur,
                           &length_or_end,
                           ety,
                           Unwind::InCleanup,
                           ptr_based)
        });

        let succ = self.succ; // FIXME(#43234)
        let loop_block = self.drop_loop(
            succ,
            cur,
            &length_or_end,
            ety,
            unwind,
            ptr_based);

        let cur = Place::Local(cur);
        let zero = self.constant_usize(0);
        let mut drop_block_stmts = vec![];
        drop_block_stmts.push(self.assign(&length, Rvalue::Len(self.place.clone())));
        if ptr_based {
            let tmp_ty = tcx.mk_mut_ptr(self.place_ty(self.place));
            let tmp = Place::Local(self.new_temp(tmp_ty));
            // tmp = &mut P;
            // cur = tmp as *mut T;
            // end = Offset(cur, len);
            drop_block_stmts.push(self.assign(&tmp, Rvalue::Ref(
                tcx.types.re_erased,
                BorrowKind::Mut { allow_two_phase_borrow: false },
                self.place.clone()
            )));
            drop_block_stmts.push(self.assign(&cur, Rvalue::Cast(
                CastKind::Misc, Operand::Move(tmp), iter_ty
            )));
            drop_block_stmts.push(self.assign(&length_or_end,
                Rvalue::BinaryOp(BinOp::Offset,
                     Operand::Copy(cur), Operand::Move(length)
            )));
        } else {
            // index = 0 (length already pushed)
            drop_block_stmts.push(self.assign(&cur, Rvalue::Use(zero)));
        }
        let drop_block = self.elaborator.patch().new_block(BasicBlockData {
            statements: drop_block_stmts,
            is_cleanup: unwind.is_cleanup(),
            terminator: Some(Terminator {
                source_info: self.source_info,
                kind: TerminatorKind::Goto { target: loop_block }
            })
        });

        // FIXME(#34708): handle partially-dropped array/slice elements.
        let reset_block = self.drop_flag_reset_block(DropFlagMode::Deep, drop_block, unwind);
        self.drop_flag_test_block(reset_block, succ, unwind)
    }

    /// The slow-path - create an "open", elaborated drop for a type
    /// which is moved-out-of only partially, and patch `bb` to a jump
    /// to it. This must not be called on ADTs with a destructor,
    /// as these can't be moved-out-of, except for `Box<T>`, which is
    /// special-cased.
    ///
    /// This creates a "drop ladder" that drops the needed fields of the
    /// ADT, both in the success case or if one of the destructors fail.
    fn open_drop<'a>(&mut self) -> BasicBlock {
        let ty = self.place_ty(self.place);
        match ty.sty {
            ty::Closure(def_id, substs) => {
                let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
                self.open_drop_for_tuple(&tys)
            }
            // Note that `elaborate_drops` only drops the upvars of a generator,
            // and this is ok because `open_drop` here can only be reached
            // within that own generator's resume function.
            // This should only happen for the self argument on the resume function.
            // It effetively only contains upvars until the generator transformation runs.
            // See librustc_mir/transform/generator.rs for more details.
            ty::Generator(def_id, substs, _) => {
                let tys : Vec<_> = substs.upvar_tys(def_id, self.tcx()).collect();
                self.open_drop_for_tuple(&tys)
            }
            ty::Tuple(tys) => {
                self.open_drop_for_tuple(tys)
            }
            ty::Adt(def, substs) => {
                if def.is_box() {
                    self.open_drop_for_box(def, substs)
                } else {
                    self.open_drop_for_adt(def, substs)
                }
            }
            ty::Dynamic(..) => {
                let unwind = self.unwind; // FIXME(#43234)
                let succ = self.succ;
                self.complete_drop(Some(DropFlagMode::Deep), succ, unwind)
            }
            ty::Array(ety, size) => {
                let size = size.assert_usize(self.tcx());
                self.open_drop_for_array(ety, size)
            },
            ty::Slice(ety) => self.open_drop_for_array(ety, None),

            _ => bug!("open drop from non-ADT `{:?}`", ty)
        }
    }

    /// Return a basic block that drop a place using the context
    /// and path in `c`. If `mode` is something, also clear `c`
    /// according to it.
    ///
    /// if FLAG(self.path)
    ///     if let Some(mode) = mode: FLAG(self.path)[mode] = false
    ///     drop(self.place)
    fn complete_drop<'a>(&mut self,
                         drop_mode: Option<DropFlagMode>,
                         succ: BasicBlock,
                         unwind: Unwind) -> BasicBlock
    {
        debug!("complete_drop({:?},{:?})", self, drop_mode);

        let drop_block = self.drop_block(succ, unwind);
        let drop_block = if let Some(mode) = drop_mode {
            self.drop_flag_reset_block(mode, drop_block, unwind)
        } else {
            drop_block
        };

        self.drop_flag_test_block(drop_block, succ, unwind)
    }

    fn drop_flag_reset_block(&mut self,
                             mode: DropFlagMode,
                             succ: BasicBlock,
                             unwind: Unwind) -> BasicBlock
    {
        debug!("drop_flag_reset_block({:?},{:?})", self, mode);

        let block = self.new_block(unwind, TerminatorKind::Goto { target: succ });
        let block_start = Location { block: block, statement_index: 0 };
        self.elaborator.clear_drop_flag(block_start, self.path, mode);
        block
    }

    fn elaborated_drop_block<'a>(&mut self) -> BasicBlock {
        debug!("elaborated_drop_block({:?})", self);
        let unwind = self.unwind; // FIXME(#43234)
        let succ = self.succ;
        let blk = self.drop_block(succ, unwind);
        self.elaborate_drop(blk);
        blk
    }

    fn box_free_block<'a>(
        &mut self,
        adt: &'tcx ty::AdtDef,
        substs: &'tcx Substs<'tcx>,
        target: BasicBlock,
        unwind: Unwind,
    ) -> BasicBlock {
        let block = self.unelaborated_free_block(adt, substs, target, unwind);
        self.drop_flag_test_block(block, target, unwind)
    }

    fn unelaborated_free_block<'a>(
        &mut self,
        adt: &'tcx ty::AdtDef,
        substs: &'tcx Substs<'tcx>,
        target: BasicBlock,
        unwind: Unwind
    ) -> BasicBlock {
        let tcx = self.tcx();
        let unit_temp = Place::Local(self.new_temp(tcx.mk_unit()));
        let free_func = tcx.require_lang_item(lang_items::BoxFreeFnLangItem);
        let args = adt.variants[VariantIdx::new(0)].fields.iter().enumerate().map(|(i, f)| {
            let field = Field::new(i);
            let field_ty = f.ty(self.tcx(), substs);
            Operand::Move(self.place.clone().field(field, field_ty))
        }).collect();

        let call = TerminatorKind::Call {
            func: Operand::function_handle(tcx, free_func, substs, self.source_info.span),
            args: args,
            destination: Some((unit_temp, target)),
            cleanup: None,
            from_hir_call: false,
        }; // FIXME(#43234)
        let free_block = self.new_block(unwind, call);

        let block_start = Location { block: free_block, statement_index: 0 };
        self.elaborator.clear_drop_flag(block_start, self.path, DropFlagMode::Shallow);
        free_block
    }

    fn drop_block<'a>(&mut self, target: BasicBlock, unwind: Unwind) -> BasicBlock {
        let block = TerminatorKind::Drop {
            location: self.place.clone(),
            target,
            unwind: unwind.into_option()
        };
        self.new_block(unwind, block)
    }

    fn drop_flag_test_block(&mut self,
                            on_set: BasicBlock,
                            on_unset: BasicBlock,
                            unwind: Unwind)
                            -> BasicBlock
    {
        let style = self.elaborator.drop_style(self.path, DropFlagMode::Shallow);
        debug!("drop_flag_test_block({:?},{:?},{:?},{:?}) - {:?}",
               self, on_set, on_unset, unwind, style);

        match style {
            DropStyle::Dead => on_unset,
            DropStyle::Static => on_set,
            DropStyle::Conditional | DropStyle::Open => {
                let flag = self.elaborator.get_drop_flag(self.path).unwrap();
                let term = TerminatorKind::if_(self.tcx(), flag, on_set, on_unset);
                self.new_block(unwind, term)
            }
        }
    }

    fn new_block<'a>(&mut self,
                     unwind: Unwind,
                     k: TerminatorKind<'tcx>)
                     -> BasicBlock
    {
        self.elaborator.patch().new_block(BasicBlockData {
            statements: vec![],
            terminator: Some(Terminator {
                source_info: self.source_info, kind: k
            }),
            is_cleanup: unwind.is_cleanup()
        })
    }

    fn new_temp(&mut self, ty: Ty<'tcx>) -> Local {
        self.elaborator.patch().new_temp(ty, self.source_info.span)
    }

    fn terminator_loc(&mut self, bb: BasicBlock) -> Location {
        let mir = self.elaborator.mir();
        self.elaborator.patch().terminator_loc(mir, bb)
    }

    fn constant_usize(&self, val: u16) -> Operand<'tcx> {
        Operand::Constant(box Constant {
            span: self.source_info.span,
            ty: self.tcx().types.usize,
            user_ty: None,
            literal: ty::Const::from_usize(self.tcx(), val.into()),
        })
    }

    fn assign(&self, lhs: &Place<'tcx>, rhs: Rvalue<'tcx>) -> Statement<'tcx> {
        Statement {
            source_info: self.source_info,
            kind: StatementKind::Assign(lhs.clone(), box rhs)
        }
    }
}


text:
package co.polarr.demo.autoenhance;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onBtnClick(View view) {
        switch (view.getId()) {
            case R.id.camera_btn:
                startActivity(new Intent(this, CameraActivity.class));

                break;
            case R.id.photo_btn: {
                startActivity(new Intent(this, PhotoDemoActivity.class));

                break;
            }
        }
    }
}


text:
package com.example.thmonitor.thread;

/**
 * Created by Administrator on 2017/4/24.
 */

public class sendThread implements Runnable {

    public void run() {
        while (true) {
            try {
                Thread.sleep(1000 * 60);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}


text:
module JsonValidation
  module Validators
    class MinProperties < Validator
      type :object

      def validate(value, value_path)
        schema['minProperties'] <= value.size
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns="http://kefirsf.org/kefirbb/schema"
               xsi:schemaLocation="http://kefirsf.org/kefirbb/schema http://kefirsf.org/kefirbb/schema/kefirbb-1.0.xsd">

    <scope name="escapeXml">

            <pattern>&</pattern>
            <template>&amp;</template>

            <pattern>'</pattern>
            <template>&apos;</template>

            <pattern><</pattern>
            <template>&lt;</template>

            <pattern>></pattern>
            <template>&gt;</template>

            <pattern>"</pattern>
            <template>&quot;</template>

    </scope>

    <scope name="basic" parent="escapeXml">

            <pattern>

</pattern>
            <template><br/></template>

            <pattern>
</pattern>
            <template><br/></template>

            <pattern>
</pattern>
            <template><br/></template>

            <pattern>
</pattern>
            <template><br/></template>

    </scope>

    <scope name="ROOT" parent="basic">

        <coderef name="bold"/>
        <coderef name="u"/>
        <coderef name="s"/>
        <coderef name="i"/>
    </scope>

        <pattern ignoreCase="true">*<var inherit="true"/>*</pattern>
        <template><b><var/></b></template>

        <pattern ignoreCase="true">+<var inherit="true"/>+</pattern>
        <template><u><var/></u></template>

        <pattern ignoreCase="true">-<var inherit="true"/>-</pattern>
        <template><s><var/></s></template>

        <pattern ignoreCase="true">_<var inherit="true"/>_</pattern>
        <template><i><var/></i></template>

</configuration>


text:
from itertools import combinations

from holoviews.core.options import Store, Options

def option_intersections(backend):
    intersections = []
    options = Store.options(backend)
    for k, opts in sorted(options.items()):
        if len(k) > 1: continue
        valid_options = {k: set(o.allowed_keywords)
                         for k, o in opts.groups.items()}
        for g1, g2 in combinations(Options._option_groups, 2):
            intersection = valid_options[g1] & valid_options[g2]
            if intersection:
                intersections.append((k, intersection))
    return intersections


text:
yarn install

cd semantic
gulp build-css
gulp build-assets
cd ../

echo "export class Settings {
    public static RECAPTCHA_KEY: string = \"$BOTBOX_RECAPTCHA_SITEKEY\";
    public static API_BASE_URL: string = \"$BOTBOX_DOMAIN_NAME/api/\";
}" > app/settings.ts

webpack --config=webpack.prod.config.js

docker build -t botbox-web:$BOTBOX_VERSION .


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

class Dashboard_Model extends CI_Model{

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

    public function get_active_room_count()
    {
        $query = "SELECT count(id) as count FROM room_details WHERE status='active'";
        $result = $this->db->query($query);
        $result = $result->result();
        return $result[0]->count;
    }

    public function get_active_computer_count()
    {
        $query = "SELECT count(id) as count FROM computer_details WHERE status != 'Out of service'";
        $result = $this->db->query($query);
        $result = $result->result();
        return $result[0]->count;
    }

    public function get_open_issue_count()
    {
        $query = "SELECT count(id) as count FROM issues WHERE status='open'";
        $result = $this->db->query($query);
        $result = $result->result();
        return $result[0]->count;
    }

    public function get_inventory_item_count()
    {
        $query = "SELECT SUM(available) as count FROM inventory_details";
        $result = $this->db->query($query);
        $result = $result->result();
        return $result[0]->count;
    }

    public function get_recent_issues()
    {
        $this->db->where('status', 'open');
        $result = $this->db->get('issues', 5, 0);
        return $result->result();
    }

    public function opened_issues_by_date()
    {
        $query = "SELECT opened_date, count(id) AS count FROM issues GROUP BY opened_date";
        $result = $this->db->query($query);
        return $result->result();
    }

    public function closed_issues_by_date()
    {
        $query = "SELECT closed_date, count(id) AS count FROM issues GROUP BY closed_date";
        $result = $this->db->query($query);
        return $result->result();
    }

    public function computers_with_most_issues()
    {
        $query = "SELECT computer_code, count(id) as count FROM `issue_history` GROUP BY computer_code ORDER BY count DESC LIMIT 10 ";
        $result = $this->db->query($query);
        return $result->result();
    }
}


text:
package auth

import (
	"testing"
	"time"
	"github.com/sirupsen/logrus"
	"os"
	"strings"
)

func TestMain(m *testing.M) {
	logrus.SetLevel(logrus.DebugLevel)
	os.Exit(m.Run())
}

func TestValidJwt(t *testing.T) {
	origUserId := "Bob"
	token, err := GenerateJwt(origUserId, 1 * time.Second)
	if err != nil {
		t.Fatal(err)
	}
	userId, err := ValidateJwt(token)
	if err != nil {
		t.Fatal(err)
	}
	if userId != origUserId {
		t.Fatalf("UserId %s should be %s", userId, origUserId)
	}
}

func TestNoExpirationJwt(t *testing.T) {
	origUserId := "Alice"
	token, err := GenerateJwt(origUserId, 0)
	if err != nil {
		t.Fatal(err)
	}
	userId, err := ValidateJwt(token)
	if err != nil {
		t.Fatal(err)
	}
	if userId != origUserId {
		t.Fatalf("UserId %s should be %s", userId, origUserId)
	}
}

func TestExpirationJwt(t *testing.T) {
	origUserId := "Bob"
	token, err := GenerateJwt(origUserId, 1 * time.Second)
	if err != nil {
		t.Fatal(err)
	}
	time.Sleep(2 * time.Second)
	_, err = ValidateJwt(token)
	if err == nil || !strings.Contains(err.Error(), "expired") {
		t.Fatalf("The token should be expired")
	}
}


text:
var mongoose = require('mongoose');
    // bcrypt   = require('bcrypt-nodejs'),
    // Q        = require('q'),
    // SALT_WORK_FACTOR  = 10;

var UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },

  password: {
    type: String,
    required: true
  },
  // salt: String
});

//***authentication commented out until we reach that feature***

// UserSchema.methods.comparePasswords = function (candidatePassword) {
//   var defer = Q.defer();
//   var savedPassword = this.password;
//   bcrypt.compare(candidatePassword, savedPassword, function (err, isMatch) {
//     if (err) {
//       defer.reject(err);
//     } else {
//       defer.resolve(isMatch);
//     }
//   });
//   return defer.promise;
// };

// UserSchema.pre('save', function (next) {
//   var user = this;

//   // only hash the password if it has been modified (or is new)
//   if (!user.isModified('password')) {
//     return next();
//   }

//   // generate a salt
//   bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
//     if (err) {
//       return next(err);
//     }

//     // hash the password along with our new salt
//     bcrypt.hash(user.password, salt, null, function(err, hash) {
//       if (err) {
//         return next(err);
//       }

//       // override the cleartext password with the hashed one
//       user.password = hash;
//       user.salt = salt;
//       next();
//     });
//   });
// });

module.exports = mongoose.model('users', UserSchema);


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class net.sourceforge.pmd.lang.java.rule.optimizations.AbstractOptimizationRule (PMD Java 5.2.2 API)</title>
<meta name="date" content="2014-12-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
net.sourceforge.pmd.lang.java.rule.optimizations.AbstractOptimizationRule

Packages that use AbstractOptimizationRule

Package
Description

net.sourceforge.pmd.lang.java.rule.logging

net.sourceforge.pmd.lang.java.rule.optimizations

Uses of AbstractOptimizationRule in net.sourceforge.pmd.lang.java.rule.logging

Subclasses of AbstractOptimizationRule in net.sourceforge.pmd.lang.java.rule.logging

Modifier and Type
Class and Description

class
GuardDebugLoggingRule

class
GuardLogStatementJavaUtilRule

class
GuardLogStatementRule

Check that log.debug, log.trace, log.error, etc...

Uses of AbstractOptimizationRule in net.sourceforge.pmd.lang.java.rule.optimizations

Subclasses of AbstractOptimizationRule in net.sourceforge.pmd.lang.java.rule.optimizations

Modifier and Type
Class and Description

class
AvoidInstantiatingObjectsInLoopsRule

class
LocalVariableCouldBeFinalRule

class
MethodArgumentCouldBeFinalRule

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2002–2014 InfoEther. All rights reserved.


text:
jQuery( function( $ ){

	var getVideoEmbed = function( videoId ) {
		return '<iframe src="https://player.vimeo.com/video/' +
			encodeURI( videoId ) +
			'?autoplay=1&title=0&byline=0&portrait=0" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
	};

	$('body').on( 'click', 'a[href^="#siteorigin-learn-"]', function( e ) {
		var $$ = $(this);
		var lessonId = $$.attr( 'href' ).replace( '#siteorigin-learn-', '' );
		if( lessonId && soLearn.lessons.hasOwnProperty( lessonId ) ) {
			e.preventDefault();
			var lesson = soLearn.lessons[ lessonId ];

			$( '#siteorigin-learn' ).show();
			var dialog = $( '#siteorigin-learn-dialog' );

			// Add all the data
			dialog
				.find( '.video-iframe' ).hide().end()
				.find( '.poster-wrapper' ).data( 'video', lesson.video ).end()
				.find( '.video-title' ).html( lesson.title ).end()
				.find( '.main-poster' ).hide().attr( 'src', lesson.poster ).show( ).end()
				.find( '.learn-description' ).html( lesson.description ).end()
				.find( '.form-description' ).html( lesson.form_description ).end()
				.find( 'input[name="lesson_id"]' ).val( lessonId ).end()
				.css({
					'margin-top': - dialog.outerHeight() / 2,
					'margin-left': - dialog.outerWidth() / 2,
				});
		}
	} );

	$('body').on( 'mouseover', 'a[href^="#siteorigin-learn-"]', function( e ) {
		// Only do this if the dialog is hidden
		if( $( '#siteorigin-learn' ).is( ':visible' ) ) return;

		var $$ = $(this);
		var lessonId = $$.attr( 'href' ).replace( '#siteorigin-learn-', '' );
		if( lessonId && soLearn.lessons.hasOwnProperty( lessonId ) ) {
			// This preloads the image.
			$( '#siteorigin-learn-dialog .main-poster' ).attr( 'src', soLearn.lessons[ lessonId ].poster );
		}
	} );

	// General actions of the dialog
	$( '#siteorigin-learn-overlay' ).add( '#siteorigin-learn .learn-close' ).click( function(){
		$( '#siteorigin-learn' )
			.hide()
			.find( '.video-iframe' ).empty().hide().end()
			.find( '.poster-wrapper' ).show();
	} );

	$( '#siteorigin-learn form' ).submit( function( e ){
		var $$ = $( this );

		// Check the content
		var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		var email = $$.find( 'input[name="email"]' );

		if( email.val() === '' || ! re.test( email.val() ) ) {
			e.preventDefault();
			alert( $$.data( 'email-error' ) );
			return;
		}

		$( '#siteorigin-learn .learn-close' ).click();
	} );

	$( '#siteorigin-learn' ).find( '.main-poster, .play-button, .video-play-info, .video-play-info-text' ).click( function(){
		$( '#siteorigin-learn' )
			.find( '.poster-wrapper' ).hide().end()
			.find( '.video-iframe' ).show().html( getVideoEmbed( $( '#siteorigin-learn .poster-wrapper' ).data( 'video' ) ) );
	} );

    $(document).keyup(function(e) {
		// when escape is pressed
		if ( e.keyCode === 27 && $( '#siteorigin-learn-overlay' ).is( ':visible' ) ) {
			e.preventDefault();
			$( '#siteorigin-learn .learn-close' ).click();
		}
    });
} );


text:
package org.txazo.designpattern.behavior.mediator;

/**
 * Tenant - 租客
 */
public class Tenant extends Customer {

    public Tenant(String name, RealEstateMediator mediator) {
        super(name, mediator);
        mediator.setTenant(this);
    }

    public void intendRent(String description) {
        mediator.sendMessage(description, this);
    }

}


text:
layout: page
title: 'RecordService Overview'
---

RecordService provides an abstraction layer between compute frameworks and data storage. It provides row- and column-level security, and other advantages as well.

## The Impetus

The Sentry community considered how to enforce a common set of column-level authorization permissions across Hadoop. Building Sentry support into each Hadoop component as well as various applications that interact with Hadoop would require massive effort and continual maintenance.

Instead, the community conceived the idea of a common API for accessing tabular data as _records_ — a unified data access path that can be used by multiple Hadoop components and applications with minimal code changes.

![Unified Data Access Path](img/unifiedDataAccessPath.png){:height="85%" width="85%"}

## The Benefits
* RecordService provides fine-grained data permissions and enforcement across Hadoop.
* Clients work independent of on-disk storage format.
* The unified data access path provides a single place to implement and test file format-related changes.
* Components swap transparently above or below RecordService.
* Performance is boosted via Impala's optimized scanner, dynamic code generation, and parquet implementation.
* Existing MapReduce and Spark jobs gain Impala-quality performance.
* Make projections over original source datasets instead of making copies/subsets.

## The Design
RecordService provides the following services.

* RecordServicePlanner — Generates tasks, performs authorization checks, handles metadata access. Called during input split generation.
* RecordServiceWorker — Executes tasks, reads and writes to the storage layer.
    * Builds on Impala's highly optimized I/O scheduler and file parsers.
    * Returns rows in a canonical format.
* Thrift APIs.
* Client Integration Libraries — Allow easy migration to RecordService.

![Record Service Architecture Overview ](img/RecordServiceArchitectureOverview.png){:height="85%" width="85%"}

[morphlines-intro]: {{site.baseurl}}/morphlines/


text:
import * as aws from 'aws-sdk';
import * as cli from 'cli-color';
import * as dateformat from 'dateformat';
import * as _ from 'lodash';
import {sprintf} from 'sprintf-js';
import {FAILURE, SUCCESS} from '../statusCodes';
import {COMPLETE, FAILED, IN_PROGRESS, SKIPPED} from './statusTypes';

export const COLUMN2_START = 25;
export const DEFAULT_STATUS_PADDING = 35;
export const MIN_STATUS_PADDING = 17;
export const MAX_PADDING = 60;

export function renderTimestamp(ts: Date) {
  return dateformat(ts);
}

export const formatTimestamp = (s: string) => cli.xterm(253)(s);

export const formatSectionHeading = (s: string) => cli.xterm(255)(cli.bold(s));
export const formatSectionLabel = (s: string) => cli.xterm(255)(s);
export const formatSectionEntry = (label: string, data: string): string =>
  ' ' + formatSectionLabel(sprintf(`%-${COLUMN2_START - 1}s `, label)) + data + '\n';
export const printSectionEntry = (label: string, data: string): boolean =>
  process.stdout.write(formatSectionEntry(label, data));

export const formatLogicalId = (s: string) => cli.xterm(252)(s);
export const formatStackOutputName = formatLogicalId;
export const formatStackExportName = formatLogicalId;

export function calcPadding<T>(items: T[], selector: (x:T) => string): number {
  return Math.min(_.max(_.map(items, i => selector(i).length)) as number, MAX_PADDING);
}

export function colorizeResourceStatus(status: string, padding = DEFAULT_STATUS_PADDING): string {
  padding = (_.isNumber(padding) && padding >= MIN_STATUS_PADDING) ? padding : MIN_STATUS_PADDING;
  const padded = sprintf(`%-${padding}s`, status);
  const fail = cli.redBright;
  const progress = cli.yellow;
  const complete = cli.green;
  const skipped = cli.blue;

  if (_.includes(FAILED, status)) {
    return fail(padded);
  } else if (_.includes(SKIPPED, status)) {
    return skipped(padded);
  } else if (_.includes(COMPLETE, status)) {
    return complete(padded);
  } else if (_.includes(IN_PROGRESS, status)) {
    return progress(padded);
  } else {
    return padded;
  }
}

export const prettyFormatSmallMap = (map: {[key: string]: string}): string => {
  let out = '';
  _.forOwn(map, (v, key) => {
    if (out !== '') {
      out += ', ';
    }
    out += key + '=' + v;
  })
  return out;
}

export const prettyFormatTags = (tags?: aws.CloudFormation.Tags): string => {
  if (_.isUndefined(tags) || tags.length === 0) {
    return '';
  }
  return prettyFormatSmallMap(_.fromPairs(_.map(tags, (tag) => [tag.Key, tag.Value])));
}

export const prettyFormatParameters = (params?: aws.CloudFormation.Parameters): string => {
  if (_.isUndefined(params) || params.length === 0) {
    return '';
  }
  return prettyFormatSmallMap(_.fromPairs(_.map(params, p => [p.ParameterKey, p.ParameterValue])));
}

export function showFinalComandSummary(wasSuccessful: boolean): number {
  if (wasSuccessful) {
    console.log(formatSectionHeading(sprintf(`%-${COLUMN2_START}s`, 'Command Summary:')),
                cli.black(cli.bgGreenBright('Success')), '👍');
    return SUCCESS;
  } else {
    console.log(formatSectionHeading(sprintf(`%-${COLUMN2_START}s`, 'Command Summary:')),
                cli.bgRedBright('Failure'), ' (╯°□°)╯︵ ┻━┻ ', 'Fix and try again.');
    return FAILURE;
  }
}

export function formatDuration(seconds: number) {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  return [
    h ? `${h}h` : 0,
    m ? `${m}m` : 0,
    s ? `${s}s` : 0,
  ].filter(a => a).join(' ');
}


text:
module SettingAccessors
  module Converters
    class PolymorphicConverter < Base
      def parse_value
        value
      end
    end
  end
end