text:
FMT_BEGIN_NAMESPACE

namespace internal{

enum class numeric_system {
  standard,
  // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.
  alternative
};

// Parses a put_time-like format string and invokes handler actions.
template <typename Char, typename Handler>
FMT_CONSTEXPR const Char *parse_chrono_format(
    const Char *begin, const Char *end, Handler &&handler) {
  auto ptr = begin;
  while (ptr != end) {
    auto c = *ptr;
    if (c == '}') break;
    if (c != '%') {
      ++ptr;
      continue;
    }
    if (begin != ptr)
      handler.on_text(begin, ptr);
    ++ptr; // consume '%'
    if (ptr == end)
      throw format_error("invalid format");
    c = *ptr++;
    switch (c) {
    case '%':
      handler.on_text(ptr - 1, ptr);
      break;
    case 'n': {
      const char newline[] = "\n";
      handler.on_text(newline, newline + 1);
      break;
    }
    case 't': {
      const char tab[] = "\t";
      handler.on_text(tab, tab + 1);
      break;
    }
    // Day of the week:
    case 'a':
      handler.on_abbr_weekday();
      break;
    case 'A':
      handler.on_full_weekday();
      break;
    case 'w':
      handler.on_dec0_weekday(numeric_system::standard);
      break;
    case 'u':
      handler.on_dec1_weekday(numeric_system::standard);
      break;
    // Month:
    case 'b':
      handler.on_abbr_month();
      break;
    case 'B':
      handler.on_full_month();
      break;
    // Hour, minute, second:
    case 'H':
      handler.on_24_hour(numeric_system::standard);
      break;
    case 'I':
      handler.on_12_hour(numeric_system::standard);
      break;
    case 'M':
      handler.on_minute(numeric_system::standard);
      break;
    case 'S':
      handler.on_second(numeric_system::standard);
      break;
    // Other:
    case 'c':
      handler.on_datetime(numeric_system::standard);
      break;
    case 'x':
      handler.on_loc_date(numeric_system::standard);
      break;
    case 'X':
      handler.on_loc_time(numeric_system::standard);
      break;
    case 'D':
      handler.on_us_date();
      break;
    case 'F':
      handler.on_iso_date();
      break;
    case 'r':
      handler.on_12_hour_time();
      break;
    case 'R':
      handler.on_24_hour_time();
      break;
    case 'T':
      handler.on_iso_time();
      break;
    case 'p':
      handler.on_am_pm();
      break;
    case 'z':
      handler.on_utc_offset();
      break;
    case 'Z':
      handler.on_tz_name();
      break;
    // Alternative representation:
    case 'E': {
      if (ptr == end)
        throw format_error("invalid format");
      c = *ptr++;
      switch (c) {
      case 'c':
        handler.on_datetime(numeric_system::alternative);
        break;
      case 'x':
        handler.on_loc_date(numeric_system::alternative);
        break;
      case 'X':
        handler.on_loc_time(numeric_system::alternative);
        break;
      default:
        throw format_error("invalid format");
      }
      break;
    }
    case 'O':
      if (ptr == end)
        throw format_error("invalid format");
      c = *ptr++;
      switch (c) {
      case 'w':
        handler.on_dec0_weekday(numeric_system::alternative);
        break;
      case 'u':
        handler.on_dec1_weekday(numeric_system::alternative);
        break;
      case 'H':
        handler.on_24_hour(numeric_system::alternative);
        break;
      case 'I':
        handler.on_12_hour(numeric_system::alternative);
        break;
      case 'M':
        handler.on_minute(numeric_system::alternative);
        break;
      case 'S':
        handler.on_second(numeric_system::alternative);
        break;
      default:
        throw format_error("invalid format");
      }
      break;
    default:
      throw format_error("invalid format");
    }
    begin = ptr;
  }
  if (begin != ptr)
    handler.on_text(begin, ptr);
  return ptr;
}

struct chrono_format_checker {
  void report_no_date() { throw format_error("no date"); }

  template <typename Char>
  void on_text(const Char *, const Char *) {}
  void on_abbr_weekday() { report_no_date(); }
  void on_full_weekday() { report_no_date(); }
  void on_dec0_weekday(numeric_system) { report_no_date(); }
  void on_dec1_weekday(numeric_system) { report_no_date(); }
  void on_abbr_month() { report_no_date(); }
  void on_full_month() { report_no_date(); }
  void on_24_hour(numeric_system) {}
  void on_12_hour(numeric_system) {}
  void on_minute(numeric_system) {}
  void on_second(numeric_system) {}
  void on_datetime(numeric_system) { report_no_date(); }
  void on_loc_date(numeric_system) { report_no_date(); }
  void on_loc_time(numeric_system) { report_no_date(); }
  void on_us_date() { report_no_date(); }
  void on_iso_date() { report_no_date(); }
  void on_12_hour_time() {}
  void on_24_hour_time() {}
  void on_iso_time() {}
  void on_am_pm() {}
  void on_utc_offset() { report_no_date(); }
  void on_tz_name() { report_no_date(); }
};

template <typename Int>
inline int to_int(Int value) {
  FMT_ASSERT(value >= (std::numeric_limits<int>::min)() &&
             value <= (std::numeric_limits<int>::max)(), "invalid value");
  return static_cast<int>(value);
}

template <typename FormatContext, typename OutputIt>
struct chrono_formatter {
  FormatContext &context;
  OutputIt out;
  std::chrono::seconds s;
  std::chrono::milliseconds ms;

  typedef typename FormatContext::char_type char_type;

  explicit chrono_formatter(FormatContext &ctx, OutputIt o)
    : context(ctx), out(o) {}

  int hour() const { return to_int((s.count() / 3600) % 24); }

  int hour12() const {
    auto hour = to_int((s.count() / 3600) % 12);
    return hour > 0 ? hour : 12;
  }

  int minute() const { return to_int((s.count() / 60) % 60); }
  int second() const { return to_int(s.count() % 60); }

  std::tm time() const {
    auto time = std::tm();
    time.tm_hour = hour();
    time.tm_min = minute();
    time.tm_sec = second();
    return time;
  }

  void write(int value, int width) {
    typedef typename int_traits<int>::main_type main_type;
    main_type n = to_unsigned(value);
    int num_digits = internal::count_digits(n);
    if (width > num_digits)
      out = std::fill_n(out, width - num_digits, '0');
    out = format_decimal<char_type>(out, n, num_digits);
  }

  void format_localized(const tm &time, const char *format) {
    auto locale = context.locale().template get<std::locale>();
    auto &facet = std::use_facet<std::time_put<char_type>>(locale);
    std::basic_ostringstream<char_type> os;
    os.imbue(locale);
    facet.put(os, os, ' ', &time, format, format + std::strlen(format));
    auto str = os.str();
    std::copy(str.begin(), str.end(), out);
  }

  void on_text(const char_type *begin, const char_type *end) {
    std::copy(begin, end, out);
  }

  // These are not implemented because durations don't have date information.
  void on_abbr_weekday() {}
  void on_full_weekday() {}
  void on_dec0_weekday(numeric_system) {}
  void on_dec1_weekday(numeric_system) {}
  void on_abbr_month() {}
  void on_full_month() {}
  void on_datetime(numeric_system) {}
  void on_loc_date(numeric_system) {}
  void on_loc_time(numeric_system) {}
  void on_us_date() {}
  void on_iso_date() {}
  void on_utc_offset() {}
  void on_tz_name() {}

  void on_24_hour(numeric_system ns) {
    if (ns == numeric_system::standard)
      return write(hour(), 2);
    auto time = tm();
    time.tm_hour = hour();
    format_localized(time, "%OH");
  }

  void on_12_hour(numeric_system ns) {
    if (ns == numeric_system::standard)
      return write(hour12(), 2);
    auto time = tm();
    time.tm_hour = hour();
    format_localized(time, "%OI");
  }

  void on_minute(numeric_system ns) {
    if (ns == numeric_system::standard)
      return write(minute(), 2);
    auto time = tm();
    time.tm_min = minute();
    format_localized(time, "%OM");
  }

  void on_second(numeric_system ns) {
    if (ns == numeric_system::standard) {
      write(second(), 2);
      if (ms != std::chrono::milliseconds(0)) {
        *out++ = '.';
        write(to_int(ms.count()), 3);
      }
      return;
    }
    auto time = tm();
    time.tm_sec = second();
    format_localized(time, "%OS");
  }

  void on_12_hour_time() { format_localized(time(), "%r"); }

  void on_24_hour_time() {
    write(hour(), 2);
    *out++ = ':';
    write(minute(), 2);
  }

  void on_iso_time() {
    on_24_hour_time();
    *out++ = ':';
    write(second(), 2);
  }

  void on_am_pm() { format_localized(time(), "%p"); }
};
}  // namespace internal

template <typename Period> FMT_CONSTEXPR const char *get_units() {
  return FMT_NULL;
}
template <> FMT_CONSTEXPR const char *get_units<std::atto>() { return "as"; }
template <> FMT_CONSTEXPR const char *get_units<std::femto>() { return "fs"; }
template <> FMT_CONSTEXPR const char *get_units<std::pico>() { return "ps"; }
template <> FMT_CONSTEXPR const char *get_units<std::nano>() { return "ns"; }
template <> FMT_CONSTEXPR const char *get_units<std::micro>() { return "µs"; }
template <> FMT_CONSTEXPR const char *get_units<std::milli>() { return "ms"; }
template <> FMT_CONSTEXPR const char *get_units<std::centi>() { return "cs"; }
template <> FMT_CONSTEXPR const char *get_units<std::deci>() { return "ds"; }
template <> FMT_CONSTEXPR const char *get_units<std::ratio<1>>() { return "s"; }
template <> FMT_CONSTEXPR const char *get_units<std::deca>() { return "das"; }
template <> FMT_CONSTEXPR const char *get_units<std::hecto>() { return "hs"; }
template <> FMT_CONSTEXPR const char *get_units<std::kilo>() { return "ks"; }
template <> FMT_CONSTEXPR const char *get_units<std::mega>() { return "Ms"; }
template <> FMT_CONSTEXPR const char *get_units<std::giga>() { return "Gs"; }
template <> FMT_CONSTEXPR const char *get_units<std::tera>() { return "Ts"; }
template <> FMT_CONSTEXPR const char *get_units<std::peta>() { return "Ps"; }
template <> FMT_CONSTEXPR const char *get_units<std::exa>() { return "Es"; }
template <> FMT_CONSTEXPR const char *get_units<std::ratio<60>>() {
  return "m";
}
template <> FMT_CONSTEXPR const char *get_units<std::ratio<3600>>() {
  return "h";
}

template <typename Rep, typename Period, typename Char>
struct formatter<std::chrono::duration<Rep, Period>, Char> {
 private:
  align_spec spec;
  internal::arg_ref<Char> width_ref;
  mutable basic_string_view<Char> format_str;
  typedef std::chrono::duration<Rep, Period> duration;

  struct spec_handler {
    formatter &f;
    basic_parse_context<Char> &context;

    typedef internal::arg_ref<Char> arg_ref_type;

    template <typename Id>
    FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
      context.check_arg_id(arg_id);
      return arg_ref_type(arg_id);
    }

    FMT_CONSTEXPR arg_ref_type make_arg_ref(internal::auto_id) {
      return arg_ref_type(context.next_arg_id());
    }

    void on_error(const char *msg) { throw format_error(msg); }
    void on_fill(Char fill) { f.spec.fill_ = fill; }
    void on_align(alignment align) { f.spec.align_ = align; }
    void on_width(unsigned width) { f.spec.width_ = width; }

