text:
package org.apache.hive.hcatalog.common;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStore;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hive.hcatalog.NoExitSecurityManager;
import org.apache.hive.hcatalog.cli.SemanticAnalysis.HCatSemanticAnalyzer;
import org.apache.thrift.TException;
import org.junit.AfterClass;
import org.junit.BeforeClass;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestHiveClientCache {

  private static final Logger LOG = LoggerFactory.getLogger(TestHiveClientCache.class);
  final HiveConf hiveConf = new HiveConf();

  @BeforeClass
  public static void setUp() throws Exception {
  }

  @AfterClass
  public static void tearDown() throws Exception {
  }

  @Test
  public void testCacheHit() throws IOException, MetaException, LoginException {
    HiveClientCache cache = new HiveClientCache(1000);
    HiveClientCache.ICacheableMetaStoreClient client = (HiveClientCache.ICacheableMetaStoreClient) cache.get(hiveConf);
    assertNotNull(client);
    client.close(); // close shouldn't matter

    // Setting a non important configuration should return the same client only
    hiveConf.setIntVar(HiveConf.ConfVars.DYNAMICPARTITIONMAXPARTS, 10);
    HiveClientCache.ICacheableMetaStoreClient client2 = (HiveClientCache.ICacheableMetaStoreClient) cache.get(hiveConf);
    assertNotNull(client2);
    assertSame(client, client2);
    assertEquals(client.getUsers(), client2.getUsers());
    client2.close();
  }

  @Test
  public void testCacheMiss() throws IOException, MetaException, LoginException {
    HiveClientCache cache = new HiveClientCache(1000);
    IMetaStoreClient client = cache.get(hiveConf);
    assertNotNull(client);

    // Set different uri as it is one of the criteria deciding whether to return the same client or not
    hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, " "); // URIs are checked for string equivalence, even spaces make them different
    IMetaStoreClient client2 = cache.get(hiveConf);
    assertNotNull(client2);
    assertNotSame(client, client2);
  }

  /**
   * Check that a new client is returned for the same configuration after the expiry time.
   * Also verify that the expiry time configuration is honoured
   */
  @Test
  public void testCacheExpiry() throws IOException, MetaException, LoginException, InterruptedException {
    HiveClientCache cache = new HiveClientCache(1);
    HiveClientCache.ICacheableMetaStoreClient client = (HiveClientCache.ICacheableMetaStoreClient) cache.get(hiveConf);
    assertNotNull(client);

    Thread.sleep(2500);
    HiveClientCache.ICacheableMetaStoreClient client2 = (HiveClientCache.ICacheableMetaStoreClient) cache.get(hiveConf);
    client.close();
    assertTrue(client.isClosed()); // close() after *expiry time* and *a cache access* should  have tore down the client

    assertNotNull(client2);
    assertNotSame(client, client2);
  }

  /**
   * Check that a *new* client is created if asked from different threads even with
   * the same hive configuration
   * @throws ExecutionException
   * @throws InterruptedException
   */
  @Test
  public void testMultipleThreadAccess() throws ExecutionException, InterruptedException {
    final HiveClientCache cache = new HiveClientCache(1000);

    class GetHiveClient implements Callable<IMetaStoreClient> {
      @Override
      public IMetaStoreClient call() throws IOException, MetaException, LoginException {
        return cache.get(hiveConf);
      }
    }

    ExecutorService executor = Executors.newFixedThreadPool(2);

    Callable<IMetaStoreClient> worker1 = new GetHiveClient();
    Callable<IMetaStoreClient> worker2 = new GetHiveClient();
    Future<IMetaStoreClient> clientFuture1 = executor.submit(worker1);
    Future<IMetaStoreClient> clientFuture2 = executor.submit(worker2);
    IMetaStoreClient client1 = clientFuture1.get();
    IMetaStoreClient client2 = clientFuture2.get();
    assertNotNull(client1);
    assertNotNull(client2);
    assertNotSame(client1, client2);
  }

  @Test
  public void testCloseAllClients() throws IOException, MetaException, LoginException {
    final HiveClientCache cache = new HiveClientCache(1000);
    HiveClientCache.ICacheableMetaStoreClient client1 = (HiveClientCache.ICacheableMetaStoreClient) cache.get(hiveConf);
    hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, " "); // URIs are checked for string equivalence, even spaces make them different
    HiveClientCache.ICacheableMetaStoreClient client2 = (HiveClientCache.ICacheableMetaStoreClient) cache.get(hiveConf);
    cache.closeAllClientsQuietly();
    assertTrue(client1.isClosed());
    assertTrue(client2.isClosed());
  }

  /**
   * Test that a long table name actually breaks the HMSC. Subsequently check that isOpen() reflects
   * and tells if the client is broken
   */
  @Ignore("hangs indefinitely")
  @Test
  public void testHMSCBreakability() throws IOException, MetaException, LoginException, TException, AlreadyExistsException,
      InvalidObjectException, NoSuchObjectException, InterruptedException {
    // Setup
    LocalMetaServer metaServer = new LocalMetaServer();
    metaServer.start();

    final HiveClientCache cache = new HiveClientCache(1000);
    HiveClientCache.CacheableHiveMetaStoreClient client =
        (HiveClientCache.CacheableHiveMetaStoreClient) cache.get(metaServer.getHiveConf());

    assertTrue(client.isOpen());

    final String DB_NAME = "test_db";
    final String LONG_TABLE_NAME = "long_table_name_" + new BigInteger(200, new Random()).toString(2);

    try {
      client.dropTable(DB_NAME, LONG_TABLE_NAME);
    } catch (Exception e) {
    }
    try {
      client.dropDatabase(DB_NAME);
    } catch (Exception e) {
    }

    client.createDatabase(new Database(DB_NAME, "", null, null));

    List<FieldSchema> fields = new ArrayList<FieldSchema>();
    fields.add(new FieldSchema("colname", serdeConstants.STRING_TYPE_NAME, ""));
    Table tbl = new Table();
    tbl.setDbName(DB_NAME);
    tbl.setTableName(LONG_TABLE_NAME);
    StorageDescriptor sd = new StorageDescriptor();
    sd.setCols(fields);
    tbl.setSd(sd);
    sd.setSerdeInfo(new SerDeInfo());

    // Break the client
    try {
      client.createTable(tbl);
      fail("Exception was expected while creating table with long name");
    } catch (Exception e) {
    }

    assertFalse(client.isOpen());
    metaServer.shutDown();
  }

  private static class LocalMetaServer implements Runnable {
    public final int MS_PORT = 20101;
    private final HiveConf hiveConf;
    private final SecurityManager securityManager;
    public final static int WAIT_TIME_FOR_BOOTUP = 30000;

    public LocalMetaServer() {
      securityManager = System.getSecurityManager();
      System.setSecurityManager(new NoExitSecurityManager());
      hiveConf = new HiveConf(TestHiveClientCache.class);
      hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, "thrift://localhost:"
          + MS_PORT);
      hiveConf.setIntVar(HiveConf.ConfVars.METASTORETHRIFTCONNECTIONRETRIES, 3);
      hiveConf.setIntVar(HiveConf.ConfVars.METASTORETHRIFTFAILURERETRIES, 3);
      hiveConf.set(HiveConf.ConfVars.SEMANTIC_ANALYZER_HOOK.varname,
          HCatSemanticAnalyzer.class.getName());
      hiveConf.set(HiveConf.ConfVars.PREEXECHOOKS.varname, "");
      hiveConf.set(HiveConf.ConfVars.POSTEXECHOOKS.varname, "");
      hiveConf.set(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY.varname,
          "false");
      System.setProperty(HiveConf.ConfVars.PREEXECHOOKS.varname, " ");
      System.setProperty(HiveConf.ConfVars.POSTEXECHOOKS.varname, " ");
    }

    public void start() throws InterruptedException {
      Thread thread = new Thread(this);
      thread.start();
      Thread.sleep(WAIT_TIME_FOR_BOOTUP); // Wait for the server to bootup
    }

    @Override
    public void run() {
      try {
        HiveMetaStore.main(new String[]{"-v", "-p", String.valueOf(MS_PORT)});
      } catch (Throwable t) {
        LOG.error("Exiting. Got exception from metastore: ", t);
      }
    }

    public HiveConf getHiveConf() {
      return hiveConf;
    }

    public void shutDown() {
      System.setSecurityManager(securityManager);
    }
  }
}


text:
class DesignationFileUploader < CarrierWave::Uploader::Base
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{model.organization.slug}/#{mounted_as}/#{model.id}"
  end
