text:
package edu.samplu.admin.test;

import edu.samplu.common.ITUtil;
import edu.samplu.common.WebDriverITBase;
import edu.samplu.common.WebDriverUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static com.thoughtworks.selenium.SeleneseTestBase.fail;
import static com.thoughtworks.selenium.SeleneseTestCase.assertEquals;

/**
 * Tests docsearch url parameters
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class DocumentSearchURLParametersITBase extends WebDriverITBase {

    @Override
    public String getTestUrl() {
        return ITUtil.PORTAL;
    }

    private static final String DOCUMENT_TYPE_NAME = "KualiNotification";
    private static final String ADVANCED_SEARCH_ONLY_FIELD = "applicationDocumentId";

    protected static final Map<String, String> CORE_FIELDS = new HashMap<String, String>();
    static {
        // basic
        CORE_FIELDS.put("documentTypeName", DOCUMENT_TYPE_NAME);
        CORE_FIELDS.put("documentId", "1234");
        CORE_FIELDS.put("initiatorPrincipalName", "CURRENT_USER");
        CORE_FIELDS.put("dateCreated", "11/11/11");

    }
    protected static final Map<String, String> BASIC_FIELDS = new HashMap<String, String>();
    static {
        BASIC_FIELDS.putAll(CORE_FIELDS);
        // searchable attrs
        BASIC_FIELDS.put("documentAttribute.notificationContentType", "testType");
        BASIC_FIELDS.put("documentAttribute.notificationChannel", "testChannel");
        BASIC_FIELDS.put("documentAttribute.notificationProducer", "testProducer");
        BASIC_FIELDS.put("documentAttribute.notificationPriority", "testPriority");
        BASIC_FIELDS.put("documentAttribute.notificationRecipients", "testRecipients");
        BASIC_FIELDS.put("documentAttribute.notificationSenders", "testSenders");
        BASIC_FIELDS.put("saveName", "testBasicSearchFields_saved_search");
        BASIC_FIELDS.put("isAdvancedSearch", "NO");
    }

    protected static final Map<String, String> ADVANCED_FIELDS = new HashMap<String, String>();
    static {
        ADVANCED_FIELDS.put("approverPrincipalName", "testApproverName");
        ADVANCED_FIELDS.put("viewerPrincipalName", "testViewerName");
        ADVANCED_FIELDS.put("applicationDocumentId", "testApplicationDocumentId");
        // ADVANCED_FIELDS.put("routeNodeName", "Adhoc Routing");
        ADVANCED_FIELDS.put("dateApproved", "01/01/01");
        ADVANCED_FIELDS.put("dateLastModified", "02/02/02");
        ADVANCED_FIELDS.put("dateFinalized", "03/03/03");
        ADVANCED_FIELDS.put("title", "test title");
        ADVANCED_FIELDS.put("isAdvancedSearch", "YES");
    }

    String getDocSearchURL(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry: params.entrySet()) {
            sb.append(URLEncoder.encode(entry.getKey()) + "=" + URLEncoder.encode(entry.getValue()) + "&");
        }
        return getDocSearchURL(sb.toString());

    }
    protected String getDocSearchURL(String params) {
        return ITUtil.getBaseUrlString() + "/kew/DocumentSearch.do?" + params;
    }

    private WebElement findElementByTagAndName(String tag, String name) {
        return driver.findElement(By.cssSelector(tag + "[name=" + name + "]"));
    }

    private WebElement findInput(String name) {
        return driver.findElement(By.xpath("//input[@name='" + name + "']"));
    }

    protected WebElement findModeToggleButton() {
        WebElement toggleAdvancedSearch = null;
        try {
            return driver.findElement(By.id("toggleAdvancedSearch"));
        } catch (NoSuchElementException e) {
            fail("toggleAdvancedSearch button not found");
            return null;
        }
    }

    protected void assertSearchDetailMode(WebElement e, boolean advanced) {
        assertEquals((advanced ? "basic" : "detailed") + " search", e.getAttribute("title"));

        try {
            findInput(ADVANCED_SEARCH_ONLY_FIELD);
            if (!advanced) fail("Advanced search field found in basic search");
        } catch (NoSuchElementException nsee) {
            if (advanced) fail("Advanced search field not found in advancedsearch");
        }
    }

    protected void assertInputValues(Map<String, String> fields) {
        boolean quickmode = false;
        for (Map.Entry<String, String> entry: fields.entrySet()) {
            String value = findInput(entry.getKey()).getAttribute("value");
            assertEquals("Field '" + entry.getKey() + "' expected '" + entry.getValue() + "' got '" + value + "'", entry.getValue(), value);
            if (!quickmode) { // do the first find slow to make sure the screen has finished loading, then do them fast, else some tests take minutes to run
                driver.manage().timeouts().implicitlyWait(WebDriverUtil.SHORT_IMPLICIT_WAIT_TIME, TimeUnit.SECONDS);
                quickmode = true;
            }
        }
        if (quickmode) {
            driver.manage().timeouts().implicitlyWait(WebDriverUtil.DEFAULT_IMPLICIT_WAIT_TIME, TimeUnit.SECONDS);
        }
    }

    protected void assertInputPresence(Map<String, String> fields, boolean present) {
        boolean quickmode = false;
        for (String name: fields.keySet()) {
            if (present) {
                assertTrue("Expected field '" + name + "' to be present", driver.findElements(By.name(name)).size() != 0);
            } else {
                assertEquals("Expected field '" + name + "' not to be present", 0, driver.findElements(By.name(name)).size());
            }
            if (!quickmode) { // do the first find slow to make sure the screen has finished loading, then do them fast, else some tests take minutes to run
                driver.manage().timeouts().implicitlyWait(WebDriverUtil.SHORT_IMPLICIT_WAIT_TIME, TimeUnit.SECONDS);
                quickmode = true;
            }
        }
        if (quickmode) {
            driver.manage().timeouts().implicitlyWait(WebDriverUtil.DEFAULT_IMPLICIT_WAIT_TIME, TimeUnit.SECONDS);
        }
    }
}


text:
package org.sagebionetworks.web.client.widget.table.v2.results.cell;

import java.util.Date;
import org.sagebionetworks.web.client.GlobalApplicationState;
import org.sagebionetworks.web.client.GlobalApplicationStateImpl;
import org.sagebionetworks.web.client.StringUtils;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class DateCellEditor implements CellEditor {

	private DateCellEditorView view;
	private Long originalTime;
	GlobalApplicationState globalAppState;

	@Inject
	public DateCellEditor(DateCellEditorView view, GlobalApplicationState globalAppState) {
		this.view = view;
		this.globalAppState = globalAppState;
	}

	@Override
	public boolean isValid() {
		// The editor will not allow bad values.
		return true;
	}

	@Override
	public Widget asWidget() {
		return view.asWidget();
	}

	@Override
	public void setValue(String value) {
		value = StringUtils.emptyAsNull(value);
		Date date = null;
		originalTime = null;
		if (value != null) {
			originalTime = Long.parseLong(value);
			Long time = originalTime;
			if (globalAppState.isShowingUTCTime()) {
				time += GlobalApplicationStateImpl.getTimezoneOffsetMs();
			}
			date = new Date(time);
		}
		view.setValue(date);
	}

	@Override
	public String getValue() {
		Date date = view.getValue();
		if (date != null) {
			Long time = date.getTime();
			if (globalAppState.isShowingUTCTime()) {
				time -= GlobalApplicationStateImpl.getTimezoneOffsetMs();
			}
			if (originalTime != null) {
				double originalSeconds = Math.floor(originalTime / 1000);
				double newSeconds = Math.floor(time / 1000);
				if (originalSeconds == newSeconds) {
					time = originalTime;
				}
			}
			return Long.toString(time);
		}
		return null;
	}

	@Override
	public HandlerRegistration addKeyDownHandler(KeyDownHandler handler) {
		return view.addKeyDownHandler(handler);
	}

	@Override
	public void fireEvent(GwtEvent<?> event) {
		view.fireEvent(event);
	}

	@Override
	public int getTabIndex() {
		return view.getTabIndex();
	}

	@Override
	public void setAccessKey(char key) {
		view.setAccessKey(key);
	}

	@Override
	public void setFocus(boolean focused) {
		view.setFocus(focused);
	}

	@Override
	public void setTabIndex(int index) {
		view.setTabIndex(index);
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php
App::uses('ComandaAppController', 'Comanda.Controller');

class ObservacionesController extends ComandaAppController
{
    public $paginate = array(
        'order' => array('Observacion.created' => 'asc'),
        // 'paramType' => 'querystring',
    );

    public $scaffold;

    public function index() {
        $this->Prg->commonProcess();
        $conds = $this->Observacion->parseCriteria( $this->Prg->parsedParams() );
        $this->Paginator->settings['conditions'] = $conds;

        $this->Observacion->recursive = 0;

        $observacion = $this->Paginator->paginate('Observacion');

        $this->set('observacion',$observacion);
    }
    public function add() {

        if (!empty($this->request->data)) {
            $this->Observacion->create();
            if ($this->Observacion->save($this->request->data)) {
                $this->Session->setFlash(__('La Observación ha sido guardada'), 'Risto.flash_success');
                $this->redirect(array('action'=>'index'));
            } else {
                $this->Session->setFlash(__('La Observación no ha podido ser guardada, vuelva a intentar.'), 'Risto.flash_error');
            }
        }
        $this->render('form');
    }

    public function edit($id = null) {

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('La Observación Inválida.'), 'Risto.flash_error');
            $this->redirect(array('action'=>'index'));
        }
        if (!empty($this->request->data)) {
            if ($this->Observacion->save($this->request->data)) {
                $this->Session->setFlash(__('La Observación ha sido guardada'), 'Risto.flash_success');
                $this->redirect(array('action'=>'index'));
            } else {
                $this->Session->setFlash(__('La Observación no ha podido ser guardada, vuelva a intentar.'), 'Risto.flash_error');
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->Observacion->read(null, $id);
        }
        $this->render('form');
    }

    public function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('ID de la Observación Inválida'), 'Risto.flash_error');
        }
        if ($this->Observacion->delete($id)) {
            $this->Session->setFlash(__('La Observación Borrada'), 'Risto.flash_success');
        }
        $this->redirect(array('action'=>'index'));
    }

}


text:
package ninja.egg82.nbt.core;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class NullNBTList implements INBTList {
	//vars

	//constructor
	public NullNBTList() {

	}

	//public
	public int size() {
		return 0;
	}
	public boolean isEmpty() {
		return true;
	}

	public boolean contains(Object o) {
		return false;
	}
	public boolean containsAll(Collection<?> c) {
		return false;
	}

	public Object[] toArray() {
		return null;
	}
	public <T> T[] toArray(T[] a) {
		return null;
	}

	public void add(int index, Object element) {

	}
	public boolean add(Object e) {
		return false;
	}
	public Object set(int index, Object element) {
		return null;
	}
	public boolean addAll(Collection<? extends Object> c) {
		return false;
	}
	public boolean addAll(int index, Collection<? extends Object> c) {
		return false;
	}

	public boolean remove(Object o) {
		return false;
	}
	public Object remove(int index) {
		return null;
	}
	public boolean removeAll(Collection<?> c) {
		return false;
	}
	public boolean retainAll(Collection<?> c) {
		return false;
	}

	public void clear() {

	}

	public Object get(int index) {
		return null;
	}

	public int indexOf(Object o) {
		return -1;
	}
	public int lastIndexOf(Object o) {
		return -1;
	}

	public Iterator<Object> iterator() {
		return null;
	}
	public ListIterator<Object> listIterator() {
		return null;
	}
	public ListIterator<Object> listIterator(int index) {
		return null;
	}

	public List<Object> subList(int fromIndex, int toIndex) {
		return null;
	}

	public INBTCompound addCompound(int index) {
		return new NullNBTCompound();
	}
	public INBTCompound addCompound() {
		return new NullNBTCompound();
	}
	public INBTCompound setCompound(int index) {
		return new NullNBTCompound();
	}
	public INBTCompound getCompound(int index) {
		return new NullNBTCompound();
	}

	public INBTList addList(int index) {
		return new NullNBTList();
	}
	public INBTList addList() {
		return new NullNBTList();
	}
	public INBTList setList(int index) {
		return new NullNBTList();
	}
	public INBTList getList(int index) {
		return new NullNBTList();
	}

	public Object getObject(int index) {
		return null;
	}
	public <T> T getObject(int index, Class<T> type) {
		return null;
	}

	public byte[] serialize() throws IOException {
		return new byte[0];
	}
	public void serialize(OutputStream stream) throws IOException {

	}
	public String toString() {
		return "[]";
	}

	public boolean isValidList() {
		return false;
	}

	//private

}


text:
namespace Lucene {

/// General purpose thread-local map.
template <typename TYPE>
class CloseableThreadLocal : public LuceneObject {
public:
    typedef boost::shared_ptr<TYPE> localDataPtr;
    typedef Map<int64_t, localDataPtr> MapLocalData;

    CloseableThreadLocal() {
        localData = MapLocalData::newInstance();
    }

public:
    localDataPtr get() {
        SyncLock syncLock(this);
        typename MapLocalData::iterator local = localData.find(LuceneThread::currentId());
        if (local != localData.end()) {
            return local->second;
        }
        localDataPtr initial(initialValue());
        if (initial) {
            localData.put(LuceneThread::currentId(), initial);
        }
        return initial;
    }

    void set(const localDataPtr& data) {
        SyncLock syncLock(this);
        localData.put(LuceneThread::currentId(), data);
    }

    void close() {
        SyncLock syncLock(this);
        localData.remove(LuceneThread::currentId());
    }

protected:
    MapLocalData localData;

    virtual localDataPtr initialValue() {
        return localDataPtr(); // override
    }
};

}

#endif


text:
import {Action} from '@ngrx/store';
import {type} from '../utils/type';

export const ActionTypes = {
    READY_STATE: type('[App] Ready State'),
    LOGGED_OUT_STATE: type('[App] Logged Out State'),
    DISCONNECTED_STATE: type('[App] Disconnected State')
};

export class AppReadyAction implements Action {
    type = ActionTypes.READY_STATE;
}

export class AppDisconnectedState implements Action {
    type = ActionTypes.DISCONNECTED_STATE;
}

export class AppLoggedOutState implements Action {
    type = ActionTypes.LOGGED_OUT_STATE;
}

export type Actions
    = AppReadyAction
    | AppDisconnectedState
    | AppLoggedOutState;


text:
require 'codeclimate-test-reporter'
CodeClimate::TestReporter.start

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

require 'map_print'

require 'minitest/mock'
require 'minitest/autorun'
require 'webmock/minitest'

WebMock.disable_net_connect!

MiniTest.after_run do
  WebMock.allow_net_connect!
end


text:
<div class="rezgo-ajax-container" id="rezgo-ajax-container-<?=$site->requestNum('pg')?>" style="display:none;">

	<?  if($site->requestNum('pg') == 1) { ?>

		<? if($site->requestStr('search_for') OR $site->requestStr('start_date') OR $site->requestStr('end_date') OR $site->requestStr('tags') OR $site->requestNum('cid')) { ?>

				Results
				<? if($site->requestStr('search_for')) { ?> for keyword <a class="rezgo-breadcrumb-link" data-toggle="tooltip" data-placement="top" title="Click to clear keywords" href="<?=$site->base?>/?start_date=<?=$site->requestStr('start_date')?>&end_date=<?=$site->requestStr('end_date')?>&tags=<?=$site->requestStr('tags')?>" target="_top">"<?=stripslashes($site->requestStr('search_for'))?>"<? } ?>
				<? if($site->requestStr('tags')) { ?> tagged with <a class="rezgo-breadcrumb-link" data-toggle="tooltip" data-placement="top" title="Click to clear tags" href="<?=$site->base?>/?start_date=<?=$site->requestStr('start_date')?>&end_date=<?=$site->requestStr('end_date')?>&search_in=<?=$site->requestStr('search_in')?>&search_for=<?=$site->requestStr('search_for')?>" target="_top">"<?=$site->requestStr('tags')?>"<? } ?>
				<? if($site->requestNum('cid')) { ?> supplied by <a class="rezgo-breadcrumb-link" data-toggle="tooltip" data-placement="top" title="Click to clear supplier"  href="<?=$site->base?>/?start_date=<?=$site->requestStr('start_date')?>&end_date=<?=$site->requestStr('end_date')?>" target="_top">"<?=$site->getCompanyName($site->requestNum('cid'))?>"<? } ?>
				<? if($site->requestStr('start_date') AND $site->requestStr('end_date')) { ?>
				 between <a class="rezgo-breadcrumb-link" data-toggle="tooltip" data-placement="top" title="Click to clear date search" href="<?=$site->base?>/?search_in=<?=$site->requestStr('search_in')?>&search_for=<?=$site->requestStr('search_for')?>&tags=<?=$site->requestStr('tags')?>" target="_top"><?=$site->requestStr('start_date')?> and <?=$site->requestStr('end_date')?>
				<? } elseif($site->requestStr('start_date')) { ?>
				 for <a class="rezgo-breadcrumb-link" data-toggle="tooltip" data-placement="top" title="Click to clear date search" href="<?=$site->base?>/?search_in=<?=$site->requestStr('search_in')?>&search_for=<?=$site->requestStr('search_for')?>&tags=<?=$site->requestStr('tags')?>" target="_top"><?=$site->requestStr('start_date')?>
				<? } elseif($site->requestStr('end_date')) { ?>
				 for <a class="rezgo-breadcrumb-link" data-toggle="tooltip" data-placement="top" title="Click to clear date search" href="<?=$site->base?>/?search_in=<?=$site->requestStr('search_in')?>&search_for=<?=$site->requestStr('search_for')?>&tags=<?=$site->requestStr('tags')?>" target="_top"><?=$site->requestStr('end_date')?>
				<? } ?>
				<a href="<?=$site->base?>/" class="rezgo-list-clear pull-right hidden-xs" target="_top">clear
        <a href="<?=$site->base?>/" class="rezgo-list-clear-xs hidden-sm hidden-md hidden-lg" target="_top">clear

		<? } else { ?>

		<? } ?>

	<? }  ?>

	<? if(!$site->getTours()) { ?>

Sorry, there were no results for your search.

	<? } ?>

	<?
		$tourList = $site->getTours();
		if($tourList[REZGO_RESULTS_PER_PAGE]) {
			$moreButton = 1;
			unset($tourList[REZGO_RESULTS_PER_PAGE]);
		} else { $moreButton = 0; }
	?>

  <? $available_items = 0; ?>

	<? foreach( $tourList as $item ): ?>

	<?
	$site->readItem($item) ;

	$item_unavailable = ($site->requestStr('start_date') AND count($site->getTourAvailability($item)) == 0) ? 1 : 0;

	if (!$item_unavailable) {
		$available_items++;
	}

	$tour_details_link = $site->base.'details/'.$item->com.'/'.$site->seoEncode($item->item);
	?>

    <div itemscope itemtype="http://schema.org/Product" class="rezgo-list-item<?=(($item_unavailable) ? ' rezgo-inventory-unavailable' : '')?>">

		    		<? if ($item->media->image[0]) { ?>

		        	  <a href="<?=$tour_details_link?>" itemprop="url" target="_top">
			            <img src="<?=$item->media->image[0]->path?>" border="0" />

		        <? } else { ?>

		        <? } ?>

<a href="<?=$tour_details_link?>" itemprop="url" target="_top"><?=$item->item?>

			          <?
									$text = strip_tags($item->details->overview);
									$text = $text." ";
									$text = substr($text, 0, 200);
									$text = substr($text, 0, strrpos($text,' '));
									echo $text;

									if(strlen(strip_tags($item->details->overview)) > 200) {
										echo ' … read more';
									}
								?>

							<?
                unset($location);

                if($site->exists($item->location_name)) $location['name'] = $item->location_name;
                if($site->exists($item->location_address)) $location['address'] = $item->location_address;
                if($site->exists($item->city)) $location['city'] = $item->city;
                if($site->exists($item->state)) $location['state'] = $item->state;
                if($site->exists($item->country)) $location['country'] = ucwords($site->countryName(strtolower($item->country)));

                if(count($location) > 0) {
              ?>

              	Location
	              <?
									if ($location['address'] != '') {
										echo '
										'.($location['name'] != '' ? ''.$location['name'].' - ' : '').'
										'.$location['address'].'';
									} else {
										echo '
										'.($location['city'] != '' ? ''.$location['city'].', ' : '').'
										'.($location['state'] != '' ? ''.$location['state'].', ' : '').'
										'.($location['country'] != '' ? ''.$location['country'].'' : '');
										//echo implode(', ', $location);
									}
	              ?>

              <? } ?>

              <? if($site->exists($item->starting)) { ?>

                	Starting from
									<?=$site->formatCurrency($item->starting)?>

              <? } ?>

              <a href="<?=$tour_details_link?>" itemprop="url" class="btn rezgo-btn-detail btn-lg btn-block" target="_top">More details

 	<? endforeach; // end foreach( $tourList as $item ): ?>

  <? //echo 'available_items: '.$available_items ?>

|||<?=$moreButton?>


text:
Meteor.methods({
  base64Encode: function (unencoded) {
    return new Buffer(unencoded || '').toString('base64');
  },
  // Accept node inserts and updates from Drupal.
  DrupalSaveNode: function (data) {
    var currentTime = Math.floor(new Date().getTime() / 1000);
    // Implementation of simple security.
    if (Meteor.settings.drupal_ddp.simple_security === true) {
      if (Meteor.settings.drupal_ddp.simple_security_token !== data.simple_security) {
        throw new Meteor.Error("Security token does not match!");
      }
    }

    if (Meteor.settings.drupal_ddp.debug_data === true) { console.log(data); }

    // Handle Nodes.
    if (data.content.ddp_type == 'node') {
      var actualColl = DrupalDdp.collections[data.content.type];
      if (!actualColl) {
        throw new Meteor.Error("You haven't registered this type of collection yet.");
      }

      // If content is flagged for deletion, remove.
      if (data.content.delete_content) {
        // Delete existing posts.
        actualColl.remove({nid: data.content.nid});
      }
      // Otherwise, insert/update.
      else {
        // Update existing posts.
        actualColl.upsert({nid: data.content.nid},{$set: data.content});
      }

      // Return object as an acknowledgement of Meteor getting data.
      var returnMessage = {
        'nid': data.content.nid,
        'type': data.content.type,
        'timestamp': currentTime
      };
      return returnMessage;
    }

    // Handle Taxonomies.
    if (data.content.ddp_type == 'taxonomy') {
      var actualTax = DrupalDdp.taxonomies[data.content.vocabulary_machine_name];
      if (!actualTax) {
        throw new Meteor.Error("You haven't registered this taxonomy vocabulary yet.");
      }
      if (data.content.delete_content) {
        // Delete existing taxonomies.
        actualTax.remove({tid: data.content.tid});
      }
      else {
        actualTax.upsert({
          tid: data.content.tid
        },{
          $set: data.content
        });
      }

      // Return object as an acknowledgement of Meteor getting data.
      var returnMessage = {
        'tid': data.content.tid,
        'vocab': data.content.vocabulary_machine_name,
        'timestamp': currentTime
      };
      return returnMessage;
    }

    // Handle Users.
    if (data.content.ddp_type == 'user') {
      // Clean up data and prepare profile information
      cleanUpProfile = [
        'rdf_mapping',
        'original',
        'data',
        'name',
        'mail',
        'pass',
        'ddp_type'
      ];
      profileData = _.omit(data.content, cleanUpProfile);

      if (data.content.delete_content) {
        // Delete existing user.
        userId = Meteor.users.findOne({'profile.uid' : data.content.uid})._id;
        Meteor.users.remove(userId);
      }
      else if (!(Meteor.users.findOne({'profile.uid' : data.content.uid}))) {
        // Create User.
        Accounts.createUser({
          username: data.content.name,
          email : data.content.mail,
          password : data.content.pass,
          profile  : profileData
        });
      }
      else {
        Meteor.users.update(
          {'profile.uid' : data.content.uid},
          {$set:
            {
              'emails.0.address' : data.content.mail,
              'username' : data.content.name,
              'profile' : profileData
            },
          }
        );
      }

      // Return object as an acknowledgement of Meteor getting data.
      var returnMessage = {
        'uid': data.content.uid,
        'timestamp': currentTime
      };
      return returnMessage;
    }

    if (data.content.ddp_type === 'update_user_password') {
      var bcrypt = NpmModuleBcrypt;
      var bcryptHash = Meteor.wrapAsync(bcrypt.hash);
      var passwordHash = bcryptHash(data.content.sha_pass, 10);

      var userId = null;

      // In the event that the user doesn't exist yet
      // (very rare) AND the 'update_user_password' request
      // arrives, then create the user with basic info.
      if (!(Meteor.users.findOne({'profile.uid' : data.content.uid}))) {
        userId = Accounts.createUser({
          username: data.content.name,
          email : data.content.mail,
          password : data.content.sha_pass,
          profile: {
            uid : data.content.uid
          }
        });
      } else {
        userId = Meteor.users.findOne({
          'profile.uid': data.content.uid
        })._id;
      }

      // Set user password and 'verify' their account.
      Meteor.users.update({_id : userId}, {$set: {'services.password.bcrypt' : passwordHash}});
      Meteor.users.update({_id : userId}, {$set: {'emails.0.verified' : true}});

      // Return object as an acknowledgement of Meteor getting data.
      var returnMessage = {
        'uid': data.content.uid,
        'timestamp': currentTime
      };
      return returnMessage;
    }
  },
  getDrupalSessionToken: function(type) {
    if (type === 'read') {
      var options = {
        url: Meteor.settings.drupal_ddp.drupal_url + "/restws/session/token",
        username : Meteor.settings.drupal_ddp.restws_read_user,
        password : Meteor.settings.drupal_ddp.restws_read_pass,
      };
    } else {
      var options = {
        url: Meteor.settings.drupal_ddp.drupal_url + "/restws/session/token",
        username : Meteor.settings.drupal_ddp.restws_user,
        password : Meteor.settings.drupal_ddp.restws_pass,
      };
    }

    if (Meteor.settings.drupal_ddp.debug_data === true) {
      console.log('== Connection Options ==');
      console.log(options);
    }

    var auth = 'Basic ' + Meteor.call('base64Encode', options.username + ':' + options.password);

    try {
      var result = HTTP.post(options.url, {
        headers: {
          Authorization: auth
        }
      });

      tokenResponse = {
        token: result.content,
        cookie: result.headers['set-cookie'][0],
      };

      if (Meteor.settings.drupal_ddp.debug_data === true) {
        console.log('== Connection Successful: Token ==');
        console.log(tokenResponse);
      }

      return tokenResponse;
    } catch (e) {
      if (Meteor.settings.drupal_ddp.debug_data === true) {
        console.log('== Error Creating Token ==');
        console.log(e);
      } else {
        return false;
      }
    }
  },
  /**
   * Function to update node content in Drupal.
   *
   * @parame node
   *   JSON node content to write back to Drupal.
   * @param numTries
   *   Number of tries to write to Drupal. Accounts for the stored session token
   *   being stale the first try around.
   */
  updateNodeInDrupal: function(node, numTries) {
    // Setting default for numTries to 1.
    numTries = typeof numTries !== 'undefined' ?  numTries : 1;
    // If session token exist via ServerSession, then return the token.
    var tokenCookie = ServerSession.get('restws_write_token');

    if (Meteor.settings.drupal_ddp.debug_data === true) {
      console.log('== Base URL and Endpoint ==');
      console.log(Meteor.settings.drupal_ddp.drupal_url);
      console.log(Meteor.settings.drupal_ddp.drupal_url + '/node/' + node.nid);

      console.log('== Token (writing to Drupal) ==');
      console.log(tokenCookie);
    }

    // Clean up node to remove some unsupported fields in Drupal.
    node = Meteor.call('cleanUpNode', node);

    if (Meteor.settings.drupal_ddp.debug_data === true) {
      console.log('== Content Going back to drupal ==');
      console.log(node);
    }

    // Try to make connection and send data back to Drupal.
    try {
      baseUrl = Meteor.settings.drupal_ddp.drupal_url;
      endpoint = baseUrl + '/node/' + node.nid;

      var result = HTTP.put(
        endpoint,
        {
          headers: {
            'Content-type': 'application/json',
            'X-CSRF-Token': tokenCookie.token,
            'Accept': 'application/json',
            'Cookie': tokenCookie.cookie,
          },
          data: node
        }
      );
      return result;
    } catch (e) {
      // Try to send data with cached token, if that fails,
      // get new token and try again.  If THAT fails, display
      // error.
      if (numTries < 2) {
        sessionToken = Meteor.call('getDrupalSessionToken', 'write');
        ServerSession.set('restws_write_token', sessionToken);

        console.log('== Cached session token invalid, fetching new session token. ==');
        console.log(node);

        // After new SessionToken is set, recursively call function.
        numTries++;
        Meteor.call('updateNodeInDrupal', node, numTries);
      } else {
        if (Meteor.settings.drupal_ddp.debug_data === true) {
          console.log('== Server Error Response ==');
          console.log(e);
        }
        return false;
      }
    }
  },
  cleanUpNode: function(node) {
    // These are items in a node that aren't supported for writing
    // via restws in Drupal.
    cleanUpNode = [
      'is_new',
      'vid',
      'ddp_type',
      'comment',
      'comments',
      'changed',
      'url',
      'edit_url',
      'comment_count',
      'comment_count_new',
      'revision',
      'language',
      'author',
      'field_tags',
      'field_image',
      'created',
      'status',
      'promote',
      'sticky',
    ];

    // Fix for any early adopters. content structure in meteor changed.
    // Preparing the node to be sent back to Drupal.
    if (node.hasOwnProperty('content')) {
      node = node.content;
    } else {
      // Add '_id' to the list of fields to be removed from
      // the node.
      cleanUpNode.push('_id');
    }

    // Check for File fields and Taxonomy fields to
    // remove because restws can't handle the heat.
    _.each(node, function(value, key, obj){
      // If obj is array
      if (_.isArray(value) && !_.isNull(value) && !_.isEmpty(value)) {
        // If 'file' exists here, then it's a file_field,
        // add key cleanUpNode array.
        if (_.has(value[0], 'file')) {
          cleanUpNode.push(key);
        }

        // If 'tid' exists here, then it's a taxonomy term,
        // add key to cleanUpNode array.
        if (_.has(value[0], 'tid')) {
          cleanUpNode.push(key);
        }
      }
    });

    // Remove fields from node object that aren't supported
    // for writing back to drupal.
    node = _.omit(node, cleanUpNode);

    return node;
  }
});