    template <typename Id>
    void on_dynamic_width(Id arg_id) {
      f.width_ref = make_arg_ref(arg_id);
    }
  };

 public:
  formatter() : spec() {}

  FMT_CONSTEXPR auto parse(basic_parse_context<Char> &ctx)
      -> decltype(ctx.begin()) {
    auto begin = ctx.begin(), end = ctx.end();
    if (begin == end) return begin;
    spec_handler handler{*this, ctx};
    begin = internal::parse_align(begin, end, handler);
    if (begin == end) return begin;
    begin = internal::parse_width(begin, end, handler);
    end = parse_chrono_format(begin, end, internal::chrono_format_checker());
    format_str = basic_string_view<Char>(&*begin, internal::to_unsigned(end - begin));
    return end;
  }

  template <typename FormatContext>
  auto format(const duration &d, FormatContext &ctx)
      -> decltype(ctx.out()) {
    auto begin = format_str.begin(), end = format_str.end();
    memory_buffer buf;
    typedef output_range<decltype(ctx.out()), Char> range;
    basic_writer<range> w(range(ctx.out()));
    if (begin == end || *begin == '}') {
      if (const char *unit = get_units<Period>())
        format_to(buf, "{}{}", d.count(), unit);
      else if (Period::den == 1)
        format_to(buf, "{}[{}]s", d.count(), Period::num);
      else
        format_to(buf, "{}[{}/{}]s", d.count(), Period::num, Period::den);
      internal::handle_dynamic_spec<internal::width_checker>(
        spec.width_, width_ref, ctx);
    } else {
      auto out = std::back_inserter(buf);
      internal::chrono_formatter<FormatContext, decltype(out)> f(ctx, out);
      f.s = std::chrono::duration_cast<std::chrono::seconds>(d);
      f.ms = std::chrono::duration_cast<std::chrono::milliseconds>(d - f.s);
      parse_chrono_format(begin, end, f);
    }
    w.write(buf.data(), buf.size(), spec);
    return w.out();
  }
};

FMT_END_NAMESPACE

#endif  // FMT_CHRONO_H_


text:
puremvc.define({
        name: 'game.controller.StartupCommand',
        parent: puremvc.MacroCommand
    },

    // INSTANCE MEMBERS
    {
        /**
         * Add the sub-commands for this MacroCommand
         * @override
         */
        initializeMacroCommand: function () {
            this.addSubCommand( game.controller.StartupControllerCommand );
            this.addSubCommand( game.controller.StartupModelCommand );
            this.addSubCommand( game.controller.StartupViewCommand );
        }
    }
);

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using Nickymaco.SQL.Iterator;

namespace Nickymaco.SQL.Collections
{
    public class DynamicObjectCollection : IEnumerable<DynamicExtentObject>
    {
        public readonly IEnumerator<DynamicExtentObject> _iterator;

        public DynamicObjectCollection(DynamicObjectRecordsReaderIterator iterator)
        {
            _iterator = iterator;
        }

        public DynamicObjectCollection(DynamicObjectDataTableIterator iterator)
        {
            _iterator = iterator;
        }

        public IEnumerator<DynamicExtentObject> GetEnumerator()
        {
            return GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _iterator;
        }
    }
}


text:
package org.pentaho.di.shared;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.apache.commons.vfs.FileObject;
import org.pentaho.di.cluster.ClusterSchema;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.partition.PartitionSchema;
import org.pentaho.di.trans.step.StepMeta;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Based on a piece of XML, this factory will give back a list of objects.
 * In other words, it does XML de-serialisation
 *
 * @author Matt
 *
 */
public class SharedObjects
{
	private static Class<?> PKG = SharedObjects.class; // for i18n purposes, needed by Translator2!!   $NON-NLS-1$

	private static final String XML_TAG = "sharedobjects";

	private String filename;

	private Map<SharedEntry, SharedObjectInterface> objectsMap;

    private class SharedEntry
    {
        public String className;
        public String objectName;

        /**
         * @param className
         * @param objectName
         */
        public SharedEntry(String className, String objectName)
        {
            this.className = className;
            this.objectName = objectName;
        }

        public boolean equals(Object obj)
        {
            SharedEntry sharedEntry = (SharedEntry) obj;
            return className.equals(sharedEntry.className) && objectName.equals(objectName);
        }

        public int hashCode()
        {
            return className.hashCode() ^ objectName.hashCode();
        }

    }

    public SharedObjects(String sharedObjectsFile) throws KettleXMLException
    {
        try
        {
            this.filename = createFilename(sharedObjectsFile);
            this.objectsMap = new Hashtable<SharedEntry, SharedObjectInterface>();

            // Extra information
            FileObject file = KettleVFS.getFileObject(filename);

            // If we have a shared file, load the content, otherwise, just keep this one empty
            if (file.exists())
            {
                Document document = XMLHandler.loadXMLFile(file);
                Node sharedObjectsNode = XMLHandler.getSubNode(document, XML_TAG);
                if (sharedObjectsNode!=null)
                {
                    List<SlaveServer> privateSlaveServers = new ArrayList<SlaveServer>();
                    List<DatabaseMeta> privateDatabases = new ArrayList<DatabaseMeta>();

                    NodeList childNodes = sharedObjectsNode.getChildNodes();
                    // First load databases & slaves
                    //
                    for (int i=0;i<childNodes.getLength();i++)
                    {
                        Node node = childNodes.item(i);
                        String nodeName = node.getNodeName();

                        SharedObjectInterface isShared = null;

                        if (nodeName.equals(DatabaseMeta.XML_TAG))
                        {
                            DatabaseMeta sharedDatabaseMeta = new DatabaseMeta(node);
                            isShared = sharedDatabaseMeta;
                            privateDatabases.add(sharedDatabaseMeta);
                        }
                        else if (nodeName.equals(SlaveServer.XML_TAG))
                        {
                            SlaveServer sharedSlaveServer = new SlaveServer(node);
                            isShared = sharedSlaveServer;
                            privateSlaveServers.add(sharedSlaveServer);
                        }

                        if (isShared!=null)
                        {
                            isShared.setShared(true);
                            storeObject(isShared);
                        }
                    }

                    // Then load the other objects that might reference databases & slaves
                    //
                    for (int i=0;i<childNodes.getLength();i++)
                    {
                        Node node = childNodes.item(i);
                        String nodeName = node.getNodeName();

                        SharedObjectInterface isShared = null;

                        if (nodeName.equals(StepMeta.XML_TAG))
                        {
                            StepMeta stepMeta = new StepMeta(node, privateDatabases, null);
                            stepMeta.setDraw(false); // don't draw it, keep it in the tree.
                            isShared = stepMeta;
                        }
                        else if (nodeName.equals(PartitionSchema.XML_TAG))
                        {
                            isShared = new PartitionSchema(node);
                        }
                        else if (nodeName.equals(ClusterSchema.XML_TAG))
                        {
                            isShared = new ClusterSchema(node, privateSlaveServers);
                        }

                        if (isShared!=null)
                        {
                            isShared.setShared(true);
                            storeObject(isShared);
                        }
                    }
                }
            }
        }
        catch(Exception e)
        {
            throw new KettleXMLException(BaseMessages.getString(PKG, "SharedOjects.Readingfile.UnexpectedError", sharedObjectsFile), e);
        }
    }

    public static final String createFilename(String sharedObjectsFile)
    {
        String filename;
        if (Const.isEmpty(sharedObjectsFile))
        {
            // First fallback is the environment/kettle variable ${KETTLE_SHARED_OBJECTS}
            // This points to the file
            filename = Variables.getADefaultVariableSpace().getVariable(Const.KETTLE_SHARED_OBJECTS);

            // Last line of defence...
            if (Const.isEmpty(filename))
            {
                filename = Const.getSharedObjectsFile();
            }
        }
        else
        {
            filename = sharedObjectsFile;
        }
        return filename;
    }

    public SharedObjects() throws KettleXMLException
    {
        this(null);
    }

    public Map<SharedEntry, SharedObjectInterface> getObjectsMap()
    {
        return objectsMap;
    }

    public void setObjectsMap(Map<SharedEntry, SharedObjectInterface> objects)
    {
        this.objectsMap = objects;
    }

    /**
     * Store the sharedObject in the object map.
     * It is possible to have 2 different types of shared object with the same name.
     * They will be stored separately.
     *
     * @param sharedObject
     */
    public void storeObject(SharedObjectInterface sharedObject)
    {
        SharedEntry key = new SharedEntry(sharedObject.getClass().getName(), sharedObject.getName());
        objectsMap.put(key, sharedObject);
    }

    /**
     * Remove the sharedObject from the object map.
     *
     * @param sharedObject
     */
    public void removeObject(SharedObjectInterface sharedObject)
    {
        SharedEntry key = new SharedEntry(sharedObject.getClass().getName(), sharedObject.getName());
        objectsMap.remove(key);
    }

    public void saveToFile() throws IOException, KettleException
    {
        OutputStream outputStream = KettleVFS.getOutputStream(filename, false);

        PrintStream out = new PrintStream(outputStream);

        out.print(XMLHandler.getXMLHeader(Const.XML_ENCODING));
        out.println("<"+XML_TAG+">");

        Collection<SharedObjectInterface> collection = objectsMap.values();
        for (SharedObjectInterface sharedObject : collection)
        {
            out.println(sharedObject.getXML());
        }

        out.println("</"+XML_TAG+">");

        out.flush();
        out.close();
        outputStream.close();
    }

	/**
	 * @return the filename
	 */
	public String getFilename() {
		return filename;
	}

	/**
	 * @param filename the filename to set
	 */
	public void setFilename(String filename) {
		this.filename = filename;
	}

	/**
   * Return the shared object with the given class and name
   * @param clazz The class of the shared object
   * @param objectName the name of the object
   * @return The shared object or null if none was found.
   */
  public SharedObjectInterface getSharedObject(Class<SharedObjectInterface> clazz, String objectName) {
    return getSharedObject(clazz.getName(), objectName);
  }

  /**
   * Return the shared object with the given class name and object name
   * @param clasName The class name of the shared object
   * @param objectName the name of the object
   * @return The shared object or null if none was found.
   */
  public SharedObjectInterface getSharedObject(String className, String objectName) {
    SharedEntry entry = new SharedEntry(className, objectName);
    return objectsMap.get(entry);
  }

  /**
   * Get the shared database with the specified name
   * @param name The name of the shared database
   * @return The database or null if nothing was found.
   */
  public DatabaseMeta getSharedDatabase(String name) {
    return (DatabaseMeta)getSharedObject(DatabaseMeta.class.getName(), name);
  }
}


text:
> {%= description %}

**Heads up!** front-matter is handled in verb by default, this module can be used separately if you want to disable the defaults.

{%= include("install-npm", {save: true}) %}

## Usage

```js
verb.use(require('{%= name %}'));
```

Verb uses [gray-matter], visit that project to see all available front-matter options.

## Run tests

Install dev dependencies:

```bash
npm i -d && npm test
```

## Contributing
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue]({%= bugs.url %})

## Author
{%= include("author") %}

## License
{%= copyright() %}
{%= license() %}

***

{%= include("footer") %}

{%= reflinks() %}
<!-- deps: helper-reflinks -->


text:
package org.n52.sos.ogc.swe;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

import org.junit.Test;
import org.n52.sos.ogc.sos.SosEnvelope;
import org.n52.sos.ogc.swe.SweConstants.SweCoordinateName;
import org.n52.sos.ogc.swe.simpleType.SweQuantity;

import com.vividsolutions.jts.geom.Envelope;

/**
 * @author Eike Hinderk
 *         Jürrens
 *
 * @since 4.0.0
 */
public class SosSweEnvelopeTest {