end

redpajama_set_name: RedPajamaGithub


text:
import React, { PureComponent } from 'react';

export default class VideoThumbnail extends PureComponent {

    props: {
		imgSrc: string,
		title: string,
		videoId: string,
	};

    openVideo = () => {
        const { videoId } = this.props;
        window.open('https://www.youtube.com/watch?v=' + videoId, '_blank');
    }

    render() {
        const { imgSrc, title } = this.props;

        return (

                <div className="video-img" style={{ backgroundImage: `url(${imgSrc})` }} />

{title}

        );
    }
}


text:
package commands

import (
	"fmt"
	"strings"

	"github.com/ambientsound/pms/api"
	"github.com/ambientsound/pms/input/lexer"
	"github.com/ambientsound/pms/keysequence"
)

// Bind maps a key sequence to the execution of a command.
type Bind struct {
	newcommand
	api      api.API
	sentence string
	seq      keysequence.KeySequence
}

// NewBind returns Bind.
func NewBind(api api.API) Command {
	return &Bind{
		api: api,
	}
}

// Parse implements Command.
func (cmd *Bind) Parse() error {

	// Use the key sequence parser for parsing the next token.
	parser := keysequence.NewParser(cmd.S)

	// Parse a valid key sequence from the scanner.
	seq, err := parser.ParseKeySequence()
	if err != nil {
		return err
	}
	cmd.seq = seq

	// Treat the rest of the line as the literal action to execute when the bind succeeds.
	sentence := make([]string, 0, 32)
	for {
		tok, lit := cmd.Scan()
		if tok == lexer.TokenEnd {
			break
		} else if tok == lexer.TokenIdentifier {
			// Quote identifiers?
		}
		sentence = append(sentence, lit)
	}

	if len(sentence) == 0 {
		return fmt.Errorf("Unexpected END, expected identifier")
	}

	cmd.sentence = strings.Join(sentence, "")
	return nil
}

// Exec implements Command.
func (cmd *Bind) Exec() error {
	sequencer := cmd.api.Sequencer()
	return sequencer.AddBind(cmd.seq, cmd.sentence)
}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ExportCsvComponent } from './export-csv.component';
import { FilterService } from '../../services/filter.service';
import { SpaceQuery } from '../../models/space';
import { NgLetModule } from '../../shared/ng-let';
import { TooltipModule } from 'ngx-bootstrap';

@NgModule({
  imports: [CommonModule, NgLetModule, TooltipModule],
  declarations: [ExportCsvComponent],
  exports: [ExportCsvComponent],
  providers: [FilterService, SpaceQuery],
})
export class ExportCsvModule {}


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

<TITLE>
Uses of Class org.apache.pig.experimental.logical.relational.LogicalSchema (Pig 0.7.0 API)
</TITLE>

<META NAME="date" CONTENT="2010-05-05">

<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
org.apache.pig.experimental.logical.relational.LogicalSchema

Packages that use LogicalSchema

org.apache.pig.experimental.logical.relational

org.apache.pig.experimental.logical.rules

Uses of LogicalSchema in org.apache.pig.experimental.logical.relational

Fields in org.apache.pig.experimental.logical.relational declared as LogicalSchema

 LogicalSchema
LogicalSchema.LogicalFieldSchema.schema

protected  LogicalSchema
LogicalRelationalOperator.schema

Methods in org.apache.pig.experimental.logical.relational that return LogicalSchema

abstract  LogicalSchema
LogicalRelationalOperator.getSchema()

          Get the schema for the output of this relational operator.

 LogicalSchema
LOUnion.getSchema()

 LogicalSchema
LOStore.getSchema()

 LogicalSchema
LOSplitOutput.getSchema()

 LogicalSchema
LOSplit.getSchema()

 LogicalSchema
LOLoad.getSchema()

          Get the schema for this load.

 LogicalSchema
LOJoin.getSchema()

 LogicalSchema
LOInnerLoad.getSchema()

 LogicalSchema
LOGenerate.getSchema()

 LogicalSchema
LOForEach.getSchema()

 LogicalSchema
LOFilter.getSchema()

 LogicalSchema
LOCogroup.getSchema()

static LogicalSchema
LogicalSchema.merge(LogicalSchema s1,
      LogicalSchema s2)

          Merge two schemas.

Methods in org.apache.pig.experimental.logical.relational with parameters of type LogicalSchema

static LogicalSchema
LogicalSchema.merge(LogicalSchema s1,
      LogicalSchema s2)

          Merge two schemas.

 void
LogicalRelationalOperator.neverUseForRealSetSchema(LogicalSchema schema)

          Only to be used by unit tests.

 void
LOLoad.setScriptSchema(LogicalSchema schema)

Constructors in org.apache.pig.experimental.logical.relational with parameters of type LogicalSchema

LogicalSchema.LogicalFieldSchema(String alias,
                                 LogicalSchema schema,
                                 byte type)

LogicalSchema.LogicalFieldSchema(String alias,
                                 LogicalSchema schema,
                                 byte type,
                                 long uid)

LOLoad(FileSpec loader,
       LogicalSchema schema,
       LogicalPlan plan)

Uses of LogicalSchema in org.apache.pig.experimental.logical.rules

Methods in org.apache.pig.experimental.logical.rules with parameters of type LogicalSchema

protected  Set<Integer>
ColumnPruneHelper.getColumns(LogicalSchema schema,
           Set<Long> uids)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © ${year} The Apache Software Foundation


text:
package com.example.team8capstone.glasstestapplication;

import com.example.team8capstone.glasstestapplication.image.ImageActivity;
import com.example.team8capstone.glasstestapplication.video.VideoActivity;

import com.google.android.glass.media.Sounds;
import com.google.android.glass.view.WindowUtils;
import com.google.android.glass.widget.CardBuilder;
import com.google.android.glass.widget.CardScrollAdapter;
import com.google.android.glass.widget.CardScrollView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.text.format.Time;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.Window;
import android.widget.AdapterView;

