text:
package datafu.hourglass.demo;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.Schema.Type;
import org.apache.avro.file.DataFileStream;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.DatumReader;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import datafu.hourglass.fs.PathUtils;
import datafu.hourglass.test.Schemas;
import datafu.hourglass.test.PartitionCollapsingTests;
import datafu.hourglass.test.TestBase;
import datafu.hourglass.test.util.DailyTrackingWriter;

@Test(groups="pcl")
public class Examples extends TestBase
{
  private Logger _log = Logger.getLogger(PartitionCollapsingTests.class);

  private static final Schema EVENT_SCHEMA;

  private GenericRecord _record;
  private DailyTrackingWriter _eventWriter;

  static
  {
    EVENT_SCHEMA = Schemas.createRecordSchema(Examples.class, "Event",
                                              new Field("id", Schema.create(Type.LONG), null, null));

    System.out.println("Event schema: " + EVENT_SCHEMA.toString(true));
  }

  public Examples() throws IOException
  {
    super();
  }

  @BeforeClass
  public void beforeClass() throws Exception
  {
    super.beforeClass();
  }

  @AfterClass
  public void afterClass() throws Exception
  {
    super.afterClass();
  }

  @BeforeMethod
  public void beforeMethod(Method method) throws IOException
  {
    _log.info("*** Running " + method.getName());

    _log.info("*** Cleaning input and output paths");
    getFileSystem().delete(new Path(getDataPath(), "data"), true);
    getFileSystem().delete(new Path(getDataPath(), "output"), true);
    getFileSystem().mkdirs(new Path(getDataPath(), "data"));
    getFileSystem().mkdirs(new Path(getDataPath(), "output"));

    _record = new GenericData.Record(EVENT_SCHEMA);
    _eventWriter = new DailyTrackingWriter(new Path(getDataPath(), "data/event"),EVENT_SCHEMA,getFileSystem());
  }

  @Test
  public void countByMember() throws IOException, InterruptedException, ClassNotFoundException
  {
    // setup
    openDayForEvent(2013, 3, 15);
    storeIds(1,1,1);
    storeIds(2);
    storeIds(3,3);
    closeDayForEvent();

    openDayForEvent(2013, 3, 16);
    storeIds(1,1);
    storeIds(2,2);
    storeIds(3);
    closeDayForEvent();

    // run
    new CountById().run(createJobConf(),getDataPath() + "/data/event",getDataPath() + "/output");

    // verify

    checkOutputFolderCount(new Path(getDataPath(), "output"), 1);

    HashMap<Long,Integer> counts = loadOutputCounts(new Path(getDataPath(), "output"), "20130316");

    checkSize(counts,3);
    checkIdCount(counts,1,5);
    checkIdCount(counts,2,3);
    checkIdCount(counts,3,3);

    // more data
    openDayForEvent(2013, 3, 17);
    storeIds(1,1);
    storeIds(2,2,2);
    storeIds(3,3);
    closeDayForEvent();

    // run
    new CountById().run(createJobConf(),getDataPath() + "/data/event",getDataPath() + "/output");

    counts = loadOutputCounts(new Path(getDataPath(), "output"), "20130317");

    checkSize(counts,3);
    checkIdCount(counts,1,7);
    checkIdCount(counts,2,6);
    checkIdCount(counts,3,5);
  }

  @Test
  public void estimateNumMembers() throws IOException, InterruptedException, ClassNotFoundException
  {
    openDayForEvent(2013, 3, 1);
    // lots of members logged in this day
    for (int i=1; i<=10000; i++)
    {
      storeIds(i);
    }
    closeDayForEvent();

    // but only a handful logged in the remaining days
    for (int i=2; i<=30; i++)
    {
      openDayForEvent(2013, 3, i);
      storeIds(1,2,3,4,5);
      closeDayForEvent();
    }

    // run
    new EstimateCardinality().run(createJobConf(),getDataPath() + "/data/event", getDataPath() + "/output/daily", getDataPath() + "/output/summary",30);

    // verify
    checkIntermediateFolderCount(new Path(getDataPath(), "output/daily"), 30);
    checkOutputFolderCount(new Path(getDataPath(), "output/summary"), 1);
    Assert.assertTrue(Math.abs(10000L - loadMemberCount(new Path(getDataPath(), "output/summary"),"20130330").longValue())/10000.0 < 0.005);

    // more data
    openDayForEvent(2013, 3, 31);
    storeIds(6,7,8,9,10);
    closeDayForEvent();

    // run
    new EstimateCardinality().run(createJobConf(),getDataPath() + "/data/event", getDataPath() + "/output/daily", getDataPath() + "/output/summary",30);

    // verify
    checkIntermediateFolderCount(new Path(getDataPath(), "output/daily"), 31);
    checkOutputFolderCount(new Path(getDataPath(), "output/summary"), 1);
    Assert.assertEquals(loadMemberCount(new Path(getDataPath(), "output/summary"),"20130331").longValue(),10L);
  }

  private void openDayForEvent(int year, int month, int day) throws IOException
  {
    System.out.println(String.format("start day: %04d %02d %02d",year,month,day));
    _eventWriter.open(year, month, day);
  }

  private void closeDayForEvent() throws IOException
  {
    _eventWriter.close();
  }

  private void storeIds(long... ids) throws IOException
  {
    for (long id : ids)
    {
      storeId(id);
    }
  }

  private void storeId(long id) throws IOException
  {
    _record.put("id", id);
    System.out.println("record: " + _record.toString());
    _eventWriter.append(_record);
  }

  private void checkIdCount(HashMap<Long,Integer> counts, long id, long count)
  {
    Assert.assertTrue(counts.containsKey(id));
    Assert.assertEquals(counts.get(id).intValue(), count);
  }

  private void checkSize(HashMap<Long,Integer> counts, int expectedSize)
  {
    if (counts.size() != expectedSize)
    {
      StringBuilder sb = new StringBuilder("Expected count " + expectedSize + " does not match actual " + counts.size() + ", contents:\n");
      List<Long> keys = new ArrayList<Long>(counts.keySet());
      Collections.sort(keys);
      for (Long k : keys)
      {
        sb.append(k.toString() + " => " + counts.get(k).toString() + "\n");
      }
      Assert.fail(sb.toString());
    }
  }

  private void checkOutputFolderCount(Path path, int expectedCount) throws IOException
  {
    Assert.assertEquals(countOutputFolders(path),expectedCount,"Found: " + listOutputFolders(path));
  }

  private void checkIntermediateFolderCount(Path path, int expectedCount) throws IOException
  {
    Assert.assertEquals(countIntermediateFolders(path),expectedCount,"Found: " + listIntermediateFolders(path));
  }

  private int countIntermediateFolders(Path path) throws IOException
  {
    FileSystem fs = getFileSystem();
    return fs.globStatus(new Path(path,"*/*/*"),PathUtils.nonHiddenPathFilter).length;
  }

  private int countOutputFolders(Path path) throws IOException
  {
    FileSystem fs = getFileSystem();
    return fs.listStatus(path,PathUtils.nonHiddenPathFilter).length;
  }

  private String listOutputFolders(Path path) throws IOException
  {
    StringBuilder sb = new StringBuilder();
    for (FileStatus stat : getFileSystem().listStatus(path,PathUtils.nonHiddenPathFilter))
    {
      sb.append(stat.getPath().getName());
      sb.append(",");
    }
    return sb.toString();
  }