text:
#include <QtCore>

#include "../../src/SmtpMime"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // First create the SmtpClient object and set the user and the password.

    SmtpClient smtp("smtp.gmail.com", 465, SmtpClient::SslConnection);

    smtp.setUser("your_email@host.com");
    smtp.setPassword("your_password");

    // Create a MimeMessage

    MimeMessage message;

    EmailAddress sender("your_email_address@host.com", "Your Name");
    message.setSender(&sender);

    EmailAddress to("recipient@host.com", "Recipient's Name");
    message.addRecipient(&to);

    message.setSubject("SmtpClient for Qt - Example 3 - Html email with images");

    // Now we need to create a MimeHtml object for HTML content
    MimeHtml html;

    html.setHtml("
 Hello!
"
                 "
 This is the first image
"
                 ""
                 "
 This is the second image
"
                 "");

    // Create a MimeInlineFile object for each image
    MimeInlineFile image1 (new QFile("image1.jpg"));

    // An unique content id must be setted
    image1.setContentId("image1");
    image1.setContentType("image/jpg");

    MimeInlineFile image2 (new QFile("image2.jpg"));
    image2.setContentId("image2");
    image2.setContentType("image/jpg");

    message.addPart(&html);
    message.addPart(&image1);
    message.addPart(&image2);

    // Now the email can be sended
    if (!smtp.connectToHost()) {
        qDebug() << "Failed to connect to host!" << endl;
        return -1;
    }

    if (!smtp.login()) {
        qDebug() << "Failed to login!" << endl;
        return -2;
    }

    if (!smtp.sendMail(message)) {
        qDebug() << "Failed to send mail!" << endl;
        return -3;
    }

    smtp.quit();

}