    @Test
    public final void should_create_valid_sosSweEnvelope_from_sosEnvelope() {
        final int srid = 52;
        final double x1 = 1;
        final double y1 = 2;
        final double y2 = 3;
        final double x2 = 4;
        final String uom = "deg";
        final SosEnvelope sosEnvelope = new SosEnvelope(new Envelope(x1, x2, y1, y2), srid);
        final SweEnvelope sweEnvelope = new SweEnvelope(sosEnvelope, uom);

        // srid
        assertThat(sweEnvelope.getReferenceFrame(), is(Integer.toString(srid)));
        // x1
        assertThat((Double) sweEnvelope.getLowerCorner().getCoordinates().get(0).getValue().getValue(), is(new Double(
                x1)));
        // y1
        assertThat((Double) sweEnvelope.getLowerCorner().getCoordinates().get(1).getValue().getValue(), is(new Double(
                y1)));
        // x2
        assertThat((Double) sweEnvelope.getUpperCorner().getCoordinates().get(0).getValue().getValue(), is(new Double(
                x2)));
        // y2
        assertThat((Double) sweEnvelope.getUpperCorner().getCoordinates().get(1).getValue().getValue(), is(new Double(
                y2)));
        // uom
        assertThat(((SweQuantity) sweEnvelope.getLowerCorner().getCoordinates().get(0).getValue()).getUom(), is(uom));
        assertThat(((SweQuantity) sweEnvelope.getLowerCorner().getCoordinates().get(1).getValue()).getUom(), is(uom));
        assertThat(((SweQuantity) sweEnvelope.getUpperCorner().getCoordinates().get(0).getValue()).getUom(), is(uom));
        assertThat(((SweQuantity) sweEnvelope.getUpperCorner().getCoordinates().get(1).getValue()).getUom(), is(uom));
        // northing
        assertThat(sweEnvelope.getLowerCorner().getCoordinates().get(0).getName(),
                is(SweCoordinateName.easting.name()));
        assertThat(sweEnvelope.getUpperCorner().getCoordinates().get(0).getName(),
                is(SweCoordinateName.easting.name()));
        // easting
        assertThat(sweEnvelope.getLowerCorner().getCoordinates().get(1).getName(),
                is(SweCoordinateName.northing.name()));
        assertThat(sweEnvelope.getUpperCorner().getCoordinates().get(1).getName(),
                is(SweCoordinateName.northing.name()));
    }

}


text:
/**
 * A helper object used to assert interface implementation. This object is
 * used only to assist tests. The Help object is not a dependency of the
 * puremvc implementation.
 *
 * @author David Foley | david@objectkit.com
 */
Help=
{
    exportPureMvcActors: function (scope)
	{
	    // ensure global scope in testdriver context
	    if (null == scope)
	       scope= window;

	    var puremvc= scope.puremvc;
	    if (null == puremvc)
	       throw new Error('Puremvc is not defined')
	    // variables declared without var are implicit globals
		Model			= puremvc.Model;
		View			= puremvc.View;
		Controller		= puremvc.Controller;
		SimpleCommand	= puremvc.SimpleCommand;
		MacroCommand	= puremvc.MacroCommand;
		Facade			= puremvc.Facade;
		Mediator		= puremvc.Mediator;
		Observer		= puremvc.Observer;
		Notifier		= puremvc.Notifier;
		Notification	= puremvc.Notification;
		Proxy			= puremvc.Proxy;
		define          = puremvc.define;
		declare			= puremvc.declare;

		if (console)
			console.info('Exported PureMVC actors', this)
	}
};

Help.exportPureMvcActors(this);


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

<TITLE>
TaxPricingEngine (ATG Java API)
</TITLE>

<META NAME="date" CONTENT="2013-04-01">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

atg.commerce.pricing

Interface TaxPricingEngine

All Superinterfaces:
PricingEngine

All Known Implementing Classes:
TaxPricingEngineImpl

public interface TaxPricingEngine
extends PricingEngine

This extension of the PricingEngine interface describes an object whose job it is
 to determine prices for ShippingGroup objects.
 Implementations of this interface are asked to determine the price for the tax associated
 with an input Order object.  The interface is very simple.  There's exactly one way
 to ask for a tax price.  Calling code provides the pricing context by inputting the Order,
 any pricing models (promotions), a locale in which the pricing should occur, the current
 profile, and any extra parameters that they feel might be necessary.  Be aware, though,
 that the extra parameters are ignored in all DCS implementations of this interface.

Field Summary

static java.lang.String
CLASS_VERSION

          Class version string

Method Summary

 TaxPriceInfo
priceTax(Order pOrder,
         java.util.Collection pPricingModels,
         java.util.Locale pLocale,
         RepositoryItem pProfile,
         java.util.Map pExtraParameters)

          Tax an order within a context

Methods inherited from interface atg.commerce.pricing.PricingEngine

getPricingModels

Field Detail

CLASS_VERSION

static final java.lang.String CLASS_VERSION

Class version string

See Also:
Constant Field Values

Method Detail

priceTax

TaxPriceInfo priceTax(Order pOrder,
                      java.util.Collection pPricingModels,
                      java.util.Locale pLocale,
                      RepositoryItem pProfile,
                      java.util.Map pExtraParameters)
                      throws PricingException

Tax an order within a context

Parameters:
pOrder - The order to tax
pPricingModels - A Collection of RepositoryItems representing PricingModels
pLocale - The Locale to use for pricing
pProfile - The user's profile
pExtraParameters - A Map of extra parameters to be used in the pricing, may be null

Returns:
TaxPriceInfo representing the tax quote for the order

Throws:

PricingException

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?xml version="1.0" ?>

Test Case

DISPLAY-020

Title

Number of shares field

Objective

This test case is intended to verify the following implied or specified requirements:

rtnv shall have a displayable and editable field that allows a user to enter the number of shares owned of a given ticker symbol.

The objective of this test case is to verify that the requirements specified above related to the attributes of the stock number of shares field are implemented and funtioning.

Setup

Actions

 Using the display initiated by test case DISPLAY-010, select the "Number of shares field" (Number of Shares).

 Verify a numeric keypad is displayed and that numbers (0-9) and the decimal point (.) can be entered.

Expected

The field that contains the number of shares should allow the user to enter whole and factional values that store the number of shares held in the portfolio.

Results

PASSED

Cleanup

Unnecessary

Requirements

RTNV-EXT-IF-020


text:
// Author: abliss@google.com (Adam Bliss)

#ifndef NET_INSTAWEB_SPRITER_LIBPNG_IMAGE_LIBRARY_H_
#define NET_INSTAWEB_SPRITER_LIBPNG_IMAGE_LIBRARY_H_

// TODO(huibao): Move LibpngImageLibrary to pagespeed/kernel/image/.
// Refactor LibpngImageLibrary. This class can be split into 3 parts:
// reader, writer, and canvas creater. The first two parts can be merged
// with png_optimizer.cc and png_optimizer.h.

extern "C" {
#ifdef USE_SYSTEM_LIBPNG
#include "png.h"  // NOLINT
#else
#include "third_party/libpng/png.h"
#endif
}  // extern "C"

#include "net/instaweb/spriter/image_library_interface.h"
#include "pagespeed/kernel/base/string.h"

namespace net_instaweb {
namespace spriter {

/**
 * An implementation of the ImageLibraryInterface using direct calls to libpng.
 * The advantage of this over OpenCV is that it can handle transparency.  The
 * output of this library is always an RGBA PNG with 8 bits per channel (so
 * 16-bit images will be degraded).
 */
class LibpngImageLibrary : public ImageLibraryInterface {
 public:
  LibpngImageLibrary(const FilePath& base_input_path,
                     const FilePath& base_output_path,
                     Delegate* delegate);
  virtual ~LibpngImageLibrary() {}

 protected:
  // Images are immutable rectangular regions of pixels.
  class Image : public ImageLibraryInterface::Image {
   public:
    // Takes ownership of rows.
    Image(ImageLibraryInterface* lib,
          png_structp png_struct, png_infop png_info, png_bytep* rows);
    virtual ~Image();

    virtual bool GetDimensions(int* out_width, int* out_height) const;
    const png_bytep* Rows() const;

   private:
    png_structp png_struct_;
    png_infop png_info_;
    png_bytep* rows_;
    DISALLOW_COPY_AND_ASSIGN(Image);
  };

  // Read an image from disk.  Return NULL (after calling delegate
  // method) on error.  Caller owns the returned pointer.
  virtual ImageLibraryInterface::Image* ReadFromFile(const FilePath& path);

  // Canvases are mutable rectangles onto which a program may draw.
  // For now, we support stamping images into a canvas, and writing
  // a canvas to a file.
  class Canvas : public ImageLibraryInterface::Canvas {
   public:
    Canvas(ImageLibraryInterface* lib, const Delegate* d,
           const GoogleString& base_out_path,
           int width, int height);
    virtual ~Canvas();
    virtual bool DrawImage(const ImageLibraryInterface::Image* image, int x,
                           int y);
    virtual bool WriteToFile(const FilePath& write_path, ImageFormat format);

   private:
    const Delegate* delegate_;
    const GoogleString base_out_path_;
    int width_;
    int height_;
    png_bytep* rows_;
    DISALLOW_COPY_AND_ASSIGN(Canvas);
  };

  virtual ImageLibraryInterface::Canvas* CreateCanvas(int width, int height);

 private:
  friend class LibpngImageLibraryTest;
  DISALLOW_COPY_AND_ASSIGN(LibpngImageLibrary);
};

}  // namespace spriter
}  // namespace net_instaweb

#endif  // NET_INSTAWEB_SPRITER_LIBPNG_IMAGE_LIBRARY_H_


text:
from __future__ import absolute_import

import wrapt
import re

from ....log import logger
from ....singletons import tracer
from .collectors import _storage_api