  private String listIntermediateFolders(Path path) throws IOException
  {
    StringBuilder sb = new StringBuilder();
    for (FileStatus stat : getFileSystem().globStatus(new Path(path,"*/*/*"),PathUtils.nonHiddenPathFilter))
    {
      sb.append(stat.getPath().getName());
      sb.append(",");
    }
    return sb.toString();
  }

  private Long loadMemberCount(Path path, String timestamp) throws IOException
  {
    FileSystem fs = getFileSystem();
    Assert.assertTrue(fs.exists(new Path(path, timestamp)));
    for (FileStatus stat : fs.globStatus(new Path(path,timestamp + "/*.avro")))
    {
      _log.info(String.format("found: %s (%d bytes)",stat.getPath(),stat.getLen()));
      FSDataInputStream is = fs.open(stat.getPath());
      DatumReader <GenericRecord> reader = new GenericDatumReader<GenericRecord>();
      DataFileStream<GenericRecord> dataFileStream = new DataFileStream<GenericRecord>(is, reader);

      try
      {
        GenericRecord r = dataFileStream.next();
        Long count = (Long)((GenericRecord)r.get("value")).get("count");
        Assert.assertNotNull(count);
        System.out.println("found count: " + count);
        return count;
      }
      finally
      {
        dataFileStream.close();
      }
    }
    throw new RuntimeException("found no data");
  }

  private HashMap<Long,Integer> loadOutputCounts(Path path, String timestamp) throws IOException
  {
    HashMap<Long,Integer> counts = new HashMap<Long,Integer>();
    FileSystem fs = getFileSystem();
    Assert.assertTrue(fs.exists(new Path(path, timestamp)));
    for (FileStatus stat : fs.globStatus(new Path(path,timestamp + "/*.avro")))
    {
      _log.info(String.format("found: %s (%d bytes)",stat.getPath(),stat.getLen()));
      FSDataInputStream is = fs.open(stat.getPath());
      DatumReader <GenericRecord> reader = new GenericDatumReader<GenericRecord>();
      DataFileStream<GenericRecord> dataFileStream = new DataFileStream<GenericRecord>(is, reader);

      try
      {
        while (dataFileStream.hasNext())
        {
          GenericRecord r = dataFileStream.next();
          _log.info("found: " + r.toString());
          Long memberId = (Long)((GenericRecord)r.get("key")).get("member_id");
          Assert.assertNotNull(memberId);
          Integer count = (Integer)((GenericRecord)r.get("value")).get("count");
          Assert.assertNotNull(count);
          Assert.assertFalse(counts.containsKey(memberId));
          counts.put(memberId, count);
        }
      }
      finally
      {
        dataFileStream.close();
      }
    }
    return counts;
  }
}


text:
"""
@brief      test log(time=702s)
"""
import unittest
from pyquickhelper.loghelper import fLOG, noLOG
from pyquickhelper.pycode import get_temp_folder, add_missing_development_version
import ensae_teaching_cs

class TestNotebookRunnerExposeLong2(unittest.TestCase):

    def setUp(self):
        fLOG("add missing dependencies", OutputPrint=__name__ == "__main__")
        add_missing_development_version(["pymyinstall", "pyensae", "pymmails"],
                                        __file__, hide=True)

    def test_notebook_runner_exposelong2(self):
        fLOG(
            __file__,
            self._testMethodName,
            OutputPrint=__name__ == "__main__")
        from ensae_teaching_cs.automation.notebook_test_helper import ls_notebooks, execute_notebooks, clean_function_1a
        temp = get_temp_folder(__file__, "temp_notebookexposelong2_")
        keepnote = ls_notebooks("expose")
        execute_notebooks(temp, keepnote, (lambda i, n: "paris_parcours" in n),
                          fLOG=fLOG, deepfLOG=fLOG if __name__ == "__main__" else noLOG,
                          clean_function=clean_function_1a, dump=ensae_teaching_cs)

if __name__ == "__main__":
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
package com.br.studyfragments.tutorial.vogella;

import android.app.Fragment;
import android.content.Context;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import com.br.studyfragments.R;

import java.util.Date;
import java.util.List;

/**
 * Created by r028367 on 05/01/2017.
 */

public class FragmentList extends Fragment {

    private OnItemSelectedListener itemListener;
    private List<String> dates;
    ArrayAdapter<String> adapter;

    public List<String> getDates() {
        return dates;
    }

    public void addDate(String date) {
        if(dates != null) {
            dates.add(date);
            adapter.notifyDataSetChanged();
        }
    }

    public FragmentList() {

    }

    private Button addDate;
    private ListView listDate;

    public static final String EXTRA_URL = "TAG";

    public static FragmentList newInstance(String ... args) {
        FragmentList fragment = new FragmentList();
        Bundle bundle = new Bundle();
        for(String arg : args)
            bundle.putString(EXTRA_URL, arg);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnItemSelectedListener) {
            itemListener = (OnItemSelectedListener) context;
        } else {
            throw new RuntimeException(context.toString() + " must implement OnItemSelectedListener");
        }
    }

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        dates = new ArrayList<>();
        /*
        *
        * */
        View view = inflater.inflate(R.layout.fragment_list, container, false);
        addDate = (Button) view.findViewById(R.id.button_list_frag);
        //addDate.setOnClickListener(clickListener);
        listDate = (ListView) view.findViewById(R.id.frag_list_date);
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, dates);
        listDate.setAdapter(adapter);

        listDate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

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

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

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

    /*
    * android:onClick="updateDetail"
    * esse atributo que pode ser utilizado num botao,
    * nao funciona em botoes que estao em fragments. Para adicionar
    * um metodo a um botao no fragment temos que implemenar um Listener
    * */
    public void updateDetail(View view) {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String dt = dateFormat.format(date);
        itemListener.onItemSelected(dt);
    }

    // listener para chamar o metodo updateDetail
    public View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            updateDetail(view);
        }
    };

    public interface OnItemSelectedListener {
        public void onItemSelected(String link);
    }

}


text:
import argparse
import sys

import numpy as np
import skimage.filters
import skimage.io
import skimage.util

threshOptions = {
    'gaussian': lambda img_raw, bz: skimage.filters.threshold_local(img_raw, bz, method='gaussian'),
    'mean': lambda img_raw, bz: skimage.filters.threshold_local(img_raw, bz, method='mean'),
    'median': lambda img_raw, bz: skimage.filters.threshold_local(img_raw, bz, method='median')
}

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Segment Foci')
    parser.add_argument('input_file', type=argparse.FileType('r'), default=sys.stdin, help='input file')
    parser.add_argument('out_file', type=argparse.FileType('w'), default=sys.stdin, help='out file (TIFF)')
    parser.add_argument('block_size', type=int, default=5, help='Odd size of pixel neighborhood which is used to calculate the threshold value')
    parser.add_argument('thresh_type', choices=threshOptions.keys(), help='thresholding method')
    parser.add_argument('dark_background', default=True, type=bool, help='True if background is dark')
    args = parser.parse_args()

    img_in = skimage.io.imread(args.input_file.name)
    img_in = np.reshape(img_in, [img_in.shape[0], img_in.shape[1]])
    thresh = threshOptions[args.thresh_type](img_in, args.block_size)

    if args.dark_background:
        res = img_in > thresh
    else:
        res = img_in <= thresh

    res = skimage.util.img_as_uint(res)
    skimage.io.imsave(args.out_file.name, res, plugin="tifffile")


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="mm_button_accept">Hyväksy</string>
    <string name="mm_button_decline">Hylkää</string>
    <string name="mm_button_open">Avaa</string>
    <string name="mm_button_cancel">Peruuta</string>
    <string name="mm_button_settings">asetukset</string>
