text:
package org.fcrepo.client.batch;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Properties;
import java.util.Vector;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.fcrepo.common.Constants;
import org.fcrepo.utilities.XmlTransformUtility;

/**
 * @author Bill Niebel
 * @version $Id$
 */
class BatchXforms
        implements Constants {

    private final HashMap<String, String> formatMap =
            new HashMap<String, String>();

    private String additionsPath = null;

    private String objectsPath = null;

    private String xformPath = null;

    private String modelPath = null;

    private Transformer transformer = null;

    BatchXforms(Properties optValues)
            throws Exception {

        // The template format controls which xsl stylesheet is to be applied
        // Valid values are METS_EXT1_1.uri and FOXML1_1.uri
        if (optValues.getProperty(BatchTool.OBJECTFORMAT)
                .equalsIgnoreCase(FOXML1_1.uri)) {
            xformPath = Constants.FEDORA_HOME + "/client/lib/foxml-merge.xsl";
            formatMap.put(BatchTool.OBJECTFORMAT, "FOXML");
        } else if (optValues.getProperty(BatchTool.OBJECTFORMAT)
                .equalsIgnoreCase(METS_EXT1_1.uri)) {
            xformPath = Constants.FEDORA_HOME + "/client/lib/mets-merge.xsl";
            formatMap.put(BatchTool.OBJECTFORMAT, "METS");
        } else {
            System.err.println("Unknown objectTemplate format: "
                    + optValues.getProperty(BatchTool.OBJECTFORMAT));
            throw new Exception();
        }
        additionsPath = optValues.getProperty(BatchTool.ADDITIONSPATH);
        objectsPath = optValues.getProperty(BatchTool.OBJECTSPATH);
        modelPath = optValues.getProperty(BatchTool.CMODEL);
        if (!BatchTool.argOK(additionsPath)) {
            System.err.println("additionsPath required");
            throw new Exception();
        }
        if (!BatchTool.argOK(objectsPath)) {
            System.err.println("objectsPath required");
            throw new Exception();
        }
        if (!BatchTool.argOK(xformPath)) {
            System.err.println("xformPath required");
            throw new Exception();
        }

    }

    private boolean good2go = false;

    final void prep() throws Exception {
        good2go = true;
    }

    private Vector<String> keys = null;

    /* package */Vector getKeys() {
        return keys;
    }

    final void process() throws TransformerConfigurationException, Exception {
        TransformerFactory tfactory = XmlTransformUtility.getTransformerFactory();
        keys = new Vector<String>();
        if (good2go) {
            File file4catch = null;
            int files4catch = 0;
            int badFileCount = 0;
            int succeededBuildCount = 0;
            int failedBuildCount = 0;
            try {
                File[] files = null;
                {
                    // System.err.println("additions path " + additionsPath);
                    File additionsDirectory = new File(additionsPath);
                    files = additionsDirectory.listFiles();
                }
                //int badFileCount = 0;
                files4catch = files.length;
                for (int i = 0; i < files.length; i++) {
                    //System.err.println("another it");
                    file4catch = files[i];
                    if (!files[i].isFile()) {
                        badFileCount++;
                        System.err
                                .println("additions directory contains unexpected directory or file: "
                                        + files[i].getName());
                    } else {
                        //System.err.println("before tfactory.newTransformer()"); //<<==

                        File f = new File(xformPath);
                        //System.err.println("File " + xformPath + " exists=[" + (f.exists()) + "]");

                        StreamSource ss = new StreamSource(f);
                        //System.err.println("ss null=[" + (ss == null) + "]");
                        /*
                         * Reader r = ss.getReader(); System.err.println("r
                         * null=[" + (r == null) + "]"); BufferedReader br = new
                         * BufferedReader(r); System.err.println("br null=[" +
                         * (br == null) + "]"); String st = br.readLine();
                         * System.err.println("st null=[" + (st == null) + "]");
                         * System.err.println("first line[" + st + "]");
                         * System.err.println("after dummy SS"); //<<==
                         * System.err.println("support?=[" +
                         * tfactory.getFeature(StreamSource.FEATURE) + "]"); //<<==
                         */

                        transformer = tfactory.newTransformer(ss); //xformPath

                        //System.err.println("after tfactory.newTransformer(); is transformer null? " + (transformer == null));

                        // As of Fedora 2.0, CREATEDATE attribute should be omitted and allow Fedora server to assign
                        // creation dates at time of object ingest.
                        /*
                         * GregorianCalendar calendar = new GregorianCalendar();
                         * String year =
                         * Integer.toString(calendar.get(Calendar.YEAR)); String
                         * month = leftPadded(1+
                         * calendar.get(Calendar.MONTH),2); String dayOfMonth =
                         * leftPadded(calendar.get(Calendar.DAY_OF_MONTH),2);
                         * String hourOfDay =
                         * leftPadded(calendar.get(Calendar.HOUR_OF_DAY),2);
                         * String minute =
                         * leftPadded(calendar.get(Calendar.MINUTE),2); String
                         * second = leftPadded(calendar.get(Calendar.SECOND),2);
                         * transformer.setParameter("date", year + "-" + month +
                         * "-" + dayOfMonth + "T" + hourOfDay + ":" + minute +
                         * ":" + second);
                         */
                        //"2002-05-20T06:32:00"
                        //System.err.println("about to xform " + count++);
                        //System.err.println(">>>>>>>>>>>>" + files[i].getPath());
                        //System.err.println("objectsPath [" + objectsPath + "]");
                        /*
                         * for (int bb=0; bb<objectsPath.length(); bb++) { char
                         * c = objectsPath.charAt(bb); int n =
                         * Character.getNumericValue(c); boolean t =
                         * Character.isISOControl(c);
                         * System.err.print("["+c+"("+n+")"+t+"]"); }
                         */
                        //System.err.println("File.separator " + File.separator);
                        //System.err.println("files[i].getName() " + files[i].getName());
                        //System.err.println("before calling xform");
                        //String temp = "file://" + files[i].getPath(); //(files[i].getPath()).replaceFirst("C:", "file:///C:");
                        URI uri = files[i].toURI();
                        String temp = uri.toString();
                        //System.err.println("path is [" + temp); //files[i].getPath());
                        transformer.setParameter("subfilepath", temp); //files[i].getPath());

                        //System.out.println("fis");
                        FileInputStream fis = new FileInputStream(modelPath);
                        //System.out.println("fos");
                        FileOutputStream fos =
                                new FileOutputStream(objectsPath
                                        + File.separator + files[i].getName());
                        //System.out.println("fos");
                        try {
                            //transform(new FileInputStream(files[i]), new FileOutputStream (objectsPath + File.separator + files[i].getName()));
                            transform(fis, fos);
                            //System.out.println("Fedora METS XML created at " + files[i].getName());
                            succeededBuildCount++;
                            //System.out.println("before keys.add()");
                            keys.add(files[i].getName());
                            //System.out.println("after keys.add()");
                        } catch (Exception e) {
                            //for now, follow processing as-is and throw out rest of batch
                            throw e;
                        } finally { // so that files are available to outside editor during batchtool client use
                            //System.out.println("before fis.close");
                            fis.close();
                            //System.out.println("before fos.close");
                            fos.close();
                            //System.out.println("after fos.close()");
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println("Fedora "
                        + formatMap.get(BatchTool.OBJECTFORMAT)
                        + " XML failed for " + file4catch.getName());
                System.err.println("exception: " + e.getMessage()
                        + " , class is " + e.getClass());
                failedBuildCount++;
            } finally {
            }
            System.err.println("\n" + "Batch Build Summary");
            System.err.println("\n"
                    + (succeededBuildCount + failedBuildCount + badFileCount)
                    + " files processed in this batch");
            System.err.println("\t" + succeededBuildCount + " Fedora "
                    + formatMap.get(BatchTool.OBJECTFORMAT)
                    + " XML documents successfully created");
            System.err.println("\t" + failedBuildCount + " Fedora "
                    + formatMap.get(BatchTool.OBJECTFORMAT)
                    + " XML documents failed");
            System.err.println("\t" + badFileCount
                    + " unexpected files in directory");
            System.err
                    .println("\t"
                            + (files4catch - (succeededBuildCount
                                    + failedBuildCount + badFileCount))
                            + " files ignored after error");
        }
    }

    public static final void main(String[] args) {
        try {
            Properties miscProperties = new Properties();
            miscProperties
                    .load(new FileInputStream("c:\\batchdemo\\batchtool.properties"));
            BatchXforms batchXforms = new BatchXforms(miscProperties);
            batchXforms.prep();
            batchXforms.process();
        } catch (Exception e) {
        }
    }

    public void transform(InputStream sourceStream, OutputStream destStream)
            throws TransformerException, TransformerConfigurationException {
        //System.err.println("before transformer.transform()");
        transformer.transform(new StreamSource(sourceStream),
                              new StreamResult(destStream));
        //System.err.println("after transformer.transform()");
    }

}


text:
package model;

import java.io.Serializable;

//Objeto que contém as informações do arquivo de configuração.
/**
 * Classe de domínio que contém as informações do arquivo de login do paciente
 */
public class LoginDomain implements Serializable{

	/** Versão do atributo serialVersionUID */
	private static final long serialVersionUID = 1L;

	/** Login do paciente */
	private String login;
	/** Senha do paciente*/
	private String senha;
	/** Link de envio das informações para o servidor REIS */
	private String link;

	/**
	 * Método para obter o login do paciente
	 * @return String Login do paciente
	 */
	public String getLogin() {
		return login;
	}

	/**
	 * Método para informar o login do paciente
	 * @param login  Login do paciente
	 */
	public void setLogin(String login) {
		this.login = login;
	}

	/**
	 * Método para obter a senha do paciente
	 * @return String Senha do paciente
	 */
	public String getSenha() {
		return senha;
	}

	/**
	 * Método para informar a senha do paciente
	 * @param senha Senha do paciente
	 */
	public void setSenha(String senha) {
		this.senha = senha;
	}

	/**
	 * Método para obter o link de envio das informações para o servidor REIS
	 * @return String link de envio das informações para o servidor REIS
	 */
	public String getLink() {
		return link;
	}

	/**
	 * Método para informar o link de envio das informações para o servidor REIS
	 * @param link Link de envio das informações para o servidor REIS
	 */
	public void setLink(String link) {
		this.link = link;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.achur.avalon.processors;

import com.achur.avalon.entity.Game;
import com.achur.avalon.entity.Player;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

import java.util.List;
import java.util.Set;

public class Constants {

  /**
   * Number of allowed votes before the game is over.
   */
  public static final int MAX_VOTES = 5;

  /**
   * The roles that are bad.
   */
  public static final Set<Player.Role> BAD_ROLES = ImmutableSet.of(
      Player.Role.ASSASSIN,
      Player.Role.MINION,
      Player.Role.MORGANA,
      Player.Role.MORDRED);

  /**
   * The minimum number of players necessary.
   */
  public static final Integer MIN_PLAYERS = 5;

  /**
   * The number of bad players for each total number of players, starting with
   * MIN_PLAYERS.
   */
  public static final List<Integer> BAD_PLAYER_COUNTS = ImmutableList.of(
      2, 2, 3, 3, 3, 4);

  /**
   * The number of quests in a game.
   */
  public static final Integer NUM_QUESTS = 5;

  /**
   * The maximum number of players.
   */
  public static final Integer MAX_PLAYERS = MIN_PLAYERS + BAD_PLAYER_COUNTS.size() - 1;

  /**
   * The number of players sent on each mission, for each number of players.
   * A negative value means two fails are required to fail the mission.
   */
  private static final List<ImmutableList<Integer>> NUM_MISSION_PLAYERS =
      ImmutableList.of(
          ImmutableList.of(2, 3, 2, 3 ,3),
          ImmutableList.of(2, 3, 3, 3, 4),
          ImmutableList.of(2, 3, 3, -4, 4),
          ImmutableList.of(3, 4, 4, -5, 5),
          ImmutableList.of(3, 4, 4, -5, 5),
          ImmutableList.of(3, 4, 4, -5, 5));

  /**
   * @param totalPlayers The number of players in the game.
   * @param currentQuest the number of the current quest (indexed from 0).
   * @return the number of players going on the current quest.
   */
  public static int getNumPlayers(int totalPlayers, int currentQuest) {
    return Math.abs(
        NUM_MISSION_PLAYERS.get(totalPlayers - MIN_PLAYERS).get(currentQuest));
  }

  /**
   * @param totalPlayers  The number of players in the game.
   * @return The number of bad players in the game.
   */
  public static int getNumBadPlayers(int totalPlayers) {
    if (totalPlayers < MIN_PLAYERS) {
      return BAD_PLAYER_COUNTS.get(0);
    }
    return BAD_PLAYER_COUNTS.get(totalPlayers - MIN_PLAYERS);
  }

  /**
   * @param totalPlayers The number of players in the game.
   * @param currentQuest the number of the current quest (indexed from 0).
   * @return the number of fails required to fail the current quest.
   */
  public static int getNumFailsRequired(int totalPlayers, int currentQuest) {
    return NUM_MISSION_PLAYERS.get(totalPlayers - MIN_PLAYERS).get(currentQuest) > 0 ?
        1 : 2;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    xmlns:android="http://schemas.android.com/apk/res/android" />
    <android.support.v7.widget.CardView
        android:id="@+id/sehricontainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"

        android:layout_marginBottom="5dp"

        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        >
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:paddingTop="@dimen/default_cardViewPadding"
        android:paddingBottom="@dimen/default_cardViewPadding"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="80dp"

            android:background="@drawable/fab_circle_red"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"

            android:textAlignment="center"
            android:padding="50dp"

            android:layout_height="80dp"
            android:id="@+id/textView5" />
        <TextView
            android:id="@+id/tv_main_date"
            android:layout_width="match_parent"

            android:text="1"

            android:textAlignment="center"

            android:textSize="30dp"
            android:textStyle="bold"
            android:textColor="@color/main_white"

            android:layout_height="wrap_content"
            android:layout_marginLeft="40dp"
            android:layout_marginStart="40dp"
            android:layout_centerVertical="true"
            android:layout_alignLeft="@+id/textView5"
            android:layout_alignStart="@+id/textView5"
            android:layout_toStartOf="@+id/tv_sehri_time"
            android:layout_alignRight="@+id/textView5"
            android:layout_alignEnd="@+id/textView5" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sehri Time"
            android:textColor="@color/assent"
            android:textSize="20sp"
            android:id="@+id/label_sehritime"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Iftari Time"
            android:id="@+id/textView6"
            android:textColor="@color/main_teal"
            android:textSize="20sp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="5dp"
            android:layout_alignTop="@+id/label_sehritime"
            android:layout_toRightOf="@+id/label_sehritime"
            android:layout_alignBottom="@+id/label_sehritime" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="04:05"
            android:textSize="20sp"
            android:id="@+id/tv_sehri_time"
            android:textColor="@color/assent"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="06:35"
            android:layout_marginTop="10dp"
            android:textSize="20sp"
            android:textColor="@color/main_teal"
            android:id="@+id/tv_iftari_time"
            android:layout_centerVertical="true"
            android:layout_alignLeft="@+id/textView6"
            android:layout_alignStart="@+id/textView6"
            android:layout_marginLeft="16dp"
            android:layout_marginStart="16dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Day"
            android:textColor="@color/main_white"
            android:id="@+id/textView7"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_centerVertical="true"
            android:layout_alignLeft="@+id/textView5"
            android:layout_alignStart="@+id/textView5" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Date :"
            android:id="@+id/textView8"
            android:textSize="15sp"
            android:textColor="@color/main_text_color"
            android:layout_alignBottom="@+id/textView5"
            android:layout_alignRight="@+id/label_sehritime"
            android:layout_alignEnd="@+id/label_sehritime" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:textSize="15sp"
            android:id="@+id/tv_chris_date"
            android:layout_alignBottom="@+id/textView8"
            android:layout_alignLeft="@+id/textView6"
            android:layout_alignStart="@+id/textView6" />

    </RelativeLayout>
</android.support.v7.widget.CardView>

</FrameLayout>


text:
function test() {
  waitForExplicitFinish();

  // Setup a phony handler to ensure the app pane will be populated.
  var handler = Cc["@mozilla.org/uriloader/web-handler-app;1"].
                createInstance(Ci.nsIWebHandlerApp);
  handler.name = "App pane alive test";
  handler.uriTemplate = "http://test.mozilla.org/%s";

  var extps = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
              getService(Ci.nsIExternalProtocolService);
  var info = extps.getProtocolHandlerInfo("apppanetest");
  info.possibleApplicationHandlers.appendElement(handler, false);

  var hserv = Cc["@mozilla.org/uriloader/handler-service;1"].
              getService(Ci.nsIHandlerService);
  hserv.store(info);

  function observer(win, topic, data) {
    if (topic != "app-handler-pane-loaded")
      return;

    Services.obs.removeObserver(observer, "app-handler-pane-loaded");
    runTest(win);
  }
  Services.obs.addObserver(observer, "app-handler-pane-loaded", false);

  openDialog("chrome://browser/content/preferences/preferences.xul", "Preferences",
             "chrome,titlebar,toolbar,centerscreen,dialog=no", "paneApplications");
}

function runTest(win) {
  var sel = win.document.documentElement.getAttribute("lastSelected");
  ok(sel == "paneApplications", "Specified pane was opened");

  var rbox = win.document.getElementById("handlersView");
  ok(rbox, "handlersView is present");

  var items = rbox && rbox.getElementsByTagName("richlistitem");
  ok(items && items.length > 0, "App handler list populated");

  var handlerAdded = false;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type == "apppanetest")
      handlerAdded = true;
  }
  ok(handlerAdded, "apppanetest protocol handler was successfully added");

  win.close();
  finish();
}


text:
from spec import Spec, eq_, raises

from invoke.parser import Parser, Context, Argument, ParseError

class Parser_(Spec):
    def can_take_initial_context(self):
        c = Context()
        p = Parser(initial=c)
        eq_(p.initial, c)

    def can_take_initial_and_other_contexts(self):
        c1 = Context('foo')
        c2 = Context('bar')
        p = Parser(initial=Context(), contexts=[c1, c2])
        eq_(p.contexts['foo'], c1)
        eq_(p.contexts['bar'], c2)

    def can_take_just_other_contexts(self):
        c = Context('foo')
        p = Parser(contexts=[c])
        eq_(p.contexts['foo'], c)

    def can_take_just_contexts_as_non_keyword_arg(self):
        c = Context('foo')
        p = Parser([c])
        eq_(p.contexts['foo'], c)

    @raises(ValueError)
    def raises_ValueError_for_unnamed_Contexts_in_contexts(self):
        Parser(initial=Context(), contexts=[Context()])

    @raises(ValueError)
    def raises_error_for_context_name_clashes(self):
        Parser(contexts=(Context('foo'), Context('foo')))

    @raises(ValueError)
    def raises_error_for_context_alias_and_name_clashes(self):
        Parser((Context('foo', aliases=('bar',)), Context('bar')))

    @raises(ValueError)
    def raises_error_for_context_name_and_alias_clashes(self):
        # I.e. inverse of the above, which is a different code path.
        Parser((Context('foo'), Context('bar', aliases=('foo',))))

    def takes_ignore_unknown_kwarg(self):
        Parser(ignore_unknown=True)

    def ignore_unknown_defaults_to_False(self):
        eq_(Parser().ignore_unknown, False)

    class parse_argv:
        def parses_sys_argv_style_list_of_strings(self):
            "parses sys.argv-style list of strings"
            # Doesn't-blow-up tests FTL
            mytask = Context(name='mytask')
            mytask.add_arg('arg')
            p = Parser(contexts=[mytask])
            p.parse_argv(['mytask', '--arg', 'value'])

        def returns_only_contexts_mentioned(self):
            task1 = Context('mytask')
            task2 = Context('othertask')
            result = Parser((task1, task2)).parse_argv(['othertask'])
            eq_(len(result), 1)
            eq_(result[0].name, 'othertask')

        @raises(ParseError)
        def raises_error_if_unknown_contexts_found(self):
            Parser().parse_argv(['foo', 'bar'])

        def unparsed_does_not_share_state(self):
            r = Parser(ignore_unknown=True).parse_argv(['self'])
            eq_(r.unparsed, ['self'])
            r2 = Parser(ignore_unknown=True).parse_argv(['contained'])
            eq_(r.unparsed, ['self']) # NOT ['self', 'contained']
            eq_(r2.unparsed, ['contained']) # NOT ['self', 'contained']

        def ignore_unknown_returns_unparsed_argv_instead(self):
            r = Parser(ignore_unknown=True).parse_argv(['foo', 'bar', '--baz'])
            eq_(r.unparsed, ['foo', 'bar', '--baz'])

        def ignore_unknown_does_not_mutate_rest_of_argv(self):
            p = Parser([Context('ugh')], ignore_unknown=True)
            r = p.parse_argv(['ugh', 'what', '-nowai'])
            # NOT: ['what', '-n', '-w', '-a', '-i']
            eq_(r.unparsed, ['what', '-nowai'])

        def always_includes_initial_context_if_one_was_given(self):
            # Even if no core/initial flags were seen
            t1 = Context('t1')
            init = Context()
            result = Parser((t1,), initial=init).parse_argv(['t1'])
            eq_(result[0].name, None)
            eq_(result[1].name, 't1')

        def returned_contexts_are_in_order_given(self):
            t1, t2 = Context('t1'), Context('t2')
            r = Parser((t1, t2)).parse_argv(['t2', 't1'])
            eq_([x.name for x in r], ['t2', 't1'])

        def returned_context_member_arguments_contain_given_values(self):
            c = Context('mytask', args=(Argument('boolean', kind=bool),))
            result = Parser((c,)).parse_argv(['mytask', '--boolean'])
            eq_(result[0].args['boolean'].value, True)

        def inverse_bools_get_set_correctly(self):
            arg = Argument('myarg', kind=bool, default=True)
            c = Context('mytask', args=(arg,))
            r = Parser((c,)).parse_argv(['mytask', '--no-myarg'])
            eq_(r[0].args['myarg'].value, False)

        def arguments_which_take_values_get_defaults_overridden_correctly(self): # noqa
            args = (Argument('arg', kind=str), Argument('arg2', kind=int))
            c = Context('mytask', args=args)
            argv = ['mytask', '--arg', 'myval', '--arg2', '25']
            result = Parser((c,)).parse_argv(argv)
            eq_(result[0].args['arg'].value, 'myval')
            eq_(result[0].args['arg2'].value, 25)

        def returned_arguments_not_given_contain_default_values(self):
            # I.e. a Context with args A and B, invoked with no mention of B,
            # should result in B existing in the result, with its default value
            # intact, and not e.g. None, or the arg not existing.
            a = Argument('name', kind=str)
            b = Argument('age', default=7)
            c = Context('mytask', args=(a, b))
            Parser((c,)).parse_argv(['mytask', '--name', 'blah'])
            eq_(c.args['age'].value, 7)

        def returns_remainder(self):
            "returns -- style remainder string chunk"
            r = Parser((Context('foo'),)).parse_argv(
                ['foo', '--', 'bar', 'biz']
            )
            eq_(r.remainder, "bar biz")

        def clones_initial_context(self):
            a = Argument('foo', kind=bool)
            eq_(a.value, None)
            c = Context(args=(a,))
            p = Parser(initial=c)
            assert p.initial is c
            r = p.parse_argv(['--foo'])
            assert p.initial is c
            c2 = r[0]
            assert c2 is not c
            a2 = c2.args['foo']
            assert a2 is not a
            eq_(a.value, None)
            eq_(a2.value, True)

        def clones_noninitial_contexts(self):
            a = Argument('foo')
            eq_(a.value, None)
            c = Context(name='mytask', args=(a,))
            p = Parser(contexts=(c,))
            assert p.contexts['mytask'] is c
            r = p.parse_argv(['mytask', '--foo', 'val'])
            assert p.contexts['mytask'] is c
            c2 = r[0]
            assert c2 is not c
            a2 = c2.args['foo']
            assert a2 is not a
            eq_(a.value, None)
            eq_(a2.value, 'val')

        class parsing_errors:
            def setup(self):
                self.p = Parser([Context(name='foo', args=[Argument('bar')])])

            @raises(ParseError)
            def missing_flag_values_raise_ParseError(self):
                self.p.parse_argv(['foo', '--bar'])

            def attaches_context_to_ParseErrors(self):
                try:
                    self.p.parse_argv(['foo', '--bar'])
                except ParseError as e:
                    assert e.context is not None

            def attached_context_is_None_outside_contexts(self):
                try:
                    Parser().parse_argv(['wat'])
                except ParseError as e:
                    assert e.context is None

        class positional_arguments:
            def _basic(self):
                arg = Argument('pos', positional=True)
                mytask = Context(name='mytask', args=[arg])
                return Parser(contexts=[mytask])

            def single_positional_arg(self):
                r = self._basic().parse_argv(['mytask', 'posval'])
                eq_(r[0].args['pos'].value, 'posval')

            @raises(ParseError)
            def omitted_positional_arg_raises_ParseError(self):
                self._basic().parse_argv(['mytask'])

            def positional_args_eat_otherwise_valid_context_names(self):
                mytask = Context('mytask', args=[
                    Argument('pos', positional=True),
                    Argument('nonpos', default='default')
                ])
                Context('lolwut')
                result = Parser([mytask]).parse_argv(['mytask', 'lolwut'])
                r = result[0]
                eq_(r.args['pos'].value, 'lolwut')
                eq_(r.args['nonpos'].value, 'default')
                eq_(len(result), 1) # Not 2

            def positional_args_can_still_be_given_as_flags(self):
                # AKA "positional args can come anywhere in the context"
                pos1 = Argument('pos1', positional=True)
                pos2 = Argument('pos2', positional=True)
                nonpos = Argument('nonpos', positional=False, default='lol')
                mytask = Context('mytask', args=[pos1, pos2, nonpos])
                eq_(mytask.positional_args, [pos1, pos2])
                r = Parser([mytask]).parse_argv([
                    'mytask',
                    '--nonpos', 'wut',
                    '--pos2', 'pos2val',
                    'pos1val',
                ])[0]
                eq_(r.args['pos1'].value, 'pos1val')
                eq_(r.args['pos2'].value, 'pos2val')
                eq_(r.args['nonpos'].value, 'wut')

        class equals_signs:
            def _compare(self, argname, invoke, value):
                c = Context('mytask', args=(Argument(argname, kind=str),))
                r = Parser((c,)).parse_argv(['mytask', invoke])
                eq_(r[0].args[argname].value, value)

            def handles_equals_style_long_flags(self):
                self._compare('foo', '--foo=bar', 'bar')

            def handles_equals_style_short_flags(self):
                self._compare('f', '-f=bar', 'bar')

            def does_not_require_escaping_equals_signs_in_value(self):
                self._compare('f', '-f=biz=baz', 'biz=baz')

        def handles_multiple_boolean_flags_per_context(self):
            c = Context('mytask', args=(
                Argument('foo', kind=bool), Argument('bar', kind=bool)
            ))
            r = Parser([c]).parse_argv(['mytask', '--foo', '--bar'])
            a = r[0].args
            eq_(a.foo.value, True)
            eq_(a.bar.value, True)

    class optional_arg_values:
        def setup(self):
            self.parser = self._parser()

        def _parser(self, arguments=None):
            if arguments is None:
                arguments = (
                    Argument(
                        names=('foo', 'f'),
                        optional=True,
                        default='mydefault'
                    ),
                )
            self.context = Context('mytask', args=arguments)
            return Parser([self.context])

        def _parse(self, argstr, parser=None):
            parser = parser or self.parser
            return parser.parse_argv(['mytask'] + argstr.split())

        def _expect(self, argstr, expected, parser=None):
            result = self._parse(argstr, parser)
            eq_(result[0].args.foo.value, expected)

        def no_value_becomes_True_not_default_value(self):
            self._expect('--foo', True)
            self._expect('-f', True)

        def value_given_gets_preserved_normally(self):
            for argstr in (
                '--foo whatever',
                '--foo=whatever',
                '-f whatever',
                '-f=whatever',
            ):
                self._expect(argstr, 'whatever')

        def not_given_at_all_uses_default_value(self):
            self._expect('', 'mydefault')

        class ambiguity_sanity_checks:
            def _test_for_ambiguity(self, invoke, parser=None):
                msg = "is ambiguous"
                try:
                    self._parse(invoke, parser or self.parser)
                # Expected result
                except ParseError as e:
                    assert msg in str(e)
                # No exception occurred at all? Bollocks.
                else:
                    assert False
                # Any other exceptions will naturally cause failure here.

            def unfilled_posargs(self):
                p = self._parser((
                    Argument('foo', optional=True),
                    Argument('bar', positional=True)
                ))
                self._test_for_ambiguity("--foo uhoh", p)

            def flaglike_value(self):
                self._test_for_ambiguity("--foo --bar")

            def no_ambiguity_with_flaglike_value_if_option_val_was_given(self):
                p = self._parser((
                    Argument('foo', optional=True),
                    Argument('bar', kind=bool)
                ))
                # This should NOT raise a ParseError.
                result = self._parse("--foo hello --bar", p)
                eq_(result[0].args['foo'].value, 'hello')
                eq_(result[0].args['bar'].value, True)

            def actual_other_flag(self):
                self._parser((
                    Argument('foo', optional=True),
                    Argument('bar')
                ))
                self._test_for_ambiguity("--foo --bar")

            def task_name(self):
                # mytask --foo myothertask
                c1 = Context('mytask', args=(Argument('foo', optional=True),))
                c2 = Context('othertask')
                p = Parser([c1, c2])
                self._test_for_ambiguity("--foo othertask", p)

    class task_repetition:
        def is_happy_to_handle_same_task_multiple_times(self):
            task1 = Context('mytask')
            result = Parser((task1,)).parse_argv(['mytask', 'mytask'])
            eq_(len(result), 2)
            [eq_(x.name, 'mytask') for x in result]

        def task_args_work_correctly(self):
            task1 = Context('mytask', args=(Argument('meh'),))
            result = Parser((task1,)).parse_argv(
                ['mytask', '--meh', 'mehval1', 'mytask', '--meh', 'mehval2']
            )
            eq_(result[0].args.meh.value, 'mehval1')
            eq_(result[1].args.meh.value, 'mehval2')

class ParseResult_(Spec):
    "ParseResult"
    def setup(self):
        self.context = Context('mytask',
            args=(Argument('foo', kind=str), Argument('bar')))
        argv = ['mytask', '--foo', 'foo-val', '--', 'my', 'remainder']
        self.result = Parser((self.context,)).parse_argv(argv)

    def acts_as_a_list_of_parsed_contexts(self):
        eq_(len(self.result), 1)
        eq_(self.result[0].name, 'mytask')

    def exhibits_remainder_attribute(self):
        eq_(self.result.remainder, 'my remainder')


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

<TITLE>
Uses of Class app.VisualizerScreen
</TITLE>

<META NAME="date" CONTENT="2013-05-03">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
app.VisualizerScreen

Packages that use VisualizerScreen

app

Uses of VisualizerScreen in app

Subclasses of VisualizerScreen in app

 class
App

          Hlavna trieda, spusti sa aplikacia.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
import React from 'react';
import ReactDOM from 'react-dom';
import SellingPlatformApp from '../src/sellplatform/SellingPlatformApp';
import renderer from 'react-test-renderer';

describe.skip('Selling Platform Application tests', () => {

  it('renders the SellingPlatformApp without crashing', () => {

    const container = document.createElement('div');
    ReactDOM.render(<SellingPlatformApp />, container);
  });

  it('matches SellingPlatformApp to snapshot', () => {

    const component = renderer.create(
      <SellingPlatformApp />
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });

});


text:
<?php

namespace Manhattan\PublicBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ContactType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text', array(
                'required' => true,
                'label' => 'Name',
                'attr' => array(
                    'class' => 'text'
                )
            ))
            ->add('company', 'text', array(
                'required' => true,
                'label' => 'Company',
                'attr' => array(
                    'class' => 'text'
                )
            ))
            ->add('email', 'email', array(
                'required' => true,
                'label' => 'Email',
                'attr' => array(
                    'class' => 'text'
                )
            ))
            ->add('phone', 'telephone', array(
                'required' => true,
                'label' => 'Phone',
                'attr' => array(
                    'class' => 'text'
                )
            ))
            ->add('subject', 'subject', array(
                'attr' => array(
                    'class' => 'custom radio'
                ),
                'expanded' => true,
                'required' => true,
                'label' => 'Subject'
            ))
            ->add('message', 'textarea', array(
                'required' => true,
                'label' => 'Message',
                'attr' => array(
                    'class' => 'input-text'
                )
            ))
            ->add('knowledge', 'text', array(
                'required' => false,
                'label' => false,
                'attr' => array(
                    'class' => 'input-text'
                )
            ))
            ->add('happens', 'datetime', array(
                'required' => true,
                'read_only' => true,
                'label' => false,
                'widget' => 'single_text'
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Manhattan\PublicBundle\Entity\Contact',
            'error_mapping' => array(
                'contactValid' => 'email'
            ),
        ));
    }

    public function getName()
    {
        return 'contact';
    }
}


text:
package com.cloudera.sqoop.orm;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

import junit.framework.TestCase;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.cloudera.sqoop.SqoopOptions;
import com.cloudera.sqoop.manager.ConnManager;
import com.cloudera.sqoop.testutil.DirUtil;
import com.cloudera.sqoop.testutil.HsqldbTestServer;
import com.cloudera.sqoop.testutil.ImportJobTestCase;
import com.cloudera.sqoop.tool.ImportTool;
import com.cloudera.sqoop.util.ClassLoaderStack;
import java.lang.reflect.Field;

/**
 * Test that the ClassWriter generates Java classes based on the given table,
 * which compile.
 */
public class TestClassWriter extends TestCase {

  public static final Log LOG =
      LogFactory.getLog(TestClassWriter.class.getName());

  // instance variables populated during setUp, used during tests
  private HsqldbTestServer testServer;
  private ConnManager manager;
  private SqoopOptions options;

  @Before
  public void setUp() {
    testServer = new HsqldbTestServer();
    org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger();
    root.setLevel(org.apache.log4j.Level.DEBUG);
    try {
      testServer.resetServer();
    } catch (SQLException sqlE) {
      LOG.error("Got SQLException: " + sqlE.toString());
      fail("Got SQLException: " + sqlE.toString());
    } catch (ClassNotFoundException cnfe) {
      LOG.error("Could not find class for db driver: " + cnfe.toString());
      fail("Could not find class for db driver: " + cnfe.toString());
    }

    manager = testServer.getManager();
    options = testServer.getSqoopOptions();

    // sanity check: make sure we're in a tmp dir before we blow anything away.
    assertTrue("Test generates code in non-tmp dir!",
        CODE_GEN_DIR.startsWith(ImportJobTestCase.TEMP_BASE_DIR));
    assertTrue("Test generates jars in non-tmp dir!",
        JAR_GEN_DIR.startsWith(ImportJobTestCase.TEMP_BASE_DIR));

    // start out by removing these directories ahead of time
    // to ensure that this is truly generating the code.
    File codeGenDirFile = new File(CODE_GEN_DIR);
    File classGenDirFile = new File(JAR_GEN_DIR);

    if (codeGenDirFile.exists()) {
      LOG.debug("Removing code gen dir: " + codeGenDirFile);
      if (!DirUtil.deleteDir(codeGenDirFile)) {
        LOG.warn("Could not delete " + codeGenDirFile + " prior to test");
      }
    }

    if (classGenDirFile.exists()) {
      LOG.debug("Removing class gen dir: " + classGenDirFile);
      if (!DirUtil.deleteDir(classGenDirFile)) {
        LOG.warn("Could not delete " + classGenDirFile + " prior to test");
      }
    }
  }

  @After
  public void tearDown() {
    try {
      manager.close();
    } catch (SQLException sqlE) {
      LOG.error("Got SQLException: " + sqlE.toString());
      fail("Got SQLException: " + sqlE.toString());
    }
  }

  static final String CODE_GEN_DIR = ImportJobTestCase.TEMP_BASE_DIR
      + "sqoop/test/codegen";
  static final String JAR_GEN_DIR = ImportJobTestCase.TEMP_BASE_DIR
      + "sqoop/test/jargen";

  /**
   * Run a test to verify that we can generate code and it emits the output
   * files where we expect them.
   * @return
   */
  private File runGenerationTest(String [] argv, String classNameToCheck) {
    File codeGenDirFile = new File(CODE_GEN_DIR);
    File classGenDirFile = new File(JAR_GEN_DIR);

    try {
      options = new ImportTool().parseArguments(argv,
          null, options, true);
    } catch (Exception e) {
      LOG.error("Could not parse options: " + e.toString());
    }

    CompilationManager compileMgr = new CompilationManager(options);
    ClassWriter writer = new ClassWriter(options, manager,
        HsqldbTestServer.getTableName(), compileMgr);

    try {
      writer.generate();
      compileMgr.compile();
      compileMgr.jar();
    } catch (IOException ioe) {
      LOG.error("Got IOException: " + ioe.toString());
      fail("Got IOException: " + ioe.toString());
    }

    String classFileNameToCheck = classNameToCheck.replace('.',
        File.separatorChar);
    LOG.debug("Class file to check for: " + classFileNameToCheck);

    // Check that all the files we expected to generate (.java, .class, .jar)
    // exist.
    File tableFile = new File(codeGenDirFile, classFileNameToCheck + ".java");
    assertTrue("Cannot find generated source file for table!",
        tableFile.exists());
    LOG.debug("Found generated source: " + tableFile);

    File tableClassFile = new File(classGenDirFile, classFileNameToCheck
        + ".class");
    assertTrue("Cannot find generated class file for table!",
        tableClassFile.exists());
    LOG.debug("Found generated class: " + tableClassFile);

    File jarFile = new File(compileMgr.getJarFilename());
    assertTrue("Cannot find compiled jar", jarFile.exists());
    LOG.debug("Found generated jar: " + jarFile);

    // check that the .class file made it into the .jar by enumerating
    // available entries in the jar file.
    boolean foundCompiledClass = false;
    try {
      JarInputStream jis = new JarInputStream(new FileInputStream(jarFile));

      LOG.debug("Jar file has entries:");
      while (true) {
        JarEntry entry = jis.getNextJarEntry();
        if (null == entry) {
          // no more entries.
          break;
        }

        if (entry.getName().equals(classFileNameToCheck + ".class")) {
          foundCompiledClass = true;
          LOG.debug(" * " + entry.getName());
        } else {
          LOG.debug("   " + entry.getName());
        }
      }

      jis.close();
    } catch (IOException ioe) {
      fail("Got IOException iterating over Jar file: " + ioe.toString());
    }

    assertTrue("Cannot find .class file " + classFileNameToCheck
        + ".class in jar file", foundCompiledClass);

    LOG.debug("Found class in jar - test success!");
    return jarFile;
  }

  /**
   * Test that we can generate code. Test that we can redirect the --outdir
   * and --bindir too.
   */
  @Test
  public void testCodeGen() {

    // Set the option strings in an "argv" to redirect our srcdir and bindir.
    String [] argv = {
      "--bindir",
      JAR_GEN_DIR,
      "--outdir",
      CODE_GEN_DIR,
    };

    runGenerationTest(argv, HsqldbTestServer.getTableName());
  }

  private static final String OVERRIDE_CLASS_NAME = "override";

  /**
   * Test that we can generate code with a custom class name.
   */
  @Test
  public void testSetClassName() {

    // Set the option strings in an "argv" to redirect our srcdir and bindir
    String [] argv = {
      "--bindir",
      JAR_GEN_DIR,
      "--outdir",
      CODE_GEN_DIR,
      "--class-name",
      OVERRIDE_CLASS_NAME,
    };

    runGenerationTest(argv, OVERRIDE_CLASS_NAME);
  }

  private static final String OVERRIDE_CLASS_AND_PACKAGE_NAME =
      "override.pkg.prefix.classname";

  /**
   * Test that we can generate code with a custom class name that includes a
   * package.
   */
  @Test
  public void testSetClassAndPackageName() {

    // Set the option strings in an "argv" to redirect our srcdir and bindir
    String [] argv = {
      "--bindir",
      JAR_GEN_DIR,
      "--outdir",
      CODE_GEN_DIR,
      "--class-name",
      OVERRIDE_CLASS_AND_PACKAGE_NAME,
    };

    runGenerationTest(argv, OVERRIDE_CLASS_AND_PACKAGE_NAME);
  }

  private static final String OVERRIDE_PACKAGE_NAME =
      "special.userpackage.name";

  /**
   * Test that we can generate code with a custom class name that includes a
   * package.
   */
  @Test
  public void testSetPackageName() {

    // Set the option strings in an "argv" to redirect our srcdir and bindir
    String [] argv = {
      "--bindir",
      JAR_GEN_DIR,
      "--outdir",
      CODE_GEN_DIR,
      "--package-name",
      OVERRIDE_PACKAGE_NAME,
    };

    runGenerationTest(argv, OVERRIDE_PACKAGE_NAME + "."
        + HsqldbTestServer.getTableName());
  }

  // Test the SQL identifier -> Java identifier conversion.
  @Test
  public void testJavaIdentifierConversion() {
    assertNull(ClassWriter.getIdentifierStrForChar(' '));
    assertNull(ClassWriter.getIdentifierStrForChar('\t'));
    assertNull(ClassWriter.getIdentifierStrForChar('\r'));
    assertNull(ClassWriter.getIdentifierStrForChar('\n'));
    assertEquals("x", ClassWriter.getIdentifierStrForChar('x'));
    assertEquals("_", ClassWriter.getIdentifierStrForChar('-'));
    assertEquals("_", ClassWriter.getIdentifierStrForChar('_'));

    assertEquals("foo", ClassWriter.toJavaIdentifier("foo"));
    assertEquals("_class", ClassWriter.toJavaIdentifier("class"));
    assertEquals("_class", ClassWriter.toJavaIdentifier("cla ss"));
    assertEquals("_int", ClassWriter.toJavaIdentifier("int"));
    assertEquals("thisismanywords", ClassWriter.toJavaIdentifier(
        "this is many words"));
    assertEquals("_9isLegalInSql", ClassWriter.toJavaIdentifier(
        "9isLegalInSql"));
    assertEquals("____", ClassWriter.toJavaIdentifier("___"));
    assertEquals("__class", ClassWriter.toJavaIdentifier("_class"));
  }

  @Test
  public void testWeirdColumnNames() throws SQLException {
    // Recreate the table with column names that aren't legal Java identifiers.
    String tableName = HsqldbTestServer.getTableName();
    Connection connection = testServer.getConnection();
    Statement st = connection.createStatement();
    try {
      st.executeUpdate("DROP TABLE " + tableName + " IF EXISTS");
      st.executeUpdate("CREATE TABLE " + tableName
          + " (class INT, \"9field\" INT)");
      st.executeUpdate("INSERT INTO " + tableName + " VALUES(42, 41)");
      connection.commit();
    } finally {
      st.close();
      connection.close();
    }

    String [] argv = {
      "--bindir",
      JAR_GEN_DIR,
      "--outdir",
      CODE_GEN_DIR,
      "--package-name",
      OVERRIDE_PACKAGE_NAME,
    };

    runGenerationTest(argv, OVERRIDE_PACKAGE_NAME + "."
        + HsqldbTestServer.getTableName());
  }

  /**
   * Test the generated equals method.
   * @throws IOException
   * @throws ClassNotFoundException
   * @throws IllegalAccessException
   * @throws InstantiationException
   * @throws NoSuchMethodException
   * @throws SecurityException
   * @throws InvocationTargetException
   * @throws IllegalArgumentException
   */
  @Test
  public void testEqualsMethod() throws IOException, ClassNotFoundException,
      InstantiationException, IllegalAccessException, NoSuchMethodException,
      InvocationTargetException {

    // Set the option strings in an "argv" to redirect our srcdir and bindir
    String [] argv = {
      "--bindir",
      JAR_GEN_DIR,
      "--outdir",
      CODE_GEN_DIR,
      "--class-name",
      OVERRIDE_CLASS_AND_PACKAGE_NAME,
    };

    File ormJarFile = runGenerationTest(argv, OVERRIDE_CLASS_AND_PACKAGE_NAME);
    ClassLoader prevClassLoader = ClassLoaderStack.addJarFile(
        ormJarFile.getCanonicalPath(),
        OVERRIDE_CLASS_AND_PACKAGE_NAME);
    Class tableClass = Class.forName(
        OVERRIDE_CLASS_AND_PACKAGE_NAME,
        true,
        Thread.currentThread().getContextClassLoader());
    Method setterIntField1 =
        tableClass.getMethod("set_INTFIELD1", Integer.class);
    Method setterIntField2 =
        tableClass.getMethod("set_INTFIELD2", Integer.class);
    Method equalsImplementation = tableClass.getMethod("equals", Object.class);

    Object instance1 = tableClass.newInstance();
    Object instance2 = tableClass.newInstance();

    // test reflexivity
    assertTrue((Boolean) equalsImplementation.invoke(instance1, instance1));

    // test equality for uninitialized fields
    assertTrue((Boolean) equalsImplementation.invoke(instance1, instance2));

    // test symmetry
    assertTrue((Boolean) equalsImplementation.invoke(instance2, instance1));

    // test reflexivity with initialized fields
    setterIntField1.invoke(instance1, new Integer(1));
    setterIntField2.invoke(instance1, new Integer(2));
    assertTrue((Boolean) equalsImplementation.invoke(instance1, instance1));

    // test difference in both fields
    setterIntField1.invoke(instance2, new Integer(3));
    setterIntField2.invoke(instance2, new Integer(4));
    assertFalse((Boolean) equalsImplementation.invoke(instance1, instance2));

    // test difference in second field
    setterIntField1.invoke(instance2, new Integer(1));
    setterIntField2.invoke(instance2, new Integer(3));
    assertFalse((Boolean) equalsImplementation.invoke(instance1, instance2));

    // test difference in first field
    setterIntField1.invoke(instance2, new Integer(3));
    setterIntField2.invoke(instance2, new Integer(2));
    assertFalse((Boolean) equalsImplementation.invoke(instance1, instance2));

    // test equality for initialized fields
    setterIntField1.invoke(instance2, new Integer(1));
    setterIntField2.invoke(instance2, new Integer(2));
    assertTrue((Boolean) equalsImplementation.invoke(instance1, instance2));

    if (null != prevClassLoader) {
      ClassLoaderStack.setCurrentClassLoader(prevClassLoader);
    }
  }

  private static final String USERMAPPING_CLASS_AND_PACKAGE_NAME =
      "usermapping.pkg.prefix.classname";

  @Test
  public void testUserMapping() throws IOException, ClassNotFoundException,
      InstantiationException, IllegalAccessException, NoSuchMethodException,
      InvocationTargetException {

    // Set the option strings in an "argv" to redirect our srcdir and bindir
    String [] argv = {
      "--bindir", JAR_GEN_DIR,
      "--outdir", CODE_GEN_DIR,
      "--class-name", USERMAPPING_CLASS_AND_PACKAGE_NAME,
      "--map-column-java", "INTFIELD1=String",
    };

    File ormJarFile = runGenerationTest(argv,
            USERMAPPING_CLASS_AND_PACKAGE_NAME);
    ClassLoader prevClassLoader = ClassLoaderStack.addJarFile(
        ormJarFile.getCanonicalPath(),
        USERMAPPING_CLASS_AND_PACKAGE_NAME);
    Class tableClass = Class.forName(
        USERMAPPING_CLASS_AND_PACKAGE_NAME,
        true,
        Thread.currentThread().getContextClassLoader());

    try {
      Field intfield = tableClass.getDeclaredField("INTFIELD1");

      assertEquals(String.class, intfield.getType());
    } catch (NoSuchFieldException ex) {
      fail("Can't find field for INTFIELD1");
    } catch (SecurityException ex) {
      fail("Can't find field for INTFIELD1");
    }

    if (null != prevClassLoader) {
      ClassLoaderStack.setCurrentClassLoader(prevClassLoader);
    }
  }
}


text:
from django.apps import AppConfig

class BaseConfig(AppConfig):
    name = "pontoon.base"
    verbose_name = "Base"

    def ready(self):
        super().ready()

        # Load celery app so celery.shared_task uses it for executing
        # tasks.
        from pontoon.base.celeryapp import app as celery_app  # NOQA

        # Load and register signals.
        from pontoon.base import signals  # NOQA


text:
package scaffold.presentation.uml;

import scaffold.presentation.uml.form.UMLAssociationForm;
import scaffold.modeling.uml.basic.cm.CmAssociation;
import scaffold.platform.graphics.graph.Graph;

import java.awt.event.MouseEvent;

public class UMLAssociationLink extends UMLLink {
    // use the UMLLink.create() to ensure initialize() is called
    UMLAssociationLink(LinkType ltype, Graph graph, UMLEndPoint ep1, UMLEndPoint ep2, CmAssociation assoc) {
        super(ltype, graph, ep1, ep2);

        this.setModelElement(assoc);
    }

    @Override
    public void mouseClicked(MouseEvent event) {
        if (event.getClickCount() == 2) {
            //lazy create the form to save on load time
            if (associationForm == null) {
                this.associationForm = new UMLAssociationForm(assoc);
            }

            associationForm.loadValues();
            associationForm.setLocation(event.getXOnScreen(), event.getYOnScreen());
            associationForm.setLocationRelativeTo(null); //center dialog on screen
            associationForm.setVisible(true);
        }
    }

    private UMLAssociationForm      associationForm;
}


text:
<?php

/**
 * DO NOT EDIT!
 * This file was automatically generated via bin/generate-validator-spec.php.
 */

namespace AmpProject\Validator\Spec\Tag;

use AmpProject\Format;
use AmpProject\Html\Tag as Element;
use AmpProject\Validator\Spec\AttributeList;
use AmpProject\Validator\Spec\Identifiable;
use AmpProject\Validator\Spec\SpecRule;
use AmpProject\Validator\Spec\Tag;

/**
 * Tag class Fefuncr.
 *
 * @package ampproject/amp-toolbox.
 *
 * @property-read string $tagName
 * @property-read string $mandatoryParent
 * @property-read array<string> $attrLists
 * @property-read string $specUrl
 * @property-read string $mandatoryAncestor
 * @property-read array<string> $htmlFormat
 */
final class Fefuncr extends Tag implements Identifiable
{
    /**
     * ID of the tag.
     *
     * @var string
     */
    const ID = 'FEFUNCR';

    /**
     * Array of spec rules.
     *
     * @var array
     */
    const SPEC = [
        SpecRule::TAG_NAME => Element::FEFUNCR,
        SpecRule::MANDATORY_PARENT => Element::FECOMPONENTTRANSFER,
        SpecRule::ATTR_LISTS => [
            AttributeList\SvgCoreAttributes::ID,
            AttributeList\SvgTransferFunctionAttributes::ID,
        ],
        SpecRule::SPEC_URL => 'https://amp.dev/documentation/guides-and-tutorials/learn/spec/amphtml/#svg',
        SpecRule::MANDATORY_ANCESTOR => Element::SVG,
        SpecRule::HTML_FORMAT => [
            Format::AMP,
            Format::AMP4ADS,
        ],
    ];
}


text:
/**
 * src/make.js
 * Author: H.Alper Tuna <halpertuna@gmail.com>
 * Date: 28.08.2016
 */

import { lenses } from './Lens';

export default (lensName, type, renderer) => {
  let instanceOf = null;
  let inputType = type;
  if (typeof type === 'function') {
    instanceOf = inputType;
    inputType = 'object';
  }
  lenses[lensName] = {
    instanceOf,
    inputType,
    renderer,
  };
};


text:
"""The tests for the Netgear Arlo sensors."""
from collections import namedtuple
from unittest.mock import patch

import pytest

from homeassistant.components.arlo import DATA_ARLO, sensor as arlo
from homeassistant.components.arlo.sensor import SENSOR_TYPES
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.const import PERCENTAGE

def _get_named_tuple(input_dict):
    return namedtuple("Struct", input_dict.keys())(*input_dict.values())

def _get_sensor(hass, name="Last", sensor_type="last_capture", data=None):
    if data is None:
        data = {}
    sensor_entry = next(
        sensor_entry for sensor_entry in SENSOR_TYPES if sensor_entry.key == sensor_type
    )
    sensor_entry.name = name
    sensor = arlo.ArloSensor(data, sensor_entry)
    sensor.hass = hass
    return sensor

@pytest.fixture()
def default_sensor(hass):
    """Create an ArloSensor with default values."""
    return _get_sensor(hass)

@pytest.fixture()
def battery_sensor(hass):
    """Create an ArloSensor with battery data."""
    data = _get_named_tuple({"battery_level": 50})
    return _get_sensor(hass, "Battery Level", "battery_level", data)

@pytest.fixture()
def temperature_sensor(hass):
    """Create a temperature ArloSensor."""
    return _get_sensor(hass, "Temperature", "temperature")

@pytest.fixture()
def humidity_sensor(hass):
    """Create a humidity ArloSensor."""
    return _get_sensor(hass, "Humidity", "humidity")

@pytest.fixture()
def cameras_sensor(hass):
    """Create a total cameras ArloSensor."""
    data = _get_named_tuple({"cameras": [0, 0]})
    return _get_sensor(hass, "Arlo Cameras", "total_cameras", data)

@pytest.fixture()
def captured_sensor(hass):
    """Create a captured today ArloSensor."""
    data = _get_named_tuple({"captured_today": [0, 0, 0, 0, 0]})
    return _get_sensor(hass, "Captured Today", "captured_today", data)

class PlatformSetupFixture:
    """Fixture for testing platform setup call to add_entities()."""

    def __init__(self):
        """Instantiate the platform setup fixture."""
        self.sensors = None
        self.update = False

    def add_entities(self, sensors, update):
        """Mock method for adding devices."""
        self.sensors = sensors
        self.update = update

@pytest.fixture()
def platform_setup():
    """Create an instance of the PlatformSetupFixture class."""
    return PlatformSetupFixture()

@pytest.fixture()
def mock_dispatch():
    """Mock the dispatcher connect method."""
    target = "homeassistant.components.arlo.sensor.async_dispatcher_connect"
    with patch(target) as _mock:
        yield _mock

def test_setup_with_no_data(platform_setup, hass):
    """Test setup_platform with no data."""
    arlo.setup_platform(hass, None, platform_setup.add_entities)
    assert platform_setup.sensors is None
    assert not platform_setup.update

def test_setup_with_valid_data(platform_setup, hass):
    """Test setup_platform with valid data."""
    config = {
        "monitored_conditions": [
            "last_capture",
            "total_cameras",
            "captured_today",
            "battery_level",
            "signal_strength",
            "temperature",
            "humidity",
            "air_quality",
        ]
    }

    hass.data[DATA_ARLO] = _get_named_tuple(
        {
            "cameras": [_get_named_tuple({"name": "Camera", "model_id": "ABC1000"})],
            "base_stations": [
                _get_named_tuple({"name": "Base Station", "model_id": "ABC1000"})
            ],
        }
    )

    arlo.setup_platform(hass, config, platform_setup.add_entities)
    assert len(platform_setup.sensors) == 8
    assert platform_setup.update

def test_sensor_name(default_sensor):
    """Test the name property."""
    assert default_sensor.name == "Last"

async def test_async_added_to_hass(default_sensor, mock_dispatch):
    """Test dispatcher called when added."""
    await default_sensor.async_added_to_hass()
    assert len(mock_dispatch.mock_calls) == 1
    kall = mock_dispatch.call_args
    args, kwargs = kall
    assert len(args) == 3
    assert args[0] == default_sensor.hass
    assert args[1] == "arlo_update"
    assert not kwargs

def test_sensor_state_default(default_sensor):
    """Test the state property."""
    assert default_sensor.state is None

def test_sensor_device_class__battery(battery_sensor):
    """Test the battery device_class."""
    assert battery_sensor.device_class == SensorDeviceClass.BATTERY

def test_sensor_device_class(temperature_sensor):
    """Test the device_class property."""
    assert temperature_sensor.device_class == SensorDeviceClass.TEMPERATURE

def test_unit_of_measure(default_sensor, battery_sensor):
    """Test the unit_of_measurement property."""
    assert default_sensor.unit_of_measurement is None
    assert battery_sensor.unit_of_measurement == PERCENTAGE

def test_device_class(default_sensor, temperature_sensor, humidity_sensor):
    """Test the device_class property."""
    assert default_sensor.device_class is None
    assert temperature_sensor.device_class == SensorDeviceClass.TEMPERATURE
    assert humidity_sensor.device_class == SensorDeviceClass.HUMIDITY

def test_attribution(default_sensor, temperature_sensor, humidity_sensor):
    """Test the device_class property."""
    assert default_sensor.attribution == "Data provided by arlo.netgear.com"
    assert temperature_sensor.attribution == "Data provided by arlo.netgear.com"
    assert humidity_sensor.attribution == "Data provided by arlo.netgear.com"

def test_update_total_cameras(cameras_sensor):
    """Test update method for total_cameras sensor type."""
    cameras_sensor.update()
    assert cameras_sensor.state == 2

def test_update_captured_today(captured_sensor):
    """Test update method for captured_today sensor type."""
    captured_sensor.update()
    assert captured_sensor.state == 5

def _test_attributes(hass, sensor_type):
    data = _get_named_tuple({"model_id": "TEST123"})
    sensor = _get_sensor(hass, "test", sensor_type, data)
    attrs = sensor.extra_state_attributes
    assert attrs.get("brand") == "Netgear Arlo"
    assert attrs.get("model") == "TEST123"

def test_state_attributes(hass):
    """Test attributes for camera sensor types."""
    _test_attributes(hass, "battery_level")
    _test_attributes(hass, "signal_strength")
    _test_attributes(hass, "temperature")
    _test_attributes(hass, "humidity")
    _test_attributes(hass, "air_quality")

def test_attributes_total_cameras(cameras_sensor):
    """Test attributes for total cameras sensor type."""
    attrs = cameras_sensor.extra_state_attributes
    assert attrs.get("brand") == "Netgear Arlo"
    assert attrs.get("model") is None

def _test_update(hass, sensor_type, key, value):
    data = _get_named_tuple({key: value})
    sensor = _get_sensor(hass, "test", sensor_type, data)
    sensor.update()
    assert sensor.state == value

def test_update(hass):
    """Test update method for direct transcription sensor types."""
    _test_update(hass, "battery_level", "battery_level", 100)
    _test_update(hass, "signal_strength", "signal_strength", 100)
    _test_update(hass, "temperature", "ambient_temperature", 21.4)
    _test_update(hass, "humidity", "ambient_humidity", 45.1)
    _test_update(hass, "air_quality", "ambient_air_quality", 14.2)


text:
© {{ site.time | date: '%Y' }} {{ site.author.name }}
   with help from Jekyll Bootstrap-3. Theme: dbyll by dbtek.


text:
const { slugify } = require('./utils');
const path = require('path');

function unprefix (path, prefix) {
  if (path.startsWith(prefix)) {
    return path.slice(prefix.length);
  }
  return path;
}

module.exports = function (settings) {
  const sitePath = settings.SITE_URL
    .replace(/[?#](.*?)$/g, '')
    .replace(/^([a-z]*:)?\/\/[^/]+/g, '');

  const router = function (type, obj, with_file) {
    let url_tmpl = '';
    const opt = type.toUpperCase() + '_URL';
    if (!(opt in settings)) {
      throw new Error(`No known URL routing for content type "${type}"`);
    }
    else {
      url_tmpl = settings[opt];
      obj = obj || {};
    }

    if (typeof obj === 'string' || obj instanceof String) {
      // convert strings to objects usable by the below
      const s_obj = slugify(obj);
      obj = { slug: s_obj, title: s_obj };
    }

    let result = obj.url;
    if (!result) {
      result = url_tmpl.replace(/:(\w+)/g, (a, bit) => (bit in obj ? obj[bit] : '_MISSING_'));
      result = path.join(sitePath, result);
    }

    result = result
      .replace(/-{2,}/, '-')               // collapse dashes
      .replace(/[\\/-]+(?=\/)/g, '')       // trim any \/- before a slash
      .replace(/\/[\\/-]+/g, '/')          // trim any \/- after a slash
      .replace(/-+(\.[a-z0-9_]+)?$/, '$1') // remove file extensions
      .replace(/^-/, '');                  // don't end with a dash

    // cache the generated url
    if (obj && !obj.url) {
      obj.url = result;
    }

    if (with_file) {
      if (with_file === true) { with_file = 'index.html'; }
      result = unprefix(path.join(result, with_file), sitePath);
    }

    return result;
  };

  router.sitePath = sitePath;

  return router;
};


text:
Languages

French (Native)

English (Professional)

Chinese (Basic)

Dutch (Basic)


text:
var express = require('express');
var app = new express();
var bodyParser = require('body-parser');
var path = require('path');

var port = process.env.PORT || 8080;

// parse application/json
app.use(bodyParser.json());

app.use(express.static('public'));

app.get('/', function(req,res){
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(port, function () {
    console.log('Server is running on port: '+port);
});


text:
//***************************************************************************
// Practica C y D - LIGE - 2º B Ing. Tec. en Informática de Gestión
// Alumno: Gorka Suárez García
//***************************************************************************
package com.sgu.daos;
import com.sgu.objs.ObjUniversidad;
import com.sgu.daos.DaoUtil;
import com.sgu.util.Tracer;
import java.util.LinkedList;

/**
 *
Title: com.sgu.daos.DaoUniversidad

 *
Description: Objeto para acceder a los datos de una universidad.

 * @author Gorka Suárez García
 * @version 1.0
 */
public class DaoUniversidad
{
    //=======================================================================
    // Zona pública de la clase.
    //=======================================================================
    /**
     * Constructor de la clase.
     */
    public DaoUniversidad ()
    {
        this.tracer = new Tracer();
        this.util = new DaoUtil();
        this.tracer.debug("DaoUniversidad", "DaoUniversidad()", "Objeto creado.");
    }

    //-----------------------------------------------------------------------
    /**
     * Método para insertar una universidad en la base de datos.
     * @param obj Objeto con los datos del elemento.
     */
    public void insertar (ObjUniversidad obj)
    {
        this.tracer.debug("DaoUniversidad", "insertar()", "Iniciando la inserción...");
        String valores = obj.getID() + ", '" + obj.getNombre() + "', '" + obj.getDireccion() + "'";
        this.util.insertar("UNIVERSIDADES", valores);
        this.tracer.debug("DaoUniversidad", "insertar()", "Insercion finalizada.");
    }

    //-----------------------------------------------------------------------
    /**
     * Método para eliminar una universidad en la base de datos.
     * @param id ID del elemento.
     */
    public void eliminar (int id)
    {
        this.tracer.debug("DaoUniversidad", "eliminar()", "Iniciando eliminación...");
        String condicion = "ID=" + id;
        this.util.eliminar("UNIVERSIDADES", condicion);
        this.tracer.debug("DaoUniversidad", "eliminar()", "Eliminación finalizada.");
    }

    //-----------------------------------------------------------------------
    /**
     * Método para modificar una universidad en la base de datos.
     * @param obj Objeto con los datos del elemento.
     */
    public void modificar (ObjUniversidad obj)
    {
        this.tracer.debug("DaoUniversidad", "actualizar()", "Iniciando la modificación...");
        String condicion = "ID=" + obj.getID();
        String valores = "NOMBRE='" + obj.getNombre() + "', DIRECCION='" + obj.getDireccion() + "'";
        this.util.modificar("UNIVERSIDADES", valores, condicion);
        this.tracer.debug("DaoUniversidad", "actualizar()", "Modificación finalizada.");
    }

    //-----------------------------------------------------------------------
    /**
     * Método para saber si está una universidad en la base de datos.
     * @param id ID del elemento.
     * @return boolean Devuelve si existe o no.
     */
    public boolean existe (int id)
    {
        this.tracer.debug("DaoUniversidad", "existe()", "Iniciando la busqueda...");
        boolean existe = false;

        try
        {
            String query = "SELECT * FROM UNIVERSIDADES WHERE ID=" + id;
            ConsultaUniversidad result = new ConsultaUniversidad();
            this.util.consultar(query, result);

            LinkedList<ObjUniversidad> lista = result.getLista();
            for(ObjUniversidad regact : lista)
            {
                if((regact.getID() != 0) && (id == regact.getID()))
                {
                    this.tracer.debug("DaoUniversidad", "existe()", "La consulta no es nula.");
                    existe = true;
                    break;
                }
            }
        }
        catch(Exception e)
        {
            this.tracer.error("DaoUniversidad", "existe()", e.getMessage());
        }

        this.tracer.debug("DaoUniversidad", "existe()", "busqueda finalizada.");
        return existe;
    }

    //-----------------------------------------------------------------------
    /**
     * Método para obtener una universidad en la base de datos.
     * @param id ID del elemento.
     * @return Devuelve el elemento si lo encuentra.
     */
    public ObjUniversidad buscar (int id)
    {
        this.tracer.debug("DaoUniversidad", "buscar()", "Iniciando la consulta...");
        ObjUniversidad obj = null;

        try
        {
            String query = "SELECT * FROM UNIVERSIDADES WHERE ID=" + id;
            ConsultaUniversidad result = new ConsultaUniversidad();
            this.util.consultar(query, result);

            LinkedList<ObjUniversidad> lista = result.getLista();
            for(ObjUniversidad regact : lista)
            {
                if((regact.getID() != 0) && (id == regact.getID()))
                {
                    this.tracer.debug("DaoUniversidad", "buscar()", "La consulta no es nula.");
                    obj = new ObjUniversidad(regact);
                    break;
                }
            }
        }
        catch(Exception e)
        {
            this.tracer.error("DaoUniversidad", "buscar()", e.getMessage());
        }

        this.tracer.debug("DaoUniversidad", "buscar()", "Busqueda finalizada.");
        return obj;
    }

    //-----------------------------------------------------------------------
    /**
     * Método para obtener una universidad en la base de datos.
     * @return LinkedList<ObjUniversidad> Una lista con todos los elementos de la tabla.
     */
    public LinkedList<ObjUniversidad> buscar ()
    {
        this.tracer.debug("DaoUniversidad", "buscar()", "Iniciando la consulta...");
        LinkedList<ObjUniversidad> lista = null;

        try
        {
            String query = "SELECT * FROM UNIVERSIDADES";
            ConsultaUniversidad result = new ConsultaUniversidad();
            this.util.consultar(query, result);
            lista = result.getLista();
        }
        catch(Exception e)
        {
            this.tracer.error("DaoUniversidad", "buscar()", e.getMessage());
        }

        this.tracer.debug("DaoUniversidad", "buscar()", "Busqueda finalizada.");
        return lista;
    }

    //=======================================================================
    // Zona privada de la clase.
    //=======================================================================
    private Tracer tracer;
    private DaoUtil util;
}


text:
package ai.h2o.sparkling.backend.utils

import ai.h2o.sparkling.backend.utils.ReflectionUtils._
import ai.h2o.sparkling.backend.utils.SupportedTypes._
import org.apache.spark.unsafe.types.UTF8String
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

import scala.reflect.runtime.universe._

@RunWith(classOf[JUnitRunner])
class SupportedTypesTestSuite extends FunSuite {

  test("Infer type from a value") {
    def mustBe[T](expected: SupportedType, value: T): Unit = assert(supportedTypeOf(value) == expected)

    mustBe(Boolean, true)
    mustBe(Boolean, false)
    mustBe(Byte, 1.asInstanceOf[Byte])
    mustBe(Byte, -1.asInstanceOf[Byte])
    mustBe(Short, 2.asInstanceOf[Short])
    mustBe(Short, -2.asInstanceOf[Short])
    mustBe(Integer, 3)
    mustBe(Integer, -3)
    mustBe(Long, 4L)
    mustBe(Long, -4L)
    mustBe(Float, 5.1f)
    mustBe(Float, -5.2f)
    mustBe(Double, 6.3)
    mustBe(Double, -6.3)
    mustBe(Double, math.Pi)
    mustBe(Timestamp, new java.sql.Timestamp(1472777182999L))
    mustBe(Date, java.sql.Date.valueOf("2016-12-24"))
    mustBe(String, "")
    mustBe(String, "Hello H2O")
  }

  test("Fail to infer type from a weird value") {
    def mustFail[T](msg: String, value: T): Unit =
      try {
        val t = supportedTypeOf(value)
        fail(s"Not acceptable: $msg: got $t")
      } catch {
        case _: IllegalArgumentException => //success
      }

    mustFail("Null", null)
    mustFail("Date", new java.util.Date(12345L))
    mustFail("Option(None)", None)
    mustFail("Option(Some)", Some("one"))
  }

  test("Infer type from simple scala type") {
    import scala.reflect.runtime.universe.definitions._

    val stringCheck = SupportedTypes.String.matches(typeOf[String])
    assert(stringCheck, "Problems with String type")

    def mustBe[T](expected: SupportedType, t: Type): Unit = assert(SupportedTypes.byType(t) == expected)

    mustBe(Boolean, BooleanTpe)
    mustBe(Boolean, typeOf[scala.Boolean])
    mustBe(Boolean, typeOf[java.lang.Boolean])
    mustBe(Byte, ByteTpe)
    mustBe(Byte, typeOf[scala.Byte])
    mustBe(Byte, typeOf[java.lang.Byte])
    mustBe(Short, ShortTpe)
    mustBe(Short, typeOf[scala.Short])
    mustBe(Short, typeOf[java.lang.Short])
    mustBe(Integer, IntTpe)
    mustBe(Integer, typeOf[scala.Int])
    mustBe(Integer, typeOf[java.lang.Integer])
    mustBe(Long, LongTpe)
    mustBe(Long, typeOf[scala.Long])
    mustBe(Long, typeOf[java.lang.Long])
    mustBe(Float, FloatTpe)
    mustBe(Float, typeOf[scala.Float])
    mustBe(Float, typeOf[java.lang.Float])
    mustBe(Double, DoubleTpe)
    mustBe(Double, typeOf[scala.Double])
    mustBe(Double, typeOf[java.lang.Double])
    mustBe(Timestamp, typeOf[java.sql.Timestamp])
    mustBe(Date, typeOf[java.sql.Date])
    mustBe(String, typeOf[String])
    mustBe(UTF8, typeOf[UTF8String])
  }

  test("Infer type from optional scala type") {

    def mustBe[T](expected: SupportedType, t: Type): Unit = assert(SupportedTypes.byType(t) == expected)

    mustBe(OptionalType(Boolean), typeOf[Option[scala.Boolean]])
    mustBe(OptionalType(Byte), typeOf[Option[scala.Byte]])
    mustBe(OptionalType(Short), typeOf[Option[scala.Short]])
    mustBe(OptionalType(Integer), typeOf[Option[scala.Int]])
    mustBe(OptionalType(Long), typeOf[Option[scala.Long]])
    mustBe(OptionalType(Float), typeOf[Option[scala.Float]])
    mustBe(OptionalType(Double), typeOf[Option[scala.Double]])
    mustBe(OptionalType(Timestamp), typeOf[Option[java.sql.Timestamp]])
    mustBe(OptionalType(Date), typeOf[Option[java.sql.Date]])
    mustBe(OptionalType(String), typeOf[Option[String]])
    mustBe(OptionalType(UTF8), typeOf[Option[UTF8String]])
  }

  test("Find By String") {
    def mustBe[T](expected: SupportedType, name: String): Unit = assert(SupportedTypes.byName(name) == expected)

    mustBe(Boolean, "Boolean")
    mustBe(Byte, "Byte")
    mustBe(Short, "Short")
    mustBe(Integer, "Integer")
    mustBe(Long, "Long")
    mustBe(Float, "Float")
    mustBe(Double, "Double")
    mustBe(Timestamp, "Timestamp")
    mustBe(Date, "Date")
    mustBe(String, "String")
    mustBe(UTF8, "UTF8")
  }
}