try:
    from google.cloud import storage

    logger.debug('Instrumenting google-cloud-storage')

    def _collect_tags(api_request):
        """
        Extract span tags from Google Cloud Storage API request. Returns None if the request is not
        supported.

        :param: dict
        :return: dict or None
        """
        method, path = api_request.get('method', None), api_request.get('path', None)

        if method not in _storage_api:
            return

        try:
            params = api_request.get('query_params', {})
            data = api_request.get('data', {})

            if path in _storage_api[method]:
                # check is any of string keys matches the path exactly
                return _storage_api[method][path](params, data)
            else:
                # look for a regex that matches the string
                for (matcher, collect) in _storage_api[method].items():
                    if not isinstance(matcher, re.Pattern):
                        continue

                    m = matcher.match(path)
                    if m is None:
                        continue

                    return collect(params, data, m)
        except Exception:
            logger.debug("instana.instrumentation.google.cloud.storage._collect_tags: ", exc_info=True)

    def execute_with_instana(wrapped, instance, args, kwargs):
        # batch requests are traced with finish_batch_with_instana()
        if isinstance(instance, storage.Batch):
            return wrapped(*args, **kwargs)

        parent_span = tracer.active_span

        # return early if we're not tracing
        if parent_span is None:
            return wrapped(*args, **kwargs)

        tags = _collect_tags(kwargs)

        # don't trace if the call is not instrumented
        if tags is None:
            logger.debug('uninstrumented Google Cloud Storage API request: %s' % kwargs)
            return wrapped(*args, **kwargs)

        with tracer.start_active_span('gcs', child_of=parent_span) as scope:
            for (k, v) in tags.items():
                scope.span.set_tag(k, v)

            try:
                kv = wrapped(*args, **kwargs)
            except Exception as e:
                scope.span.log_exception(e)
                raise
            else:
                return kv

    def download_with_instana(wrapped, instance, args, kwargs):
        parent_span = tracer.active_span

        # return early if we're not tracing
        if parent_span is None:
            return wrapped(*args, **kwargs)

        with tracer.start_active_span('gcs', child_of=parent_span) as scope:
            scope.span.set_tag('gcs.op', 'objects.get')
            scope.span.set_tag('gcs.bucket', instance.bucket.name)
            scope.span.set_tag('gcs.object', instance.name)

            start = len(args) > 4 and args[4] or kwargs.get('start', None)
            if start is None:
                start = ''

            end = len(args) > 5 and args[5] or kwargs.get('end', None)
            if end is None:
                end = ''

            if start != '' or end != '':
                scope.span.set_tag('gcs.range', '-'.join((start, end)))

            try:
                kv = wrapped(*args, **kwargs)
            except Exception as e:
                scope.span.log_exception(e)
                raise
            else:
                return kv

    def upload_with_instana(wrapped, instance, args, kwargs):
        parent_span = tracer.active_span

        # return early if we're not tracing
        if parent_span is None:
            return wrapped(*args, **kwargs)

        with tracer.start_active_span('gcs', child_of=parent_span) as scope:
            scope.span.set_tag('gcs.op', 'objects.insert')
            scope.span.set_tag('gcs.bucket', instance.bucket.name)
            scope.span.set_tag('gcs.object', instance.name)

            try:
                kv = wrapped(*args, **kwargs)
            except Exception as e:
                scope.span.log_exception(e)
                raise
            else:
                return kv

    def finish_batch_with_instana(wrapped, instance, args, kwargs):
        parent_span = tracer.active_span

        # return early if we're not tracing
        if parent_span is None:
            return wrapped(*args, **kwargs)

        with tracer.start_active_span('gcs', child_of=parent_span) as scope:
            scope.span.set_tag('gcs.op', 'batch')
            scope.span.set_tag('gcs.projectId', instance._client.project)
            scope.span.set_tag('gcs.numberOfOperations', len(instance._requests))

            try:
                kv = wrapped(*args, **kwargs)
            except Exception as e:
                scope.span.log_exception(e)
                raise
            else:
                return kv

    wrapt.wrap_function_wrapper('google.cloud.storage._http', 'Connection.api_request', execute_with_instana)
    wrapt.wrap_function_wrapper('google.cloud.storage.blob', 'Blob._do_download', download_with_instana)
    wrapt.wrap_function_wrapper('google.cloud.storage.blob', 'Blob._do_upload', upload_with_instana)
    wrapt.wrap_function_wrapper('google.cloud.storage.batch', 'Batch.finish', finish_batch_with_instana)
except ImportError:
    pass


text:
var express = require('express');
var app = express();

var http = require("http");
var fs = require("fs");

var events = require("events");

var commandEvent = new events.EventEmitter();
var responseEvent = new events.EventEmitter();

var clients = {};
var connectKeys = {};

function clientCleanup(){
    var now = (new Date).getTime();
    for(var clientId in clients){
        if(now - clients[clientId].lastSeen > 45000) { //45 seconds.
            var cKey = clients[clientId].connectKey;
            if(connectKeys.hasOwnProperty(cKey)){
                delete connectKeys[cKey]
            }
            delete clients[clientId];
        }
    }
}

setInterval(clientCleanup, 10000);

function Client(){
    this.clientKey = "";
    this.clientId = "";
    this.connectKey = "";
    this.lastSeen = (new Date).getTime();
    this.commandQueue = [];
}

var niceChars = "23456789CFGHJMPQRVWX";
function genTypableRandom(len){
    var out = "";
    for(var i=0;i<len;i++){
        out += niceChars.charAt(Math.random() * niceChars.length);
    }
    return out;
}