</resources>


text:
/**
 * Access to EV3 ports
 */
package lejos.hardware.port;


text:
<?php

function start_checkup()
{
	$required_extensions = Array(
				'pcntl',
				'sqlite3',
				'posix',
				'sockets'
				);

	$required_php_version = '5.3.0';

	//Test PHP Version
	if(version_compare(PHP_VERSION, $required_php_version, '<'))
	{
		return "Your version of PHP (".PHP_VERSION.") is too old. You require at least PHP ".$required_php_version;
	}

	//Test if launching interface is CLI
	if(PHP_SAPI != "cli") return "The script seems to be launched in a different interface instead of CLI mode";

	//Test required extensions
	foreach($required_extensions as $value)
	{
		if(!extension_loaded($value))
			return "A required extension of PHP is missing (".$value.")";
	}

	//Test List and Transfers files
	if(!file_exists(DB_FILE)) return "The List file (".DB_FILE.") doesn't exist.";
	if(!file_exists(TRANSFERS_FILE)) return "The Transfers file (".TRANSFERS_FILE.") doesn't exist.";

	return TRUE; //Everything is fine!
}

?>


text:
package files

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"

	"github.com/lfq7413/tomato/config"
	"github.com/lfq7413/tomato/errs"
	"github.com/lfq7413/tomato/files/tencentcos"
)

// tencentAdapter 腾讯云存储
// TODO 测试
type tencentAdapter struct {
	cos *tencentcos.COS
}

func newTencentAdapter() *tencentAdapter {
	cos := &tencentcos.COS{
		AppID:     config.TConfig.TencentAppID,
		SecretID:  config.TConfig.TencentSecretID,
		SecretKey: config.TConfig.TencentSecretKey,
		Bucket:    config.TConfig.TencentBucket,
	}
	t := &tencentAdapter{
		cos: cos,
	}
	return t
}

func (t *tencentAdapter) createFile(filename string, data []byte, contentType string) error {
	code, err := t.cos.PutObject(filename, data)
	if code != 200 || err != nil {
		return errs.E(errs.FileSaveError, "createFile failed.")
	}
	return nil
}

func (t *tencentAdapter) deleteFile(filename string) error {
	code, err := t.cos.DeleteObject(filename)
	if code != 200 || err != nil {
		return errs.E(errs.FileDeleteError, "deleteFile failed.")
	}
	return nil
}

func (t *tencentAdapter) getFileData(filename string) ([]byte, error) {
	return t.download(filename)
}

func (t *tencentAdapter) getFileLocation(filename string) string {
	if config.TConfig.FileDirectAccess {
		return fmt.Sprintf("http://%s-%s.file.myqcloud.com/%s", t.cos.Bucket, t.cos.AppID, url.QueryEscape(filename))
	}
	return config.TConfig.ServerURL + "/files/" + config.TConfig.AppID + "/" + url.QueryEscape(filename)
}

func (t *tencentAdapter) getFileStream(filename string) (FileStream, error) {
	return nil, errs.E(errs.FileReadError, "no such file or directory")
}

func (t *tencentAdapter) getAdapterName() string {
	return "tencentAdapter"
}

func (t *tencentAdapter) download(filename string) ([]byte, error) {
	path := fmt.Sprintf("http://%s-%s.file.myqcloud.com/%s", t.cos.Bucket, t.cos.AppID, url.QueryEscape(filename))
	request, err := http.NewRequest("GET", path, nil)
	if err != nil {
		return nil, err
	}

	client := http.DefaultClient
	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	if response.StatusCode != 200 {
		return nil, errs.E(errs.FileReadError, "no such file or directory")
	}

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	return body, nil
}


text:
/**
 * This file provides an abstract OS API for entering and exiting critical sections.
 * It furthermore provides macros to define and initialize an optional spinlock
 * if the used chip is a multi-core chip. If a single-core chip is used, just disabling interrupts
 * is sufficient to guarantee consecutive, non-interrupted execution of a critical section.
 * Hence, the spinlock is unneccessary and will be automatically ommitted by the macros.
 */
#pragma once

#include "freertos/portmacro.h"
#include "spinlock.h"