import java.util.ArrayList;
import java.util.List;
import java.lang.Runtime;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class MainActivity extends Activity implements MediaPlayer.OnCompletionListener {
    // Array of Card Infos
    private ArrayList<CardInfo> cardInfos = new ArrayList<CardInfo>();

    // Other variables used (name is self explanatory)
    private CardScrollView mCardScroller;
    private boolean mVoiceMenuEnabled = true;
    private CardScrollAdapter mAdapter;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private boolean isPaused = false;

    private Intent image;
    private Intent video;

//    private static final String TAG = "LogEntryStart";
//
//    private StringBuilder log=new StringBuilder();
//
//    private Time time = new Time();

//    private boolean hasPlayed = false;

//    private int currentSlide = 0;

    private AudioManager am;how to make a license file

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

        // Sets Card Info
        setCardInfo();

        // Instantiates a new intent for the ImageActivity that will be activated when
        // the user wishes to view a picture
        image = new Intent(this, ImageActivity.class);

        // Instantiates a new intent for the VideoActivity that will be activated when
        // the user wishes to view a video
        video = new Intent(this, VideoActivity.class);

        // Requests a voice menu on this activity. As for any other window feature,
        // be sure to request this before setContentView() is called
        getWindow().requestFeature(WindowUtils.FEATURE_VOICE_COMMANDS);

        // Ensure screen stays on during demo.
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        mCardScroller = new CardScrollView(this);
        mAdapter = new CardAdapter(createCards(this), this, cardInfos);
        mCardScroller.setAdapter(mAdapter);
        setCardScrollerListener();
        setContentView(mCardScroller);

//        try {
//            Process process = Runtime.getRuntime().exec("logcat -d");
//            BufferedReader bufferedReader = new BufferedReader(
//                    new InputStreamReader(process.getInputStream()));
//
//
//            String line = "";
//            while ((line = bufferedReader.readLine()) != null) {
//                log.append(line);
//            }
//
//        } catch (IOException e) {
//        }

        // Set mediaPlayer volume to max
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_SYSTEM);
        am.setStreamVolume(AudioManager.STREAM_SYSTEM,am.getStreamMaxVolume(AudioManager.STREAM_SYSTEM),0);

    }

    // When the MediaPlayer finishes, close and refresh the menu
    public void onCompletion(MediaPlayer mediaplayer) {
        getWindow().closePanel(WindowUtils.FEATURE_VOICE_COMMANDS);
        closeOptionsMenu();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCardScroller.activate();
//        time.setToNow();
//        Log.i(TAG,time.toString() + ", " + "MainActivity activated" + " LogEntryEnd");
//        Log.i(TAG,time.toString() + ", " + "Current Slide:" + mCardScroller.getSelectedItemPosition() + " LogEntryEnd");
    }

    @Override
    protected void onPause() {
        if (mediaPlayer.isPlaying()){
            mediaPlayer.reset();
        }

        mCardScroller.deactivate();
//        time.setToNow();
//        Log.i(TAG, time.toString() + ", " + "MainActivity deactivated" + " LogEntryEnd");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // Release the MediaPlayer when the activity finishes
        mediaPlayer.release();
//        time.setToNow();
//        Log.i(TAG,time.toString() + ", " + "MainActivity destroyed" + " LogEntryEnd");
//        try {
//            File file = new File(Environment.getExternalStorageDirectory()+"/"+Environment.DIRECTORY_DOWNLOADS + "/log_" + time.toString().replace("/","_") + ".txt");
//
//            BufferedWriter output = new BufferedWriter(new FileWriter(file));
//            output.write(log.toString());
//            output.close();
//        }
//        catch (Exception e){
//            Log.e(TAG,e.getMessage());
//        }
        super.onDestroy();
    }

    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        if (featureId == WindowUtils.FEATURE_VOICE_COMMANDS ||
                featureId == Window.FEATURE_OPTIONS_PANEL) {
            getMenuInflater().inflate(R.menu.voice_menu, menu);
//            time.setToNow();
//            Log.i(TAG,time.toString() + ", " + "Menu created" + " LogEntryEnd");
            return true;
        }
        // Good practice to pass through, for options menu.
        return super.onCreatePanelMenu(featureId, menu);
    }

    @Override
    public boolean onPreparePanel(int featureId, View view, Menu menu) {
        if (featureId == WindowUtils.FEATURE_VOICE_COMMANDS ||
                featureId == Window.FEATURE_OPTIONS_PANEL) {

            int position = mCardScroller.getSelectedItemPosition();

            addDefaultMenuOptions(menu, position);
            addCustomMenuOptions(menu, position);

            // If the MediaPlayer is playing, add media options
            if (mediaPlayer.isPlaying() || isPaused){
                addMediaMenuOptions(menu);

            }

            collapseMenu(menu,1);
//            time.setToNow();
//            Log.i(TAG,time.toString() + ", " + "Menu populated" + " LogEntryEnd");

            // Dynamically decides between enabling/disabling voice menu.
            return mVoiceMenuEnabled;
        }

        // Good practice to pass through, for options menu.
        return super.onPreparePanel(featureId, view, menu);
    }

    // Add default menu options
    private void addDefaultMenuOptions(Menu menu, int position){
        menu.add(Menu.NONE,10,Menu.NONE,"next");
        menu.add(Menu.NONE,11,Menu.NONE,"back");
        menu.addSubMenu(Menu.NONE,12,Menu.NONE,"goto");
        setGotoMenuOptions(menu, position);
        menu.addSubMenu(Menu.NONE,13,Menu.NONE,"exit");
        menu.findItem(13).getSubMenu().add(Menu.NONE,14,Menu.NONE,"yes");
    }

    private void setGotoMenuOptions(Menu menu, int position) {
        // Add menu options based on slide position
        for (CardInfo cardInfo : cardInfos) {
            if (!cardInfo.hasHeader) {
                menu.findItem(12).getSubMenu().add(Menu.NONE, cardInfo.goTo, Menu.NONE, Integer.toString(cardInfo.slideNumber + 1));
            }
            else {
                menu.findItem(12).getSubMenu().add(Menu.NONE, cardInfo.goTo, Menu.NONE, cardInfo.header);
            }
        }
    }

    private void addCustomMenuOptions(Menu menu, int position){

        // Add and adjust menu options based on slide content
        menu.findItem(12).getSubMenu().removeItem(cardInfos.get(0).offset + position);

        if (position == 0){
            menu.removeItem(11);
        }

        if (position == cardInfos.size() - 1){
            menu.removeItem(10);
        }

        if (cardInfos.get(position).hasAudio){
            if (!mediaPlayer.isPlaying() && !isPaused) {
                menu.add(Menu.NONE,1,Menu.NONE,"play audio");
            }
        }

        if (cardInfos.get(position).hasVideo){
            menu.add(Menu.NONE,0,Menu.NONE,"play video");
        }

        if (cardInfos.get(position).hasImage){
            menu.add(Menu.NONE,2,Menu.NONE,"view picture");
        }

    }

    private void addMediaMenuOptions(Menu menu){
        menu.add(Menu.NONE,3,Menu.NONE,"stop media");
        menu.addSubMenu(Menu.NONE,9,Menu.NONE,"media options");
        if (isPaused){
            menu.findItem(9).getSubMenu().add(Menu.NONE,4,Menu.NONE,"resume");
        }
        else {
            menu.findItem(9).getSubMenu().add(Menu.NONE,5,Menu.NONE,"pause");
        }
        menu.findItem(9).getSubMenu().add(Menu.NONE,6,Menu.NONE,"rewind");
        menu.findItem(9).getSubMenu().add(Menu.NONE,7,Menu.NONE,"fast forward");
        menu.findItem(9).getSubMenu().add(Menu.NONE,8,Menu.NONE,"play from beginning");
//        menu.findItem(9).getSubMenu().add(Menu.NONE,15,Menu.NONE,"volume up");
//        menu.findItem(9).getSubMenu().add(Menu.NONE,16,Menu.NONE,"volume down");
    }

    // Collapse a menu to prevent menu options from going off the viewable screen
    private void collapseMenu(Menu menu, int level){
//        if (level == 1){
//            if (menu.size() > 4){
//                menu.addSubMenu(Menu.NONE,level*100,Menu.NONE,"more options");
//            }
//        }
//        else {
//            if (menu.size() > 3){
//                menu.addSubMenu(Menu.NONE,level*100,Menu.NONE,"more options");
//            }
//        }
//
//        if (level == 1){
//            if (menu.size() > 4){
//                for (int i = 3; i < menu.size(); i++){
//                    if (!(menu.getItem(i).getItemId()/100 >= 1)){
//                        if(menu.getItem(i).hasSubMenu()){
//                            reMenu(menu.findItem(level*100).getSubMenu(), menu.getItem(i));
//                        }
//                        else {
//                            menu.findItem(level*100).getSubMenu().add(Menu.NONE,menu.getItem(i).getItemId(),Menu.NONE,menu.getItem(i).getTitle());
//                        }
//                        menu.removeItem(menu.getItem(i).getItemId());
//                    }
//                }
//            }
//        }
//        else {
//            if (menu.size() > 3){
//                for (int i = 2; i < menu.size(); i++){
//                    if (!(menu.getItem(i).getItemId()/100 >= 1)){
//                        if(menu.getItem(i).hasSubMenu()){
//                            reMenu(menu.findItem(level*100).getSubMenu(), menu.getItem(i));
//                        }
//                        else {
//                            menu.findItem(level*100).getSubMenu().add(Menu.NONE,menu.getItem(i).getItemId(),Menu.NONE,menu.getItem(i).getTitle());
//                        }
//                        menu.removeItem(menu.getItem(i).getItemId());
//                    }
//                }
//            }
//        }

        for (int i = 0; i < menu.size(); i++){
            if (menu.getItem(i).hasSubMenu()){
                collapseMenu(menu.getItem(i).getSubMenu(),level+1);
            }
        }
        menu.add(Menu.NONE,99,Menu.NONE,"cancel");
    }

    // Add a pre-populated SubMenu to another Menu
    private void reMenu(Menu menu, MenuItem reMenu){
        menu.addSubMenu(Menu.NONE,reMenu.getItemId(),Menu.NONE,reMenu.getTitle());
        for (int i = 0; i < reMenu.getSubMenu().size(); i++){
            if (reMenu.getSubMenu().getItem(i).hasSubMenu()){
                menu.findItem(reMenu.getItemId()).getSubMenu().addSubMenu(Menu.NONE,reMenu.getSubMenu().getItem(i).getItemId(),Menu.NONE,reMenu.getSubMenu().getItem(i).getTitle());
                reMenu(menu.findItem(reMenu.getItemId()).getSubMenu().findItem(reMenu.getSubMenu().getItem(i).getItemId()).getSubMenu(),reMenu.getSubMenu().getItem(i));
            }
            else{
                menu.findItem(reMenu.getItemId()).getSubMenu().add(Menu.NONE,reMenu.getSubMenu().getItem(i).getItemId(),Menu.NONE,reMenu.getSubMenu().getItem(i).getTitle());
            }
        }
    }

    // Set menu item actions
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        if (featureId == WindowUtils.FEATURE_VOICE_COMMANDS ||
                featureId == Window.FEATURE_OPTIONS_PANEL) {
            switch (item.getItemId()) {
                case 2:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "ImageActivity started" + " LogEntryEnd");
                    startActivity(image);
                    break;
                case 1:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "MediaPlayer started" + " LogEntryEnd");
                    mediaPlayer.start();
                    break;
                case 0:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "VideoActivity started" + " LogEntryEnd");
                    startActivity(video);
                    break;
                case 3:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "MediaPlayer stopped" + " LogEntryEnd");
                    mediaPlayer.pause();
                    mediaPlayer.seekTo(0);
                    isPaused = false;
                    break;
                case 4:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "MediaPlayer resumed" + " LogEntryEnd");
                    mediaPlayer.start();
                    isPaused = false;
                    break;
                case 5:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "MediaPlayer paused" + " LogEntryEnd");
                    mediaPlayer.pause();
                    isPaused = true;
                    break;
                case 6:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "MediaPlayer rewinded" + " LogEntryEnd");
                    if (mediaPlayer.getCurrentPosition() < 3000){
                        mediaPlayer.seekTo(0);
                    }
                    else {
                        mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - 3000);
                    }
                    break;
                case 7:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "ImageActivity fast forwarded" + " LogEntryEnd");
                    if (mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition() < 3000){
                        mediaPlayer.seekTo(mediaPlayer.getDuration());
                    }
                    else {
                        mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + 3000);
                    }
                    break;
                case 8:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "MediaPlayer restarted" + " LogEntryEnd");
                    mediaPlayer.seekTo(0);
                    isPaused = false;
                    break;
                case 10:
                    if (mCardScroller.getSelectedItemPosition() < cardInfos.size())
                    {
                        mCardScroller.setSelection(mCardScroller.getSelectedItemPosition() + 1);
                    }
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "Next slide selected" + " LogEntryEnd");
                    break;
                case 11:
                    if (mCardScroller.getSelectedItemPosition() > 0)
                    {
                        mCardScroller.setSelection(mCardScroller.getSelectedItemPosition() - 1);
                    }
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "Previous slide selected" + " LogEntryEnd");
                    break;
                case 14:
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "Exit selected" + " LogEntryEnd");
                    finish();
                    break;