var printableChars = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[/]^+`abcdefghijklmnopqrstuvwxyz{|}~";
function genPrintableRandom(len){
    var out = "";
    for(var i=0;i<len;i++){
        out += printableChars.charAt(Math.random() * printableChars.length);
    }
    return out;
}

function luaEncode(obj){
    var out = "{";

    for(prop in obj){
        out +=  "["+JSON.stringify(prop)+"] = ";
        if(obj[prop] instanceof Object) { //both lua and JS use integer indexed objects as arrays.
            out += luaEncode(obj[prop]);
        }else if(obj[prop] instanceof String){
            //LUA escapes the newline character itself, instead of using \n
            out += JSON.stringify(obj[prop]).replace("\\n","\\\n");
        }else{
            out += JSON.stringify(obj[prop]);
        }
        out += ",";
    }

    out += "}";
    return out;
}

Client.prototype.genKeys = function (){
    this.clientId = genPrintableRandom(20);
    this.clientKey = genPrintableRandom(10);
    this.connectKey = genTypableRandom(4);
};

Client.prototype.getId = function (){
    return this.clientId;
};

Client.prototype.getKey = function (){
    return this.clientKey;
};

Client.prototype.getConnect = function (){
    return this.connectKey;
};

Client.prototype.checkKey = function (inKey){
    return this.clientKey === inKey;
};

function findClient(res,inData){
    var inJson;
    try {
	inJson = JSON.parse(inData);
	}catch(e){
	console.log("Recieved malformated JSON: ", e.message);
        res.end(jsonDie(100,"Bad Request"));
        return false;
	}
    if(!inJson || !inJson.hasOwnProperty("i") || ! inJson.hasOwnProperty("k")){
        res.end(jsonDie(100,"Bad Request"));
        return false;
    }
    if(!clients.hasOwnProperty(inJson.i)){
        res.end(jsonDie(101,"No such session or bad key"));
        return false;
    }
    var client = clients[inJson.i];
    if(!client.checkKey(inJson.k)){
        res.end(jsonDie(101,"No such session or bad key"));
        return false;
    }
    return client;
}

function jsonDie(code,reason){
	return JSON.stringify({
	err: {
	code: code,
	reason: reason
	}});
}

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

app.post('/getcmd', function(req,res){
    var inData = '';
    req.on('data', function (d) {
        inData += d;
        if(inData.length > 128)
            req.connection.destroy();
    });
    req.on('end', function () {
        var client = findClient(res,inData);
        if(!client) return; //Connection has already been dealt with
        client.lastSeen = (new Date).getTime();
        if(client.commandQueue.length > 0){
            res.end(client.commandQueue[0]);
            client.commandQueue.splice(0,1);
        }else{
            var deathTimeout;
            var cmdCallback = function(cmd) {
                clearTimeout(deathTimeout);
                res.end(luaEncode(cmd));
            };
            commandEvent.once(client.clientId, cmdCallback);
            deathTimeout = setTimeout(function (){
                commandEvent.removeListener(client.clientId, cmdCallback);
                res.end("{action=\"ping\"}");
            },20000);
        }
    });
});

app.post('/response', function (req,res){
    var respData = '';
    req.on('data', function (d) {
        respData += d;
        if(respData.length > 1e8)
            req.connection.destroy();
    });
    req.on('end', function () {
        var client = findClient(res,respData);
        if(!client) return;
        client.lastSeen = (new Date).getTime();
        var inJson = JSON.parse(respData);
        responseEvent.emit(client.clientId, inJson.r);
    });

    res.end();
});

app.post("/qcmd", function (req,res){
    var qData = '';
    req.on('data', function (d) {
        qData += d;
        if(qData.length > 1e8)
            req.connection.destroy();
    });
    req.on('end', function () {
        var client = findClient(res, qData);
        if(!client){
            return;
        }
        var inJson = JSON.parse(qData);
        var deathTimeout;
        var respCb =  function (d) {
            res.end(JSON.stringify(d));
            clearTimeout(deathTimeout);
        };
        deathTimeout = setTimeout(function (){
            res.end(jsonDie(200,"Timeout while waiting for response from ComputerCraft"));
            responseEvent.removeListener(client.clientId, respCb);
        },4000);
        responseEvent.once(client.clientId,respCb);
        if(!commandEvent.emit(client.clientId, inJson.cmd))
        client.commandQueue.push(inJson.cmd);
        console.log("Command Q'd: " + JSON.stringify(inJson.cmd));
    });
});

app.post("/attach", function (req,res){
   var inData = '';
    req.on('data', function (d) {
        inData += d;
        if(inData.length > 128)
        req.connection.destroy();
    });
    req.on('end', function () {
        if(connectKeys.hasOwnProperty(inData)){
            client = connectKeys[inData];
            res.end(JSON.stringify({k: client.getKey(), i: client.getId()}));
            delete connectKeys[inData];
        }else
            res.end(
        	jsonDie(101,"No such session or bad key")
            );
    });
});

app.post("/connect", function (req,res){
    var client = new Client();
    client.genKeys();
    var payload = {
        k : client.getKey(),
        i : client.getId(),
        c : client.getConnect()
    };
    clients[client.getId()] = client;
    connectKeys[client.getConnect()] = client;
    console.log("Client Connected: ",payload);
    res.end(luaEncode(payload));
});

app.post("/get", function (req, res) {
    res.write("Part One");
    setInterval(function (){
        res.end("Part the next");
    },2000);
});

app.listen(8889);


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Bull. Bot. Res. , Harbin 10(3):39. 1990

#### Original name
null

### Remarks
null


text:
An Omniauth 1.0 Strategy for yahoo

For more information see the following:

 * https://github.com/intridea/omniauth/wiki/List-of-Strategies

Release notes:

 * Version 0.0.8

  - Handle empty emails array

 * Version 0.0.7

  - Add licence to gemspec

 * Version 0.0.6

  - Incorporate changes from jdjkelly to name fields

 * Version 0.0.5

  - Use HTTPS for social API

 * Version 0.0.4

  - Added skip_info? patch from mkdynamic

 * Version 0.0.3

  - Added primary email as per famoseagle

 * Version 0.0.1

   - First cut


text:
title: "discardComments"
layout: Optimisation
identifier: discardcomments
---

<!-- This file was automatically generated. -->

Removes comments in and around rules, selectors & declarations. Note that any
special comments marked with `!` are kept by default.


text:
package org.nustaq.kson;

/**
 *
 * Created by ruedi on 07.08.2014.
 */
public class KsonStringOutput implements KsonCharOutput {

    StringBuilder builder = new StringBuilder();

    @Override
    public void writeChar(char c) {
        builder.append(c);
    }

    @Override
    public void writeString(String s) {
        builder.append(s);
    }

    @Override
    public char lastChar() {
        if ( builder.length() > 0 ) {
            return builder.charAt(builder.length()-1);
        }
        return 0;
    }

    @Override
    public void back(int i) {
        builder.setLength(builder.length()-i);
    }

    public StringBuilder getBuilder() {
        return builder;
    }

    public void setBuilder(StringBuilder builder) {
        this.builder = builder;
    }

    public String toString() {
        return builder.toString();
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>3 reasons you should not be using Array.prototype.forEach</title>
  <meta name="description" content="One of the main problems with forEach is that it primarily relies on side effects, whereas some native Array.prototype alternatives make use of semantically-...">

  <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,400italic,300italic,600italic,700,700italic' rel='stylesheet' type='text/css'>
  <link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css'>
  <link rel="shortcut icon" href="/images/favicon.ico?v=1.1">
  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="http://joshbeam.github.io/javascript/2015/08/15/3-reasons-you-should-not-be-using-foreach.html">
  <link rel="alternate" type="application/rss+xml" title="Front End Collision" href="http://joshbeam.github.io/feed.xml" />

    <hgroup>

Front End Collision

Blog of software engineer Josh Beam

    </hgroup>

      Home

      About

      Reading List

3 reasons you should not be using Array.prototype.forEach

      15 August 2015 — Josh Beam — javascript

    All Posts

One of the main problems with forEach is that it primarily relies on side effects, whereas some native Array.prototype alternatives make use of semantically-correct programming paradigms (such as reduction, mapping, and filtering) and may in turn introduce less incidental complexity (and enhance readability) when writing code.

3) You should be filtering

In this example, we have an array, and we want to eliminate items from an array that don't meet a specific criteria. Here's how you'll see it done with forEach:

Bad

var filteredArray = [];

[1, 2, 3, 4, 5].forEach(function(number) {
  if(number > 3) {
    filteredArray.push(number);
  }
});

console.log(filteredArray);

[4, 5]

This is a typical implementation. With forEach, you simply push each object to a completely new array. You'll notice that this introduces extra state to maintain. More state equals more brainpower needed to understand what is happening.

Luckily, Array.prototype.filter already has you covered there. It simply returns a new array of the items we want.

Good

var filtered = [1, 2, 3, 4, 5].filter(isBig);

function isBig(number) {
  return number > 3;
}

console.log(filtered);

[4, 5]

2) You should be mapping

In this example, we want to "change" each value in an array to something else. Here's how we'd do it with forEach:

Bad

var stringNames = [];

var names = [{
  first: 'Josh',
  last: 'Beam'
},
{
  first: 'Ozzy',
  last: 'Osbourne'
}]

names.forEach(function(name) {
  stringNames.push(name.first + ' ' + name.last);
});

["Josh Beam", "Ozzy Osbourne"]

Again, naked looping requires us to create additional state within our application.

Here, we're gonna use map instead. Again, it simply returns a new array without requiring us to do it ourselves:

Good

var names = [{
  first: 'Josh',
  last: 'Beam'
},
{
  first: 'Ozzy',
  last: 'Osbourne'
}]

names = names.map(fullName);

function fullName(name) {
  return name.first + ' ' + name.last;
}

console.log(names);

["Josh Beam", "Ozzy Osbourne"]

1) You should be reducing

Here, we want to combine certain values in an array.

Bad

var total = 0;

[1, 2, 3, 4, 5].forEach(function(number) {
  total += number;
});

console.log(total);

15

In other words, when you think "reduce", think about "collapsing" items into a new item. Another way to think of it is to imagine you have an array filled with the words of a sentence, and you want to concatenate them all into one string.

Good

var total = [1, 2, 3, 4, 5].reduce(addAll);

function addAll(total, current) {
  return total + current;
}

console.log(total);

15

Conclusion

You'll notice one of the overarching concepts of all these three methods is that they all take the "functional route", where they don't necessarily require the manual creation of additional state. It is possible to introduce side effects within these methods, however, they don't primarily rely on side effects to function. In other words, you'll see that Array.prototype.forEach primarly relies on side effects. It never returns a value other than undefined unless you explicity force it to.

Why am I referring to functional programming in the context of JavaScript, which is clearly not a functional programming language? Well, to quote the omniscient Wikipedia article on functional programming:

Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program

In other words, it can take more "brain power" to understand what is happening in a forEach loop whose sole purpose is to mutate outside data based on side effects, whereas map, reduce, and filter all have immediate and clear semantic meanings to the programmer (that's not to say, though, that you can't use the power of those methods for evil).

Like this post?

Share it with your followers
or

follow me on Twitter!

      © 2015 Joshua Beam

www.joshbe.am

GitHub

Resume

@joshbeam92

josh@frontendcollisionblog.com

  <form class="search">
    <input type="text" class="search-box" id="search" /><input type="submit" class="search-button" value="Search" />
  </form>

Please enable JavaScript to view the comments powered by Disqus.


text:
package org.apache.jackrabbit.oak.security.authorization.permission;

import java.util.Collections;
import java.util.Set;
import javax.annotation.Nonnull;

import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.core.ImmutableRoot;
import org.apache.jackrabbit.oak.plugins.tree.ImmutableTree;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.RepositoryPermission;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.TreePermission;
import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants;

/**
 * Implementation of the {@code CompiledPermissions} interface that grants full
 * permission everywhere.
 */
public final class AllPermissions implements CompiledPermissions {

    private static final CompiledPermissions INSTANCE = new AllPermissions();

    private AllPermissions() {
    }

    public static CompiledPermissions getInstance() {
        return INSTANCE;
    }

    @Override
    public void refresh(@Nonnull ImmutableRoot root, @Nonnull String workspaceName) {
        // nop
    }

    @Override
    public RepositoryPermission getRepositoryPermission() {
        return RepositoryPermission.ALL;
    }

    @Override
    public TreePermission getTreePermission(@Nonnull ImmutableTree tree, @Nonnull TreePermission parentPermission) {
        return TreePermission.ALL;
    }

    @Override
    public boolean isGranted(ImmutableTree tree, PropertyState property, long permissions) {
        return true;
    }

    @Override
    public boolean isGranted(String path, long permissions) {
        return true;
    }

    @Override
    public Set<String> getPrivileges(ImmutableTree tree) {
        return Collections.singleton(PrivilegeConstants.JCR_ALL);
    }

    @Override
    public boolean hasPrivileges(ImmutableTree tree, String... privilegeNames) {
        return true;
    }
}


text:
(function (GGRC, can) {
  'use strict';

  GGRC.ListLoaders.TreeBaseLoader('GGRC.ListLoaders.SubTreeLoader', {}, {
    load: function (params, models) {
      return GGRC.Utils.QueryAPI.makeRequest(params)
        .then(function (response) {
          var mapped = [];
          models.forEach(function (modelName, idx) {
            var values = can.makeArray(response[idx][modelName].values);
            var models = values.map(function (source) {
              return CMS.Models[modelName].model(source);
            });
            mapped = mapped.concat(models);
          });
          return mapped;
        })
        .then(function (list) {
          var mappedToCurrent = [];
          var rest = [];
          var related = GGRC.Utils.CurrentPage.related;

          list.forEach(function (inst) {
            var relates = related.attr(inst.type);
            if (relates && relates[inst.id]) {
              mappedToCurrent.push(inst);
            } else {
              rest.push(inst);
            }
          });
          mappedToCurrent = mappedToCurrent.concat(rest);
          return this.insertInstancesFromMappings(mappedToCurrent);
        }.bind(this));
    }
  });
})(GGRC, can);


text:
Pipes
======

Pipes are functions that may be used when serving files to alter parts
of the response. These are invoked by adding a pipe= query parameter
taking a | separated list of pipe functions and parameters. The pipe
functions are applied to the response from left to right. For example::

  GET /sample.txt?pipe=slice(1,200)|status(404).

This would serve bytes 1 to 199, inclusive, of foo.txt with the HTTP status
code 404.

There are several built-in pipe functions, and it is possible to add
more using the `@pipe` decorator on a function, if required.

Built-In Pipes
--------------

sub
~~~

Used to substitute variables from the server environment, or from the
request into the response.

Substitutions are marked in a file using a block delimited by `{{`
and `}}`. Inside the block the following variables are available:

  `{{host}}`
    The host name of the server excluding any subdomain part.

  `{{domains[]}}`
    The domain name of a particular subdomain
      e.g. `{{domains[www]}}` for the `www` subdomain.

  `{{ports[][]}}`
    The port number of servers, by protocol
      e.g. `{{ports[http][0]}}` for the first (and, depending on setup,
      possibly only) http server

  `{{headers[]}}`
    The HTTP headers in the request
      e.g. `{{headers[X-Test]}}` for a hypothetical `X-Test` header.

  `{{GET[]}}`
    The query parameters for the request
      e.g. `{{GET[id]}}` for an id parameter sent with the request.

So, for example, to write a javascript file called `xhr.js` that
depends on the host name of the server, without hardcoding, one might
write::

    var server_url = http://{{host}}/path/to/resource;
    //Create the actual XHR and so on

The file would then be included as:

    <script src="xhr.js?pipe=sub"></script>

This pipe can also be enabled by using a filename `*.sub.ext`, e.g. the file above could be called `xhr.sub.js`.

status
~~~~~~

Used to set the HTTP status of the response, for example::

    example.js?pipe=status(410)

headers
~~~~~~~

Used to add or replace http headers in the response. Takes two or
three arguments; the header name, the header value and whether to
append the header rather than replace an existing header (default:
False). So, for example, a request for::

    example.html?pipe=header(Content-Type,text/plain)

causes example.html to be returned with a text/plain content type
whereas::

    example.html?pipe=header(Content-Type,text/plain,True)

Will cause example.html to be returned with both text/html and
text/plain content-type headers.

slice
~~~~~

Used to send only part of a response body. Takes the start and,
optionally, end bytes as arguments, although either can be null to
indicate the start or end of the file, respectively. So for example::

    example.txt?pipe=slice(10,20)

Would result in a response with a body containing 10 bytes of
example.txt including byte 10 but excluding byte 20.

::

    example.txt?pipe=slice(10)

Would cause all bytes from byte 10 of example.txt to be sent, but::

    example.txt?pipe=slice(null,20)

Would send the first 20 bytes of example.txt.

trickle
~~~~~~~

Used to send the body of a response in chunks with delays. Takes a
single argument that is a microsyntax consisting of colon-separated
commands. There are three types of commands:

* Bare numbers represent a number of bytes to send

* Numbers prefixed `d` indicate a delay in seconds

* Numbers prefixed `r` must only appear at the end of the command, and
  indicate that the preceding N items must be repeated until there is
  no more content to send. The number of items to repeat must be even.

In the absence of a repetition command, the entire remainder of the content is
sent at once when the command list is exhausted. So for example::

    example.txt?pipe=trickle(d1)

causes a 1s delay before sending the entirety of example.txt.

::

    example.txt?pipe=trickle(100:d1)

causes 100 bytes of example.txt to be sent, followed by a 1s delay,
and then the remainder of the file to be sent. On the other hand::

    example.txt?pipe=trickle(100:d1:r2)

Will cause the file to be sent in 100 byte chunks separated by a 1s
delay until the whole content has been sent.

:mod:`Interface <pipes>`
------------------------

.. automodule:: wptserve.pipes
   :members:


text:
package org.usfirst.frc4089.FRC2016Robot.Util;

import java.util.Comparator;

public class VisionParticleMeasurements implements Comparator<VisionParticleMeasurements>,
	Comparable<VisionParticleMeasurements> {
	public double TotalParticleArea;
	public double BoundingRectLeft;
	public double BoundingRectWidth;
	public double BoundingRectTop;
	public double BoundingRectHeight;
	public double ImageCoverageArea;
	public double BoundingRectCoverageArea;
	public double AspectRatio;
	public double RelativeSkewness;
	public double NetPerimeterDistance;

	@Override
	public int compareTo(VisionParticleMeasurements that) {
		// TODO Auto-generated method stub
		return (int)(that.TotalParticleArea - this.TotalParticleArea);
	}
	@Override
	public int compare(VisionParticleMeasurements that, VisionParticleMeasurements theOtherThing) {
		// TODO Auto-generated method stub
		return (int)(that.TotalParticleArea - theOtherThing.TotalParticleArea);
	}
}


text:
package jds;

import java.util.AbstractCollection;
import java.util.Iterator;

/**
 * An implementation of a LIFO Stack as a singly-linked list.
 *
 * @param <T> the class of objects stored in the queue
 */
public class SLListStack<T> extends AbstractCollection<T> {

	class Node {
		T x;
		Node next;
	}

	Node head;
	Node tail;
	int n;

	public Iterator<T> iterator() {
		return new SLIterator();
	}

	@Override
	public int size() {
		return n;
	}

	/**
	 * Stack peek operation - return head's data element
	 * @return x
	 */
	public T peek() {
		return head.x;
	}

	/**
	 * Stack push operation - push x onto the head of the list
	 * @param x the element to push onto the stack
	 * @return x
	 */
	public T push(T x) {
		Node u = new Node();
		u.x = x;
		u.next = head;
		head = u;
		if (n == 0)
			tail = u;
		n++;
		return x;
	}

	/**
	 * Stack pop operation - pop off the head of the list
	 * @return the element popped off
	 */
	public T pop() {
		if (n == 0)	return null;
		T x = head.x;
		head = head.next;
		if (--n == 0) tail = null;
		return x;
	}

	class SLIterator implements Iterator<T> {
		protected Node p;

		public SLIterator() {
			p = head;
		}
		public boolean hasNext() {
			return p != null;
		}
		public T next() {
			T x = p.x;
			p = p.next;
			return x;
		}
		public void remove() {
			throw new UnsupportedOperationException();
		}
	}

}


text:
OroConfigBundle enables developers to define the application configuration settings in the YAML configuration files in any bundle. It also enables the application users to set values for the application-wide or user-specific settings in the System Configuration UI.

## Usage

- [Configuration Reference](./Resources/doc/system_configuration.md)
- [Config management](./Resources/doc/config_management.md)
- [Add new configuration scope](./Resources/doc/add_new_config_scope.md)
- [Conditions](./Resources/doc/reference/conditions.md)
- [Behat](./Resources/doc/behat.md)


text:
NeFS Edit allows opening and modifying NeFS archive files. These archive files are used by Ego Engine games such as DiRT 4 and DiRT Rally 2.

There are two components to this project.
- NefsLib - a C# library for working with NeFS archives.
- NefsEdit - a Windows Forms application that uses NefsLib.

## Acknowledgements
[@Gigi1237]( https://github.com/Gigi1237 ) - encryption/reversing contributions


text:
using WebKit::WebDevToolsFrontend;
using WebKit::WebString;

DevToolsClient::DevToolsClient(RenderViewImpl* render_view)
    : content::RenderViewObserver(render_view) {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  web_tools_frontend_.reset(
      WebDevToolsFrontend::create(
          render_view->webview(),
          this,
          ASCIIToUTF16(command_line.GetSwitchValueASCII(switches::kLang))));
}

DevToolsClient::~DevToolsClient() {
}

bool DevToolsClient::OnMessageReceived(const IPC::Message& message) {
  DCHECK(RenderThreadImpl::current());

  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(DevToolsClient, message)
    IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend,
                        OnDispatchOnInspectorFrontend)
    IPC_MESSAGE_UNHANDLED(handled = false);
  IPC_END_MESSAGE_MAP()

  return handled;
}

void DevToolsClient::sendMessageToBackend(const WebString& message)  {
  Send(new DevToolsAgentMsg_DispatchOnInspectorBackend(routing_id(),
                                                       message.utf8()));
}

void DevToolsClient::activateWindow() {
  Send(new DevToolsHostMsg_ActivateWindow(routing_id()));
}

void DevToolsClient::closeWindow() {
  Send(new DevToolsHostMsg_CloseWindow(routing_id()));
}

void DevToolsClient::moveWindowBy(const WebKit::WebFloatPoint& offset) {
  Send(new DevToolsHostMsg_MoveWindow(routing_id(), offset.x, offset.y));
}

void DevToolsClient::requestDockWindow() {
  Send(new DevToolsHostMsg_RequestDockWindow(routing_id()));
}

void DevToolsClient::requestUndockWindow() {
  Send(new DevToolsHostMsg_RequestUndockWindow(routing_id()));
}

void DevToolsClient::requestSetDockSide(const WebKit::WebString& side) {
  Send(new DevToolsHostMsg_RequestSetDockSide(routing_id(), side.utf8()));
}

void DevToolsClient::openInNewTab(const WebKit::WebString& url) {
  Send(new DevToolsHostMsg_OpenInNewTab(routing_id(),
                                        url.utf8()));
}

void DevToolsClient::save(const WebKit::WebString& url,
                          const WebKit::WebString& content,
                          bool save_as) {
  Send(new DevToolsHostMsg_Save(routing_id(),
                                url.utf8(),
                                content.utf8(),
                                save_as));
}

void DevToolsClient::append(const WebKit::WebString& url,
                            const WebKit::WebString& content) {
  Send(new DevToolsHostMsg_Append(routing_id(),
                                  url.utf8(),
                                  content.utf8()));
}

void DevToolsClient::OnDispatchOnInspectorFrontend(const std::string& message) {
  web_tools_frontend_->dispatchOnInspectorFrontend(
      WebString::fromUTF8(message));
}


text:
/*
 * Module: to_erl.c
 *
 * This module implements a process that opens two specified FIFOs, one
 * for reading and one for writing; reads from its stdin, and writes what
 * it has read to the write FIF0; reads from the read FIFO, and writes to
 * its stdout.
 *
  ________                            _________
 |        |--<-- pipe.r (fifo1) --<--|         |
 | to_erl |                          | run_erl | (parent)
 |________|-->-- pipe.w (fifo2) -->--|_________|
                                          ^ master pty
                                          |
                                          | slave pty
                                      ____V____
                                     |         |
                                     |  "erl"  | (child)
                                     |_________|
 */
#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <dirent.h>
#include <signal.h>
#include <errno.h>
#ifdef HAVE_SYS_IOCTL_H
#  include <sys/ioctl.h>
#endif

#include "run_erl.h"
#include "safe_string.h"   /* strn_cpy, strn_catf, sn_printf, etc. */

#ifdef __clang_analyzer__
   /* CodeChecker does not seem to understand inline asm in FD_ZERO */
#  undef FD_ZERO
#  define FD_ZERO(FD_SET_PTR) memset(FD_SET_PTR, 0, sizeof(fd_set))
#endif

#if defined(O_NONBLOCK)
# define DONT_BLOCK_PLEASE O_NONBLOCK
#else
# define DONT_BLOCK_PLEASE O_NDELAY
# if !defined(EAGAIN)
#  define EAGAIN -3898734
# endif
#endif

#ifdef HAVE_STRERROR
#  define STRERROR(x) strerror(x)
#else
#  define STRERROR(x) ""
#endif

#define noDEBUG

#define PIPE_DIR        "/tmp/"
#define PIPE_STUBNAME   "erlang.pipe"
#define PIPE_STUBLEN    strlen(PIPE_STUBNAME)

#ifdef DEBUG
#define STATUS(s)  { fprintf(stderr, (s)); fflush(stderr); }
#else
#define STATUS(s)
#endif

#ifndef FILENAME_MAX
#define FILENAME_MAX 250
#endif

static struct termios tty_smode, tty_rmode;
static int tty_eof = 0;
static int recv_sig = 0;
static int protocol_ver = RUN_ERL_LO_VER; /* assume lowest to begin with */

static int write_all(int fd, const char* buf, int len);
static int window_size_seq(char* buf, size_t bufsz);
static int version_handshake(char* buf, int len, int wfd);
#ifdef DEBUG
static void show_terminal_settings(struct termios *);
#endif

static void handle_ctrlc(int sig)
{
    /* Reinstall the handler, and signal break flag */
    signal(SIGINT,handle_ctrlc);
    recv_sig = SIGINT;
}

static void handle_sigwinch(int sig)
{
    recv_sig = SIGWINCH;
}

static void usage(char *pname)
{
    fprintf(stderr, "Usage: %s [-h|-F] [pipe_name|pipe_dir/]\n", pname);
    fprintf(stderr, "\t-h\tThis help text.\n");
    fprintf(stderr, "\t-F\tForce connection even though pipe is locked by other to_erl process.\n");
}

int main(int argc, char **argv)
{
    char  FIFO1[FILENAME_MAX], FIFO2[FILENAME_MAX];
    int i, len, wfd, rfd;
    fd_set readfds;
    char buf[BUFSIZ];
    char pipename[FILENAME_MAX];
    int pipeIx = 1;
    int force_lock = 0;
    int got_some = 0;

    if (argc >= 2 && argv[1][0]=='-') {
	switch (argv[1][1]) {
	case 'h':
	    usage(argv[0]);
	    exit(1);
	case 'F':
	    force_lock = 1;
	    break;
	default:
	    fprintf(stderr,"Invalid option '%s'\n",argv[1]);
	    exit(1);
	}
	pipeIx = 2;
    }

#ifdef DEBUG
    fprintf(stderr, "%s: pid is : %d\n", argv[0], (int)getpid());
#endif

    strn_cpy(pipename, sizeof(pipename),
	     (argv[pipeIx] ? argv[pipeIx] : PIPE_DIR));

    if(*pipename && pipename[strlen(pipename)-1] == '/') {
	/* The user wishes us to find a pipe name in the specified */
	/* directory */
	int highest_pipe_num = 0;
	DIR *dirp;
	struct dirent *direntp;

	dirp = opendir(pipename);
	if(!dirp) {
	    fprintf(stderr, "Can't access pipe directory %s: %s\n", pipename, strerror(errno));
	    exit(1);
	}

	/* Check the directory for existing pipes */

	while((direntp=readdir(dirp)) != NULL) {
	    if(strncmp(direntp->d_name,PIPE_STUBNAME,PIPE_STUBLEN)==0) {
		int num = atoi(direntp->d_name+PIPE_STUBLEN+1);
		if(num > highest_pipe_num)
		    highest_pipe_num = num;
	    }
	}
	closedir(dirp);
	strn_catf(pipename, sizeof(pipename), (highest_pipe_num?"%s.%d":"%s"),
		  PIPE_STUBNAME, highest_pipe_num);
    } /* if */

    /* read FIFO */
    sn_printf(FIFO1,sizeof(FIFO1),"%s.r",pipename);
    /* write FIFO */
    sn_printf(FIFO2,sizeof(FIFO2),"%s.w",pipename);

    /* Check that nobody is running to_erl on this pipe already */
    if ((wfd = open (FIFO1, O_WRONLY|DONT_BLOCK_PLEASE, 0)) >= 0) {
	/* Open as server succeeded -- to_erl is already running! */
	close(wfd);
	fprintf(stderr, "Another to_erl process already attached to pipe "
			"%s.\n", pipename);
	if (force_lock) {
	    fprintf(stderr, "But we proceed anyway by force (-F).\n");
	}
	else {
	    exit(1);
	}
    }

    if ((rfd = open (FIFO1, O_RDONLY|DONT_BLOCK_PLEASE, 0)) < 0) {
#ifdef DEBUG
	fprintf(stderr, "Could not open FIFO %s for reading.\n", FIFO1);
#endif
	fprintf(stderr, "No running Erlang on pipe %s: %s\n", pipename, strerror(errno));
	exit(1);
    }
#ifdef DEBUG
    fprintf(stderr, "to_erl: %s opened for reading\n", FIFO1);
#endif

    if ((wfd = open (FIFO2, O_WRONLY|DONT_BLOCK_PLEASE, 0)) < 0) {
#ifdef DEBUG
	fprintf(stderr, "Could not open FIFO %s for writing.\n", FIFO2);
#endif
	fprintf(stderr, "No running Erlang on pipe %s: %s\n", pipename, strerror(errno));
	close(rfd);
	exit(1);
    }
#ifdef DEBUG
    fprintf(stderr, "to_erl: %s opened for writing\n", FIFO2);
#endif

    fprintf(stderr, "Attaching to %s (^D to exit)\n\n", pipename);

    /* Set break handler to our handler */
    signal(SIGINT,handle_ctrlc);

    /*
     * Save the current state of the terminal, and set raw mode.
     */
    if (tcgetattr(0, &tty_rmode) , 0) {
	fprintf(stderr, "Cannot get terminals current mode\n");
	exit(-1);
    }
    tty_smode = tty_rmode;
    tty_eof = '\004'; /* Ctrl+D to exit */
#ifdef DEBUG
    show_terminal_settings(&tty_rmode);
#endif
    tty_smode.c_iflag =
	1*BRKINT |/*Signal interrupt on break.*/
        1*IGNPAR |/*Ignore characters with parity errors.*/
        0;

#if 0
0*IGNBRK |/*Ignore break condition.*/
0*PARMRK |/*Mark parity errors.*/
0*INPCK  |/*Enable input parity check.*/
0*INLCR  |/*Map NL to CR on input.*/
0*IGNCR  |/*Ignore CR.*/
0*ICRNL  |/*Map CR to NL on input.*/
0*IUCLC  |/*Map upper-case to lower-case on input.*/
0*IXON   |/*Enable start/stop output control.*/
0*IXANY  |/*Enable any character to restart output.*/
0*IXOFF  |/*Enable start/stop input control.*/
0*IMAXBEL|/*Echo BEL on input line too long.*/
#endif

    tty_smode.c_oflag =
    OPOST    |/*Post-process output.*/
    0*ONLCR  |/*Map NL to CR-NL on output.*/
#ifdef XTABS
    1*XTABS  |/*Expand tabs to spaces. (Linux)*/
#endif
#ifdef OXTABS
    1*OXTABS |/*Expand tabs to spaces. (FreeBSD)*/
#endif
#ifdef NL0
    1*NL0    |/*Select newline delays*/
#endif
#ifdef CR0
    1*CR0    |/*Select carriage-return delays*/
#endif
#ifdef TAB0
    1*TAB0   |/*Select horizontal tab delays*/
#endif
#ifdef BS0
    1*BS0    |/*Select backspace delays*/
#endif
#ifdef VT0
    1*VT0    |/*Select vertical tab delays*/
#endif
#ifdef FF0
    1*FF0    |/*Select form feed delays*/
#endif
											    0;

#if 0
0*OLCUC  |/*Map lower case to upper on output.*/
0*OCRNL  |/*Map CR to NL on output.*/
0*ONOCR  |/*No CR output at column 0.*/
0*ONLRET |/*NL performs CR function.*/
0*OFILL  |/*Use fill characters for delay.*/
0*OFDEL  |/*Fill is DEL, else NULL.*/
0*NL1    |
0*CR1    |
0*CR2    |
0*CR3    |
0*TAB1   |
0*TAB2   |
0*TAB3   |/*Expand tabs to spaces.*/
0*BS1    |
0*VT1    |
0*FF1    |
#endif

    /* JALI: removed setting the tty_smode.c_cflag flags, since this is not */
    /* advisable if this is a *real* terminal, such as the console. In fact */
    /* this may hang the entire machine, deep, deep down (signalling break */
    /* or toggling the abort switch doesn't help) */

    tty_smode.c_lflag =
									0;

#if 0
0*ISIG   |/*Enable signals.*/
0*ICANON |/*Canonical input (erase and kill processing).*/
0*XCASE  |/*Canonical upper/lower presentation.*/
0*ECHO   |/*Enable echo.*/
0*ECHOE  |/*Echo erase character as BS-SP-BS.*/
0*ECHOK  |/*Echo NL after kill character.*/
0*ECHONL |/*Echo NL.*/
0*NOFLSH |/*Disable flush after interrupt or quit.*/
0*TOSTOP |/*Send SIGTTOU for background output.*/
0*ECHOCTL|/*Echo control characters as ^char, delete as ^?.*/
0*ECHOPRT|/*Echo erase character as character erased.*/
0*ECHOKE |/*BS-SP-BS erase entire line on line kill.*/
0*FLUSHO |/*Output is being flushed.*/
0*PENDIN |/*Retype pending input at next read or input character.*/
0*IEXTEN |/*Enable extended (implementation-defined) functions.*/
#endif

    tty_smode.c_cc[VMIN]      =0;/* Note that VMIN is the same as VEOF! */
    tty_smode.c_cc[VTIME]     =0;/* Note that VTIME is the same as VEOL! */
    tty_smode.c_cc[VINTR]     =3;

    tcsetattr(0, TCSADRAIN, &tty_smode);

#ifdef DEBUG
    show_terminal_settings(&tty_smode);
#endif
    /*
     * 	 "Write a ^L to the FIFO which causes the other end to redisplay
     *    the input line."
     * This does not seem to work as was intended in old comment above.
     * However, this control character is now (R12B-3) used by run_erl
     * to trigger the version handshaking between to_erl and run_erl
     * at the start of every new to_erl-session.
     */

    if (write(wfd, "\014", 1) < 0) {
	fprintf(stderr, "Error in writing ^L to FIFO.\n");
    }

    /*
     * read and write
     */
    while (1) {
	FD_ZERO(&readfds);
	FD_SET(0, &readfds);
	FD_SET(rfd, &readfds);
	if (select(rfd + 1, &readfds, NULL, NULL, NULL) < 0) {
	    if (recv_sig) {
		FD_ZERO(&readfds);
	    }
	    else {
		fprintf(stderr, "Error in select.\n");
		break;
	    }
	}
	len = 0;

	/*
	 * Read from terminal and write to FIFO
         */
	if (recv_sig) {
	    switch (recv_sig) {
	    case SIGINT:
		fprintf(stderr, "[Break]\n\r");
		buf[0] = '\003';
		len = 1;
		break;
	    case SIGWINCH:
		len = window_size_seq(buf,sizeof(buf));
		break;
	    default:
		fprintf(stderr,"Unexpected signal: %u\n",recv_sig);
	    }
	    recv_sig = 0;
	}
	else if (FD_ISSET(0, &readfds)) {
	    len = read(0, buf, sizeof(buf));
	    if (len <= 0) {
		close(rfd);
		close(wfd);
		if (len < 0) {
		    fprintf(stderr, "Error in reading from stdin.\n");
		} else {
		    fprintf(stderr, "[EOF]\n\r");
		}
		break;
	    }
	    /* check if there is an eof character in input */
	    for (i = 0; i < len && buf[i] != tty_eof; i++);
	    if (buf[i] == tty_eof) {
		fprintf(stderr, "[Quit]\n\r");
		break;
	    }
	}

	if (len) {
#ifdef DEBUG
	    write_all(1, buf, len);
#endif
	    if (write_all(wfd, buf, len) != len) {
		fprintf(stderr, "Error in writing to FIFO.\n");
		close(rfd);
		close(wfd);
		break;
	    }
	    STATUS("\" OK\r\n");
	}

	/*
	 * Read from FIFO, write to terminal.
	 */
	if (FD_ISSET(rfd, &readfds)) {
	    STATUS("FIFO read: ");
	    len = read(rfd, buf, BUFSIZ);
	    if (len < 0 && errno == EAGAIN) {
		/*
		 * No data this time, but the writing end of the FIFO is still open.
		 * Do nothing.
		 */
		;
	    } else if (len <= 0) {
		/*
		 * Either an error or end of file. In either case, break out
		 * of the loop.
		 */
		close(rfd);
		close(wfd);
		if (len < 0) {
		    fprintf(stderr, "Error in reading from FIFO.\n");
		} else
		    fprintf(stderr, "[End]\n\r");
		break;
	    } else {
		if (!got_some) {
		    if ((len=version_handshake(buf,len,wfd)) < 0) {
			close(rfd);
			close(wfd);
			break;
		    }
		    if (protocol_ver >= 1) {
			/* Tell run_erl size of terminal window */
			signal(SIGWINCH, handle_sigwinch);
			raise(SIGWINCH);
		    }
		    got_some = 1;
		}

		/*
		 * We successfully read at least one character. Write what we got.
		 */
		STATUS("Terminal write: \"");
		if (write_all(1, buf, len) != len) {
		    fprintf(stderr, "Error in writing to terminal.\n");
		    close(rfd);
		    close(wfd);
		    break;
		}
		STATUS("\" OK\r\n");
	    }
	}
    }

    /*
     * Reset terminal characterstics
     * XXX
     */
    tcsetattr(0, TCSADRAIN, &tty_rmode);
    return 0;
}

/* Call write() until entire buffer has been written or error.
 * Return len or -1.
 */
static int write_all(int fd, const char* buf, int len)
{
    int left = len;
    int written;
    while (left) {
	written = write(fd,buf,left);
	if (written < 0) {
	    return -1;
	}
	left -= written;
	buf += written;
    }
    return len;
}

static int window_size_seq(char* buf, size_t bufsz)
{
#ifdef TIOCGWINSZ
    struct winsize ws;
    static const char prefix[] = "\033_";
    static const char suffix[] = "\033\\";
    /* This Esc sequence is called "Application Program Command"
       and seems suitable to use for our own customized stuff. */

    if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == 0) {
	int len = sn_printf(buf, bufsz, "%swinsize=%u,%u%s",
			    prefix, ws.ws_col, ws.ws_row, suffix);
	return len;
    }
#endif /* TIOCGWINSZ */
    return 0;
}

/*   to_erl                     run_erl
 *     |                           |
 *     |---------- '\014' -------->| (session start)
 *     |                           |
 *     |<---- "[run_erl v1-0]" ----| (version interval)
 *     |                           |
 *     |--- Esc_"version=1"Esc\ -->| (common version)
 *     |                           |
 */
static int version_handshake(char* buf, int len, int wfd)
{
    unsigned re_high=0, re_low;
    char *end = find_str(buf,len,"]\n");

    if (end && sscanf(buf,"[run_erl v%u-%u",&re_high,&re_low)==2) {
	char wbuf[30];
	int wlen;

	if (re_low > RUN_ERL_HI_VER || re_high < RUN_ERL_LO_VER) {
	    fprintf(stderr,"Incompatible versions: to_erl=v%u-%u run_erl=v%u-%u\n",
		    RUN_ERL_HI_VER, RUN_ERL_LO_VER, re_high, re_low);
	    return -1;
	}
	/* Choose highest common version */
	protocol_ver = re_high < RUN_ERL_HI_VER ? re_high : RUN_ERL_HI_VER;

	wlen = sn_printf(wbuf, sizeof(wbuf), "\033_version=%u\033\\",
			 protocol_ver);
	if (write_all(wfd, wbuf, wlen) < 0) {
	    fprintf(stderr,"Failed to send version handshake\n");
	    return -1;
	}
	end += 2;
	len -= (end-buf);
	memmove(buf,end,len);

    }
    else {  /* we assume old run_erl without version handshake */
	protocol_ver = 0;
    }

    if (re_high != RUN_ERL_HI_VER) {
	fprintf(stderr,"run_erl has different version, "
		"using common protocol level %u\n", protocol_ver);
    }

    return len;
}

#ifdef DEBUG
#define S(x)  ((x) > 0 ? 1 : 0)

static void show_terminal_settings(struct termios *t)
{
  fprintf(stderr,"c_iflag:\n");
  fprintf(stderr,"Signal interrupt on break:   BRKINT  %d\n", S(t->c_iflag & BRKINT));
  fprintf(stderr,"Map CR to NL on input:       ICRNL   %d\n", S(t->c_iflag & ICRNL));
  fprintf(stderr,"Ignore break condition:      IGNBRK  %d\n", S(t->c_iflag & IGNBRK));
  fprintf(stderr,"Ignore CR:                   IGNCR   %d\n", S(t->c_iflag & IGNCR));
  fprintf(stderr,"Ignore char with par. err's: IGNPAR  %d\n", S(t->c_iflag & IGNPAR));
  fprintf(stderr,"Map NL to CR on input:       INLCR   %d\n", S(t->c_iflag & INLCR));
  fprintf(stderr,"Enable input parity check:   INPCK   %d\n", S(t->c_iflag & INPCK));
  fprintf(stderr,"Strip character              ISTRIP  %d\n", S(t->c_iflag & ISTRIP));
  fprintf(stderr,"Enable start/stop input ctrl IXOFF   %d\n", S(t->c_iflag & IXOFF));
  fprintf(stderr,"ditto output ctrl            IXON    %d\n", S(t->c_iflag & IXON));
  fprintf(stderr,"Mark parity errors           PARMRK  %d\n", S(t->c_iflag & PARMRK));
  fprintf(stderr,"\n");
  fprintf(stderr,"c_oflag:\n");
  fprintf(stderr,"Perform output processing    OPOST   %d\n", S(t->c_oflag & OPOST));
  fprintf(stderr,"\n");
  fprintf(stderr,"c_cflag:\n");
  fprintf(stderr,"Ignore modem status lines    CLOCAL  %d\n", S(t->c_cflag & CLOCAL));
  fprintf(stderr,"\n");
  fprintf(stderr,"c_local:\n");
  fprintf(stderr,"Enable echo                  ECHO    %d\n", S(t->c_lflag & ECHO));
  fprintf(stderr,"\n");
  fprintf(stderr,"c_cc:\n");
  fprintf(stderr,"c_cc[VEOF]                           %d\n", t->c_cc[VEOF]);
}
#endif


text:
package org.apache.usergrid.security.salt;

import java.util.UUID;

/**
 * Salt provider that does not return a salt
 *
 * @author tnine
 */
public class NoOpSaltProvider implements SaltProvider {

    /* (non-Javadoc)
     * @see org.apache.usergrid.security.salt.SaltProvider#getSalt(java.util.UUID, java.util.UUID)
     */
    @Override
    public String getSalt( UUID applicationId, UUID userId ) {
        return "";
    }
}


text:
module Musicality
module Parsing

module Key
  include Treetop::Runtime

  def root
    @root ||= :key
  end

  include Pitch

  module Key0
    def pitch_letter
      elements[0]
    end

    def mod
      elements[1]
    end

    def major_minor
      elements[2]
    end
  end

  module Key1
    def to_key
      sem = pitch_letter.to_semitone
      modval = 0
      if !mod.empty?
        modval = case mod.text_value
        when "#" then 1
        when "b" then -1
        end
      end

      triad_type = if major_minor.text_value.include?("maj")
        Musicality::Key::MAJOR
      else
        Musicality::Key::MINOR
      end

      return Musicality::Key.new(sem + modval, triad_type: triad_type)
    end
  end

  def _nt_key
    start_index = index
    if node_cache[:key].has_key?(index)
      cached = node_cache[:key][index]
      if cached
        node_cache[:key][index] = cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
        @index = cached.interval.end
      end
      return cached
    end

    i0, s0 = index, []
    r1 = _nt_pitch_letter
    s0 << r1
    if r1
      if has_terminal?(@regexps[gr = '\A[#b]'] ||= Regexp.new(gr), :regexp, index)
        r3 = true
        @index += 1
      else
        terminal_parse_failure('[#b]')
        r3 = nil
      end
      if r3
        r2 = r3
      else
        r2 = instantiate_node(SyntaxNode,input, index...index)
      end
      s0 << r2
      if r2
        r4 = _nt_major_minor
        s0 << r4
      end
    end
    if s0.last
      r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
      r0.extend(Key0)
      r0.extend(Key1)
    else
      @index = i0
      r0 = nil
    end

    node_cache[:key][start_index] = r0

    r0
  end

  def _nt_major_minor
    start_index = index
    if node_cache[:major_minor].has_key?(index)
      cached = node_cache[:major_minor][index]
      if cached
        node_cache[:major_minor][index] = cached = SyntaxNode.new(input, index...(index + 1)) if cached == true
        @index = cached.interval.end
      end
      return cached
    end

    i0 = index
    if (match_len = has_terminal?("maj", false, index))
      r1 = instantiate_node(SyntaxNode,input, index...(index + match_len))
      @index += match_len
    else
      terminal_parse_failure('"maj"')
      r1 = nil
    end
    if r1
      r1 = SyntaxNode.new(input, (index-1)...index) if r1 == true
      r0 = r1
    else
      if (match_len = has_terminal?("min", false, index))
        r2 = instantiate_node(SyntaxNode,input, index...(index + match_len))
        @index += match_len
      else
        terminal_parse_failure('"min"')
        r2 = nil
      end
      if r2
        r2 = SyntaxNode.new(input, (index-1)...index) if r2 == true
        r0 = r2
      else
        @index = i0
        r0 = nil
      end
    end

    node_cache[:major_minor][start_index] = r0

    r0
  end

end

class KeyParser < Treetop::Runtime::CompiledParser
  include Key
end

end
end


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Database\Driver\pgsql\Delete.
 */

namespace Drupal\Core\Database\Driver\pgsql;

use Drupal\Core\Database\Query\Delete as QueryDelete;

/**
 * PostgreSQL implementation of \Drupal\Core\Database\Query\Delete.
 */
class Delete extends QueryDelete {

  /**
   * {@inheritdoc}
   */
  public function execute() {
    $this->connection->addSavepoint();
    try {
      $result = parent::execute();
    }
    catch (\Exception $e) {
      $this->connection->rollbackSavepoint();
      throw $e;
    }
    $this->connection->releaseSavepoint();

    return $result;
  }

}


text:
from mock import Mock

from allura.lib import helpers as h
from tg import tmpl_context as c
from forgetracker.tracker_main import MilestoneController

def test_unicode_lookup():
    # can't use name= in constructor, that's special attribute for Mock
    milestone = Mock()
    milestone.name = 'Перспектива'
    milestone_field = Mock(milestones=[milestone])
    milestone_field.name = '_milestone'

    app = Mock(globals=Mock(milestone_fields=[milestone_field]))

    with h.push_config(c, app=app):
        root = None
        field = 'milestone'
        # u'Перспектива'
        milestone_urlparam = '%D0%9F%D0%B5%D1%80%D1%81%D0%BF%D0%B5%D0%BA%D1%82%D0%B8%D0%B2%D0%B0'
        mc = MilestoneController(root, field, milestone_urlparam)

    assert mc.milestone  # check that it is found
    assert mc.milestone.name == 'Перспектива'


text:
cask "fsnotes" do
  version "4.7.1"
  sha256 "53d7b3dc4db871dbe7a7c447008b4e1bea90f7e9feb04a5a07773cf4ff0d8b78"

  # github.com/glushchenko/fsnotes/ was verified as official when first introduced to the cask
  url "https://github.com/glushchenko/fsnotes/releases/download/#{version}/FSNotes_#{version}.zip"
  appcast "https://github.com/glushchenko/fsnotes/releases.atom"
  name "FSNotes"
  desc "Notes manager"
  homepage "https://fsnot.es/"

  app "FSNotes.app"

  zap trash: [
    "~/Library/Application Scripts/co.fluder.FSNotes",
    "~/Library/Containers/co.fluder.FSNotes",
  ]
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="keyline_one">16dp</dimen>
    <dimen name="keyline_two">72dp</dimen>

    <dimen name="btn_size">56dp</dimen>
    <dimen name="btn_container_width">72dp</dimen>
    <dimen name="btn_container_height">216dp</dimen>
    <dimen name="ad_view_height">50dp</dimen>

    <dimen name="arrow_size">128dp</dimen>

    <dimen name="fab_bottom_margin">0dp</dimen>
    <dimen name="fab_borderwidth">0dp</dimen>
    <dimen name="fab_elevation">0dp</dimen>
</resources>


text:
title: '**Hank Phillippi Ryan** -  *Say No More: A Jane Ryland Novel*'
published: true
start_at: 2016-11-01 19:00:00
image_path:
book_category:
program: '-writers-and-readers'
ticketed: false
test:
book_isbn:
  - '9780765385352'
---

Working on an exposé of sexual assaults on college campuses, reporter Jane Ryland has just convinced a date rape victim to reveal her heartbreaking experience on camera. However, a disturbing anonymous message―SAY NO MORE―has Jane scared, and starts a quest with her homicide detective boyfriend, Jake, to balance the consequences of the truth.


text:
div.dataTables_length label {
    width: 460px;
    float: left;
    text-align: left;
}

div.dataTables_length select {
    width: 75px;
}

div.dataTables_filter label {
    float: right;
    width: 460px;
}

div.dataTables_info {
    padding-top: 8px;
}

div.dataTables_paginate {
    float: right;
    margin: 0;
}

table {
    margin: 1em 0;
    clear: both;
}


text:
if [ "${TRAVIS_PULL_REQUEST}" = "false" ]; then
    echo '$TRAVIS_PULL_REQUEST is false, running tests and publishing'
    ./gradlew clean test bintrayUpload -x distTar -x distZip -Pbuild=${TRAVIS_BUILD_NUMBER} -Prelease=2.0
else
    echo '$TRAVIS_PULL_REQUEST is not false ($TRAVIS_PULL_REQUEST), running just tests and skipping publish'
    ./gradlew clean test
fi


text:
<?php

namespace Graze\Gigya\Validation;

use Graze\Gigya\Exception\InvalidTimestampException;
use Graze\Gigya\Exception\InvalidUidSignatureException;
use Graze\Gigya\Response\ResponseInterface;

/**
 * Class UidSignatureValidator.
 */
class UidSignatureValidator implements ResponseValidatorInterface
{
    /**
     * @var string
     */
    private $secret;

    /**
     * @var Signature
     */
    private $signature;

    /**
     * @param Signature $signature
     * @param string    $secret
     */
    public function __construct(Signature $signature, $secret)
    {
        $this->secret    = $secret;
        $this->signature = $signature;
    }

    /**
     * Can validate.
     *
     * @param ResponseInterface $response
     *
     * @return bool
     */
    public function canValidate(ResponseInterface $response)
    {
        $data = $response->getData();

        return ($data->has('UID') &&
            $data->has('UIDSignature') &&
            $data->has('signatureTimestamp'));
    }

    /**
     * Throws exceptions if any errors are found.
     *
     * @param ResponseInterface $response
     *
     * @return bool
     */
    public function validate(ResponseInterface $response)
    {
        $data = $response->getData();

        return $this->validateUid(
            $data->get('UID'),
            $data->get('signatureTimestamp'),
            $data->get('UIDSignature')
        );
    }

    /**
     * @param ResponseInterface $response
     *
     * @throws InvalidTimestampException
     * @throws InvalidUidSignatureException
     *
     * @return void
     */
    public function assert(ResponseInterface $response)
    {
        $data = $response->getData();

        $this->assertUid(
            $data->get('UID'),
            $data->get('signatureTimestamp'),
            $data->get('UIDSignature'),
            $response
        );
    }

    /**
     * Validate the provided Uid signature is valid.
     *
     * @param string $uid
     * @param int    $timestamp Unix Timestamp
     * @param string $signature
     *
     * @return bool
     */
    public function validateUid($uid, $timestamp, $signature)
    {
        return ($this->signature->checkTimestamp($timestamp) &&
            $signature == $this->signature->getUidSignature($uid, $timestamp, $this->secret));
    }

    /**
     * @param string            $uid
     * @param int               $timestamp Unix Timestamp
     * @param string            $signature
     * @param ResponseInterface $response
     *
     * @throws InvalidTimestampException
     * @throws InvalidUidSignatureException
     *
     * @return bool
     */
    private function assertUid($uid, $timestamp, $signature, ResponseInterface $response)
    {
        if (!$this->signature->checkTimestamp($timestamp)) {
            throw new InvalidTimestampException($timestamp, $response);
        }
        $expected = $this->signature->getUidSignature($uid, $timestamp, $this->secret);
        if ($signature !== $expected) {
            throw new InvalidUidSignatureException($uid, $expected, $signature, $response);
        }

        return true;
    }
}