#ifdef __cplusplus
extern "C" {
#endif

#if CONFIG_FREERTOS_UNICORE && !CONFIG_IDF_TARGET_ESP32S2
/**
 * This macro also helps users switching between spinlock declarations/definitions for multi-/single core environments
 * if the macros below aren't sufficient.
 */
#define OS_SPINLOCK 0
#else
#define OS_SPINLOCK 1
#endif

#if OS_SPINLOCK == 1
typedef spinlock_t esp_os_spinlock_t;
#endif

/**
 * Define and initialize a static (internal linking) lock for entering critical sections.
 *
 * Use this when all the critical sections are local inside a file.
 * The lock will only be defined if built for a multi-core system, otherwise it is unnecessary.
 *
 * @note When using this macro, the critical section macros esp_os_enter_critical* and esp_os_exit_critical*
 * MUST be used, otherwise normal functions would be passed an undefined variable when build for single-core systems.
 *
 * @param lock_name Variable name of the lock. This will later be used to reference the declared lock.
 * @param optional_qualifiers Qualifiers such as DRAM_ATTR and other attributes. Can be omitted if no qualifiers are
 *        required.
 *
 * Example usage:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * DEFINE_CRIT_SECTION_LOCK_STATIC(my_lock); // will have internal linking (static)
 * ...
 * esp_os_enter_critical(&my_lock);
 * ...
 * esp_os_exit_critical(&my_lock);
 * @endcode
 */
#if OS_SPINLOCK == 1
#define DEFINE_CRIT_SECTION_LOCK_STATIC(lock_name, optional_qualifiers...) static optional_qualifiers esp_os_spinlock_t lock_name = SPINLOCK_INITIALIZER
#else
#define DEFINE_CRIT_SECTION_LOCK_STATIC(lock_name, optional_qualifiers...)
#endif

/**
 * Define and initialize a non-static (external linking) lock for entering critical sections.
 *
 * Locks defined by this macro can be linked among object files but this rather exceptional.
 * Prefer the static lock definition whenever possible.
 * The lock will only be defined if built for a multi-core system, otherwise it is unnecessary.
 *
 * @note When using this macro, the critical section macros esp_os_enter_critical* and esp_os_exit_critical*
 * MUST be used, otherwise normal functions would be passed an undefined variable when build for single-core systems.
 *
 * @param lock_name Variable name of the lock. This will later be used to reference the declared lock.
 * @param optional_qualifiers Qualifiers such as DRAM_ATTR and other attributes. Can be omitted if no qualifiers are
 *        required.
 *
 * Example usage:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * DEFINE_CRIT_SECTION_LOCK(my_lock); // will have external linking (non-static)
 * ...
 * esp_os_enter_critical(&my_lock);
 * ...
 * esp_os_exit_critical(&my_lock);
 * @endcode
 */
#if OS_SPINLOCK == 1
#define DEFINE_CRIT_SECTION_LOCK(lock_name, optional_qualifiers...) optional_qualifiers esp_os_spinlock_t lock_name = SPINLOCK_INITIALIZER
#else
#define DEFINE_CRIT_SECTION_LOCK(lock_name, optional_qualifiers...)
#endif

/**
 * @brief This macro initializes a critical section lock at runtime.
 *
 * This macro basically creates a member of the initialization list, including the trailing comma.
 * If the lock is unnecessary because the architecture is single-core, this macro will not do anything.
 * This is incompatible with a lock created by DEFINE_CRIT_SECTION_LOCK_STATIC from above.
 *
 * @param lock_name Pointer to the lock.
 *
 * @note When using this macro, the critical section macros esp_os_enter_critical* and esp_os_exit_critical*
 *       MUST be used, otherwise normal functions would be passed an undefined variable when build for single-core
 *       systems.
 *
 * Example usage:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * typedef struct protected_struct_t {
 *     int member1;
 *     DECLARE_CRIT_SECTION_LOCK_IN_STRUCT(my_lock)
 *     int another_member;
 * };
 * ...
 * protected_struct_t my_protected;
 * INIT_CRIT_SECTION_LOCK_IN_STRUCT(&(my_protected.my_lock));
 * };
 * @endcode
 */
#if OS_SPINLOCK == 1
#define INIT_CRIT_SECTION_LOCK_RUNTIME(lock_name) spinlock_initialize(lock_name)
#else
#define INIT_CRIT_SECTION_LOCK_RUNTIME(lock_name)
#endif

/**
 * @brief This macro declares a critical section lock as a member of a struct.
 *
 * The critical section lock member is only declared if built for multi-core systems, otherwise it is omitted.
 *
 * @note When using this macro, the critical section macros esp_os_enter_critical* and esp_os_exit_critical*
 *       MUST be used, otherwise normal functions would be passed an undefined variable when build for single-core
 *       systems.
 * @note Do NOT add any semicolon after declaring the member with this macro.
 *       The trailing semicolon is included in the macro, otherwise -Wpedantic would complain about
 *       superfluous ";" if OS_SPINLOCK == 0.
 *
 * Example usage:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * typedef struct protected_struct_t {
 *     int member1;
 *     DECLARE_CRIT_SECTION_LOCK_IN_STRUCT(my_lock) // no semicolon!
 *     int another_member;
 * };
 * @endcode
 */
#if OS_SPINLOCK == 1
#define DECLARE_CRIT_SECTION_LOCK_IN_STRUCT(lock_name) esp_os_spinlock_t lock_name;
#else
#define DECLARE_CRIT_SECTION_LOCK_IN_STRUCT(lock_name)
#endif

/**
 * @brief This macro initializes a critical section lock as a member of a struct when using an list initialization.
 *        It has to be used together with \c DECLARE_CRIT_SECTION_LOCK_IN_STRUCT() to work.
 *
 * This macro basically creates a member of the initialization list, including the trailing comma.
 * If the lock is unnecessary because the architecture is single-core, this macro will not do anything.
 * This means that if \c lock_name is still a member of the struct, \c lock_name will be uninitialized.
 * Hence, this macro has to be used together with \c DECLARE_CRIT_SECTION_LOCK_IN_STRUCT() to correctly to declare
 * or omit the struct member \c lock_name.
 *
 * @param lock_name The field name of the lock inside the struct.
 *
 * @note When using this macro, the critical section macros esp_os_enter_critical* and esp_os_exit_critical*
 *       MUST be used, otherwise normal functions would be passed an undefined variable when build for single-core
 *       systems.
 * @note Do NOT add any comma in the initializer list after using this macro.
 *
 * Example usage:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * typedef struct protected_struct_t {
 *     int member1;
 *     DECLARE_CRIT_SECTION_LOCK_IN_STRUCT(my_lock)
 *     int another_member;
 * };
 * ...
 * protected_struct_t my_protected = {
 *     .member1 = 0,
 *     INIT_CRIT_SECTION_LOCK_IN_STRUCT(my_lock) // no comma!
 *     another_member = 47,
 * };
 * @endcode
 */
#if OS_SPINLOCK == 1
#define INIT_CRIT_SECTION_LOCK_IN_STRUCT(lock_name) .lock_name = portMUX_INITIALIZER_UNLOCKED,
#else
#define INIT_CRIT_SECTION_LOCK_IN_STRUCT(lock_name)
#endif

/**
 * @brief Enter a critical section, i.e., a section that will not be interrupted by any other task or interrupt.
 *
 * On multi-core systems, this will disable interrupts and take the spinlock \c lock. On single core systems, a
 * spinlock is unncessary, hence \c lock is ignored and interrupts are disabled only.
 *
 * @note This macro MUST be used together with any of the initialization macros, e.g.
 *       DEFINE_CRIT_SECTION_LOCK_STATIC. If not, there may be unused variables.
 *
 * @param lock Pointer to the critical section lock. Ignored if build for single core system.
 *
 * Example usage with static locks:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * DEFINE_CRIT_SECTION_LOCK_STATIC(my_lock); // will have internal linking (static)
 * ...
 * esp_os_enter_critical(&my_lock);
 * // code inside critical section
 * esp_os_exit_critical(&my_lock);
 * @endcode
 */
#if OS_SPINLOCK == 1
#define esp_os_enter_critical(lock)			portENTER_CRITICAL(lock)
#else
#define esp_os_enter_critical(lock)			vPortEnterCritical()
#endif

/**
 * @brief Exit a critical section.
 *
 * On multi-core systems, this will enable interrupts and release the spinlock \c lock. On single core systems, a
 * spinlock is unncessary, hence \c lock is ignored and interrupts are enabled only.
 *
 * @note This macro MUST be used together with any of the initialization macros, e.g.
 *       DEFINE_CRIT_SECTION_LOCK_STATIC. If not, there may be unused variables.
 *
 * @param lock Pointer to the critical section lock. Ignored if build for single core system.
 *
 * Example usage with static locks:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * DEFINE_CRIT_SECTION_LOCK_STATIC(my_lock); // will have internal linking (static)
 * ...
 * esp_os_enter_critical(&my_lock);
 * // code inside critical section
 * esp_os_exit_critical(&my_lock);
 * @endcode
 */
#if OS_SPINLOCK == 1
#define esp_os_exit_critical(lock)			portEXIT_CRITICAL(lock)
#else
#define esp_os_exit_critical(lock)			vPortExitCritical()
#endif

/**
 * @brief Enter a critical section while from ISR.
 *
 * On multi-core systems, this will disable interrupts and take the spinlock \c lock. On single core systems, a
 * spinlock is unncessary, hence \c lock is ignored and interrupts are disabled only.
 *
 * @note This macro MUST be used together with any of the initialization macros, e.g.
 *       DEFINE_CRIT_SECTION_LOCK_STATIC. If not, there may be unused variables.
 *
 * @param lock Pointer to the critical section lock. Ignored if build for single core system.
 *
 * Example usage with static locks:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * DEFINE_CRIT_SECTION_LOCK_STATIC(my_lock); // will have internal linking (static)
 * ...
 * esp_os_enter_critical(&my_lock);
 * // code inside critical section
 * esp_os_exit_critical(&my_lock);
 * @endcode
 */
#if OS_SPINLOCK == 1
#define esp_os_enter_critical_isr(lock)		portENTER_CRITICAL_ISR(lock)
#else
#define esp_os_enter_critical_isr(lock)		vPortEnterCritical()
#endif

/**
 * @brief Exit a critical section after entering from ISR.
 *
 * On multi-core systems, this will enable interrupts and release the spinlock \c lock. On single core systems, a
 * spinlock is unncessary, hence \c lock is ignored and interrupts are enabled only.
 *
 * @note This macro MUST be used together with any of the initialization macros, e.g.
 *       DEFINE_CRIT_SECTION_LOCK_STATIC. If not, there may be unused variables.
 *
 * @param lock Pointer to the critical section lock. Ignored if build for single core system.
 *
 * Example usage with static locks:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * DEFINE_CRIT_SECTION_LOCK_STATIC(my_lock); // will have internal linking (static)
 * ...
 * esp_os_enter_critical(&my_lock);
 * // code inside critical section
 * esp_os_exit_critical(&my_lock);
 * @endcode
 */
#if OS_SPINLOCK == 1
#define esp_os_exit_critical_isr(lock)		portEXIT_CRITICAL_ISR(lock)
#else
#define esp_os_exit_critical_isr(lock)		vPortExitCritical()
#endif

/**
 * @brief Enter a critical section from normal task or ISR. This macro will check if the current CPU is processing
 *        an ISR or not and enter the critical section accordingly.
 *
 * On multi-core systems, this will disable interrupts and take the spinlock \c lock. On single core systems, a
 * spinlock is unncessary, hence \c lock is ignored and interrupts are disabled only.
 *
 * @note This macro MUST be used together with any of the initialization macros, e.g.
 *       DEFINE_CRIT_SECTION_LOCK_STATIC. If not, there may be unused variables.
 *
 * @param lock Pointer to the critical section lock. Ignored if build for single core system.
 *
 * Example usage with static locks:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * DEFINE_CRIT_SECTION_LOCK_STATIC(my_lock); // will have internal linking (static)
 * ...
 * esp_os_enter_critical(&my_lock);
 * // code inside critical section
 * esp_os_exit_critical(&my_lock);
 * @endcode
 */
#if OS_SPINLOCK == 1
#define esp_os_enter_critical_safe(lock)	portENTER_CRITICAL_SAFE(lock)
#else
#define esp_os_enter_critical_safe(lock)	vPortEnterCritical()
#endif

/**
 * @brief Exit a critical section after entering via esp_os_enter_critical_safe.
 *
 * On multi-core systems, this will enable interrupts and release the spinlock \c lock. On single core systems, a
 * spinlock is unncessary, hence \c lock is ignored and interrupts are enabled only.
 *
 * @note This macro MUST be used together with any of the initialization macros, e.g.
 *       DEFINE_CRIT_SECTION_LOCK_STATIC. If not, there may be unused variables.
 *
 * @param lock Pointer to the critical section lock. Ignored if build for single core system.
 *
 * Example usage with static locks:
 * @code{c}
 * ...
 * #include "os/critical_section.h"
 * ...
 * DEFINE_CRIT_SECTION_LOCK_STATIC(my_lock); // will have internal linking (static)
 * ...
 * esp_os_enter_critical(&my_lock);
 * // code inside critical section
 * esp_os_exit_critical(&my_lock);
 * @endcode
 */
#if OS_SPINLOCK == 1
#define esp_os_exit_critical_safe(lock)		portEXIT_CRITICAL_SAFE(lock)
#else
#define esp_os_exit_critical_safe(lock)		vPortExitCritical()
#endif

#ifdef __cplusplus
}
#endif