//                case 15:
//                    am.adjustStreamVolume(AudioManager.STREAM_SYSTEM,AudioManager.ADJUST_RAISE,0);
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "Volume increased" + " LogEntryEnd");
//                    break;
//                case 16:
//                    am.adjustStreamVolume(AudioManager.STREAM_SYSTEM,AudioManager.ADJUST_LOWER,0);
//                    time.setToNow();
//                    Log.i(TAG,time.toString() + ", " + "Volume decreased" + " LogEntryEnd");
//                    break;
                default:
                    for (CardInfo cardInfo : cardInfos){
                        if (item.getItemId() == cardInfo.goTo){
                            mCardScroller.setSelection(cardInfo.slideNumber);
//                            time.setToNow();
//                            Log.i(TAG,time.toString() + ", " + "Goto selected" + " LogEntryEnd");
                            return true;
                        }
                    }
                    return true;
            }
            return true;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public boolean onMenuOpened (int featureId, Menu menu) {
//        time.setToNow();
//        Log.i(TAG,time.toString() + ", " + "Menu opened" + " LogEntryEnd");
        return true;
    }

    // When the menu is closed, refresh it
    @Override
    public void onPanelClosed (int featureId, Menu menu) {
        getWindow().invalidatePanelMenu(WindowUtils.FEATURE_VOICE_COMMANDS);
        invalidateOptionsMenu();
//        time.setToNow();
//        Log.i(TAG,time.toString() + ", " + "Menu closed" + " LogEntryEnd");
    }

    // Set media resources based on slide position
    private void setMediaResources(int position){
        if (cardInfos.get(position).hasImage){
            image.removeExtra("imageResource");
            image.putExtra("imageResource", cardInfos.get(position).imageResource);
        }

        if (cardInfos.get(position).hasAudio){
            if (!mediaPlayer.isPlaying() && !isPaused) {
                mediaPlayer = MediaPlayer.create(MainActivity.this, cardInfos.get(position).audioResource);
                mediaPlayer.setOnCompletionListener(MainActivity.this);
            }
        }

        if (cardInfos.get(position).hasVideo){
            video.removeExtra("videoResource");
            video.putExtra("videoResource", cardInfos.get(position).videoResource);
        }
    }

    // Starts audio and video when card is selected
    private void startMedia(int position) {
        if (cardInfos.get(position).hasAudio){
//            time.setToNow();
//            Log.i(TAG,time.toString() + ", " + "MediaPlayer started" + " LogEntryEnd");
            mediaPlayer.start();
        }

        if (cardInfos.get(position).hasVideo){
//            time.setToNow();
//            Log.i(TAG,time.toString() + ", " + "VideoActivity started" + " LogEntryEnd");
            startActivity(video);
        }
//        hasPlayed = true;
    }

    private void setCardScrollerListener() {
        // When an item is selected, refresh the menu
        mCardScroller.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                getWindow().invalidatePanelMenu(WindowUtils.FEATURE_VOICE_COMMANDS);
                invalidateOptionsMenu();
                setMediaResources(mCardScroller.getSelectedItemPosition());
//                time.setToNow();
//                Log.i(TAG,time.toString() + ", " + "New slide selected" + " LogEntryEnd");
//                Log.i(TAG,time.toString() + ", " + "Current slide: " + mCardScroller.getSelectedItemPosition() + " LogEntryEnd");
//                if (currentSlide != mCardScroller.getSelectedItemPosition()) {
//                    hasPlayed = false;
//                    currentSlide = mCardScroller.getSelectedItemPosition();
//                }
//                if (!hasPlayed) {
//                    startMedia(mCardScroller.getSelectedItemPosition());
//                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        // Add sound effect when an slide is clicked
        mCardScroller.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int soundEffect = Sounds.TAP;
//                time.setToNow();
//                Log.i(TAG,time.toString() + ", " + "Slide " + mCardScroller.getSelectedItemPosition() + " tapped" + " LogEntryEnd");
                // Play sound.
                am.playSoundEffect(soundEffect);
                openOptionsMenu();
            }
        });
    }

    // Create the slides for the "powerpoint" view
    private List<CardBuilder> createCards(Context context) {
        ArrayList<CardBuilder> cards = new ArrayList<CardBuilder>();

        for (CardInfo cardInfo : cardInfos){
            if (cardInfo.hasXmlLayout){
                cards.add(cardInfo.slideNumber, new CardBuilder(context,cardInfo.layout)
                        .setEmbeddedLayout(cardInfo.xmlLayout));
            }
            else {
                CardBuilder cardBuilder = new CardBuilder(context,cardInfo.layout);

                if (cardInfo.hasText){
                    cardBuilder.setText(cardInfo.text);
                }

                cards.add(cardInfo.slideNumber, cardBuilder);
            }
        }
        return cards;
    }

    // Set Card Info
    private void setCardInfo() {
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Getting to know the tie")
                .setText("• Skinny End\n" +
                        "• Fat End\n" +
                        "• Face End (Smooth)\n" +
                        "• Seam Side")
                .setVideoResource(R.raw.gettoknowtie1)
                .setImageResource(R.drawable.tpic1));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Tie Orientation")
                .setText("• Place the tie with the seam side down, against your neck\n" +
                        "• It does not matter which side of your neck the fat side is on")
                .setVideoResource(R.raw.orientation2)
                .setImageResource(R.drawable.tpic2));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Adjust for Length (Basic)")
                .setText("• Pull the fat end down until the skinny end is about at the top of your ribcage\n" +
                        "• This is a basic rule of thumb\n" +
                        "• Practice will allow for better feel for length")
                .setVideoResource(R.raw.length3)
                .setImageResource(R.drawable.tpic3));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("The X")
                .setText("• Take the fat end and cross it over the skinny end\n" +
                        "• This should form an X\n" +
                        "• Hold the center of the X with one hand, the Knot Hand\n" +
                        "• The knot hand will generally not move")
                .setVideoResource(R.raw.thex4)
                .setImageResource(R.drawable.tpic4));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("The Knot Hole")
                .setText("• The area between your neck and the X we'll call the Knot Hole \n" +
                        "• The Fat end can make four possible motions\n" +
                        "• Come out of the Hole\n" +
                        "• Go into the Hole \n" +
                        "• Go behind the Hole\n" +
                        "• Go across the front of the Hole")
                .setVideoResource(R.raw.knothole5)
                .setImageResource(R.drawable.tpic5));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Tie comes out of the Knot Hole")
                .setText("• Place hand on front of the tie and push it up through the Knot Hole\n" +
                        "• Pull the tie down in front of the X\n" +
                        "• The face side of the tie should be visible after this is done")
                .setVideoResource(R.raw.outofhole6)
                .setImageResource(R.drawable.tpic6));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Tie goes behind the Hole")
                .setText("• Take the Tie to the side and go straight across behind the hole\n" +
                        "• With the tie on your shoulder, the seam side should be visible\n" +
                        "• This will create the first Triangle\n" +
                        "• This triangle should remain close to the X")
                .setVideoResource(R.raw.behindhole7)
                .setImageResource(R.drawable.tpic7)
                .setTextSize(10));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Tie goes into the Hole")
                .setText("• Take the Tie from your shoulder and go into the hole\n" +
                        "• Pull the rest of the tie down behind the partial knot\n" +
                        "• This forms the second triangle\n" +
                        "• Notice that the seam side is again visible")
                .setVideoResource(R.raw.intothehole8)
                .setImageResource(R.drawable.tpic8));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Tighten Triangles")
                .setText("• After each triangle is formed you will want to give a slight tug on the Tie\n" +
                        "• This will help maintain the shape of the final knot\n" +
                        "• The triangles should be snug but not overly tight")
                .setVideoResource(R.raw.triangles9)
                .setImageResource(R.drawable.tpic9));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Tie goes across the Hole")
                .setText("• Place your Knot Hand index finder between the triangles\n" +
                        "• Take the Tie across the front of the hole and over your index finger\n" +
                        "• Notice the smooth side is the visible side")
                .setVideoResource(R.raw.acrosshole10)
                .setImageResource(R.drawable.tpic10));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Tie goes out of the Hole, again")
                .setText("• Make the tie go out of the hole\n" +
                        "• Then push the tie through the opening where your Knot Index finger is\n" +
                        "• Pull the fat end downward to tighten the knot\n" +
                        "• Be sure you do not lose the skinny end")
                .setVideoResource(R.raw.outofholeagain11)
                .setImageResource(R.drawable.tpic11));
        cardInfos.add(new CardInfo(cardInfos.size(), R.layout.left_column_layout)
                .setHeader("Tidy the Knot")
                .setText("• Squeeze the bottom of the knot to help form the proper shape\n" +
                        "• Pulling the tops apart can also help\n" +
                        "• Hold the bottom of the knot, and pull on the skinny end to slide the knot up to your neck")
                .setVideoResource(R.raw.tidyknot12)
                .setImageResource(R.drawable.tpic12));
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import ER from './rates/components/ExchangeRate'

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});