text:
var path = require('path'),
    gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    htmlmin = require('gulp-htmlmin'),
    connect = require('gulp-connect'),
    karma = require('gulp-karma'),
    jshint = require('gulp-jshint'),
    minifyCSS = require('gulp-minify-css'),
    sass = require('gulp-sass'),
    imagemin = require('gulp-imagemin'),
    webdriverUpdate = require("gulp-protractor").webdriver_update,
    protractor = require("gulp-protractor").protractor,
    debug = false,
    WATCH_MODE = 'watch',
    RUN_MODE = 'run';

var mode = WATCH_MODE;

gulp.task('js', function() {
  var jsTask = gulp.src('src/js/**/*.js');
  if (!debug) {
    jsTask.pipe(uglify());
  }
  jsTask.pipe(gulp.dest('public/js'))
    .pipe(connect.reload());
});

gulp.task('template', function() {
  var templateTask = gulp.src('src/template/**/*.html');
  if (!debug) {
    templateTask.pipe(htmlmin({ collapseWhitespace: true }));
  }
  templateTask.pipe(gulp.dest('public/template'))
    .pipe(connect.reload());
});

gulp.task('css', function() {
  var options = {
    errLogToConsole: true
  };
  if (!debug) {
    options.outputStyle = 'expanded';
    options.sourceComments = 'map';
  }
  var cssTask = gulp.src('src/sass/app.scss')
    .pipe(sass(options));
  if (!debug) {
    cssTask.pipe(minifyCSS());
  }
  cssTask.pipe(gulp.dest('public/css'))
    .pipe(connect.reload());
});