text:
package org.apache.accumulo.core.client.impl;

import java.util.concurrent.TimeUnit;

import org.apache.accumulo.core.client.ClientConfiguration;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.impl.KeyExtent;
import org.apache.accumulo.core.metadata.schema.MetadataSchema;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.hadoop.io.Text;
import org.easymock.EasyMock;
import org.junit.Test;

public class TableOperationsImplTest {

  @Test
  public void waitForStoreTransitionScannerConfiguredCorrectly() throws Exception {
    final String tableName = "metadata";
    Instance instance = EasyMock.createMock(Instance.class);
    Credentials credentials = EasyMock.createMock(Credentials.class);

    ClientContext context = new ClientContext(instance, credentials, new ClientConfiguration());
    TableOperationsImpl topsImpl = new TableOperationsImpl(context);

    Connector connector = EasyMock.createMock(Connector.class);
    Scanner scanner = EasyMock.createMock(Scanner.class);

    Range range = new KeyExtent(new Text("1"), null, null).toMetadataRange();

    String user = "root";
    PasswordToken token = new PasswordToken("password");

    // Credentials expectations
    EasyMock.expect(credentials.getPrincipal()).andReturn(user).atLeastOnce();
    EasyMock.expect(credentials.getToken()).andReturn(token).atLeastOnce();

    // Create the connector and scanner
    EasyMock.expect(instance.getConnector(user, token)).andReturn(connector);
    EasyMock.expect(connector.createScanner(tableName, Authorizations.EMPTY)).andReturn(scanner);

    // Fetch the columns on the scanner
    scanner.fetchColumnFamily(MetadataSchema.TabletsSection.FutureLocationColumnFamily.NAME);
    EasyMock.expectLastCall();
    scanner.fetchColumnFamily(MetadataSchema.TabletsSection.CurrentLocationColumnFamily.NAME);
    EasyMock.expectLastCall();
    scanner.fetchColumn(MetadataSchema.TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.getColumnFamily(),
        MetadataSchema.TabletsSection.TabletColumnFamily.PREV_ROW_COLUMN.getColumnQualifier());
    EasyMock.expectLastCall();

    // Set the Range
    scanner.setRange(range);
    EasyMock.expectLastCall();

    // IsolatedScanner -- make the verification pass, not really relevant
    EasyMock.expect(scanner.getRange()).andReturn(range).anyTimes();
    EasyMock.expect(scanner.getTimeout(TimeUnit.MILLISECONDS)).andReturn(Long.MAX_VALUE);
    EasyMock.expect(scanner.getBatchSize()).andReturn(1000);
    EasyMock.expect(scanner.getReadaheadThreshold()).andReturn(100l);

    EasyMock.replay(instance, credentials, connector, scanner);

    topsImpl.createMetadataScanner(tableName, range);

    EasyMock.verify(instance, credentials, connector, scanner);
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="list_lose">#DAD3F4</color>
    <color name="list_press">#AAAAAA</color>
    <color name="list_background">#EEEEEE</color>
    <color name="list_font_color">#797878</color>
    <color  name="login_backgrpund">#F1F1ED</color>
    <color name="button_no_press">#FDFFFB</color>
    <color name="button_press">#B6B6B5</color>
</resources>


text:
/* eslint-disable no-unused-expressions */
import crypto from 'crypto'
import path from 'path'
import { readFileSync, mkdirSync, statSync } from 'fs'
import { expect } from 'chai'

import { createMockServer, closeMockServer, resource } from './mock.server'

import Task from '../src/Task'

describe('Task', () => {
  let task: Task = null
  const downloadDir = path.join(__dirname, '/tmp')

  try {
    statSync(downloadDir).isDirectory()
  } catch (e) {
    mkdirSync(downloadDir)
  }

  before(createMockServer)

  it('should create task', async () => {
    task = await Task.create({url: resource.url, downloadDir})
    expect(task instanceof Task).to.be.true

    let metadata = task.metadata
    expect(metadata.url).to.eq(resource.url)
    expect(metadata.mimeType).to.eq(resource.mimeType)
    expect(metadata.totalBytes).to.eq(resource.buffer.byteLength)
    expect(metadata.resumable).to.be.true
  })

  it('should start', (done) => {
    task.on('error', done)
    task.on('end', done)
    task.start(10, 1024).catch(done)

    setTimeout(() => {
      if (task.progress !== 1) {
        task.off('end', done)
        task.stop().then(done)
      }
    }, 200)
  }).timeout(10000)

  it('should store to file', async () => {
    let file = path.resolve(__dirname, './tmp/task.tmp')
    await task.storeToFile(file)
  })

  it('should restore from file', async () => {
    let file = path.resolve(__dirname, './tmp/task.tmp')
    let task2 = await Task.restoreFromFile(file)
    expect(task2.metadata.toJSONObject()).to.deep.eq(task.metadata.toJSONObject())
    task = task2
  })

  it('should restart', (done) => {
    task.on('error', done)
    task.on('end', done)
    task.start(1).catch(done)
  }).timeout(10000)

  it('should download resource correctly', () => {
    expect(task.isRunning).to.be.false
    const downloadedBuffer = readFileSync(task.metadata.downloadPath)
    const hash1 = crypto.createHash('sha256')
    const hash2 = crypto.createHash('sha256')
    hash1.update(resource.buffer)
    hash2.update(downloadedBuffer)
    expect(hash1.digest('hex')).to.eq(hash2.digest('hex'))
    expect(task.metadata.downloadingByteCount).to.eq(0)
    expect(task.metadata.remainingByteCount).to.eq(0)
    expect(task.metadata.completedByteCount).to.eq(resource.buffer.byteLength)
    expect(task.progress).to.eq(1)
  })

  it('should raise an network error', async () => {
    try {
      await Task.create({url: resource.url + '/404', downloadDir})
    } catch (e) {
      expect(e.message).not.eq(Task.ERROR.ERR_NETWORK)
    }

    try {
      let task2 = await Task.create({url: resource.url, downloadDir})
      task2.metadata.url += '/404'

      await new Promise((resolve, reject) => {
        task2.on('error', reject)
        task2.on('end', resolve)
        task2.start()
      })
    } catch (e) {
      expect(e.message).to.eq(Task.ERROR.ERR_NETWORK)
    }
  })

  it('should raise an metadata error', async () => {
    try {
      let task2 = await Task.create({url: resource.url, downloadDir})
      task2.metadata = null

      await new Promise((resolve, reject) => {
        task2.on('error', reject)
        task2.on('end', resolve)
        task2.start()
      })
    } catch (e) {
      expect(e.message).to.eq(Task.ERROR.ERR_NO_METADATA)
    }
  })

  it('should raise an disk error', async () => {
    try {
      let task2 = await Task.create({url: resource.url, downloadDir})
      task2.fd = null

      await new Promise((resolve, reject) => {
        task2.on('error', reject)
        task2.on('end', resolve)
        task2.start()
      })
    } catch (e) {
      expect(e.message).to.eq(Task.ERROR.ERR_DISK_IO_WRITE)
    }
  })

  it('should create unresumable resource task', async () => {
    task = await Task.create({url: resource.url2, downloadDir})
    expect(task.metadata.resumable).to.be.false
    await new Promise((resolve, reject) => {
      task.on('error', reject)
      task.on('end', resolve)
      task.start()
    })
  }).timeout(10000)

  it('should download unresumable resource correctly', () => {
    expect(task.isRunning).to.be.false
    const downloadedBuffer = readFileSync(task.metadata.downloadPath)
    const hash1 = crypto.createHash('sha256')
    const hash2 = crypto.createHash('sha256')
    hash1.update(resource.buffer)
    hash2.update(downloadedBuffer)
    expect(hash1.digest('hex')).to.eq(hash2.digest('hex'))
    expect(task.metadata.downloadingByteCount).to.eq(0)
    expect(task.metadata.remainingByteCount).to.eq(0)
    expect(task.metadata.completedByteCount).to.eq(resource.buffer.byteLength)
    expect(task.progress).to.eq(1)
  })

  after(closeMockServer)
})


text:
var co = require('../index.js');
var inspect = require('inspect.js');
var sinon = require('sinon');

describe('co.series()', function() {
    'use strict';

    describe('getCallbackPromise', function(done) {
        it('Should return a callback promise', function() {
            var callback = co.getCallbackPromise();

            inspect(callback).isFunction();
            inspect(callback).isPromise();
        });

        it('Should pass a callback call', function(done) {
            var callback = co.getCallbackPromise();

            var fn = function(cb) {
                cb(null, 'ok');
            }

            callback.then(function(data) {
                inspect(data).isEql('ok');
                done();
            }).catch(function(err) {
                done(err);
            });

            fn(callback);
        });

        it('Should fail a callback call', function(done) {
            var callback = co.getCallbackPromise();

            var fn = function(cb) {
                cb('fail');
            }

            callback.then(function() {
                done('Should fail, but it passed!');
            }).catch(function(err) {
                inspect(err).isEql('fail');
                done();
            });

            fn(callback);
        });

        it('Should pass a promise call', function(done) {
            var callback = co.getCallbackPromise();

            callback.then(function(data) {
                inspect(data).isEql('ok');
                done();
            }).catch(function(err) {
                done(err);
            });

            callback.resolve('ok');
        });

        it('Should fail a promise call', function(done) {
            var callback = co.getCallbackPromise();

            callback.then(function() {
                done('Should fail, but it passed!');
            }).catch(function(err) {
                inspect(err).isEql('fail');
                done();
            });

            callback.reject('fail');
        });

        it('Should call all final functions', function(done) {
            var callback = co.getCallbackPromise();

            var final1 = sinon.stub();
            var final2 = sinon.stub();

            callback.final(final1);
            callback.final(final2);

            callback.then(function() {
                inspect(final1.calledOnce).isTrue();
                inspect(final2.calledOnce).isTrue();
                done();
            }).catch(function(err) {
                done(err);
            });

            callback.resolve('ok');
        });

        it('Should call all final functions', function(done) {
            var callback = co.getCallbackPromise();

            var final1 = sinon.stub();
            var final2 = sinon.stub();

            callback.final(final1);
            callback.final(final2);

            callback.then(function() {
                done('Should fail, but it passed!');
            }).catch(function() {
                inspect(final1.calledOnce).isTrue();
                inspect(final2.calledOnce).isTrue();
                done();
            });

            callback.reject('fail');
        });
    });

    describe('method', function() {
        it('Should call functions in series', function(done) {
            var func1 = sinon.stub();
            var func2 = sinon.stub();
            var func3 = sinon.stub();
            var isGenStub = sinon.stub();
            isGenStub.returns(false);

            func1.yields(null, 'a');
            func2.yields(null, 'b');
            func3.yields(null, 'c');

            func1.isGenerator = isGenStub;
            func2.isGenerator = isGenStub;
            func3.isGenerator = isGenStub;

            var functions = [
                func1,
                func2,
                func3
            ];

            co.series(functions).then(function(result) {
                inspect(result).isEql(['a', 'b', 'c']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });

        it('Should fail if one function rejects', function(done) {
            var func1 = sinon.stub();
            var func2 = sinon.stub();
            var func3 = sinon.stub();
            var isGenStub = sinon.stub();
            isGenStub.returns(false);

            func1.yields(null, 'a');
            func2.yields(null, 'b');
            func3.yields('Booom');

            func1.isGenerator = isGenStub;
            func2.isGenerator = isGenStub;
            func3.isGenerator = isGenStub;

            co.series([func1, func2, func3]).then(function() {
                done('Fail!');
            }).catch(function(err) {
                inspect(err).isEql('Booom');
                done();
            });
        });

        it('Should fail if one function throws an error', function(done) {
            var func1 = sinon.stub();
            var func2 = sinon.stub();
            var func3 = sinon.stub();
            var isGenStub = sinon.stub();
            isGenStub.returns(false);

            func1.yields(null, 'a');
            func2.throws('Booom');
            func3.yields(null, 'c');

            func1.isGenerator = isGenStub;
            func2.isGenerator = isGenStub;
            func3.isGenerator = isGenStub;

            co.series([func1, func2, func3]).then(function() {
                done('Fail!');
            }).catch(function(err) {
                inspect(err.name).isEql('Booom');
                done();
            });
        });

        it('Should call promises in series', function(done) {
            var promises = [
                Promise.resolve('a'),
                Promise.resolve('b'),
                Promise.resolve('c')
            ];

            co.series(promises).then(function(result) {
                inspect(result).isEql(['a', 'b', 'c']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });

        it('Should fail if one promise rejects', function(done) {
            var p1 = new Promise(function(resolve, reject) { resolve ('a'); });
            var p2 = new Promise(function(resolve, reject) { resolve ('b'); });
            var p3 = new Promise(function(resolve, reject) { reject('Booom'); });

            co.series([p1, p2, p3]).then(function(res) {
                done('Fail!');
            }).catch(function(err) {
                inspect(err).isEql('Booom');
                done();
            });
        });

        it('Should fail if one promise throws an error', function(done) {
            var p1 = new Promise(function(resolve, reject) { resolve ('a'); });
            var p2 = new Promise(function(resolve, reject) { resolve ('b'); });
            var p3 = new Promise(function(resolve, reject) { throw new Error('Booom'); });

            co.series([p1, p2, p3]).then(function(res) {
                done('Fail!');
            }).catch(function(err) {
                inspect(err.message).isEql('Booom');
                done();
            });
        });

        it('Should call generators in series', function(done) {
            var gen1 = function *() { return 'a'; };
            var gen2 = function *() { return 'b'; };
            var gen3 = function *() { return 'c'; };

            var generators = [
                gen1,
                gen2,
                gen3
            ];

            co.series(generators).then(function(result) {
                inspect(result).isEql(['a', 'b', 'c']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });

        it('Should fail if one function throws an error', function(done) {
            var gen1 = function *() { return 'a'; };
            var gen2 = function *() { return 'b'; };
            var gen3 = function *() { throw 'Booom'; };

            var generators = [
                gen1,
                gen2,
                gen3
            ];

            co.series(generators).then(function(result) {
                done('Fail!');
            }).catch(function(err) {
                inspect(err).isEql('Booom');
                done();
            });
        });
    });

    describe('series with args', function() {
        it('Should fail if args param is not an array', function() {
            inspect(co.series).withArgs([], {}, 'string').doesThrow(/must be an array/);
        });

        it('Should call functions in series', function(done) {
            var func1 = function(a, b, c, done) {
                done(null, a);
            }
            var func2 = function(a, b, c, done) {
                done(null, b);
            }
            var func3 = function(a, b, c, done) {
                done(null, c);
            }

            var functions = [
                func1,
                func2,
                func3
            ];

            var args = ['apple', 'banana', 'coconut'];
            co.series(functions, args).then(function(result) {
                inspect(result).isEql(['apple', 'banana', 'coconut']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });

        it('Should call promises in series', function(done) {
            var func1 = function(a, b, c, promise) {
                promise.resolve(a);
            }
            var func2 = function(a, b, c, promise) {
                promise.resolve(b);
            }
            var func3 = function(a, b, c, promise) {
                promise.resolve(c);
            }

            var functions = [
                func1,
                func2,
                func3
            ];

            var args = ['apple', 'banana', 'coconut'];
            co.series(functions, args).then(function(result) {
                inspect(result).isEql(['apple', 'banana', 'coconut']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });

        it('Should call promise returning function in series', function(done) {
            var func1 = function(a, b, c) {
                return Promise.resolve(a);
            }
            var func2 = function(a, b, c) {
                return Promise.resolve(b);
            }
            var func3 = function(a, b, c) {
                return Promise.resolve(c);
            }

            var functions = [
                func1,
                func2,
                func3
            ];

            var args = ['apple', 'banana', 'coconut'];
            co.series(functions, args).then(function(result) {
                inspect(result).isEql(['apple', 'banana', 'coconut']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });

        it('Should call generators in series', function(done) {
            var gen1 = function *(a, b, c) { return a; };
            var gen2 = function *(a, b, c) { return b; };
            var gen3 = function *(a, b, c) { return c; };

            var generators = [
                gen1,
                gen2,
                gen3
            ];

            var args = ['apple', 'banana', 'coconut'];
            co.series(generators, args).then(function(result) {
                inspect(result).isEql(['apple', 'banana', 'coconut']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });
    });

    describe('series with args and context', function() {
        it('Should fail if args param is not an array', function() {
            inspect(co.series).withArgs([], {}, 'string').doesThrow(/must be an array/);
        });

        it('Should call functions in series', function(done) {
            var func1 = function(a, b, c, done) {
                done(null, this.prefix + a);
            }
            var func2 = function(a, b, c, done) {
                done(null, this.prefix + b);
            }
            var func3 = function(a, b, c, done) {
                done(null, this.prefix + c);
            }

            var functions = [
                func1,
                func2,
                func3
            ];

            var args = ['apple', 'banana', 'coconut'];
            var ctx = { prefix: 'I like: ' };
            co.series(functions, ctx, args).then(function(result) {
                inspect(result).isEql(['I like: apple', 'I like: banana', 'I like: coconut']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });

        it('Should call promises in series', function(done) {
            var func1 = function(a, b, c, promise) {
                promise.resolve(this.prefix + a);
            }
            var func2 = function(a, b, c, promise) {
                promise.resolve(this.prefix + b);
            }
            var func3 = function(a, b, c, promise) {
                promise.resolve(this.prefix + c);
            }

            var functions = [
                func1,
                func2,
                func3
            ];

            var args = ['apple', 'banana', 'coconut'];
            var ctx = { prefix: 'I like: ' };
            co.series(functions, ctx, args).then(function(result) {
                inspect(result).isEql(['I like: apple', 'I like: banana', 'I like: coconut']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });

        it('Should call promise returning function in series', function(done) {
            var func1 = function(a, b, c) {
                return Promise.resolve(this.prefix + a);
            }
            var func2 = function(a, b, c) {
                return Promise.resolve(this.prefix + b);
            }
            var func3 = function(a, b, c) {
                return Promise.resolve(this.prefix + c);
            }

            var functions = [
                func1,
                func2,
                func3
            ];

            var args = ['apple', 'banana', 'coconut'];
            var ctx = { prefix: 'I like: ' };
            co.series(functions, ctx, args).then(function(result) {
                inspect(result).isEql(['I like: apple', 'I like: banana', 'I like: coconut']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });

        it('Should call generators in series', function(done) {
            var gen1 = function *(a, b, c) { return this.prefix + a; };
            var gen2 = function *(a, b, c) { return this.prefix + b; };
            var gen3 = function *(a, b, c) { return this.prefix + c; };

            var generators = [
                gen1,
                gen2,
                gen3
            ];

            var args = ['apple', 'banana', 'coconut'];
            var ctx = { prefix: 'I like: ' };
            co.series(generators, ctx, args).then(function(result) {
                inspect(result).isEql(['I like: apple', 'I like: banana', 'I like: coconut']);
                done();
            }).catch(function(err) {
                done(err);
            });
        });
    });

    describe('series with timeout', function() {
        it('Should call functions in series until timeout was reached', function(done) {
            var counter = 0;
            var func1 = function(done) {
                // never call done
                setTimeout(function() {
                    counter++;
                    done();
                }, 200);
            }

            var func2 = function(done) {
                counter++;
                done();
            }

            var func3 = function(done) {
                counter++;
                done();
            }

            co.series([func1, func2, func3], 100).then(function(result) {
                done('Should never been called!');
            }).catch(function(err) {
                inspect(err).doesMatch(/Timeout/);
                inspect(counter).isLesserThan(2);
                done();
            });
        });

        it('Should call functions in series until timeout was reached with context', function(done) {
            var counter = 0;
            var func1 = function(done) {
                // never call done
                setTimeout(function() {
                    counter++;
                    done();
                }, 200);
            }

            var func2 = function(done) {
                counter++;
                done();
            }

            var func3 = function(done) {
                counter++;
                done();
            }

            co.series([func1, func2, func3], {}, 100).then(function(result) {
                done('Should never been called!');
            }).catch(function(err) {
                inspect(err).doesMatch(/Timeout/);
                inspect(counter).isLesserThan(2);
                done();
            });
        });

        it('Should call functions in series until timeout was reached with args', function(done) {
            var counter = 0;
            var func1 = function(done) {
                // never call done
                setTimeout(function() {
                    counter++;
                    done();
                }, 2000);
            }

            var func2 = function(done) {
                counter++;
                done();
            }

            var func3 = function(done) {
                counter++;
                done();
            }

            co.series([func1, func2, func3], ['foo'], 100).then(function(result) {
                done('Should never been called!');
            }).catch(function(err) {
                inspect(err).doesMatch(/Timeout/);
                inspect(counter).isLesserThan(2);
                done();
            });
        });

        it('Should call functions in series until timeout was reached with context and args', function(done) {
            var counter = 0;
            var func1 = function(done) {
                // never call done
                setTimeout(function() {
                    counter++;
                    done();
                }, 2000);
            }

            var func2 = function(done) {
                counter++;
                done();
            }

            var func3 = function(done) {
                counter++;
                done();
            }

            co.series([func1, func2, func3], {}, ['foo'], 100).then(function(result) {
                done('Should never been called!');
            }).catch(function(err) {
                inspect(err).doesMatch(/Timeout/);
                inspect(counter).isLesserThan(2);
                done();
            });
        });
    });
});


text:
/**
 * upload a buffer to s3 and return a publicly accessible url. Usage:
 * var S3Class = require('./s3');
 * var s3 = new S3Class({
 *   accessKeyId:     <iamAccessKey>,
 *   secretAccessKey: <iamSecretKey>,
 *   bucket:          <some.bucket>,
 * });
 * var link = s3.upload('fileName.txt', 'text/plain', buffer, function(url){
 *   console.log(url);
 * })
 *
 * Note that this code expects the bucket to be in the us standard region.
 */

var AWS = require('aws-sdk');

function S3Class(options){
  this.options = options;
}

S3Class.prototype.upload = function(filename, contentType, buffer, callback){
  var bucket = this.options.bucket;

  //thanks to some genius at amazon the access keys are global variables
  //so we need to clobber them which might break other clients with different ids
  AWS.config.update({
    accessKeyId: this.options.accessKeyId,
    secretAccessKey: this.options.secretAccessKey,
  });
  var s3 = new AWS.S3();

  function done(error){
    var uploadUrl = 'http://' + bucket + '.s3.amazonaws.com/' + filename;
    callback(error, uploadUrl);
  }

  var s3 = new AWS.S3({apiVersion: '2006-03-01'});
  s3.putObject({
    Bucket:      bucket,
    Key:         filename,
    Body:        buffer,
    ACL:         'public-read',
    ContentType: contentType,
  }, done);
}

module.exports = S3Class;


text:
new_port=$(ctx node properties port)
REPLACE_WITH_A_COMMAND_THAT_WRITES_THE_TOMCAT_PORT_TO_THE_LOG_VIA_THE_CONTEXT_OBJECT

war_url=$(ctx node properties war_url)
ctx logger info "war_url: ${war_url}"

war_filename=$(ctx node properties war_filename)
ctx logger info "war_filename: ${war_filename}"

application_name=$(ctx node properties application_name)
ctx logger info "application_name: ${application_name}"

# args:
# $1 the error code of the last command (should be explicitly passed)
# $2 the message to print in case of an error
#
# an error message is printed and the script exists with the provided error code
function error_exit {
	ctx logger info "Error encountered: error code = $1, message = $2"
	exit $1
}

tomcat_home=~/tomcat
application_war=${tomcat_home}/${war_filename}
tomcat_conf_dir=${tomcat_home}/conf
server_xml_file=${tomcat_conf_dir}/server.xml
tomcat_context_path_dir=${tomcat_conf_dir}/Catalina/localhost
tomcat_context_file=${tomcat_context_path_dir}/${application_name}.xml

ctx logger info "Tomcat home: ${tomcat_home}"
ctx logger info "Application WAR: ${application_war}"
ctx logger info "Tomcat context path directory: ${tomcat_context_path_dir}"
ctx logger info "Tomcat context file: ${tomcat_context_file}"

mkdir -p ${tomcat_home}
curl --silent -k -o ${application_war} -O ${war_url} || error_exit $? "Failed downloading $1"

mkdir -p ${tomcat_context_path_dir}

# Write the context configuration
rm -f ${tomcat_context_file}

cat << EOF > ${tomcat_context_file}
<Context docBase="${application_war}" />
EOF

ctx logger info "Replacing 8080 with ${new_port} in ${server_xml_file}"
sed -i -e "s/port=\"8080\"/port=\"${new_port}\"/g" ${server_xml_file}

public_ip=$1
ctx logger info "Public IP: ${public_ip}"

application_url=http://${public_ip}:${new_port}/${application_name}
ctx logger info "Application URL: ${application_url}"

REPLACE_WITH_A_COMMAND_THAT_STORES_THE_APPLICATION_URL_IN_THE_RUNTIME_PROPERTIES_OF_THE_INSTANCE_VIA_THE_CONTEXT_OBJECT


text:
// md5:8376e8736a194dfca64b29d1bb04e5e00f4b0270

package com.gs.fw.common.mithra.test.domain;

import java.sql.Timestamp;

public class DatedEntityDescType extends DatedEntityDescTypeAbstract
{

	public DatedEntityDescType(Timestamp businessDate, Timestamp processingDate)
	{
		super(businessDate, processingDate);
	}
}