const Component = () => (

hello

)


text:
var globalScope = this;
var AutoMapperJs;
(function (AutoMapperJs) {
    describe('AutoMapper', function () {
        beforeEach(function () {
            utils.registerTools(globalScope);
            utils.registerCustomMatchers(globalScope);
            // clear mappings (please, don't try this at home!)
            for (var key in automapper._mappings) {
                if (!automapper._mappings.hasOwnProperty(key)) {
                    continue;
                }
                delete automapper._mappings[key];
            }
        });
        it('should validate mapping using strictMode set to \'true\' (with valid mappings)', function () {
            // arrange
            automapper.createMap(AssertConfigPropertiesProp, AssertConfigPropertiesProp);
            // act and assert
            automapper.assertConfigurationIsValid(true);
        });
        it('should set strictMode to \'true\' when no value is provided and validate (with valid mappings)', function () {
            // arrange
            automapper.createMap(AssertConfigPropertiesProp, AssertConfigPropertiesProp);
            // act and assert
            automapper.assertConfigurationIsValid();
        });
        // // TODO Should work!
        // it('should set strictMode to \'true\' when no value is provided and validate (with valid mappings)', () => {
        //     // arrange
        //     automapper
        //         .createMap(AssertConfigPropertiesProp, AssertConfigPropertiesProp2)
        //         .forMember('prop2', (opts: AutoMapperJs.IMemberConfigurationOptions) => opts.mapFrom('prop'));
        //     // act and assert
        //     automapper.assertConfigurationIsValid();
        // });
        // it('should set strictMode to \'true\' when no value is provided and validate (with valid nested mappings)', () => {
        //     // arrange
        //     automapper.createMap(AssertConfigPropertiesNestedProp, AssertConfigPropertiesProp)
        //         .forMember('prop', (opts: IMemberConfigurationOptions) => opts.mapFrom('level1.level2'))
        //         .forSourceMember('level1.level2', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); });
        //     // act and assert
        //     automapper.assertConfigurationIsValid();
        // });
        it('should validate mapping using strictMode set to \'false\'', function () {
            // arrange
            automapper.createMap(AssertConfigPropertiesProp, AssertConfigPropertiesProp);
            automapper.createMap('AssertMappingConfigUntestableA', 'AssertMappingConfigUntestableB');
            // act and assert
            automapper.assertConfigurationIsValid(false);
        });
        it('should fail when validating mappings using strictMode set to \'true\' (with unvalidatable mappings)', function () {
            // arrange
            automapper.createMap(AssertConfigPropertiesProp, AssertConfigPropertiesProp);
            automapper.createMap('AssertMappingConfigUntestableA', 'AssertMappingConfigUntestableB');
            // act
            try {
                automapper.assertConfigurationIsValid(true);
            }
            catch (e) {
                // assert
                var errorMessage = e.message;
                var dekeyedErrorMessage = errorMessage.substr(0, errorMessage.indexOf('\'') + 1) +
                    errorMessage.substr(errorMessage.lastIndexOf('\''));
                expect(dekeyedErrorMessage).toEqual("Mapping '' cannot be validated, since mapping.sourceType or mapping.destinationType are unspecified.");
                return;
            }
            // assert
            expect(null).fail('Expected error was not raised.');
        });
        it('should fail when auto mapping a property which does not exist on destination', function () {
            // arrange
            var srcType = AssertConfigPropertiesProp;
            var dstType = AssertConfigPropertiesProp2;
            var srcName = AutoMapperJs.AutoMapperHelper.getClassName(srcType);
            var dstName = AutoMapperJs.AutoMapperHelper.getClassName(dstType);
            automapper.createMap(srcType, dstType);
            try {
                // act
                automapper.assertConfigurationIsValid(true);
            }
            catch (e) {
                // assert
                expect(e.message).toEqual("Mapping '" + srcName + "=>" + dstName + "' is invalid: Source member 'prop' is configured to be mapped, " +
                    ("but does not exist on destination type (source: '" + srcName + "', destination: '" + dstName + "')."));
                return;
            }
            // assert
            expect(null).fail('Expected error was not raised.');
        });
        it('should succeed when mapping objects with ignored properties not existing on the other side', function () {
            // arrange
            var srcType = AssertConfigPropertiesProp;
            var dstType = AssertConfigPropertiesProp2;
            var srcName = AutoMapperJs.AutoMapperHelper.getClassName(srcType);
            var dstName = AutoMapperJs.AutoMapperHelper.getClassName(dstType);
            automapper
                .createMap(srcType, dstType)
                .forSourceMember('prop', function (opts) { opts.ignore(); })
                .forMember('prop2', function (opts) { opts.ignore(); });
            // act and assert
            automapper.assertConfigurationIsValid(true);
        });
        it('should fail when auto mapping a property which does not exist on source', function () {
            // arrange
            var srcType = AssertConfigPropertiesProp;
            var dstType = AssertConfigPropertiesPropProp2;
            var srcName = AutoMapperJs.AutoMapperHelper.getClassName(srcType);
            var dstName = AutoMapperJs.AutoMapperHelper.getClassName(dstType);
            automapper.createMap(srcType, dstType);
            try {
                // act
                automapper.assertConfigurationIsValid(true);
            }
            catch (e) {
                // assert
                expect(e.message).toEqual("Mapping '" + srcName + "=>" + dstName + "' is invalid: Destination member 'prop2' does not exist on source type (source: '" + srcName + "', destination: '" + dstName + "').");
                return;
            }
            // assert
            expect(null).fail('Expected error was not raised.');
        });
        it('should fail when providing configuration for a property which does not exist on destination', function () {
            // arrange
            var srcType = AssertConfigPropertiesProp;
            var dstType = AssertConfigPropertiesPropProp2;
            var srcName = AutoMapperJs.AutoMapperHelper.getClassName(srcType);
            var dstName = AutoMapperJs.AutoMapperHelper.getClassName(dstType);
            automapper
                .createMap(srcType, dstType)
                .forMember('prop3', function (opts) { opts.ignore(); });
            try {
                // act
                automapper.assertConfigurationIsValid(true);
            }
            catch (e) {
                // assert
                expect(e.message).toEqual("Mapping '" + srcName + "=>" + dstName + "' is invalid: Destination member 'prop3' is configured, but does not exist on destination type (source: '" + srcName + "', destination: '" + dstName + "').");
                return;
            }
            // assert
            expect(null).fail('Expected error was not raised.');
        });
        it('should fail when providing configuration for a property which does not exist on source', function () {
            // arrange
            var srcType = AssertConfigPropertiesProp;
            var dstType = AssertConfigPropertiesPropProp2;
            var srcName = AutoMapperJs.AutoMapperHelper.getClassName(srcType);
            var dstName = AutoMapperJs.AutoMapperHelper.getClassName(dstType);
            automapper
                .createMap(srcType, dstType)
                .forSourceMember('prop2', function (opts) { opts.ignore(); });
            try {
                // act
                automapper.assertConfigurationIsValid(true);
            }
            catch (e) {
                // assert
                expect(e.message).toEqual("Mapping '" + srcName + "=>" + dstName + "' is invalid: Source member 'prop2' is configured, but does not exist on source type (source: '" + srcName + "', destination: '" + dstName + "').");
                return;
            }
            // assert
            expect(null).fail('Expected error was not raised.');
        });
    });
    var AssertConfigPropertiesProp = (function () {
        function AssertConfigPropertiesProp() {
            this.prop = undefined; // TODO Wiki: properties are only available when initialized: http://stackoverflow.com/a/20534039/702357
        }
        return AssertConfigPropertiesProp;
    }());
    var AssertConfigPropertiesProp2 = (function () {
        function AssertConfigPropertiesProp2() {
            this.prop2 = undefined;
        }
        return AssertConfigPropertiesProp2;
    }());
    var AssertConfigPropertiesPropProp2 = (function () {
        function AssertConfigPropertiesPropProp2() {
            this.prop = undefined;
            this.prop2 = undefined;
        }
        return AssertConfigPropertiesPropProp2;
    }());
    var AssertConfigPropertiesNestedProp = (function () {
        function AssertConfigPropertiesNestedProp() {
            this.level1 = {
                level2: undefined
            };
        }
        return AssertConfigPropertiesNestedProp;
    }());
})(AutoMapperJs || (AutoMapperJs = {}));


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.apkfuns.hipluginlib" />