gulp.task('image', function () {
  return gulp.src('src/image/**.*')
    .pipe(imagemin())
    .pipe(gulp.dest('public/image'))
    .pipe(connect.reload());
});

gulp.task('lint', function() {
  gulp.src('src/js/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

gulp.task('karma', function() {
  // undefined.js: unfortunately necessary for now
  gulp.src(['undefined.js'])
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: mode
    }))
    .on('error', function() {});
});

gulp.task('webdriver-update', webdriverUpdate);

gulp.task('protractor', ['webdriver-update'], function(callback) {
  gulp.src(["./src/tests/*.js"])
    .pipe(protractor({
      configFile: 'protractor.conf.js',
      args: ['--baseUrl', 'http://127.0.0.1:8080']
    }))
    .on('end', function() { callback(); })
    .on('error', function() { callback(); });
});

gulp.task('connect', function() {
  gulp.watch(['index.html'], function() {
    gulp.src(['index.html'])
      .pipe(connect.reload());
  });

  connect.server({
    livereload: true
  });
});

gulp.task('kill-connect', ['protractor'], function() {
  connect.serverClose();
});

gulp.task('run-mode', function() {
  mode = RUN_MODE;
});

gulp.task('debug', function() {
  debug = true;
});

function changeNotification(event) {
  console.log('File', event.path, 'was', event.type, ', running tasks...');
}

function watch() {
  var jsWatcher = gulp.watch('src/js/**/*.js', ['js', 'lint', 'karma'/*, 'protractor'*/]),
      cssWatcher = gulp.watch('src/sass/**/*.scss', ['css']),
      imageWatcher = gulp.watch('src/image/**/*', ['image']),
      htmlWatcher = gulp.watch('src/template/**/*.html', ['template'/*, 'protractor'*/]),
      testWatcher = gulp.watch('test/**/*.js', ['karma'/*, 'protractor'*/]);

  jsWatcher.on('change', changeNotification);
  cssWatcher.on('change', changeNotification);
  imageWatcher.on('change', changeNotification);
  htmlWatcher.on('change', changeNotification);
  testWatcher.on('change', changeNotification);
}

gulp.task('all', ['css', 'js', 'lint', 'image', 'karma'/*, 'protractor'*/]);

gulp.task('default', ['all'], watch);

gulp.task('server', ['connect', 'default']);

gulp.task('test', ['run-mode', 'debug', 'connect', 'all', 'kill-connect']);


text:
/*
 * Problem 1. Odd lines
 * Write a program that reads a text file and prints on the console its odd lines.
*/
using System;
using System.IO;
class OddLines
{
    static void Main()
    {
        string fileName = @"..\..\OddLines.cs";

        Console.WriteLine("All odd lines are:");

        using (StreamReader streamReader = new StreamReader(fileName))
        {
            int lineNumber = 0;
            string line = streamReader.ReadLine();
            while (line != null)
            {
                lineNumber++;
                if (lineNumber % 2 != 0) // checking if the line is odd
                {
                    Console.WriteLine("Line {0}: {1}", lineNumber, line);
                }
                line = streamReader.ReadLine();
            }
        }
    }
}


text:
#include "jerryscript.h"

#include "test-common.h"

int
main (void)
{
  TEST_INIT ();
  jerry_init (JERRY_INIT_EMPTY);

  jerry_value_t global_obj_val = jerry_get_global_object ();

  jerry_char_t pattern[] = "[^.]+";
  uint16_t flags = JERRY_REGEXP_FLAG_GLOBAL | JERRY_REGEXP_FLAG_MULTILINE;
  jerry_value_t regex_obj = jerry_create_regexp (pattern, flags);
  TEST_ASSERT (jerry_value_is_object (regex_obj));

  const jerry_char_t func_arg_list[] = "regex";
  const jerry_char_t func_src[] = "return [regex.exec('something.domain.com'), regex.multiline, regex.global];";
  jerry_value_t func_val = jerry_parse_function (func_arg_list,
                                                 sizeof (func_arg_list) - 1,
                                                 func_src,
                                                 sizeof (func_src) - 1,
                                                 NULL);

  jerry_value_t res = jerry_call_function (func_val, global_obj_val, &regex_obj, 1);
  jerry_value_t regex_res = jerry_get_property_by_index (res, 0);
  jerry_value_t regex_res_str = jerry_get_property_by_index (regex_res, 0);
  jerry_value_t is_multiline = jerry_get_property_by_index (res, 1);
  jerry_value_t is_global = jerry_get_property_by_index (res, 2);

  const char expected_result[] = "something";
  jerry_size_t str_size = jerry_get_string_size (regex_res_str);
  TEST_ASSERT (str_size == (sizeof (expected_result) - 1));

  JERRY_VLA (jerry_char_t, res_buff, str_size);
  jerry_size_t res_size = jerry_string_to_char_buffer (regex_res_str, res_buff, str_size);

  TEST_ASSERT (res_size == str_size);
  TEST_ASSERT (strncmp (expected_result, (const char *) res_buff, res_size) == 0);
  TEST_ASSERT (jerry_get_boolean_value (is_multiline));
  TEST_ASSERT (jerry_get_boolean_value (is_global));

  jerry_release_value (regex_obj);
  jerry_release_value (res);
  jerry_release_value (func_val);
  jerry_release_value (regex_res);
  jerry_release_value (regex_res_str);
  jerry_release_value (is_multiline);
  jerry_release_value (is_global);
  jerry_release_value (global_obj_val);

  jerry_cleanup ();
  return 0;
} /* main */


text:
yii2-listjs-widget
========================