text:
<?php

	require_once('../php_image_magician.php');

	/*	Purpose: Open image
     *	Usage:	 resize('filename.type')
     * 	Params:	 filename.type - the filename to open
     */
	$magicianObj = new imageLib('sample_images/racecar.jpg');

	/*	Purpose: Convert image to black and white
     *	Usage:	 blackAndWhite()
     * 	Params:	 n/a
     */
	$magicianObj -> blackAndWhite();

	/*	Purpose: Save image
     *	Usage:	 saveImage('[filename.type]', [quality])
     * 	Params:	 filename.type - the filename and file type to save as
 	 * 			 quality - (optional) 0-100 (100 being the highest (default))
     *				Only applies to jpg & png only
     */
	$magicianObj -> saveImage('output_2.4.png', 100);

?>


text:
namespace CompulsiveSkinPicking {
	public enum ObjectiveDirection { Minimize, Maximize };
}


text:
package org.apache.camel.component.mail;

import javax.mail.Message;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.jvnet.mock_javamail.Mailbox;

/**
 * @version
 */
public class MailToMultipleEndpointsTest extends CamelTestSupport {

    @Test
    public void testMultipleEndpoints() throws Exception {
        Mailbox.clearAll();

        template.sendBodyAndHeader("direct:a", "Hello World", "Subject", "Hello a");
        template.sendBodyAndHeader("direct:b", "Bye World", "Subject", "Hello b");
        template.sendBodyAndHeader("direct:c", "Hi World", "Subject", "Hello c");

        Mailbox boxA = Mailbox.get("a@a.com");
        assertEquals(1, boxA.size());
        assertEquals("Hello a", boxA.get(0).getSubject());
        assertEquals("Hello World", boxA.get(0).getContent());
        assertEquals("me@me.com", boxA.get(0).getFrom()[0].toString());

        Mailbox boxB = Mailbox.get("b@b.com");
        assertEquals(1, boxB.size());
        assertEquals("Hello b", boxB.get(0).getSubject());
        assertEquals("Bye World", boxB.get(0).getContent());
        assertEquals("you@you.com", boxB.get(0).getFrom()[0].toString());

        Mailbox boxC = Mailbox.get("c@c.com");
        assertEquals(1, boxC.size());
        assertEquals("Hello c", boxC.get(0).getSubject());
        assertEquals("Hi World", boxC.get(0).getContent());
        assertEquals("me@me.com", boxC.get(0).getFrom()[0].toString());
        assertEquals("you@you.com", boxC.get(0).getRecipients(Message.RecipientType.CC)[0].toString());
        assertEquals("them@them.com", boxC.get(0).getRecipients(Message.RecipientType.CC)[1].toString());
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:a").to("smtp://localhost?username=james2&password=secret&To=a@a.com&From=me@me.com");

                from("direct:b").to("smtp://localhost?username=james&password=secret&To=b@b.com&From=you@you.com");

                from("direct:c").to("smtp://localhost?username=admin&password=secret&To=c@c.com&From=me@me.com&CC=you@you.com,them@them.com");
            }
        };
    }
}


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit9522d203a9bc476055ff6cbdf13e71e1::getLoader();


text:
using System;
using System.Collections.Generic;
using WireMock.Admin.Mappings;
using WireMock.Types;

namespace WireMock.Admin.Requests;

/// <summary>
/// RequestMessage Model
/// </summary>
public class LogRequestModel
{
    /// <summary>
    /// The Client IP Address.
    /// </summary>
    public string ClientIP { get; set; }

    /// <summary>
    /// The DateTime.
    /// </summary>
    public DateTime DateTime { get; set; }

    /// <summary>
    /// The Path.
    /// </summary>
    public string Path { get; set; }

    /// <summary>
    /// The Absolute Path.
    /// </summary>
    public string AbsolutePath { get; set; }

    /// <summary>
    /// Gets the url (relative).
    /// </summary>
    public string Url { get; set; }

    /// <summary>
    /// The absolute URL.
    /// </summary>
    public string AbsoluteUrl { get; set; }

    /// <summary>
    /// The ProxyUrl (if a proxy is used).
    /// </summary>
    public string? ProxyUrl { get; set; }

    /// <summary>
    /// The query.
    /// </summary>
    public IDictionary<string, WireMockList<string>>? Query { get; set; }

    /// <summary>
    /// The method.
    /// </summary>
    public string Method { get; set; }

    /// <summary>
    /// The Headers.
    /// </summary>
    public IDictionary<string, WireMockList<string>>? Headers { get; set; }

    /// <summary>
    /// The Cookies.
    /// </summary>
    public IDictionary<string, string>? Cookies { get; set; }

    /// <summary>
    /// The body (as string).
    /// </summary>
    public string? Body { get; set; }

    /// <summary>
    /// The body (as JSON object).
    /// </summary>
    public object? BodyAsJson { get; set; }

    /// <summary>
    /// The body (as bytearray).
    /// </summary>
    public byte[]? BodyAsBytes { get; set; }

    /// <summary>
    /// The body encoding.
    /// </summary>
    public EncodingModel? BodyEncoding { get; set; }

    /// <summary>
    /// The DetectedBodyType, valid values are:
    ///
    /// - None
    /// - String
    /// - Json
    /// - Bytes
    /// </summary>
    public string? DetectedBodyType { get; set; }

    /// <summary>
    /// The DetectedBodyTypeFromContentType, valid values are:
    ///
    /// - None
    /// - String
    /// - Json
    /// - Bytes
    /// </summary>
    public string? DetectedBodyTypeFromContentType { get; set; }
}


text:
..
    Copyright 2013 Rackspace Hosting

    Licensed under the Apache License, Version 2.0 (the "License"); you may
    not use this file except in compliance with the License. You may obtain
    a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    License for the specific language governing permissions and limitations
    under the License.

*********************************
Development Environment on Ubuntu
*********************************

Designate is comprised of four main components :ref:`designate-api`, :ref:`designate-central`,
:ref:`designate-mdns`, and :ref:`designate-pool-manager`, supported by a few
standard open source components. For more information see :ref:`architecture`.

There are many different options for customizing Designate, and two of these options
have a major impact on the installation process:

* The storage backend used (SQLite or MySQL)
* The DNS backend used (PowerDNS or BIND9)

This guide will walk you through setting up a typical development environment for Designate,
using BIND9 as the DNS backend and MySQL as the storage backend. For a more complete discussion on
installation & configuration options, please see :ref:`architecture` and :ref:`production-architecture`.

For this guide you will need access to an Ubuntu Server (14.04).

.. _Development Environment:

Development Environment
+++++++++++++++++++++++

Installing Designate
====================

.. index::
   double: install; designate

1. Install system package dependencies (Ubuntu)

::

   $ apt-get install python-pip python-virtualenv git
   $ apt-get build-dep python-lxml

2. Clone the Designate repo from GitHub

::

   $ mkdir openstack
   $ cd openstack
   $ git clone https://github.com/openstack/designate.git
   $ cd designate

3. Setup a virtualenv

.. note::
   This is an optional step, but will allow Designate's dependencies
   to be installed in a contained environment that can be easily deleted
   if you choose to start over or uninstall Designate.

::

   $ virtualenv --no-site-packages .venv
   $ . .venv/bin/activate

4. Install Designate and its dependencies

::

   $ pip install -r requirements.txt -r test-requirements.txt
   $ python setup.py develop

5. Change directories to the etc/designate folder.

.. note::
    Everything from here on out should take place in or below your designate/etc folder

::

   $ cd etc/designate

6. Create Designate's config files by copying the sample config files

::

   $ ls *.sample | while read f; do cp $f $(echo $f | sed "s/.sample$//g"); done

7. Make the directory for Designate's log files

::

   $ mkdir -p ../../log

8. Make the directory for Designate's state files

::

   $ mkdir -p ../../state

Configuring Designate
======================

.. index::
    double: configure; designate

Open the designate.conf file for editing

::

  $ editor designate.conf

Copy or mirror the configuration from this sample file here:

.. literalinclude:: ../examples/basic-config-sample.conf
    :language: ini

Installing RabbitMQ
===================

.. note::

    Do the following commands as "root" or via sudo <command>

Install the RabbitMQ package

::

    $ apt-get install rabbitmq-server

Create a user:

::

    $ rabbitmqctl add_user designate designate

Give the user access to the / vhost:

::

    $ sudo rabbitmqctl set_permissions -p "/" designate ".*" ".*" ".*"

Installing MySQL
================

.. index::
    double: install; mysql

Install the MySQL server package

::

    $ apt-get install mysql-server-5.5

If you do not have MySQL previously installed, you will be prompted to change the root password.
By default, the MySQL root password for Designate is "password". You can:

* Change the root password to "password"
* If you want your own password, edit the designate.conf file and change any instance of
   "mysql://root:password@127.0.0.1/designate" to "mysql://root:YOUR_PASSWORD@127.0.0.1/designate"

You can change your MySQL password anytime with the following command::

    $ mysqladmin -u root -p password NEW_PASSWORD
    Enter password <enter your old password>

Create the Designate tables

::

    $ mysql -u root -p
    Enter password: <enter your password here>

    mysql> CREATE DATABASE `designate` CHARACTER SET utf8 COLLATE utf8_general_ci;
    mysql> CREATE DATABASE `designate_pool_manager` CHARACTER SET utf8 COLLATE utf8_general_ci;
    mysql> exit;

Install additional packages

::

    $ apt-get install libmysqlclient-dev
    $ pip install mysql-python

Installing BIND9
================

.. index::
    double: install; bind9

Install the DNS server, BIND9

::

      $ apt-get install bind9

      # Update the BIND9 Configuration
      $ editor /etc/bind/named.conf.options

      # Change the corresponding lines in the config file:
      options {
        directory "/var/cache/bind";
        dnssec-validation auto;
        auth-nxdomain no; # conform to RFC1035
        listen-on-v6 { any; };
        allow-new-zones yes;
        request-ixfr no;
        recursion no;
      };

      # Disable AppArmor for BIND9
      $ touch /etc/apparmor.d/disable/usr.sbin.named
      $ service apparmor reload

      # Restart BIND9:
      $ service bind9 restart

Initialize & Start the Central Service
======================================

.. index::
   double: install; central

Sync the Designate database.

::

   $ designate-manage database sync

Start the central service.

::

   $ designate-central

You'll now be seeing the log from the central service.

Initialize & Start the API Service
==================================

.. index::
   double: install; api