List.js widget for Yii2. This widget makes List.js functionality available on any list or table in Yii2 applications.
Visit [List.js](http://www.listjs.com/) website for more info and examples.

Installation
------------

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist nterms/yii2-listjs-widget "*"
```

or add

```
"nterms/yii2-listjs-widget": "*"
```

to the require section of your `composer.json` file.

Usage
-----

Once the extension is installed, simply use it in your code by :

```php
<?= \nterms\listjs\ListJs::begin([
	'id' => 'days-list',
	'search' => true,
	'sort' => [
		'name' => [
			'label' => Yii::t('app', 'Sort by name'),
		],
	],
	'clientOptions' => [
		'valueNames' => ['name'],
	],
]); ?>

<ul class="list">
	<li><div class="name">Sunday</div></li>
	<li><div class="name">Monday</div></li>
	<li><div class="name">Tuesday</div></li>
	<li><div class="name">Wednesday</div></li>
	<li><div class="name">Thursday</div></li>
	<li><div class="name">Friday</div></li>
	<li><div class="name">Saturday</div></li>
</ul>

<?= \nterms\listjs\ListJs::end(); ?>
```

Configurations
--------------

Following properties are available for customizing the widget.

- `options`: HTML attributes for the container element.
- `search`: Whether to show the search field.
- `searchOptions`: HTML attributes (name-value pairs) for the search input tag.
- `sort`: list of name-value pairs for rendering the sorting buttons list. Value being the HTML attributes for the button. Special parameter `label` is used as the button text
	```
	...
	'sort' => [
	 'name' => [
		 'class' => 'sort',
		 'label' => Yii::t('app', 'Sort by name'),
	 ],
	],
	...

	```
- `clientOptions`: Options for List.js. Read [this](http://www.listjs.com/docs/options) for list of options.
- `content`: HTML content, preferably a list or table. If the widget is used in content capturing mode this will be ignored.
- `view`: Name of the view file to render the content. If the widget is used in content capturing mode or a string is assigned to `content` property this will be ignored.
- `viewParams`: Parameters to be passed to `view` when it is being rendered. This property is used only when `view` is rendered to generate the content of the widget.

License
-------

[MIT](LICENSE.md)


text:
package zerodrive.util.reflect.converter;

/**
 * 文字列を {@linkplain Float} に変換する {@linkplain TypeConverter} の実装です。
 *
 * @author AdachiHjm
 * @created 2016/01/31 17:21:09
 *
 */
public class FloatConverter implements TypeConverter<Float> {

    /**
     * @see zerodrive.util.reflect.converter.TypeConverter#convert(java.lang.String)
     */
    @Override
    public Float convert(String value) {
        return null != value ? Float.valueOf(value) : null;
    }

}


text:
package org.magcruise.gaming.tutorial.discussion.actor;

import org.magcruise.gaming.model.game.Player;
import org.magcruise.gaming.model.game.PlayerParameter;
import org.magcruise.gaming.model.game.SimpleContext;
import org.magcruise.gaming.model.game.message.ScenarioEvent;
import org.magcruise.gaming.ui.model.Form;
import org.magcruise.gaming.ui.model.attr.SimpleSubmit;
import org.magcruise.gaming.ui.model.input.TextInput;

public class Talker extends Player {

	public Talker(PlayerParameter playerParameter) {
		super(playerParameter);
	}

	public boolean isStartNegotiation(SimpleContext ctx, ScenarioEvent msg) {
		return msg.isNamed(toSymbol("start-negotiation"));
	}

	public boolean isFinish(SimpleContext ctx, ScenarioEvent msg) {
		return msg.isNamed(toSymbol("finish-negotiation"));
	}

	public void negotiation(SimpleContext ctx, ScenarioEvent msg) {
		syncRequestToInput(new Form("",
				new TextInput("", "input-msg", "END", new SimpleSubmit())),
				(param) -> {
					if (param.getArgAsString(0).equalsIgnoreCase("END")) {
						sendScenarioEvent(msg.from,
								toSymbol("finish-negotiation"));
						sendScenarioEvent(msg.to,
								toSymbol("finish-negotiation"));
					} else {
						sendScenarioEvent(name, toSymbol(""));
					}
				});
	}

}


text:
package app.dto.exportingDtos;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;

@XmlRootElement(name = "categories")
@XmlAccessorType(XmlAccessType.FIELD)
public class CategoryByProductsWrapperDto {

    @XmlElement(name = "category")
    private List<CategoryByProductsCountDto> categories;

    public CategoryByProductsWrapperDto() {
        this.categories = new ArrayList<>();
    }

    public List<CategoryByProductsCountDto> getCategories() {
        return categories;
    }

    public void setCategories(List<CategoryByProductsCountDto> categories) {
        this.categories = categories;
    }
}


text:
import * as React from 'react'

import { LabwareRender, RobotWorkSpace } from '@opentrons/components'
import { labwareImages } from './labware-images'
import styles from './styles.css'

import type { LabwareDefinition } from '../../types'

export type GalleryProps = {|
  definition: LabwareDefinition,
  className?: string,
|}

export function Gallery(props: GalleryProps): React.Node {
  const { definition, className } = props
  const { parameters: params, dimensions: dims } = definition
  const [currentImage, setCurrentImage] = React.useState(0)
  const render = (
    <RobotWorkSpace
      key="center"
      viewBox={`0 0 ${dims.xDimension} ${dims.yDimension}`}
      className={styles.robot_workspace}
    >
      {() => <LabwareRender definition={definition} />}
    </RobotWorkSpace>
  )

  const staticImages = (labwareImages[params.loadName] || []).map(
    (src, key) =>
  )

  const images = [render, ...staticImages]

  return (

          {images[currentImage]}

      {images.length > 1 && (

          {images.map((img, index) => (
            <Thumbnail key={index} onClick={() => setCurrentImage(index)}>
              {img}
            </Thumbnail>
          ))}

      )}

  )
}

type ThumbnailProps = {|
  onClick: () => mixed,
  children: React.Node,
|}

function Thumbnail(props: ThumbnailProps) {
  const { onClick, children } = props

  return (
    <button className={styles.gallery_thumbnail_container} onClick={onClick}>

{children}

    </button>
  )
}


text:
package com.watchrabbit.commons.callback;

/**
 *
 * @author Mariusz
 */
@FunctionalInterface
public interface UncheckedCallable<V> {

    V call();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="?selectableItemBackground">

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="72dp"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="16dp"
        android:layout_alignParentRight="true"
        android:layout_alignBaseline="@+id/name" />

</RelativeLayout>


text:
import React, { Component } from "react";

/**
 * Return an input element object for redux form's Field component.
 * @param {*} field
 */
const renderTextField = function(field) {
    const warning = field.meta.touched && field.meta.error ? (

{field.meta.error}

    ) : null;
    const fieldAttribute = `${field.title.toLowerCase()}Input`;
    const element = React.createElement(
        field.element,
        Object.assign(
            field.input,
            {type: field.type},
            {ref: input => { this[fieldAttribute] = input }}
        )
    );

    return (

                {field.title}

            {warning}
            {element}

    );
}

export default renderTextField;


text:
/*
 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
 *
 * The original version of this source code and documentation
 * is copyrighted and owned by Taligent, Inc., a wholly-owned
 * subsidiary of IBM. These materials are provided under terms
 * of a License Agreement between Taligent and Sun. This technology
 * is protected by multiple US and International patents.
 *
 * This notice and attribution to Taligent may not be removed.
 * Taligent is a registered trademark of Taligent, Inc.
 *
 */

package java.text;

/**
 * StringCharacterIterator implements the
 * CharacterIterator protocol for a String.
 * The StringCharacterIterator class iterates over the
 * entire String.
 *
 * @see CharacterIterator
 */

public final class StringCharacterIterator implements CharacterIterator
{
    private String text;
    private int begin;
    private int end;
    // invariant: begin <= pos <= end
    private int pos;

    /**
     * Constructs an iterator with an initial index of 0.
     */
    public StringCharacterIterator(String text)
    {
        this(text, 0);
    }

    /**
     * Constructs an iterator with the specified initial index.
     *
     * @param  text   The String to be iterated over
     * @param  pos    Initial iterator position
     */
    public StringCharacterIterator(String text, int pos)
    {
    this(text, 0, text.length(), pos);
    }

    /**
     * Constructs an iterator over the given range of the given string, with the
     * index set at the specified position.
     *
     * @param  text   The String to be iterated over
     * @param  begin  Index of the first character
     * @param  end    Index of the character following the last character
     * @param  pos    Initial iterator position
     */
    public StringCharacterIterator(String text, int begin, int end, int pos) {
        if (text == null)
            throw new NullPointerException();
        this.text = text;

        if (begin < 0 || begin > end || end > text.length())
            throw new IllegalArgumentException("Invalid substring range");

        if (pos < begin || pos > end)
            throw new IllegalArgumentException("Invalid position");

        this.begin = begin;
        this.end = end;
        this.pos = pos;
    }

    /**
     * Reset this iterator to point to a new string.  This package-visible
     * method is used by other java.text classes that want to avoid allocating
     * new StringCharacterIterator objects every time their setText method
     * is called.
     *
     * @param  text   The String to be iterated over
     * @since 1.2
     */
    public void setText(String text) {
        if (text == null)
            throw new NullPointerException();
        this.text = text;
        this.begin = 0;
        this.end = text.length();
        this.pos = 0;
    }

    /**
     * Implements CharacterIterator.first() for String.
     * @see CharacterIterator#first
     */
    public char first()
    {
        pos = begin;
        return current();
    }

    /**
     * Implements CharacterIterator.last() for String.
     * @see CharacterIterator#last
     */
    public char last()
    {
        if (end != begin) {
            pos = end - 1;
        } else {
            pos = end;
        }
        return current();
     }

    /**
     * Implements CharacterIterator.setIndex() for String.
     * @see CharacterIterator#setIndex
     */
    public char setIndex(int p)
    {
    if (p < begin || p > end)
            throw new IllegalArgumentException("Invalid index");
        pos = p;
        return current();
    }

    /**
     * Implements CharacterIterator.current() for String.
     * @see CharacterIterator#current
     */
    public char current()
    {
        if (pos >= begin && pos < end) {
            return text.charAt(pos);
        }
        else {
            return DONE;
        }
    }

    /**
     * Implements CharacterIterator.next() for String.
     * @see CharacterIterator#next
     */
    public char next()
    {
        if (pos < end - 1) {
            pos++;
            return text.charAt(pos);
        }
        else {
            pos = end;
            return DONE;
        }
    }

    /**
     * Implements CharacterIterator.previous() for String.
     * @see CharacterIterator#previous
     */
    public char previous()
    {
        if (pos > begin) {
            pos--;
            return text.charAt(pos);
        }
        else {
            return DONE;
        }
    }

    /**
     * Implements CharacterIterator.getBeginIndex() for String.
     * @see CharacterIterator#getBeginIndex
     */
    public int getBeginIndex()
    {
        return begin;
    }

    /**
     * Implements CharacterIterator.getEndIndex() for String.
     * @see CharacterIterator#getEndIndex
     */
    public int getEndIndex()
    {
        return end;
    }

    /**
     * Implements CharacterIterator.getIndex() for String.
     * @see CharacterIterator#getIndex
     */
    public int getIndex()
    {
        return pos;
    }

    /**
     * Compares the equality of two StringCharacterIterator objects.
     * @param obj the StringCharacterIterator object to be compared with.
     * @return true if the given obj is the same as this
     * StringCharacterIterator object; false otherwise.
     */
    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;
        if (!(obj instanceof StringCharacterIterator))
            return false;

        StringCharacterIterator that = (StringCharacterIterator) obj;

        if (hashCode() != that.hashCode())
            return false;
        if (!text.equals(that.text))
            return false;
        if (pos != that.pos || begin != that.begin || end != that.end)
            return false;
        return true;
    }

    /**
     * Computes a hashcode for this iterator.
     * @return A hash code
     */
    public int hashCode()
    {
        return text.hashCode() ^ pos ^ begin ^ end;
    }

    /**
     * Creates a copy of this iterator.
     * @return A copy of this
     */
    public Object clone()
    {
        try {
            StringCharacterIterator other
            = (StringCharacterIterator) super.clone();
            return other;
        }
        catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
    }

}


text:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
// Information about TIFF files
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
#ifndef MediaInfo_File_TiffH
#define MediaInfo_File_TiffH
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/File__Analyze.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Class File_Tiff
//***************************************************************************

class File_Tiff : public File__Analyze
{
public:
    //Constructor/Destructor
    File_Tiff();

private :
    //Buffer - File header
    bool FileHeader_Begin();
    void FileHeader_Parse();

    //Buffer - Per element
    void Header_Parse();
    void Data_Parse();
    void Data_Parse_Fill();

    //Elements
    void Read_Directories();
    void Read_Directory();

    //Temp
    struct ifditem
    {
        int16u Tag;
        int16u Type;
        int32u Count;
    };
    typedef std::map<int32u, ifditem> ifditems; //Key is byte offset
    ifditems IfdItems;
    typedef std::map<int16u, ZtringList> infos; //Key is Tag value
    infos Infos;
    bool LittleEndian;

    //Helpers
    void Get_X2 (int16u &Info, const char* Name);
    void Get_X4 (int32u &Info, const char* Name);
    void GetValueOffsetu(ifditem &IfdItem);
};

} //NameSpace

#endif


text:
#ifndef ZEPHYR_DRIVERS_SENSOR_ICM42670_H_
#define ZEPHYR_DRIVERS_SENSOR_ICM42670_H_

#include <zephyr/drivers/gpio.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/drivers/spi.h>
#include <zephyr/kernel.h>

struct icm42670_data {
	int16_t accel_x;
	int16_t accel_y;
	int16_t accel_z;
	uint16_t accel_sensitivity_shift;
	uint16_t accel_hz;
	uint16_t accel_fs;
	int16_t gyro_x;
	int16_t gyro_y;
	int16_t gyro_z;
	uint16_t gyro_sensitivity_x10;
	uint16_t gyro_hz;
	uint16_t gyro_fs;
	int16_t temp;
#ifdef CONFIG_ICM42670_TRIGGER
	const struct device *dev;
	struct gpio_callback gpio_cb;
	sensor_trigger_handler_t data_ready_handler;
	const struct sensor_trigger *data_ready_trigger;
	struct k_mutex mutex;
#endif
#ifdef CONFIG_ICM42670_TRIGGER_OWN_THREAD
	K_KERNEL_STACK_MEMBER(thread_stack, CONFIG_ICM42670_THREAD_STACK_SIZE);
	struct k_thread thread;
	struct k_sem gpio_sem;
#endif
#ifdef CONFIG_ICM42670_TRIGGER_GLOBAL_THREAD
	struct k_work work;
#endif
};

struct icm42670_config {
	struct spi_dt_spec spi;
	struct gpio_dt_spec gpio_int;
};

#endif /* ZEPHYR_DRIVERS_SENSOR_ICM42670_H_ */


text:
<?php namespace Devise\Pages\Fields;

class FieldsRepositoryTest extends \DeviseTestCase
{
	public function setUp()
	{
		parent::setUp();
		$this->FieldsRepository = new FieldsRepository(new \DvsField, new \DvsGlobalField);
	}

	public function test_it_finds_fields_by_key_and_page_version()
	{
		$output = $this->FieldsRepository->findFieldByKeyAndPageVersion('hello', 1, null);

		assertEquals(1, $output->id);
	}

	public function test_it_finds_trashed_fields_by_key_and_page_version()
	{
		\DvsField::find(1)->delete();

		$output = $this->FieldsRepository->findTrashedFieldByKeyAndPageVersion('hello', 1);

		assertEquals(1, $output->id);
	}

	public function test_it_finds_trashed_global_fields_by_key_and_language()
	{
		\DvsGlobalField::find(1)->delete();

		$output = $this->FieldsRepository->findTrashedGlobalFieldByKeyAndLanguage('key1', 45);

		assertEquals(1, $output->id);
	}

	public function test_it_finds_field_by_id()
	{
		$output = $this->FieldsRepository->findFieldById(1);

		assertEquals(1, $output->id);
	}

	public function test_it_finds_field_by_id_and_scope()
	{
		$output = $this->FieldsRepository->findFieldByIdAndScope(1, 'page');

		assertEquals(1, $output->id);
	}

	public function test_it_finds_trashed_field_by_id_and_scope()
	{
		\DvsField::find(1)->delete();

		$output = $this->FieldsRepository->findTrashedFieldByIdAndScope(1, 'page');

		assertEquals(1, $output->id);
	}

	public function test_it_finds_fields_by_global_key_and_language()
	{
		$output = $this->FieldsRepository->findFieldByGlobalKeyAndLanguage('key1', 45);

		assertEquals(1, $output->id);
	}
}


text:
+++
Title = "DevOpsDays Cape Town 2020"
Type = "welcome"
aliases = [
    "/events/2020-cape-town/",
    "/events/2020-cape-town/location/",
    "/events/2020-cape-town/registration/",
    "/events/2020-cape-town/sponsor/",
    "/events/2020-cape-town/propose/",
]
Description = "While our 2020 event will no longer happen, we will return in 2021."
+++

COVID-19 Update

Due to the current situation with the worldwide outbreak of COVID-19, we decided to not run our 2020 event. We do plan on being back in 2021. Please join our mailing list below, or follow us on Twitter for updates.

    As a community-run event, DevOpsDays Cape Town strives to build awareness and spread lean, collaborative practises to organisations and individuals.

    Cape Town has a thriving technology sector, respected globally, and bringing this international event here helps bridge local specialists with their global counterparts and broaden the community.

    The format of DevOpsDays Cape Town includes a single track of 45 minute talks in the morning of each event, followed by shorter talks (5-15 minutes). We spend the rest of the afternoon in Open Spaces, which are considered a key portion of the event.

                 Like Us On Facebook

                 Follow Us On Twitter

                 Follow Us On Instagram

      <link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">

      <form action="https://capetown.us14.list-manage.com/subscribe/post?u=fe32d6c23e5614eec1f3c4c0f&id=4014e7cbca" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

Get updates for DevOpsDays Cape Town in your email!

* indicates required

        Email Address  *

        <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

          Email Format

<input type="radio" value="html" name="EMAILTYPE" id="mce-EMAILTYPE-0">html

<input type="radio" value="text" name="EMAILTYPE" id="mce-EMAILTYPE-1">text

<input type="text" name="b_73fa675560db334c7a7c193b4_f0b1752604" tabindex="-1" value="">

<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button">

      </form>


text:
namespace hlcanopen {

typedef boost::variant<uint32_t, int32_t, std::string> ODEntryValue;

enum class EntryAccess : unsigned char {
    READONLY,
    WRITEONLY,
    READWRITE
};
struct ODEntry {
    EntryAccess access;
    ODEntryValue value;
};

class ObjectDictionary {
public:
    void write(SDOIndex index, ODEntryValue value) {
        ODEntry entry = map[index];
        entry.value = value;
        map[index] = entry;
    }

    bool writeCheckAccess(SDOIndex index, ODEntryValue value) {
        ODEntry entry = map[index];
        if(entry.access == EntryAccess::READONLY) {
            return false;
        } else entry.value = value;
        return true;
    }

    ODEntryValue read(SDOIndex index) {
        return map[index].value;
    }

    bool contains(SDOIndex index) {
        return map.find(index) != map.end();
    }

    EntryAccess getAccess(SDOIndex index) {
        return map[index].access;
    }

    void setAccess(SDOIndex index, EntryAccess access) {
        ODEntry entry = map[index];
        entry.access = access;
        map[index] = entry;
    }

private:
    std::map<SDOIndex, ODEntry, SDOIndexCompare> map;
};

}

#endif // OCO_OBJECT_DICTIONARY_HPP


text:
'use strict'

// Load gulp
import gulp from 'gulp'

// Load modules to run tasks from files
import requireDir from 'require-dir'
import runSequence from 'run-sequence'
const tasks = requireDir(__dirname + '/tasks') // eslint-disable-line

// Build website, either with development or minified assets and run server with live reloading
gulp.task('default', (callback) => {
  runSequence(
    'clean',
    'cachebusting',
    'metalsmith',
    'standardlint',
    'standardlinttests',
    'mocha',
    ['htmlmin', 'svgsprite', 'scss', 'webpack', 'img', 'copy'],
    ['browsersync', 'watch'],
    callback
  )
})

// Build website, either with development or minified assets depending on flag
gulp.task('deploy', (callback) => {
  runSequence(
    'clean',
    'cachebusting',
    'metalsmith',
    'standardlint',
    'standardlinttests',
    'mocha',
    ['htmlmin', 'svgsprite', 'scss', 'webpack', 'img', 'copy'],
    'crticalcss',
    callback
  )
})

// Run a task to check the code
gulp.task('auditcode', (callback) => {
  runSequence(
    'scssfmt',
    'scsslint',
    'standardlint',
    'standardlinttests',
    'mocha',
    callback
  )
})

// Run a task to build website and add tota11y
gulp.task('audita11y', (callback) => {
  runSequence(
    'deploy',
    'tota11y',
    'browsersync',
    callback
  )
})


text:
yum -y update
yum -y install selinux-policy-targeted

yum -y install audit audit-libs
systemctl enable auditd
systemctl start auditd

if [ "`getenforce`" != "Enforcing" ]; then
sed -i "s/SELINUX=disabled/SELINUX=enforcing/g" /etc/selinux/config
sed -i "s/SELINUX=permissive/SELINUX=enforcing/g" /etc/selinux/config
touch /.autorelabel
reboot
fi


text:
bool
CExprComplexValue::
getStringValue(std::string &s) const
{
  s = "{" + CStrUtil::toString(c_.real()) + ", " + CStrUtil::toString(c_.imag()) + "}";

  return true;
}

CExprValuePtr
CExprComplexValue::
execUnaryOp(CExpr *expr, CExprOpType op) const
{
  switch (op) {
    case CExprOpType::UNARY_PLUS:
      return expr->createComplexValue(c_);
    case CExprOpType::UNARY_MINUS:
      return expr->createComplexValue(-c_);
    default:
      return CExprValuePtr();
  }
}

CExprValuePtr
CExprComplexValue::
execBinaryOp(CExpr *expr, CExprValuePtr rhs, CExprOpType op) const
{
  std::complex<double> rc;

  if (! rhs->getComplexValue(rc))
    return CExprValuePtr();

  //---

  std::string result;

  switch (op) {
    case CExprOpType::PLUS:
      return expr->createComplexValue(c_ + rc);
    case CExprOpType::MINUS:
      return expr->createComplexValue(c_ - rc);
    case CExprOpType::TIMES:
      return expr->createComplexValue(c_ * rc);
    case CExprOpType::DIVIDE:
      return expr->createComplexValue(c_ / rc);
    default:
      return CExprValuePtr();
  }
}


text:
NAME=graphite
VOLUME_BASE=$(HOME)/volumes/$(NAME)

build:
	docker build -t crccheck/graphite .

# You should run `make conf storage` prior to running this the first time or
# else the configuration files won't get loaded and the database won't be
# initialized.
run:
	@mkdir -p $(VOLUME_BASE)/log/apache2
	@mkdir -p $(VOLUME_BASE)/log/supervisor
	docker run -d --name graphite \
	  -v $(VOLUME_BASE)/conf:/opt/graphite/conf \
	  -v $(VOLUME_BASE)/log/apache2:/var/log/apache2 \
	  -v $(VOLUME_BASE)/log/supervisor:/var/log/supervisor \
	  -v $(VOLUME_BASE)/storage:/opt/graphite/storage \
	  crccheck/graphite

# variation of `run` that cleans and runs in the foreground
# could be more DRY, but meh
run_debug:
	sudo rm -rf $(VOLUME_BASE)/storage
	rm -rf $(VOLUME_BASE)/log

	@mkdir -p $(VOLUME_BASE)/log/apache2
	@mkdir -p $(VOLUME_BASE)/log/supervisor
	docker run --rm --name graphite \
	  -v $(VOLUME_BASE)/conf:/opt/graphite/conf \
	  -v $(VOLUME_BASE)/log/apache2:/var/log/apache2 \
	  -v $(VOLUME_BASE)/log/supervisor:/var/log/supervisor \
	  -v $(VOLUME_BASE)/storage:/opt/graphite/storage \
	  crccheck/graphite

bash:
	dockr bash evarga/graphite

# copy the default configuration for reference
conf:
	@mkdir -p $(VOLUME_BASE)
	docker run --rm --name tmp-graphite evarga/graphite \
	  tar -c --directory /opt/graphite conf | tar -xv --directory $(VOLUME_BASE)

# copy the default configuration for reference
storage:
	@mkdir -p $(VOLUME_BASE)
	docker run --rm --name tmp-graphite evarga/graphite \
	  tar -c --directory /opt/graphite storage | tar -xv --directory $(VOLUME_BASE)


text:
import webpack from 'webpack'
import path from 'path'
import colors from 'colors'
import ExtractTextPlugin from 'extract-text-webpack-plugin'

const extractSass = new ExtractTextPlugin({
    filename: "css/[name].css",
    disable: process.env.NODE_ENV === "development"
})

const webpack_configs = webpack({
  entry: {
    index: path.join(__dirname, '../public/bundle/index'),
  },
  output: {
      path: path.join(__dirname, '../public/webpackBale'),
      filename: 'js/[name].js'
  },
  module: {
      rules: [
          {
              test: /\.css$/,
              loader: "style-loader!css-loader!resolve-url-loader"
          },
          {
            test: /\.css$/,
            use: ['style-loader', 'css-loader'],
          },
          {
            test: /\.scss$/,
            use: extractSass.extract({
              use: [{
                loader: 'css-loader',
              }, {
                loader: 'sass-loader',
              }],
                // use style-loader in development
              fallback: 'style-loader',
            }),
          },
          {
              test: /\.jsx$/,
              loader: 'babel-loader',
              exclude: /node_modules/,
              options: {
                  plugins: ['transform-runtime'],
                  presets: ['es2015', 'react']
              }
          },
          {
              test: /\.png|jpg$/,
              loader: 'url-loader'
          }
      ]
  },
  plugins: [
    extractSass,
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      compress: {
        warnings: false,
      },
    }),
  ]
})

webpack_configs.watch({ // watch options:
    aggregateTimeout: 400, // wait so long for more changes
    poll: true // use polling instead of native watchers
    // pass a number to set the polling interval
}, function(err, stats) {
    if(err){
        console.warn(colors.red(err))
    }
})

export default webpack_configs


text:
package com.thoughtworks.xstream.io.json;

import java.io.Externalizable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.core.util.FastStack;
import com.thoughtworks.xstream.io.AbstractWriter;
import com.thoughtworks.xstream.io.naming.NameCoder;
import com.thoughtworks.xstream.io.naming.NoNameCoder;
import com.thoughtworks.xstream.mapper.Mapper;

/**
 * An abstract implementation of a writer that calls abstract methods to build JSON structures. Note, that XStream's
 * implicit collection feature is only compatible with the syntax in {@link #EXPLICIT_MODE}.
 *
 * @author Jörg Schaible
 * @since 1.4
 */
public abstract class AbstractJsonWriter extends AbstractWriter {
    /**
     * DROP_ROOT_MODE drops the JSON root node.
     *

     * The root node is the first level of the JSON object i.e.
     *

     *
     *

     * { "person": {
     *     "name": "Joe"
     * }}
     *

     *

     * will be written without root simply as
     *

     *
     *

     * {
     *     "name": "Joe"
     * }
     *

     *

     * Without a root node, the top level element might now also be an array. However, it is possible to generate
     * invalid JSON unless {@link #STRICT_MODE} is also set.
     *

     *
     * @since 1.3.1
     */
    public static final int DROP_ROOT_MODE = 1;
    /**
     * STRICT_MODE prevents invalid JSON for single value objects when dropping the root.
     *

     * The mode is only useful in combination with the {@link #DROP_ROOT_MODE}. An object with a single value as first
     * node i.e.
     *

     *
     *

     * { "name": "Joe" }
     *

     *

     * is simply written as
     *

     *
     *

     * "Joe"
     *

     *

     * However, this is no longer valid JSON. Therefore you can activate {@link #STRICT_MODE} and a
     * {@link ConversionException} is thrown instead.
     *

     *
     * @since 1.3.1
     */
    public static final int STRICT_MODE = 2;
    /**
     * EXPLICIT_MODE assures that all data has its explicit equivalent in the resulting JSON.
     *

     * XStream is normally using attributes in XML that have no real equivalent in JSON. Additionally it is essential in
     * XML that the individual child elements of a tag keep order and may have the same tag name. XStream's model relies
     * on both characteristics. However, properties of a JSON object do not have a defined order, but their names have
     * to be unique. Only a JSON array defines the order of its elements.
     *

     *

     * Therefore XStream uses in explicit mode a JSON format that supports the original requirements at the expense of
     * the simplicity of the JSON objects and arrays. Each Java object will be represented by a JSON object with a
     * single property representing the name of the object and an array as value that contains two more arrays. The
     * first one contains a JSON object with all attributes, the second one the value of the Java object which can be
     * null, a string or integer value or again a new JSON object representing a Java object. Here an example of an
     * string array with one member, where the array and the string has an additional attribute 'id':
     *

     *
     *

     * {"string-array":[[{"id":"1"}],[{"string":[[{"id":"2"}],["Joe"]]}]]}
     *

     *

     * This format can be used to always deserialize into Java again.
     *

     *

     * This mode cannot combined with {@link #STRICT_MODE} or {@link #DROP_ROOT_MODE}.
     *

     *
     * @since 1.4
     */
    public static final int EXPLICIT_MODE = 4;
    /**
     * IEEE_754_MODE keeps precision of 64-bit integer values.
     *

     * In JavaScript every number is expressed as 64-bit double value with a precision of 53 bits following IEEE 754.
     * Therefore it is not possible to represent the complete value range of 64-bit integer values. Any integer value
     * > 253 (9007199254740992) or < -253 (-9007199254740992) will therefore be written as
     * string value.
     *

     *

     * CAUTION: A client must be aware that the element may contain a number or a string value.
     *

     *
     * @since 1.4.5
     * @see ECMA Specification: The Number Type
     */
    public static final int IEEE_754_MODE = 8;

    public static class Type {
        public static Type NULL = new Type();
        public static Type STRING = new Type();
        public static Type NUMBER = new Type();
        public static Type BOOLEAN = new Type();
    }

    private static class StackElement {
        final Class<?> type;
        int status;

        public StackElement(final Class<?> type, final int status) {
            this.type = type;
            this.status = status;
        }
    }

    private static class IllegalWriterStateException extends IllegalStateException {
        public IllegalWriterStateException(final int from, final int to, final String element) {
            super("Cannot turn from state "
                + getState(from)
                + " into state "
                + getState(to)
                + (element == null ? "" : " for property " + element));
        }

        private static String getState(final int state) {
            switch (state) {
            case STATE_ROOT:
                return "ROOT";
            case STATE_END_OBJECT:
                return "END_OBJECT";
            case STATE_START_OBJECT:
                return "START_OBJECT";
            case STATE_START_ATTRIBUTES:
                return "START_ATTRIBUTES";
            case STATE_NEXT_ATTRIBUTE:
                return "NEXT_ATTRIBUTE";
            case STATE_END_ATTRIBUTES:
                return "END_ATTRIBUTES";
            case STATE_START_ELEMENTS:
                return "START_ELEMENTS";
            case STATE_NEXT_ELEMENT:
                return "NEXT_ELEMENT";
            case STATE_END_ELEMENTS:
                return "END_ELEMENTS";
            case STATE_SET_VALUE:
                return "SET_VALUE";
            default:
                throw new IllegalArgumentException("Unknown state provided: "
                    + state
                    + ", cannot create message for IllegalWriterStateException");
            }
        }
    }

    private static final int STATE_ROOT = 1 << 0;
    private static final int STATE_END_OBJECT = 1 << 1;
    private static final int STATE_START_OBJECT = 1 << 2;
    private static final int STATE_START_ATTRIBUTES = 1 << 3;
    private static final int STATE_NEXT_ATTRIBUTE = 1 << 4;
    private static final int STATE_END_ATTRIBUTES = 1 << 5;
    private static final int STATE_START_ELEMENTS = 1 << 6;
    private static final int STATE_NEXT_ELEMENT = 1 << 7;
    private static final int STATE_END_ELEMENTS = 1 << 8;
    private static final int STATE_SET_VALUE = 1 << 9;

    private static final Set<Class<?>> NUMBER_TYPES = new HashSet<Class<?>>(Arrays.<Class<?>>asList(byte.class,
        Byte.class, short.class, Short.class, int.class, Integer.class, long.class, Long.class, float.class,
        Float.class, double.class, Double.class, BigInteger.class, BigDecimal.class));
    private final int mode;
    private final FastStack<StackElement> stack = new FastStack<StackElement>(16);
    private int expectedStates;

    /**
     * Construct a JSON writer.
     *
     * @since 1.4
     */
    public AbstractJsonWriter() {
        this(new NoNameCoder());
    }

    /**
     * Construct a JSON writer with a special mode.
     *
     * @param mode a bit mask of the mode constants
     * @since 1.4
     */
    public AbstractJsonWriter(final int mode) {
        this(mode, new NoNameCoder());
    }

    /**
     * Construct a JSON writer with a special name coder.
     *
     * @param nameCoder the name coder to use
     * @since 1.4
     */
    public AbstractJsonWriter(final NameCoder nameCoder) {
        this(0, nameCoder);
    }

    /**
     * Construct a JSON writer with a special mode and name coder.
     *
     * @param mode a bit mask of the mode constants
     * @param nameCoder the name coder to use
     * @since 1.4
     */
    public AbstractJsonWriter(final int mode, final NameCoder nameCoder) {
        super(nameCoder);
        this.mode = (mode & EXPLICIT_MODE) > 0 ? EXPLICIT_MODE : mode;
        stack.push(new StackElement(null, STATE_ROOT));
        expectedStates = STATE_START_OBJECT;
    }

    @Override
    public void startNode(final String name, final Class<?> clazz) {
        if (name == null) {
            throw new NullPointerException("name");
        }
        stack.push(new StackElement(clazz, stack.peek().status));
        handleCheckedStateTransition(STATE_START_OBJECT, name, null);
        expectedStates = STATE_SET_VALUE | STATE_NEXT_ATTRIBUTE | STATE_START_OBJECT | STATE_NEXT_ELEMENT | STATE_ROOT;
    }

    @Override
    public void startNode(final String name) {
        startNode(name, null);
    }

    @Override
    public void addAttribute(final String name, final String value) {
        handleCheckedStateTransition(STATE_NEXT_ATTRIBUTE, name, value);
        expectedStates = STATE_SET_VALUE | STATE_NEXT_ATTRIBUTE | STATE_START_OBJECT | STATE_NEXT_ELEMENT | STATE_ROOT;
    }

    @Override
    public void setValue(String text) {
        final Class<?> type = stack.peek().type;
        if ((type == Character.class || type == Character.TYPE) && "".equals(text)) {
            text = "\u0000";
        }
        handleCheckedStateTransition(STATE_SET_VALUE, null, text);
        expectedStates = STATE_NEXT_ELEMENT | STATE_ROOT;
    }

    @Override
    public void endNode() {
        final int size = stack.size();
        final int nextState = size > 2 ? STATE_NEXT_ELEMENT : STATE_ROOT;
        handleCheckedStateTransition(nextState, null, null);
        stack.pop();
        stack.peek().status = nextState;
        expectedStates = STATE_START_OBJECT;
        if (size > 2) {
            expectedStates |= STATE_NEXT_ELEMENT | STATE_ROOT;
        }
    }

    private void handleCheckedStateTransition(final int requiredState, final String elementToAdd,
            final String valueToAdd) {
        final StackElement stackElement = stack.peek();
        if ((expectedStates & requiredState) == 0) {
            throw new IllegalWriterStateException(stackElement.status, requiredState, elementToAdd);
        }
        final int currentState = handleStateTransition(stackElement.status, requiredState, elementToAdd, valueToAdd);
        stackElement.status = currentState;
    }

    private int handleStateTransition(int currentState, final int requiredState, final String elementToAdd,
            final String valueToAdd) {
        final int size = stack.size();
        final Class<?> currentType = stack.peek().type;
        final boolean isArray = size > 1 && isArray(currentType);
        final boolean isArrayElement = size > 1 && isArray(stack.get(size - 2).type);
        switch (currentState) {
        case STATE_ROOT:
            if (requiredState == STATE_START_OBJECT) {
                currentState = handleStateTransition(STATE_START_ELEMENTS, STATE_START_OBJECT, elementToAdd, null);
                return requiredState;
            }
            throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);

        case STATE_END_OBJECT:
            switch (requiredState) {
            case STATE_START_OBJECT:
                currentState = handleStateTransition(currentState, STATE_NEXT_ELEMENT, null, null);
                currentState = handleStateTransition(currentState, STATE_START_OBJECT, elementToAdd, null);
                return requiredState;
            case STATE_NEXT_ELEMENT:
                nextElement();
                return requiredState;
            case STATE_ROOT:
                if (((mode & DROP_ROOT_MODE) == 0 || size > 2) && (mode & EXPLICIT_MODE) == 0) {
                    endObject();
                }
                return requiredState;
            default:
                throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);
            }

        case STATE_START_OBJECT:
            switch (requiredState) {
            case STATE_SET_VALUE:
            case STATE_START_OBJECT:
            case STATE_ROOT:
            case STATE_NEXT_ELEMENT:
                if (!isArrayElement || (mode & EXPLICIT_MODE) != 0) {
                    currentState = handleStateTransition(currentState, STATE_START_ATTRIBUTES, null, null);
                    currentState = handleStateTransition(currentState, STATE_END_ATTRIBUTES, null, null);
                }
                currentState = STATE_START_ELEMENTS;

                switch (requiredState) {
                case STATE_SET_VALUE:
                    currentState = handleStateTransition(currentState, STATE_SET_VALUE, null, valueToAdd);
                    break;
                case STATE_START_OBJECT:
                    currentState = handleStateTransition(currentState, STATE_START_OBJECT, elementToAdd, null);
                    break;
                case STATE_ROOT:
                case STATE_NEXT_ELEMENT:
                    currentState = handleStateTransition(currentState, STATE_SET_VALUE, null, null);
                    currentState = handleStateTransition(currentState, requiredState, null, null);
                    break;
                }
                return requiredState;
            case STATE_START_ATTRIBUTES:
                if ((mode & EXPLICIT_MODE) != 0) {
                    startArray();
                }
                return requiredState;
            case STATE_NEXT_ATTRIBUTE:
                if ((mode & EXPLICIT_MODE) != 0 || !isArray) {
                    currentState = handleStateTransition(currentState, STATE_START_ATTRIBUTES, null, null);
                    currentState = handleStateTransition(currentState, STATE_NEXT_ATTRIBUTE, elementToAdd, valueToAdd);
                    return requiredState;
                } else {
                    return STATE_START_OBJECT;
                }
            default:
                throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);
            }

        case STATE_NEXT_ELEMENT:
            switch (requiredState) {
            case STATE_START_OBJECT:
                nextElement();
                if (!isArrayElement && (mode & EXPLICIT_MODE) == 0) {
                    addLabel(encodeNode(elementToAdd));
                    if ((mode & EXPLICIT_MODE) == 0 && isArray) {
                        startArray();
                    }
                    return requiredState;
                }
                break;
            case STATE_ROOT:
                currentState = handleStateTransition(currentState, STATE_END_OBJECT, null, null);
                currentState = handleStateTransition(currentState, STATE_ROOT, null, null);
                return requiredState;
            case STATE_NEXT_ELEMENT:
            case STATE_END_OBJECT:
                currentState = handleStateTransition(currentState, STATE_END_ELEMENTS, null, null);
                currentState = handleStateTransition(currentState, STATE_END_OBJECT, null, null);
                if ((mode & EXPLICIT_MODE) == 0 && !isArray) {
                    endObject();
                }
                return requiredState;
            case STATE_END_ELEMENTS:
                if ((mode & EXPLICIT_MODE) == 0 && isArray) {
                    endArray();
                }
                return requiredState;
            default:
                throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);
            }
            //$FALL-THROUGH$
        case STATE_START_ELEMENTS:
            switch (requiredState) {
            case STATE_START_OBJECT:
                if ((mode & DROP_ROOT_MODE) == 0 || size > 2) {
                    if (!isArrayElement || (mode & EXPLICIT_MODE) != 0) {
                        if (!"".equals(valueToAdd)) {
                            startObject();
                        }
                        addLabel(encodeNode(elementToAdd));
                    }
                    if ((mode & EXPLICIT_MODE) != 0) {
                        startArray();
                    }
                }
                if ((mode & EXPLICIT_MODE) == 0) {
                    if (isArray) {
                        startArray();
                    }
                }
                return requiredState;
            case STATE_SET_VALUE:
                if ((mode & STRICT_MODE) != 0 && size == 2) {
                    throw new ConversionException("Single value cannot be root element");
                }
                if (valueToAdd == null) {
                    if (currentType == Mapper.Null.class) {
                        addValue("null", Type.NULL);
                    } else if ((mode & EXPLICIT_MODE) == 0 && !isArray) {
                        startObject();
                        endObject();
                    }
                } else {
                    if ((mode & IEEE_754_MODE) != 0 && (currentType == long.class || currentType == Long.class)) {
                        final long longValue = Long.parseLong(valueToAdd);
                        // JavaScript supports a maximum of 2^53
                        if (longValue > 9007199254740992L || longValue < -9007199254740992L) {
                            addValue(valueToAdd, Type.STRING);
                        } else {
                            addValue(valueToAdd, getType(currentType));
                        }
                    } else {
                        addValue(valueToAdd, getType(currentType));
                    }
                }
                return requiredState;
            case STATE_END_ELEMENTS:
            case STATE_NEXT_ELEMENT:
                if ((mode & EXPLICIT_MODE) == 0) {
                    if (isArray) {
                        endArray();
                    } else {
                        endObject();
                    }
                }
                return requiredState;
            default:
                throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);
            }

        case STATE_END_ELEMENTS:
            switch (requiredState) {
            case STATE_END_OBJECT:
                if ((mode & EXPLICIT_MODE) != 0) {
                    endArray();
                    endArray();
                    endObject();
                }
                return requiredState;
            default:
                throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);
            }

        case STATE_START_ATTRIBUTES:
            switch (requiredState) {
            case STATE_NEXT_ATTRIBUTE:
                if (elementToAdd != null) {
                    final String name = ((mode & EXPLICIT_MODE) == 0 ? "@" : "") + elementToAdd;
                    startObject();
                    addLabel(encodeAttribute(name));
                    addValue(valueToAdd, Type.STRING);
                }
                return requiredState;
            }
            //$FALL-THROUGH$
        case STATE_NEXT_ATTRIBUTE:
            switch (requiredState) {
            case STATE_END_ATTRIBUTES:
                if ((mode & EXPLICIT_MODE) != 0) {
                    if (currentState == STATE_NEXT_ATTRIBUTE) {
                        endObject();
                    }
                    endArray();
                    nextElement();
                    startArray();
                }
                return requiredState;
            case STATE_NEXT_ATTRIBUTE:
                if (!isArray || (mode & EXPLICIT_MODE) != 0) {
                    nextElement();
                    final String name = ((mode & EXPLICIT_MODE) == 0 ? "@" : "") + elementToAdd;
                    addLabel(encodeAttribute(name));
                    addValue(valueToAdd, Type.STRING);
                }
                return requiredState;
            case STATE_SET_VALUE:
            case STATE_START_OBJECT:
                currentState = handleStateTransition(currentState, STATE_END_ATTRIBUTES, null, null);
                currentState = handleStateTransition(currentState, STATE_START_ELEMENTS, null, null);
                switch (requiredState) {
                case STATE_SET_VALUE:
                    if ((mode & EXPLICIT_MODE) == 0) {
                        addLabel(encodeNode("$"));
                    }
                    currentState = handleStateTransition(currentState, STATE_SET_VALUE, null, valueToAdd);
                    if ((mode & EXPLICIT_MODE) == 0) {
                        endObject();
                    }
                    break;
                case STATE_START_OBJECT:
                    currentState = handleStateTransition(currentState, STATE_START_OBJECT, elementToAdd,
                        (mode & EXPLICIT_MODE) == 0 ? "" : null);
                    break;
                case STATE_END_OBJECT:
                    currentState = handleStateTransition(currentState, STATE_SET_VALUE, null, null);
                    currentState = handleStateTransition(currentState, STATE_END_OBJECT, null, null);
                    break;
                }
                return requiredState;
            case STATE_NEXT_ELEMENT:
                currentState = handleStateTransition(currentState, STATE_END_ATTRIBUTES, null, null);
                currentState = handleStateTransition(currentState, STATE_END_OBJECT, null, null);
                return requiredState;
            case STATE_ROOT:
                currentState = handleStateTransition(currentState, STATE_END_ATTRIBUTES, null, null);
                currentState = handleStateTransition(currentState, STATE_END_OBJECT, null, null);
                currentState = handleStateTransition(currentState, STATE_ROOT, null, null);
                return requiredState;
            default:
                throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);
            }

        case STATE_END_ATTRIBUTES:
            switch (requiredState) {
            case STATE_START_ELEMENTS:
                if ((mode & EXPLICIT_MODE) == 0) {
                    nextElement();
                }
                break;
            case STATE_END_OBJECT:
                currentState = handleStateTransition(STATE_START_ELEMENTS, STATE_END_ELEMENTS, null, null);
                currentState = handleStateTransition(currentState, STATE_END_OBJECT, null, null);
                break;
            default:
                throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);
            }
            return requiredState;

        case STATE_SET_VALUE:
            switch (requiredState) {
            case STATE_END_ELEMENTS:
                if ((mode & EXPLICIT_MODE) == 0 && isArray) {
                    endArray();
                }
                return requiredState;
            case STATE_NEXT_ELEMENT:
                currentState = handleStateTransition(currentState, STATE_END_ELEMENTS, null, null);
                currentState = handleStateTransition(currentState, STATE_END_OBJECT, null, null);
                return requiredState;
            case STATE_ROOT:
                currentState = handleStateTransition(currentState, STATE_END_ELEMENTS, null, null);
                currentState = handleStateTransition(currentState, STATE_END_OBJECT, null, null);
                currentState = handleStateTransition(currentState, STATE_ROOT, null, null);
                return requiredState;
            default:
                throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);
            }
        }

        throw new IllegalWriterStateException(currentState, requiredState, elementToAdd);
    }

    /**
     * Method to return the appropriate JSON type for a Java type.
     *
     * @param clazz the type
     * @return One of the {@link Type} instances
     * @since 1.4.4
     */
    protected Type getType(final Class<?> clazz) {
        return clazz == Mapper.Null.class ? Type.NULL : clazz == Boolean.class || clazz == Boolean.TYPE
            ? Type.BOOLEAN
            : NUMBER_TYPES.contains(clazz) ? Type.NUMBER : Type.STRING;
    }

    /**
     * Method to declare various Java types to be handles as JSON array.
     *
     * @param clazz the type
     * @return true if handles as array
     * @since 1.4
     */
    protected boolean isArray(final Class<?> clazz) {
        return clazz != null
            && (clazz.isArray()
                || Collection.class.isAssignableFrom(clazz)
                || Externalizable.class.isAssignableFrom(clazz)
                || Map.class.isAssignableFrom(clazz) || Map.Entry.class.isAssignableFrom(clazz));
    }

    /**
     * Start a JSON object.
     *
     * @since 1.4
     */
    protected abstract void startObject();

    /**
     * Add a label to a JSON object.
     *
     * @param name the label's name
     * @since 1.4
     */
    protected abstract void addLabel(String name);

    /**
     * Add a value to a JSON object's label or to an array.
     *
     * @param value the value itself
     * @param type the JSON type
     * @since 1.4
     */
    protected abstract void addValue(String value, Type type);

    /**
     * Start a JSON array.
     *
     * @since 1.4
     */
    protected abstract void startArray();

    /**
     * Prepare a JSON object or array for another element.
     *
     * @since 1.4
     */
    protected abstract void nextElement();

    /**
     * End the JSON array.
     *
     * @since 1.4
     */
    protected abstract void endArray();

    /**
     * End the JSON object.
     *
     * @since 1.4
     */
    protected abstract void endObject();
}


text:
package com.ibatis.sqlmap.engine.execution;

import org.apache.ibatis.executor.BatchExecutorException;

import java.sql.BatchUpdateException;
import java.util.List;

/*
 * This exception is thrown if a java.sql.BatchUpdateException is caught
 * during the execution of any nested batch.  The exception contains the
 * java.sql.BatchUpdateException that is the root cause, as well as
 * the results from any prior nested batch that executed successfully.  This exception
 * is only thrown from the executeBatchDetailed method.
 *
 * @author Jeff Butler
 */
public class BatchException extends RuntimeException {

  private List successfulBatchResults;
  private BatchUpdateException batchUpdateException;
  private String failingSqlStatement;
  private String failingStatementId;

  public BatchException(BatchExecutorException e) {
    this(e.getMessage(),
        e.getBatchUpdateException(),
        e.getSuccessfulBatchResults(),
        e.getFailingStatementId(),
        e.getFailingSqlStatement());
  }

  /*
   *
   */
  public BatchException(String message, BatchUpdateException cause, List successfulBatchResults,
                        String failingStatementId, String failingSqlStatement) {
    super(message, cause);
    this.batchUpdateException = cause;
    this.successfulBatchResults = successfulBatchResults;
    this.failingStatementId = failingStatementId;
    this.failingSqlStatement = failingSqlStatement;
  }

  /*
   * Returns the BatchUpdateException that caused the nested batch
   * to fail.  That exception contains an array of row counts
   * that can be used to determine exactly which statemtn of the
   * batch caused the failure (or failures).
   *
   * @return the root BatchUpdateException
   */
  public BatchUpdateException getBatchUpdateException() {
    return batchUpdateException;
  }

  /*
   * Returns a list of BatchResult objects.  There will be one entry
   * in the list for each successful sub-batch executed before the failing
   * batch.
   *
   * @return the previously successful batch results (may be an empty list
   *         if no batch has executed successfully)
   */
  public List getSuccessfulBatchResults() {
    return successfulBatchResults;
  }

  /*
   * Returns the SQL statement that caused the failure
   * (not the parameters)
   *
   * @return the failing SQL string
   */
  public String getFailingSqlStatement() {
    return failingSqlStatement;
  }

  /*
   * Returns the statement id of the statement that caused the failure
   *
   * @return the statement id
   */
  public String getFailingStatementId() {
    return failingStatementId;
  }
}