Open up a new ssh window and log in to your server (or however you're communicating with your server).

::

   $ cd openstack/designate

   # Make sure your virtualenv is sourced
   $ source .venv/bin/activate

   # Start the API Service
   $ designate-api

You'll now be seeing the log from the API service.

Initialize & Start the Pool Manager Service
===========================================

.. index::
   double: install; pool-manager

Open up a new ssh window and log in to your server (or however you're communicating with your server).

::

   # Sync the Pool Manager's cache:
   $ designate-manage pool-manager-cache sync

   # Start the pool manager service:
   $ designate-pool-manager

You'll now be seeing the log from the Pool Manager service.

Initialize & Start the MiniDNS Service
===========================================

.. index::
   double: install; minidns

Open up a new ssh window and log in to your server (or however you're communicating with your server).

::

   # Start the minidns service:
   $ designate-mdns

You'll now be seeing the log from the MiniDNS service.

Exercising the API
==================

.. note:: If you have a firewall enabled, make sure to open port 53, as well as Designate's default port (9001).

Using a web browser, curl statement, or a REST client, calls can be made to the
Designate API using the following format where "api_version" is either v1 or v2
and "command" is any of the commands listed under the corresponding version at :ref:`rest`

::

   http://IP.Address:9001/api_version/command

You can find the IP Address of your server by running

::

   curl -s checkip.dyndns.org | sed -e 's/.*Current IP Address: //' -e 's/<.*$//'

A couple of notes on the API:

- Before Domains are created, you must create a server (/v1/servers).


text:
#ifndef S_ZOOM_H
#define S_ZOOM_H

#include "main/mtypes.h"
#include "s_span.h"

extern void
_swrast_write_zoomed_rgba_span(struct gl_context *ctx, GLint imgX, GLint imgY,
                               const SWspan *span, const GLvoid *rgba);

extern void
_swrast_write_zoomed_rgb_span(struct gl_context *ctx, GLint imgX, GLint imgY,
                              const SWspan *span, const GLvoid *rgb);

extern void
_swrast_write_zoomed_depth_span(struct gl_context *ctx, GLint imgX, GLint imgY,
                                const SWspan *span);

extern void
_swrast_write_zoomed_stencil_span(struct gl_context *ctx, GLint imgX, GLint imgY,
                                  GLint width, GLint spanX, GLint spanY,
                                  const GLstencil stencil[]);

extern void
_swrast_write_zoomed_z_span(struct gl_context *ctx, GLint imgX, GLint imgY,
                            GLint width, GLint spanX, GLint spanY,
                            const GLvoid *z);

#endif


text:
#pragma once
#include <aws/workdocs/WorkDocs_EXPORTS.h>
#include <aws/workdocs/WorkDocsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace WorkDocs
{
namespace Model
{

  /**
   */
  class AWS_WORKDOCS_API DeleteDocumentRequest : public WorkDocsRequest
  {
  public:
    DeleteDocumentRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeleteDocument"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
Amazon WorkDocs authentication token. Not required when using AWS
     * administrator credentials to access the API.

     */
    inline const Aws::String& GetAuthenticationToken() const{ return m_authenticationToken; }

    /**
     *
Amazon WorkDocs authentication token. Not required when using AWS
     * administrator credentials to access the API.

     */
    inline bool AuthenticationTokenHasBeenSet() const { return m_authenticationTokenHasBeenSet; }

    /**
     *
Amazon WorkDocs authentication token. Not required when using AWS
     * administrator credentials to access the API.

     */
    inline void SetAuthenticationToken(const Aws::String& value) { m_authenticationTokenHasBeenSet = true; m_authenticationToken = value; }

    /**
     *
Amazon WorkDocs authentication token. Not required when using AWS
     * administrator credentials to access the API.

     */
    inline void SetAuthenticationToken(Aws::String&& value) { m_authenticationTokenHasBeenSet = true; m_authenticationToken = std::move(value); }

    /**
     *
Amazon WorkDocs authentication token. Not required when using AWS
     * administrator credentials to access the API.

     */
    inline void SetAuthenticationToken(const char* value) { m_authenticationTokenHasBeenSet = true; m_authenticationToken.assign(value); }

    /**
     *
Amazon WorkDocs authentication token. Not required when using AWS
     * administrator credentials to access the API.

     */
    inline DeleteDocumentRequest& WithAuthenticationToken(const Aws::String& value) { SetAuthenticationToken(value); return *this;}

    /**
     *
Amazon WorkDocs authentication token. Not required when using AWS
     * administrator credentials to access the API.

     */
    inline DeleteDocumentRequest& WithAuthenticationToken(Aws::String&& value) { SetAuthenticationToken(std::move(value)); return *this;}

    /**
     *
Amazon WorkDocs authentication token. Not required when using AWS
     * administrator credentials to access the API.

     */
    inline DeleteDocumentRequest& WithAuthenticationToken(const char* value) { SetAuthenticationToken(value); return *this;}

    /**
     *
The ID of the document.

     */
    inline const Aws::String& GetDocumentId() const{ return m_documentId; }

    /**
     *
The ID of the document.

     */
    inline bool DocumentIdHasBeenSet() const { return m_documentIdHasBeenSet; }

    /**
     *
The ID of the document.

     */
    inline void SetDocumentId(const Aws::String& value) { m_documentIdHasBeenSet = true; m_documentId = value; }

    /**
     *
The ID of the document.

     */
    inline void SetDocumentId(Aws::String&& value) { m_documentIdHasBeenSet = true; m_documentId = std::move(value); }

    /**
     *
The ID of the document.

     */
    inline void SetDocumentId(const char* value) { m_documentIdHasBeenSet = true; m_documentId.assign(value); }

    /**
     *
The ID of the document.

     */
    inline DeleteDocumentRequest& WithDocumentId(const Aws::String& value) { SetDocumentId(value); return *this;}

    /**
     *
The ID of the document.

     */
    inline DeleteDocumentRequest& WithDocumentId(Aws::String&& value) { SetDocumentId(std::move(value)); return *this;}

    /**
     *
The ID of the document.

     */
    inline DeleteDocumentRequest& WithDocumentId(const char* value) { SetDocumentId(value); return *this;}

  private:

    Aws::String m_authenticationToken;
    bool m_authenticationTokenHasBeenSet = false;

    Aws::String m_documentId;
    bool m_documentIdHasBeenSet = false;
  };

} // namespace Model
} // namespace WorkDocs
} // namespace Aws


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

namespace git.jrowberg.bglib.Bluegiga.BLE.Responses.System
{
	public delegate void EndpointSetWatermarksEventHandler (object sender, EndpointSetWatermarksEventArgs e);

	public class EndpointSetWatermarksEventArgs : EventArgs
	{
		public readonly UInt16 result;

		public EndpointSetWatermarksEventArgs (UInt16 result)
		{
			this.result = result;
		}
	}
}


text:
import uuid, requests
from django.db import models
from django.utils import timezone
from django.conf import settings
from signals import request_done, request_failed

class Request(models.Model):
  NEW, RUNNING, RETRYING, FAILED, READY = range(5)
  STATUS = [
    (NEW, "New"),
    (RUNNING, "Running"),
    (RETRYING, "Retrying"),
    (FAILED, "Failed"),
    (READY, "Ready"),
  ]

  MOCK_REQUESTS_SETTING = "RESCUESTS_MOCK_REQUESTS"
  MOCK_STATUS_SETTING = "RESCUESTS_MOCK_STATUS"
  MOCK_FUNC_SETTING = "RESCUESTS_MOCK_FUNC"
  MOCK_CONTENT_SETTING = "RESCUESTS_MOCK_CONTENT"

  uuid = models.CharField(verbose_name='UUID', max_length = 127, default = uuid.uuid4)
  url = models.URLField(verbose_name='URL')
  max_retries = models.PositiveIntegerField(default = 3)
  retries = models.PositiveIntegerField(default = 0)
  last_try = models.DateTimeField(null = True, blank = True)
  status = models.PositiveIntegerField(choices = STATUS, default = NEW)

  comment = models.TextField(blank = True)

  class mock():
    def __init__(self, func, status = 200, content = None):
      self.func = func
      self.status = status
      self.content = content
      self.saved_requests_setting = False
      self.saved_func_setting = None
      self.saved_content_setting = None
      self.saved_status_setting = 200

    def __enter__(self):
      self.saved_requests_setting = getattr(settings, Request.MOCK_REQUESTS_SETTING, False)
      self.saved_func_setting = getattr(settings, Request.MOCK_FUNC_SETTING, None)
      self.saved_content_setting = getattr(settings, Request.MOCK_CONTENT_SETTING, None)
      self.saved_status_setting = getattr(settings, Request.MOCK_STATUS_SETTING, 200)

      setattr(settings, Request.MOCK_REQUESTS_SETTING, True)
      setattr(settings, Request.MOCK_FUNC_SETTING, self.func)
      setattr(settings, Request.MOCK_CONTENT_SETTING, self.content)
      setattr(settings, Request.MOCK_STATUS_SETTING, self.status)

    def __exit__(self, *args):
      setattr(settings, Request.MOCK_REQUESTS_SETTING, self.saved_requests_setting)
      setattr(settings, Request.MOCK_FUNC_SETTING, self.saved_func_setting)
      setattr(settings, Request.MOCK_CONTENT_SETTING, self.saved_content_setting)
      setattr(settings, Request.MOCK_STATUS_SETTING, self.saved_status_setting)

  def __failed(self, response, error):
    self.comment += str(error) + "\n"
    self.retries += 1
    self.status = Request.FAILED if self.retries > self.max_retries else Request.RETRYING
    self.save()
    request_failed.send(sender = Request, instance = self, response = response, error = error)

  def __succeded(self, response):
    self.status = Request.READY
    self.save()
    request_done.send(sender = Request, instance = self, response = response)

  def run(self):
    if self.status in [Request.READY, Request.FAILED]: return
    self.status = Request.RUNNING
    self.last_try = timezone.now()
    self.save()

    if getattr(settings, Request.MOCK_REQUESTS_SETTING, False):
      return self.mock_request()

    try:
      response = requests.get(self.url)
      response.raise_for_status()
    except Exception, e:
      self.__failed(response, e)
    else:
      self.__succeded(response)
    finally:
      self.save()

  def mock_request(self):
    status = getattr(settings, Request.MOCK_STATUS_SETTING, 200)
    return_func = getattr(settings, Request.MOCK_FUNC_SETTING, None)
    return_content = getattr(settings, Request.MOCK_CONTENT_SETTING, None)

    if status not in [200, 403, 404, 500]:
      raise ValueError("currently only 200, 403, 404, 500 status "
        "codes are supported")

    if return_func is None:
      raise ValueError("if you trying to mock requests, "
        "please provide a \"RESCUESTS_MOCK_FUNC\" in your settings, "
        "which will be called instead of the HTTP requests")
    elif isinstance(return_func, str):
      module, _, func = return_func.rpartition(".")
      return_func = getattr(__import__(module, fromlist = [""]), func)

    return_func(status, self.url)

    if status == 200:
      self.__succeded(self.mock_response(status, return_content))
    else:
      self.__failed(self.mock_response(status, return_content), Exception("mocked exception"))

    self.save()

  def mock_response(self, status, content):
    resp = requests.Response()
    resp.status_code = status
    resp._content = content(self) if callable(content) else content
    return resp


text:
<?php

namespace APP\EmpresaBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;

class CategoriaType extends AbstractType {

    private $empresar;

    function getEmpresar() {
        return $this->empresar;
    }

    function setEmpresar($empresar) {
        $this->empresar = $empresar;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {

        $empresar = $options['data']->getEmpresar();

        $builder
                ->add('nome')
                ->add('pai', EntityType::class, [
                    'required'=> false,
                    'placeholder' => 'Choose your gender',
                    'empty_data' => null,
                    'class' => 'EmpresaBundle:Categoria',
                    'query_builder' => function (EntityRepository $er) use ($empresar) {
                        return $er->createQueryBuilder('u')
                                ->where('u.status=1')
                                ->andWhere(' u.empresar=:empresar')
                                ->setParameter('empresar', $empresar)
                                ->orderBy('u.nome', 'ASC');
                    }]);
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver) {
        $resolver->setDefaults(array(
            'data_class' =>'APP\EmpresaBundle\Entity\Categoria'
        ));
    }

}