text:
package com.xinqihd.sns.gameserver.proto;

public final class XinqiBceMailDelete {
  private XinqiBceMailDelete() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
  }
  public interface BceMailDeleteOrBuilder
      extends com.google.protobuf.MessageOrBuilder {

    // optional int32 type = 1;
    boolean hasType();
    int getType();

    // repeated int32 deleteIndexes = 2;
    java.util.List<java.lang.Integer> getDeleteIndexesList();
    int getDeleteIndexesCount();
    int getDeleteIndexes(int index);
  }
  public static final class BceMailDelete extends
      com.google.protobuf.GeneratedMessage
      implements BceMailDeleteOrBuilder {
    // Use BceMailDelete.newBuilder() to construct.
    private BceMailDelete(Builder builder) {
      super(builder);
    }
    private BceMailDelete(boolean noInit) {}

    private static final BceMailDelete defaultInstance;
    public static BceMailDelete getDefaultInstance() {
      return defaultInstance;
    }

    public BceMailDelete getDefaultInstanceForType() {
      return defaultInstance;
    }

    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.internal_static_com_xinqihd_sns_gameserver_proto_BceMailDelete_descriptor;
    }

    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.internal_static_com_xinqihd_sns_gameserver_proto_BceMailDelete_fieldAccessorTable;
    }

    private int bitField0_;
    // optional int32 type = 1;
    public static final int TYPE_FIELD_NUMBER = 1;
    private int type_;
    public boolean hasType() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    public int getType() {
      return type_;
    }

    // repeated int32 deleteIndexes = 2;
    public static final int DELETEINDEXES_FIELD_NUMBER = 2;
    private java.util.List<java.lang.Integer> deleteIndexes_;
    public java.util.List<java.lang.Integer>
        getDeleteIndexesList() {
      return deleteIndexes_;
    }
    public int getDeleteIndexesCount() {
      return deleteIndexes_.size();
    }
    public int getDeleteIndexes(int index) {
      return deleteIndexes_.get(index);
    }

    private void initFields() {
      type_ = 0;
      deleteIndexes_ = java.util.Collections.emptyList();;
    }
    private byte memoizedIsInitialized = -1;
    public final boolean isInitialized() {
      byte isInitialized = memoizedIsInitialized;
      if (isInitialized != -1) return isInitialized == 1;

      memoizedIsInitialized = 1;
      return true;
    }

    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      getSerializedSize();
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        output.writeInt32(1, type_);
      }
      for (int i = 0; i < deleteIndexes_.size(); i++) {
        output.writeInt32(2, deleteIndexes_.get(i));
      }
      getUnknownFields().writeTo(output);
    }

    private int memoizedSerializedSize = -1;
    public int getSerializedSize() {
      int size = memoizedSerializedSize;
      if (size != -1) return size;

      size = 0;
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        size += com.google.protobuf.CodedOutputStream
          .computeInt32Size(1, type_);
      }
      {
        int dataSize = 0;
        for (int i = 0; i < deleteIndexes_.size(); i++) {
          dataSize += com.google.protobuf.CodedOutputStream
            .computeInt32SizeNoTag(deleteIndexes_.get(i));
        }
        size += dataSize;
        size += 1 * getDeleteIndexesList().size();
      }
      size += getUnknownFields().getSerializedSize();
      memoizedSerializedSize = size;
      return size;
    }

    private static final long serialVersionUID = 0L;
    @java.lang.Override
    protected java.lang.Object writeReplace()
        throws java.io.ObjectStreamException {
      return super.writeReplace();
    }

    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseFrom(
        com.google.protobuf.ByteString data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return newBuilder().mergeFrom(data).buildParsed();
    }
    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseFrom(
        com.google.protobuf.ByteString data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return newBuilder().mergeFrom(data, extensionRegistry)
               .buildParsed();
    }
    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseFrom(byte[] data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return newBuilder().mergeFrom(data).buildParsed();
    }
    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseFrom(
        byte[] data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return newBuilder().mergeFrom(data, extensionRegistry)
               .buildParsed();
    }
    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseFrom(java.io.InputStream input)
        throws java.io.IOException {
      return newBuilder().mergeFrom(input).buildParsed();
    }
    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return newBuilder().mergeFrom(input, extensionRegistry)
               .buildParsed();
    }
    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseDelimitedFrom(java.io.InputStream input)
        throws java.io.IOException {
      Builder builder = newBuilder();
      if (builder.mergeDelimitedFrom(input)) {
        return builder.buildParsed();
      } else {
        return null;
      }
    }
    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseDelimitedFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      Builder builder = newBuilder();
      if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
        return builder.buildParsed();
      } else {
        return null;
      }
    }
    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseFrom(
        com.google.protobuf.CodedInputStream input)
        throws java.io.IOException {
      return newBuilder().mergeFrom(input).buildParsed();
    }
    public static com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete parseFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return newBuilder().mergeFrom(input, extensionRegistry)
               .buildParsed();
    }

    public static Builder newBuilder() { return Builder.create(); }
    public Builder newBuilderForType() { return newBuilder(); }
    public static Builder newBuilder(com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete prototype) {
      return newBuilder().mergeFrom(prototype);
    }
    public Builder toBuilder() { return newBuilder(this); }

    @java.lang.Override
    protected Builder newBuilderForType(
        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
      Builder builder = new Builder(parent);
      return builder;
    }
    public static final class Builder extends
        com.google.protobuf.GeneratedMessage.Builder<Builder>
       implements com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDeleteOrBuilder {
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.internal_static_com_xinqihd_sns_gameserver_proto_BceMailDelete_descriptor;
      }

      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
          internalGetFieldAccessorTable() {
        return com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.internal_static_com_xinqihd_sns_gameserver_proto_BceMailDelete_fieldAccessorTable;
      }

      // Construct using com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete.newBuilder()
      private Builder() {
        maybeForceBuilderInitialization();
      }

      private Builder(BuilderParent parent) {
        super(parent);
        maybeForceBuilderInitialization();
      }
      private void maybeForceBuilderInitialization() {
        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
        }
      }
      private static Builder create() {
        return new Builder();
      }

      public Builder clear() {
        super.clear();
        type_ = 0;
        bitField0_ = (bitField0_ & ~0x00000001);
        deleteIndexes_ = java.util.Collections.emptyList();;
        bitField0_ = (bitField0_ & ~0x00000002);
        return this;
      }

      public Builder clone() {
        return create().mergeFrom(buildPartial());
      }

      public com.google.protobuf.Descriptors.Descriptor
          getDescriptorForType() {
        return com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete.getDescriptor();
      }

      public com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete getDefaultInstanceForType() {
        return com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete.getDefaultInstance();
      }

      public com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete build() {
        com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(result);
        }
        return result;
      }

      private com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete buildParsed()
          throws com.google.protobuf.InvalidProtocolBufferException {
        com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(
            result).asInvalidProtocolBufferException();
        }
        return result;
      }

      public com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete buildPartial() {
        com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete result = new com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete(this);
        int from_bitField0_ = bitField0_;
        int to_bitField0_ = 0;
        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
          to_bitField0_ |= 0x00000001;
        }
        result.type_ = type_;
        if (((bitField0_ & 0x00000002) == 0x00000002)) {
          deleteIndexes_ = java.util.Collections.unmodifiableList(deleteIndexes_);
          bitField0_ = (bitField0_ & ~0x00000002);
        }
        result.deleteIndexes_ = deleteIndexes_;
        result.bitField0_ = to_bitField0_;
        onBuilt();
        return result;
      }

      public Builder mergeFrom(com.google.protobuf.Message other) {
        if (other instanceof com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete) {
          return mergeFrom((com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete)other);
        } else {
          super.mergeFrom(other);
          return this;
        }
      }

      public Builder mergeFrom(com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete other) {
        if (other == com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete.getDefaultInstance()) return this;
        if (other.hasType()) {
          setType(other.getType());
        }
        if (!other.deleteIndexes_.isEmpty()) {
          if (deleteIndexes_.isEmpty()) {
            deleteIndexes_ = other.deleteIndexes_;
            bitField0_ = (bitField0_ & ~0x00000002);
          } else {
            ensureDeleteIndexesIsMutable();
            deleteIndexes_.addAll(other.deleteIndexes_);
          }
          onChanged();
        }
        this.mergeUnknownFields(other.getUnknownFields());
        return this;
      }

      public final boolean isInitialized() {
        return true;
      }

      public Builder mergeFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        com.google.protobuf.UnknownFieldSet.Builder unknownFields =
          com.google.protobuf.UnknownFieldSet.newBuilder(
            this.getUnknownFields());
        while (true) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              this.setUnknownFields(unknownFields.build());
              onChanged();
              return this;
            default: {
              if (!parseUnknownField(input, unknownFields,
                                     extensionRegistry, tag)) {
                this.setUnknownFields(unknownFields.build());
                onChanged();
                return this;
              }
              break;
            }
            case 8: {
              bitField0_ |= 0x00000001;
              type_ = input.readInt32();
              break;
            }
            case 16: {
              ensureDeleteIndexesIsMutable();
              deleteIndexes_.add(input.readInt32());
              break;
            }
            case 18: {
              int length = input.readRawVarint32();
              int limit = input.pushLimit(length);
              while (input.getBytesUntilLimit() > 0) {
                addDeleteIndexes(input.readInt32());
              }
              input.popLimit(limit);
              break;
            }
          }
        }
      }

      private int bitField0_;

      // optional int32 type = 1;
      private int type_ ;
      public boolean hasType() {
        return ((bitField0_ & 0x00000001) == 0x00000001);
      }
      public int getType() {
        return type_;
      }
      public Builder setType(int value) {
        bitField0_ |= 0x00000001;
        type_ = value;
        onChanged();
        return this;
      }
      public Builder clearType() {
        bitField0_ = (bitField0_ & ~0x00000001);
        type_ = 0;
        onChanged();
        return this;
      }

      // repeated int32 deleteIndexes = 2;
      private java.util.List<java.lang.Integer> deleteIndexes_ = java.util.Collections.emptyList();;
      private void ensureDeleteIndexesIsMutable() {
        if (!((bitField0_ & 0x00000002) == 0x00000002)) {
          deleteIndexes_ = new java.util.ArrayList<java.lang.Integer>(deleteIndexes_);
          bitField0_ |= 0x00000002;
         }
      }
      public java.util.List<java.lang.Integer>
          getDeleteIndexesList() {
        return java.util.Collections.unmodifiableList(deleteIndexes_);
      }
      public int getDeleteIndexesCount() {
        return deleteIndexes_.size();
      }
      public int getDeleteIndexes(int index) {
        return deleteIndexes_.get(index);
      }
      public Builder setDeleteIndexes(
          int index, int value) {
        ensureDeleteIndexesIsMutable();
        deleteIndexes_.set(index, value);
        onChanged();
        return this;
      }
      public Builder addDeleteIndexes(int value) {
        ensureDeleteIndexesIsMutable();
        deleteIndexes_.add(value);
        onChanged();
        return this;
      }
      public Builder addAllDeleteIndexes(
          java.lang.Iterable<? extends java.lang.Integer> values) {
        ensureDeleteIndexesIsMutable();
        super.addAll(values, deleteIndexes_);
        onChanged();
        return this;
      }
      public Builder clearDeleteIndexes() {
        deleteIndexes_ = java.util.Collections.emptyList();;
        bitField0_ = (bitField0_ & ~0x00000002);
        onChanged();
        return this;
      }

      // @@protoc_insertion_point(builder_scope:com.xinqihd.sns.gameserver.proto.BceMailDelete)
    }

    static {
      defaultInstance = new BceMailDelete(true);
      defaultInstance.initFields();
    }

    // @@protoc_insertion_point(class_scope:com.xinqihd.sns.gameserver.proto.BceMailDelete)
  }

  private static com.google.protobuf.Descriptors.Descriptor
    internal_static_com_xinqihd_sns_gameserver_proto_BceMailDelete_descriptor;
  private static
    com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internal_static_com_xinqihd_sns_gameserver_proto_BceMailDelete_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n\023BceMailDelete.proto\022 com.xinqihd.sns.g" +
      "ameserver.proto\032\016MailData.proto\"4\n\rBceMa" +
      "ilDelete\022\014\n\004type\030\001 \001(\005\022\025\n\rdeleteIndexes\030" +
      "\002 \003(\005B\024B\022XinqiBceMailDelete"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
      new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
        public com.google.protobuf.ExtensionRegistry assignDescriptors(
            com.google.protobuf.Descriptors.FileDescriptor root) {
          descriptor = root;
          internal_static_com_xinqihd_sns_gameserver_proto_BceMailDelete_descriptor =
            getDescriptor().getMessageTypes().get(0);
          internal_static_com_xinqihd_sns_gameserver_proto_BceMailDelete_fieldAccessorTable = new
            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
              internal_static_com_xinqihd_sns_gameserver_proto_BceMailDelete_descriptor,
              new java.lang.String[] { "Type", "DeleteIndexes", },
              com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete.class,
              com.xinqihd.sns.gameserver.proto.XinqiBceMailDelete.BceMailDelete.Builder.class);
          return null;
        }
      };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          com.xinqihd.sns.gameserver.proto.XinqiMailData.getDescriptor(),
        }, assigner);
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
========================
Mojito and npm Packaging
========================

.. _mojito_package-overview:

Overview
========

Having installed Mojito with npm 1.0, you already understand that Mojito is an
npm package. What may not be as clear is that Mojito applications are also npm
packages. Being an npm package, Mojito applications can have their own
dependencies that are installed using npm. For example, after you create a
Mojito application, you can use npm to install a local copy of the Mojito
framework in the ``node_modules`` directory. If you deployed your application
to a cloud server that has a Node.js runtime environment, your application
could be run by this locally installed copy of the Mojito
framework.

Your Mojito application can also install other npm modules, even those that
contain Mojito resources, such as mojits or middleware. Conversely, you can
create npm modules that contain Mojito resources, so other developers can
reuse your code.

Because npm allows you to use other modules or create your own, this chapter
is divided into two sections to meet the needs of the following two audiences:

- :ref:`developers using shared mojits <using_shared_mojits>`
- :ref:`authors creating npm modules that contain shared Mojito resources <author_npm_mod_shared_mojito_resource>`

.. _package_overview-resource:

Mojito Resources
----------------

A *Mojito resource* is a piece of code or functionality used by Mojito. These
resources can be installed with npm or live directly in the Mojito application.
Examples of Mojito resources could be shared mojits and middleware. Developers
using shared mojits and those authoring npm modules that contain code used by
Mojito should be familiar with the meaning of *Mojito resource* as it will be
used throughout this chapter.

.. _using_shared_mojits:

Using Shared Mojits
===================

Mojito applications can have any number of different resources installed with
npm. Each of these resources should be specified in the  package descriptor
file ``package.json`` of the Mojito application. When users run ``npm install``
in the application directory, npm modules containing Mojito resources and
those not containing Mojito resources will be installed into the
``node_modules`` directory. Your Mojito application will have access to
all of the installed npm modules as soon as the application starts.

For details about npm packages, see the
`npm's package.json handling <http://npmjs.org/doc/json.html>`_.

.. _process_spec_install_dependencies:

General Process of Using Shared Mojits
--------------------------------------

The following steps are just a guideline and not definitive instructions.
Your application may not need to install any npm modules.

#. Create a Mojito application.
#. Add any needed dependencies to ``dependencies`` object in ``package.json``.
#. Install dependencies with npm.

   ``{app_dir}$ npm install``
#. When Mojito starts, your application will have access to the installed
   npm modules.

.. _process_spec_install_dependencies_ex:

Example package.json
####################

The dependencies include Mojito, the ``async`` module, and the shared mojit
``form_mojit`` (example) that will be installed in ``node_modules`` when you
run ``npm install`` from the Mojito application directory.

.. code-block:: javascript

   {
      "name": "helloworld",
      "description": "My Mojito application",
      "version": "0.0.1",
      "author": {
        "name": "Your Name",
        "email": "nobody@yahoo-inc.com"
      },
      "contributors": [
        {
          "name": "Your Name",
          "email": "nobody@yahoo-inc.com"
        }
      ],
      "dependencies": {
        "mojito": ">= 0.3.0",
        "async": "~0.1",
        "form_mojit" : "1.x"
      },
      "engines": {
        "node": ">=0.4.5"
      },
      "scripts": {
        "start": "mojito start"
      }
   }

.. _author_npm_mod_shared_mojito_resource:

Authoring an npm Module Containing Shared Mojito Resources
==========================================================

Developers who have created Mojito resources that they would like to share with
others can package the Mojito resources in an npm module. The npm module is
simply a container for the Mojito resource(s). The npm module must specify that
it contains a Mojito resource in its ``package.json``.

.. _res_def_metadata:

General Process of Authoring an npm Module Containing Shared Mojito Resources
-----------------------------------------------------------------------------

#. Create your Mojito resource.
#. Specify that the npm module contains Mojito resources in ``package.json``.
   See :ref:`Resource Definition Metadata <resource_def_metadata>` to learn how.
#. Publish the module to the `npm registry <http://npmjs.org/doc/registry.html>`_.

.. _resource_def_metadata:

Resource Definition Metadata
----------------------------

The npm module containing a Mojito resource is specified by the ``mojito`` object
in ``package.json``. The ``mojito`` object, a property of the ``yahoo`` object,
defines the type and location of the resource as well as the required version of
Mojito to use the resource as shown in the example below. See :ref:`moj_object`
for details about the properties of the ``mojito`` object.

.. code-block:: javascript

   "yahoo": {
     "mojito": {
       "version": "{required Mojito version}",
       "type":  "{resource_type}",
       "location": "{location_of_resource}"
     }
   }

.. _moj_object:

mojito object
#############

The following table describes the properties of the ``mojito`` object that
specifies the resource type and location.

+--------------+----------------+-----------+----------------------------+
| Field Name   | Data Type      | Required? | Description                |
+==============+================+===========+============================+
| ``location`` | String         | No        | The subdirectory in the    |
|              |                |           | npm package where the      |
|              |                |           | resource can be found. The |
|              |                |           | default location is the    |
|              |                |           | package directory.         |
+--------------+----------------+-----------+----------------------------+
| ``type``     | String         | Yes       | Specifies the resource     |
|              |                |           | type. The following are    |
|              |                |           | the possible values:       |
|              |                |           | ``"mojit"``, ``"bundle"``  |
|              |                |           | See :ref:`res_types` for   |
|              |                |           | details.                   |
+--------------+----------------+-----------+----------------------------+
| ``version``  | String         | No        | The version of Mojito      |
|              |                |           | required to use the        |
|              |                |           | resource.                  |
|              |                |           | For example: ``">0.4"``    |
+--------------+----------------+-----------+----------------------------+

.. _res_types:

Mojito Package Types
####################

Currently, Mojito packages can be of type ``mojit`` or ``bundle``. See the
sections below for more details.

.. _mojit_type:

mojit
*****

The ``mojit`` type specifies that the npm module contains a mojit. The
resources in the mojit (controller, models, views, etc.) will be looked for at
the location specified by the ``"location"`` field of the ``mojito`` object.
For example, the controller will be looked for in the following location:

``{location}/controller.{affinity}.{selector}.js``

.. _bundle_type:

bundle
******

The ``bundle`` type specifies that the npm module contains several resources.

The following table shows where Mojito will automatically search for the different
resources. The ``{location}`` is the location specified by the ``location`` property of
the ``mojito`` object.

+--------------------+---------------------------------------+----------------------------------+
| Resource           | Auto-Detected Location                | Notes                            |
+====================+=======================================+==================================+
| mojits             | ``{location}/mojits/``                |                                  |
+--------------------+---------------------------------------+----------------------------------+
| actions            | ``{location}/actions/``               |                                  |
+--------------------+---------------------------------------+----------------------------------+
| addons             | ``{location}/addons/{subtype}/``      | The ``{subtype}`` for addons     |
|                    |                                       | can be ``ac`` for ActionContext  |
|                    |                                       | addons or ``view-engines`` for   |
|                    |                                       | template rendering engine.       |
+--------------------+---------------------------------------+----------------------------------+
| assets             | ``{location}/assets/``                |                                  |
+--------------------+---------------------------------------+----------------------------------+
| binders            | ``{location}/binders/``               |                                  |
+--------------------+---------------------------------------+----------------------------------+
| lang               | ``{location}/lang/``                  |                                  |
+--------------------+---------------------------------------+----------------------------------+
| models             | ``{location}/models/``                |                                  |
+--------------------+---------------------------------------+----------------------------------+
| views              | ``{location}/views/``                 |                                  |
+--------------------+---------------------------------------+----------------------------------+
| YUI modules        | ``{location}/yui_modules/``           |                                  |
|                    | ``{location}/autoload/``              |                                  |
+--------------------+---------------------------------------+----------------------------------+

.. _resource_def_examples:

Examples
--------

**package.json**

The example ``package.json`` has the ``yahoo`` object that specifies that this
npm module contains a Mojito resource.

.. code-block:: javascript

   {
     "name": "mojito_sample_app",
     "description": "A test app to show how to create the package.json file",
     "version": "0.0.2",
     "author": "Joe Hacker <jhacker@yahoo.com>",
     "contributors": [
        {"name": "Noel Jays", "email": "njays@yahoo.com"}
     ],
     "yahoo": {
       "mojito": {
         "type": "mojit",
         "version": "0.3.0"
       }
     },
     "engines": {
       "node": "> 0.4",
       "npm": "> 1.0"
     },
     "dependencies": {
       "mojito": "~0.3.0"
     }
   }

**Mojito Application Using Shared Resources**

::

   mojito_app/
              application.json
              package.json
              mojits/
                     A/
                       A.common.js
                       definition.json
                       views/
                       index/
                             index.hb.html
                       binders/
                               index/
                                     index.js
                     B/
                       ...
                     C/
                       ...
              yui_modules/
                          liba.js
                          libb.js
              node_modules/
                           mojito-mojit-RMP/
                                            package.json
                                            {
                                              "yahoo": {
                                                "mojito": {
                                                  "type": "mojit",
                                                  "version": "*"
                                                }
                                              }
                                            }
                                            controller.common.js
                           mojito-middleware-redirect/
                                                      package.json
                                                      {
                                                        "yahoo": {
                                                          "mojito": {
                                                            "type": "bundle",
                                                            "version": "*"
                                                          }
                                                        }
                                                      }
                                                      middleware/
                                                                 mojito-middleware-redirect.js
                           mojito-viewengine-dust/
                                                  package.json
                                                  {
                                                    "yahoo": {
                                                      "mojito": {
                                                        "type": "bundle",
                                                           "version": "*"
                                                      }
                                                    }
                                                  }
                                                  mojito-viewengine-dust.common.js
                                                  node_modules/
                                                               dust/
                                                                    ... actual dust library ...
                           mojito/
                                  package.json
                                  {
                                    "yahoo": {
                                      "mojito": {
                                        "type": "bundle",
                                        "location": "lib/app",
                                        "version": "*"
                                      }
                                    }
                                  }
                                  lib/
                                  app/
                                      ...
                           async/
                                 LICENSE
                                 Makefile
                                 README.md
                                 index.js
                                 lib/
                                     async.js
                                 package.json

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.7.0//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.7.0/distro-source/core/src/gwt-module.dtd">

<module>
    <inherits name="com.eas.client.Client"/>
    <inherits name="com.eas.widgets.Widgets"/>

    <source path=""/>

    <!--set-property name="user.agent" value="safari" /-->

    <!--add-linker name="xsiframe"/-->

    <!--set-configuration-property name="devModeRedirectEnabled" value="true"/-->

    <!--  enable source maps -->

    <!--set-property name="compiler.useSourceMaps" value="true" /-->

    <!-- Do not define servlets here, use web.xml -->
</module>


text:
import os, sys, re, tempfile, random, time
import util

## globals
SVM_LEARN = '/u/dgillick/tools/svm_perf/svm_perf_learn'
SVM_CLASSIFY = '/u/dgillick/tools/svm_perf/svm_perf_classify'

def get_features(sent, tag):

    tokens = sent.split()
    tags = [t.split('/')[-1] for t in tag.split()]
    #structs = [p.split()[0] for p in parse.split('(') if len(p.strip())>0]

    feats = {}

    ## number of tokens
    length = len(tokens)
    feats['len'] = length / 30.0

    ## connector words
    connectors = set(['however', 'because', 'and', 'so', 'also', 'nonetheless',
                      'still', 'but'])
    feats['connect'] = tokens[0].lower() in connectors

    ## number of capitalized words (assume 1st word is always capitalized)
    num_cap = len([1 for token in tokens[1:] if token[0].isupper()])
    feats['cap'] = 1.0 * num_cap / max((length-1), 1)

    ## pronouns (PRP$ are possessive; WP are who, what, which, when)
    num_pron = len([1 for tag in tags if tag in ['PRP$']])
    feats['prn'] = 1.0 * num_pron / length

    ## definite articles
    num_da = len([1 for token in tokens if token.lower() in ['the', 'that', 'these', 'those', 'this']])
    feats['da'] = 1.0 * num_da / length

    ## the [A-Z] construction
    feats['cap_cons'] = len(re.findall('[t|T]he [A-Z]', sent))

    ## first word
    #feats['first=%s' %tokens[0].lower()] = 1
    #feats['first_pos=%s' %tags[0]] = 1

    ## token ngrams
    ngrams = util.get_ngrams(tokens, 1, False) + util.get_ngrams(tokens, 2, True)
    for ngram in ngrams:
        feats['tok=%s' %'_'.join(ngram).lower()] = 1

    ## tag ngrams
    ngrams = util.get_ngrams(tags, 2, True) #+ util.get_ngrams(tags, 4, True)
    for ngram in ngrams:
        feats['pos=%s' %'_'.join(ngram)] = 1

    ## parser ngrams
    #ngrams = util.get_ngrams(structs, 4, True)
    #for ngram in ngrams:
    #    feats['struct=%s' %'_'.join(ngram)] = 1

    ## quotes
    feats['quotes'] = int('"' in tokens)
    #num_tokens_in_quotes = 0
    #num_quotes = 0
    #in_quotes = False
    #for token in tokens:
    #    if token == '"':
    #        in_quotes = not in_quotes
    #        num_quotes += 1
    #    else:
    #        if in_quotes: num_tokens_in_quotes += 1
    #feats['in_quotes'] = 1.0 * num_tokens_in_quotes / (length - num_quotes)

    return feats

class Hyp:
    def __init__(self):
        self.original = None
        self.features = None
        self.label = None

class Model:
    def __init__(self, path):
        self.path = path
        self.featdict = {}

    def train(self, data):
        abstract

    def classify(self, data):
        abstract

    def save(self):
        util.save_pickle(self.featdict, self.path + 'feats')

    def load(self):
        self.featdict = util.load_pickle(self.path + 'feats')

class SVM_Model(Model):

    def train(self, data):

        model_file = '%s/svm_model' %self.path

        ## integer dictionary for features
        sys.stderr.write('training. making feat dict... ')
        feat_list = set()
        for hyp in data:
            for feat in hyp.features: feat_list.add(feat)
        self.featdict = dict(zip(feat_list, range(1,len(feat_list)+1)))

        ## training data file
        sys.stderr.write('writing... ')
        lines = []
        for hyp in data:
            if hyp.label == None: util.die('expecting labeled data')
            elif hyp.label > 0.0: svm_label = '+1'
            elif hyp.label < 0.0: svm_label = '-1'
            else: continue
            line = '%s ' %svm_label
            svm_feats = [(self.featdict[f], v) for (f,v) in hyp.features.items()]
            svm_feats.sort(lambda x,y: x[0]-y[0])
            line += ' '.join(['%d:%1.4f' %(f,v) for (f,v) in svm_feats])
            lines.append(line)

        unused, train_file = tempfile.mkstemp()
        fh = open(train_file, 'w')
        fh.write('\n'.join(lines) + '\n')
        fh.close()

        ## train an svm model
        start_time = time.time()
        sys.stderr.write('running svm... ')
        options = '-v 0 -c 1' #-t 1 -r 1 -d 2' #-c 1
        cmd = '%s %s %s %s' %(SVM_LEARN, options, train_file, model_file)
        os.system(cmd)
        total_time = time.time() - start_time
        sys.stderr.write('done! time [%1.2f]\n' %total_time)

        ## clean up
        os.remove(train_file)

    def classify(self, data):

        model_file = '%s/svm_model' %self.path
        if not self.featdict: util.die('Incomplete model')
        if not os.path.isfile(model_file): util.die('no model [%s]' %model_file)

        ## testing data file
        sys.stderr.write('SVM classifying... ')
        lines = []
        for hyp in data:
            if hyp.label == None: svm_label = '0'
            elif hyp.label == 1: svm_label = '+1'
            elif hyp.label == -1: svm_label = '-1'
            else: continue
            line = '%s ' %svm_label
            svm_feats = [(self.featdict[f], v) for (f,v) in hyp.features.items() if f in self.featdict]
            svm_feats.sort(lambda x,y: x[0]-y[0])
            line += ' '.join(['%d:%1.4f' %(f,v) for (f,v) in svm_feats])
            lines.append(line)

        unused, test_file = tempfile.mkstemp()
        fh = open(test_file, 'w')
        fh.write('\n'.join(lines) + '\n')
        fh.close()

        ## classify test data
        unused, pred_file = tempfile.mkstemp()
        options = '-v 0'
        cmd = '%s %s %s %s %s' %(SVM_CLASSIFY, options, test_file, model_file, pred_file)
        os.system(cmd)

        ## get predictions
        total = 0
        preds = map(float, open(pred_file).read().splitlines())
        for hyp in data:
            hyp.pred = preds[total] #util.logit(preds[total])
            total += 1

        ## clean up
        os.remove(test_file)
        os.remove(pred_file)
        sys.stderr.write('done!\n')

        return data

    def results(self, data):
        for hyp in data:
            print hyp.label, hyp.pred, hyp.original

def featurize(sent_file, tag_file):
    """
    root.data        sentences
    root.label       labels
    root.tagged      POS tags
    note: tagger splits 3,000 into: 3/CD ,/, 000/CD
    """

    data = []
    prev = None
    sents_fh = open(sent_file)
    tags_fh = open(tag_file)
    while True:
        (sent, tags) = (sents_fh.readline().strip(), tags_fh.readline().strip())
        if not (sent or tags): break

        ## create a new hyp
        hyp = Hyp()
        hyp.original = sent
        hyp.label = None

        hyp.features = get_features(sent, tags)
        data.append(hyp)

        #print hyp.label, sent
        #print hyp.features
        #print '-------'

    return data

def load_model(path):
    model = SVM_Model(path)
    model.load()
    return model

if __name__ == '__main__':

    path = '../bourbon/nyt/svm/'
    sent_file = sys.argv[1]
    tag_file = sys.argv[2]

    model = load_model(path)
    data = featurize(sent_file, tag_file)
    data = model.classify(data)

    model.results(data)


text:
<?php declare(strict_types=1);

namespace Malios\Ast2Zephir\Generator\Expr;

use Malios\Ast2Zephir\Enum\Expr;
use Malios\Ast2Zephir\Generator\Common\NodeToCode;
use Malios\Ast2Zephir\Generator\Exception\LogicException;
use Malios\Ast2Zephir\Generator\Generator;
use Malios\Ast2Zephir\NotImplementedException;
use PhpParser\Node;
use PhpParser\Node\Expr\Cast as ExprCast;

final class Cast extends Generator
{
    use NodeToCode;

    private $template = '(%s) %s';

    private $castMapping = [
        Expr\Cast::BOOL => 'bool',
        Expr\Cast::INT => 'int',
        Expr\Cast::STRING => 'string',
        Expr\Cast::OBJECT => 'object',
        Expr\Cast::DOUBLE => 'double',
        Expr\Cast::ARRAY => 'array',
    ];

    /**
     * {@inheritdoc}
     * @see Generator::canGenerateCode()
     */
    protected function canGenerateCode(Node $node): bool
    {
        return $this->isCast($node);
    }

    /**
     * {@inheritdoc}
     * @see Generator::doGenerateCode()
     * @param ExprCast|ExprCast\Unset_ $node
     */
    protected function doGenerateCode($node): string
    {
        $type = $node->getType();
        if ($type === Expr\Cast::UNSET) {
            $code = $this->convertCastUnset($node);
            return $code;
        }

        $cast = $this->castMapping[$type] ?? null;
        if ($cast === null) {
            throw new LogicException(sprintf("Can not convert expression %s", $type));
        }

        $expr = $this->nodeToCode($node->expr, $this->finder);
        $code = sprintf($this->template, $cast, $expr);
        return $code;
    }

    private function isCast(Node $node): bool
    {
        return strpos($node->getType(), Expr\Cast::CAST) > -1;
    }

    private function convertCastUnset(Node\Expr\Cast\Unset_ $node): string
    {
        // workaround for cast unset
        if ($node->expr->getType() === Expr::VARIABLE) {
            throw new NotImplementedException();
            // See Expr\Unset_
            // $template = 'let %s = null';
        } else {
            $template = 'unset(%s)';
        }

        $expr = $this->nodeToCode($node->expr, $this->finder);
        $code = sprintf($template, $expr);
        return $code;
    }
}


text:
layout: post
title: Job posts in ECIL last date 24th Nov-2015
date: 2015-11-13 04:36
comments: true
tags:  Accounts ECIL Electronics Hindi Manager Officer Online Public-Sector Translator
archive: false
---
ECIL a professionally managed Electronics  is looking for dynamic and result oriented persons for the following positions :

- Senior Deputy General Manager : 01 post
- Dy. General Manager (Safety) : 01 post
- Senior Personnel Officer : 05 post
- Accounts Officer : 06 posts
- Junior Hindi Translator : 04 posts

**How to Apply** : Please apply Online at ECIL website from 09/11/2015 to 24/11/2015.

Details and online application form available at <https://ecil.gov.in/login.php>


text:
namespace clotho {
namespace genetics {

template < class TraitAccumType, class ResultType >
struct linear_combination {

    typedef TraitAccumType                                  trait_accum_type;
    typedef typename trait_accum_type::trait_vector_type    trait_type;
    typedef typename trait_accum_type::weight_pointer       weight_pointer;
    typedef ResultType                                      result_type;

    result_type operator()( std::shared_ptr< trait_type > s0, std::shared_ptr< trait_type > s1 ) {
        typedef typename trait_type::iterator iterator;

        iterator b = s0->begin(), e = s0->end();
        result_type res = 0.0;

        while( b != e ) {
            res += *b++;
        }

        b = s1->begin(); e = s1->end();

        while( b != e ) {
            res += *b++;
        }

        return res;
    }

    void operator()( weight_pointer a_first, weight_pointer a_last, weight_pointer b_first, weight_pointer b_last, weight_pointer res ) {
//#ifdef DEBUGGING
//        std::cerr << "Linear combination method" << std::endl;
//        std::cerr << "Trait count A: " << (a_last - a_first) << std::endl;
//        std::cerr << "Trait count B: " << (b_last - b_first) << std::endl;
//#endif  // DEBUGGING
        int i = 0, M = (a_last - a_first);

        assert( M == (b_last - b_first) );
        while( i < M ) {
            res[ i ] = a_first[ i ] + b_first[ i ];
            ++i;
        }
    }
};

template < class TraitAccumType, class RealType >
struct linear_combination< TraitAccumType, std::vector< RealType > > {

    typedef TraitAccumType                                  trait_accum_type;
    typedef typename trait_accum_type::trait_vector_type    trait_type;
    typedef std::vector< RealType >                         result_type;

    result_type operator()( std::shared_ptr < trait_type >  s0, std::shared_ptr <trait_type>  s1 ) {
        typedef typename trait_type::iterator iterator;

        iterator b = s0->begin(), e = s0->end();
        result_type res;

        while( b != e ) {
            res.push_back( *b++ );
        }

        b = s1->begin(); e = s1->end();

        size_t i = 0;
        while( b != e ) {
            res[ i++ ] += *b++;
        }

        return res;
    }
};
template < class TraitAccumType, class ResultType >
struct accumulator_helper_of< linear_combination< TraitAccumType, ResultType > > {
    typedef TraitAccumType          type;
    typedef ResultType              result_type;
};

}   // namespace genetics
}   // namespace clotho

#endif  // CLOTHO_LINEAR_COMBINATION_METHOD_HPP_


text:
package com.amazonaws.resources.identitymanagement.internal;

import java.util.Date;

import com.amazonaws.resources.ResultCapture;
import com.amazonaws.resources.identitymanagement.AccessKey;
import com.amazonaws.resources.identitymanagement.User;
import com.amazonaws.resources.internal.ResourceCodec;
import com.amazonaws.resources.internal.ResourceImpl;
import com.amazonaws.services.identitymanagement.model.DeleteAccessKeyRequest;
import com.amazonaws.services.identitymanagement.model.UpdateAccessKeyRequest;

class AccessKeyImpl implements AccessKey {
    public static final ResourceCodec<AccessKey> CODEC = new Codec();

    private final ResourceImpl resource;

    public AccessKeyImpl(ResourceImpl resource) {
        this.resource = resource;
    }

    @Override
    public boolean isLoaded() {
        return resource.isLoaded();
    }

    @Override
    public String getId() {
        return (String) resource.getIdentifier("Id");
    }

    @Override
    public String getUserName() {
        return (String) resource.getIdentifier("UserName");
    }

    @Override
    public String getSecretAccessKey() {
        return (String) resource.getAttribute("SecretAccessKey");
    }

    @Override
    public String getStatus() {
        return (String) resource.getAttribute("Status");
    }

    @Override
    public Date getCreateDate() {
        return (Date) resource.getAttribute("CreateDate");
    }

    @Override
    public User getUser() {
        ResourceImpl result = resource.getReference("User");
        if (result == null) return null;
        return new UserImpl(result);
    }

    @Override
    public void deactivate(UpdateAccessKeyRequest request) {
        deactivate(request, null);
    }

    @Override
    public void deactivate(UpdateAccessKeyRequest request, ResultCapture<Void>
            extractor) {

        resource.performAction("Deactivate", request, extractor);
    }

    @Override
    public void deactivate() {
        deactivate((ResultCapture<Void>)null);
    }

    @Override
    public void deactivate(ResultCapture<Void> extractor) {
        UpdateAccessKeyRequest request = new UpdateAccessKeyRequest();
        deactivate(request, extractor);
    }

    @Override
    public void activate(UpdateAccessKeyRequest request) {
        activate(request, null);
    }

    @Override
    public void activate(UpdateAccessKeyRequest request, ResultCapture<Void>
            extractor) {

        resource.performAction("Activate", request, extractor);
    }

    @Override
    public void activate() {
        activate((ResultCapture<Void>)null);
    }

    @Override
    public void activate(ResultCapture<Void> extractor) {
        UpdateAccessKeyRequest request = new UpdateAccessKeyRequest();
        activate(request, extractor);
    }

    @Override
    public void delete(DeleteAccessKeyRequest request) {
        delete(request, null);
    }

    @Override
    public void delete(DeleteAccessKeyRequest request, ResultCapture<Void>
            extractor) {

        resource.performAction("Delete", request, extractor);
    }

    @Override
    public void delete() {
        delete((ResultCapture<Void>)null);
    }

    @Override
    public void delete(ResultCapture<Void> extractor) {
        DeleteAccessKeyRequest request = new DeleteAccessKeyRequest();
        delete(request, extractor);
    }

    private static class Codec implements ResourceCodec<AccessKey> {
        @Override
        public AccessKey transform(ResourceImpl resource) {
            return new AccessKeyImpl(resource);
        }
    }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcsUtil;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.vcs.actions.VcsContext;
import org.jetbrains.annotations.Nullable;

/**
 * @author yole
 */
public class VcsSelectionUtil {
  private VcsSelectionUtil() {
  }

  @Nullable
  public static VcsSelection getSelection(VcsContext context) {
    Editor editor = context.getEditor();
    if (editor == null) return null;

    SelectionModel selectionModel = editor.getSelectionModel();
    if (!selectionModel.hasSelection()) {
      for (VcsSelectionProvider provider : VcsSelectionProvider.EP_NAME.getExtensionList()) {
        try {
          final VcsSelection vcsSelection = provider.getSelection(context);
          if (vcsSelection != null) return vcsSelection;
        }
        catch (IndexNotReadyException ignored) {
        }
      }
    }

    return new VcsSelection(editor.getDocument(), selectionModel);
  }
}


text:
<?php
namespace Concrete\Core\Routing;

use Concrete\Core\Support\Facade\Application;
use Response;
use Request;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;

class ControllerRouteCallback extends RouteCallback
{
    /**
     * @param Request $request
     * @param Route $route
     * @param array $parameters
     *
     * @return Response
     */
    public function execute(Request $request, Route $route, $parameters)
    {
        $controllerResolver = Application::make('Concrete\Core\Controller\ApplicationAwareControllerResolver');
        $callback = $controllerResolver->getController($request);
        $argumentsResolver = Application::make(ArgumentResolver::class);
        $arguments = $argumentsResolver->getArguments($request, $callback);
        $controller = $callback[0];
        $method = $callback[1];
        $controller->on_start();
        $response = $controller->runAction($method, $arguments);

        if ($response instanceof \Symfony\Component\HttpFoundation\Response) {
            // note, our RedirectResponse doesn't extend Response, it extends symfony2 response
            return $response;
        }
        if ($response instanceof \Concrete\Core\View\AbstractView) {
            $content = $response->render();
        } else {
            $content = null;
            $view = $controller->getViewObject();
            if (is_object($view)) {
                $view->setController($controller);
                if (isset($view) && $view instanceof \Concrete\Core\View\AbstractView) {
                    $content = $view->render();
                }
            }
        }
        $response = new Response();
        $response->setContent($content);

        return $response;
    }

    /**
     * @return array
     */
    public static function getRouteAttributes($callback)
    {
        $attributes = [];
        $attributes['_controller'] = $callback;
        $callback = new static($callback);
        $attributes['callback'] = $callback;

        return $attributes;
    }
}


text:
.. sklearn-rri documentation master file, created by sphinx

Welcome to sklearn-rri's documentation!
=======================================

.. toctree::
   :maxdepth: 4
   :caption: Contents:

   sklearn_rri

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
import os
from os.path import join

# 3rd party libs
from nose.tools import *

# PyGitup imports
from tests import basepath
from PyGitUp.git_wrapper import GitError

test_name = 'not-on-a-repo'
repo_path = join(basepath, test_name + os.sep)

def setup():
    os.makedirs(repo_path, 0o700)

@raises(GitError)
def test_not_a_git_repo():
    """ Run 'git up' being not on a git repo """
    os.chdir(repo_path)

    from PyGitUp.gitup import GitUp
    GitUp(testing=True)


text:
#include <grpc/support/port_platform.h>

#include "src/core/lib/iomgr/port.h"

#ifdef GRPC_POSIX_SOCKET_EV

#include "src/core/lib/iomgr/ev_posix.h"

#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/global_config.h"
#include "src/core/lib/iomgr/ev_epoll1_linux.h"
#include "src/core/lib/iomgr/ev_epollex_linux.h"
#include "src/core/lib/iomgr/ev_poll_posix.h"
#include "src/core/lib/iomgr/internal_errqueue.h"

GPR_GLOBAL_CONFIG_DEFINE_STRING(
    grpc_poll_strategy, "all",
    "Declares which polling engines to try when starting gRPC. "
    "This is a comma-separated list of engines, which are tried in priority "
    "order first -> last.")

grpc_core::DebugOnlyTraceFlag grpc_polling_trace(
    false, "polling"); /* Disabled by default */

/* Traces fd create/close operations */
grpc_core::DebugOnlyTraceFlag grpc_fd_trace(false, "fd_trace");
grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount(false, "fd_refcount");
grpc_core::DebugOnlyTraceFlag grpc_polling_api_trace(false, "polling_api");

// Polling API trace only enabled in debug builds
#ifndef NDEBUG
#define GRPC_POLLING_API_TRACE(format, ...)                  \
  if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_api_trace)) {     \
    gpr_log(GPR_INFO, "(polling-api) " format, __VA_ARGS__); \
  }
#else
#define GRPC_POLLING_API_TRACE(...)
#endif  // NDEBUG

/** Default poll() function - a pointer so that it can be overridden by some
 *  tests */
#ifndef GPR_AIX
grpc_poll_function_type grpc_poll_function = poll;
#else
int aix_poll(struct pollfd fds[], nfds_t nfds, int timeout) {
  return poll(fds, nfds, timeout);
}
grpc_poll_function_type grpc_poll_function = aix_poll;
#endif  // GPR_AIX

grpc_wakeup_fd grpc_global_wakeup_fd;

static const grpc_event_engine_vtable* g_event_engine = nullptr;
static const char* g_poll_strategy_name = nullptr;

typedef const grpc_event_engine_vtable* (*event_engine_factory_fn)(
    bool explicit_request);

typedef struct {
  const char* name;
  event_engine_factory_fn factory;
} event_engine_factory;

namespace {

grpc_poll_function_type real_poll_function;

int dummy_poll(struct pollfd fds[], nfds_t nfds, int timeout) {
  if (timeout == 0) {
    return real_poll_function(fds, nfds, 0);
  } else {
    gpr_log(GPR_ERROR, "Attempted a blocking poll when declared non-polling.");
    GPR_ASSERT(false);
    return -1;
  }
}

const grpc_event_engine_vtable* init_non_polling(bool explicit_request) {
  if (!explicit_request) {
    return nullptr;
  }
  // return the simplest engine as a dummy but also override the poller
  auto ret = grpc_init_poll_posix(explicit_request);
  real_poll_function = grpc_poll_function;
  grpc_poll_function = dummy_poll;

  return ret;
}
}  // namespace

#define ENGINE_HEAD_CUSTOM "head_custom"
#define ENGINE_TAIL_CUSTOM "tail_custom"

// The global array of event-engine factories. Each entry is a pair with a name
// and an event-engine generator function (nullptr if there is no generator
// registered for this name). The middle entries are the engines predefined by
// open-source gRPC. The head entries represent an opportunity for specific
// high-priority custom pollers to be added by the initializer plugins of
// custom-built gRPC libraries. The tail entries represent the same, but for
// low-priority custom pollers. The actual poller selected is either the first
// available one in the list if no specific poller is requested, or the first
// specific poller that is requested by name in the GRPC_POLL_STRATEGY
// environment variable if that variable is set (which should be a
// comma-separated list of one or more event engine names)
static event_engine_factory g_factories[] = {
    {ENGINE_HEAD_CUSTOM, nullptr},        {ENGINE_HEAD_CUSTOM, nullptr},
    {ENGINE_HEAD_CUSTOM, nullptr},        {ENGINE_HEAD_CUSTOM, nullptr},
    {"epollex", grpc_init_epollex_linux}, {"epoll1", grpc_init_epoll1_linux},
    {"poll", grpc_init_poll_posix},       {"none", init_non_polling},
    {ENGINE_TAIL_CUSTOM, nullptr},        {ENGINE_TAIL_CUSTOM, nullptr},
    {ENGINE_TAIL_CUSTOM, nullptr},        {ENGINE_TAIL_CUSTOM, nullptr},
};

static void add(const char* beg, const char* end, char*** ss, size_t* ns) {
  size_t n = *ns;
  size_t np = n + 1;
  char* s;
  size_t len;
  GPR_ASSERT(end >= beg);
  len = static_cast<size_t>(end - beg);
  s = static_cast<char*>(gpr_malloc(len + 1));
  memcpy(s, beg, len);
  s[len] = 0;
  *ss = static_cast<char**>(gpr_realloc(*ss, sizeof(char**) * np));
  (*ss)[n] = s;
  *ns = np;
}

static void split(const char* s, char*** ss, size_t* ns) {
  const char* c = strchr(s, ',');
  if (c == nullptr) {
    add(s, s + strlen(s), ss, ns);
  } else {
    add(s, c, ss, ns);
    split(c + 1, ss, ns);
  }
}

static bool is(const char* want, const char* have) {
  return 0 == strcmp(want, "all") || 0 == strcmp(want, have);
}

static void try_engine(const char* engine) {
  for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) {
    if (g_factories[i].factory != nullptr && is(engine, g_factories[i].name)) {
      if ((g_event_engine = g_factories[i].factory(
               0 == strcmp(engine, g_factories[i].name)))) {
        g_poll_strategy_name = g_factories[i].name;
        gpr_log(GPR_DEBUG, "Using polling engine: %s", g_factories[i].name);
        return;
      }
    }
  }
}

/* Call this before calling grpc_event_engine_init() */
void grpc_register_event_engine_factory(const char* name,
                                        event_engine_factory_fn factory,
                                        bool add_at_head) {
  const char* custom_match =
      add_at_head ? ENGINE_HEAD_CUSTOM : ENGINE_TAIL_CUSTOM;

  // Overwrite an existing registration if already registered
  for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) {
    if (0 == strcmp(name, g_factories[i].name)) {
      g_factories[i].factory = factory;
      return;
    }
  }

  // Otherwise fill in an available custom slot
  for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) {
    if (0 == strcmp(g_factories[i].name, custom_match)) {
      g_factories[i].name = name;
      g_factories[i].factory = factory;
      return;
    }
  }

  // Otherwise fail
  GPR_ASSERT(false);
}

/*If grpc_event_engine_init() has been called, returns the poll_strategy_name.
 * Otherwise, returns nullptr. */
const char* grpc_get_poll_strategy_name() { return g_poll_strategy_name; }

void grpc_event_engine_init(void) {
  grpc_core::UniquePtr<char> value = GPR_GLOBAL_CONFIG_GET(grpc_poll_strategy);

  char** strings = nullptr;
  size_t nstrings = 0;
  split(value.get(), &strings, &nstrings);

  for (size_t i = 0; g_event_engine == nullptr && i < nstrings; i++) {
    try_engine(strings[i]);
  }

  for (size_t i = 0; i < nstrings; i++) {
    gpr_free(strings[i]);
  }
  gpr_free(strings);

  if (g_event_engine == nullptr) {
    gpr_log(GPR_ERROR, "No event engine could be initialized from %s",
            value.get());
    abort();
  }
}

void grpc_event_engine_shutdown(void) {
  g_event_engine->shutdown_engine();
  g_event_engine = nullptr;
}

bool grpc_event_engine_can_track_errors(void) {
  /* Only track errors if platform supports errqueue. */
  if (grpc_core::kernel_supports_errqueue()) {
    return g_event_engine->can_track_err;
  }
  return false;
}

bool grpc_event_engine_run_in_background(void) {
  // g_event_engine is nullptr when using a custom iomgr.
  return g_event_engine != nullptr && g_event_engine->run_in_background;
}

grpc_fd* grpc_fd_create(int fd, const char* name, bool track_err) {
  GRPC_POLLING_API_TRACE("fd_create(%d, %s, %d)", fd, name, track_err);
  GRPC_FD_TRACE("fd_create(%d, %s, %d)", fd, name, track_err);
  return g_event_engine->fd_create(
      fd, name, track_err && grpc_event_engine_can_track_errors());
}

int grpc_fd_wrapped_fd(grpc_fd* fd) {
  return g_event_engine->fd_wrapped_fd(fd);
}

void grpc_fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd,
                    const char* reason) {
  GRPC_POLLING_API_TRACE("fd_orphan(%d, %p, %p, %s)", grpc_fd_wrapped_fd(fd),
                         on_done, release_fd, reason);
  GRPC_FD_TRACE("grpc_fd_orphan, fd:%d closed", grpc_fd_wrapped_fd(fd));

  g_event_engine->fd_orphan(fd, on_done, release_fd, reason);
}

void grpc_fd_shutdown(grpc_fd* fd, grpc_error* why) {
  GRPC_POLLING_API_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd));
  GRPC_FD_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd));
  g_event_engine->fd_shutdown(fd, why);
}

bool grpc_fd_is_shutdown(grpc_fd* fd) {
  return g_event_engine->fd_is_shutdown(fd);
}

void grpc_fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) {
  g_event_engine->fd_notify_on_read(fd, closure);
}

void grpc_fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) {
  g_event_engine->fd_notify_on_write(fd, closure);
}

void grpc_fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) {
  g_event_engine->fd_notify_on_error(fd, closure);
}

void grpc_fd_set_readable(grpc_fd* fd) { g_event_engine->fd_set_readable(fd); }

void grpc_fd_set_writable(grpc_fd* fd) { g_event_engine->fd_set_writable(fd); }

void grpc_fd_set_error(grpc_fd* fd) { g_event_engine->fd_set_error(fd); }

static size_t pollset_size(void) { return g_event_engine->pollset_size; }

static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) {
  GRPC_POLLING_API_TRACE("pollset_init(%p)", pollset);
  g_event_engine->pollset_init(pollset, mu);
}

static void pollset_shutdown(grpc_pollset* pollset, grpc_closure* closure) {
  GRPC_POLLING_API_TRACE("pollset_shutdown(%p)", pollset);
  g_event_engine->pollset_shutdown(pollset, closure);
}

static void pollset_destroy(grpc_pollset* pollset) {
  GRPC_POLLING_API_TRACE("pollset_destroy(%p)", pollset);
  g_event_engine->pollset_destroy(pollset);
}

static grpc_error* pollset_work(grpc_pollset* pollset,
                                grpc_pollset_worker** worker,
                                grpc_millis deadline) {
  GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") begin", pollset,
                         deadline);
  grpc_error* err = g_event_engine->pollset_work(pollset, worker, deadline);
  GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") end", pollset,
                         deadline);
  return err;
}

static grpc_error* pollset_kick(grpc_pollset* pollset,
                                grpc_pollset_worker* specific_worker) {
  GRPC_POLLING_API_TRACE("pollset_kick(%p, %p)", pollset, specific_worker);
  return g_event_engine->pollset_kick(pollset, specific_worker);
}

void grpc_pollset_add_fd(grpc_pollset* pollset, struct grpc_fd* fd) {
  GRPC_POLLING_API_TRACE("pollset_add_fd(%p, %d)", pollset,
                         grpc_fd_wrapped_fd(fd));
  g_event_engine->pollset_add_fd(pollset, fd);
}

void pollset_global_init() {}
void pollset_global_shutdown() {}

grpc_pollset_vtable grpc_posix_pollset_vtable = {
    pollset_global_init, pollset_global_shutdown,
    pollset_init,        pollset_shutdown,
    pollset_destroy,     pollset_work,
    pollset_kick,        pollset_size};

static grpc_pollset_set* pollset_set_create(void) {
  grpc_pollset_set* pss = g_event_engine->pollset_set_create();
  GRPC_POLLING_API_TRACE("pollset_set_create(%p)", pss);
  return pss;
}

static void pollset_set_destroy(grpc_pollset_set* pollset_set) {
  GRPC_POLLING_API_TRACE("pollset_set_destroy(%p)", pollset_set);
  g_event_engine->pollset_set_destroy(pollset_set);
}

static void pollset_set_add_pollset(grpc_pollset_set* pollset_set,
                                    grpc_pollset* pollset) {
  GRPC_POLLING_API_TRACE("pollset_set_add_pollset(%p, %p)", pollset_set,
                         pollset);
  g_event_engine->pollset_set_add_pollset(pollset_set, pollset);
}

static void pollset_set_del_pollset(grpc_pollset_set* pollset_set,
                                    grpc_pollset* pollset) {
  GRPC_POLLING_API_TRACE("pollset_set_del_pollset(%p, %p)", pollset_set,
                         pollset);
  g_event_engine->pollset_set_del_pollset(pollset_set, pollset);
}

static void pollset_set_add_pollset_set(grpc_pollset_set* bag,
                                        grpc_pollset_set* item) {
  GRPC_POLLING_API_TRACE("pollset_set_add_pollset_set(%p, %p)", bag, item);
  g_event_engine->pollset_set_add_pollset_set(bag, item);
}

static void pollset_set_del_pollset_set(grpc_pollset_set* bag,
                                        grpc_pollset_set* item) {
  GRPC_POLLING_API_TRACE("pollset_set_del_pollset_set(%p, %p)", bag, item);
  g_event_engine->pollset_set_del_pollset_set(bag, item);
}

grpc_pollset_set_vtable grpc_posix_pollset_set_vtable = {
    pollset_set_create,          pollset_set_destroy,
    pollset_set_add_pollset,     pollset_set_del_pollset,
    pollset_set_add_pollset_set, pollset_set_del_pollset_set};

void grpc_pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
  GRPC_POLLING_API_TRACE("pollset_set_add_fd(%p, %d)", pollset_set,
                         grpc_fd_wrapped_fd(fd));
  g_event_engine->pollset_set_add_fd(pollset_set, fd);
}

void grpc_pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) {
  GRPC_POLLING_API_TRACE("pollset_set_del_fd(%p, %d)", pollset_set,
                         grpc_fd_wrapped_fd(fd));
  g_event_engine->pollset_set_del_fd(pollset_set, fd);
}

bool grpc_is_any_background_poller_thread(void) {
  return g_event_engine->is_any_background_poller_thread();
}

bool grpc_add_closure_to_background_poller(grpc_closure* closure,
                                           grpc_error* error) {
  return g_event_engine->add_closure_to_background_poller(closure, error);
}

void grpc_shutdown_background_closure(void) {
  g_event_engine->shutdown_background_closure();
}

#endif  // GRPC_POSIX_SOCKET_EV


text:
layout: null
---
<!DOCTYPE html>

    <title>Pravendra Singh · pravj</title>
    <meta name="author" content="pravj">
    <meta name="description" content="Pravendra Singh">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="keywords" content="pravj, pravendra singh, iit roorkee, hackpravj, python, github, github-pages">

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

    <link rel="icon" href="/blog/public/favicon.ico">
    <link rel="stylesheet" href="//brick.a.ssl.fastly.net/Lato:100,100i/Open+Sans:300,300i">
    <link rel="stylesheet" href="https://cdn.rawgit.com/chinchang/hint.css/master/hint.min.css">
    <link rel="stylesheet" href="{{ site.baseurl }}public/css/style.css">

Pravendra Singh

Student Developer @ S-166

GITHUB

BLOG

ABOUT

      Follow @hackpravj


text:
package ru.job4j.list;

import org.junit.Test;

import java.util.Iterator;

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

/**
 * @author Ruzhev Alexander
 * @since 06.10.2017
 */
public class MyDynamicArrayTest {
    /**
     * Test for add and get.
     */
    @Test
    public void whenAddThenGet() {
        MyDynamicArray<Integer> arrayI = new MyDynamicArray<>();
        MyDynamicArray<String> arrayS = new MyDynamicArray<>();
        arrayI.add(1);
        arrayI.add(2);
        arrayS.add("A");
        arrayS.add("B");
        assertThat(1, is(arrayI.get(0)));
        assertThat(2, is(arrayI.get(1)));
        assertThat("A", is(arrayS.get(0)));
        assertThat("B", is(arrayS.get(1)));
    }

    /**
     * Test for Increase Container.
     */
    @Test
    public void whenAddThenIncreaseContainer() {
        MyDynamicArray<Integer> array = new MyDynamicArray<>(0);
        for (int i = 0; i <= 999; i++) {
            array.add(i + 1);
            assertThat(i + 1, is(array.get(i)));
        }
    }

    /**
     * Test for iterator.
     */
    @Test
    public void whenIterator() {
        MyDynamicArray<Integer> array = new MyDynamicArray<>();
        array.add(1);
        array.add(2);
        array.add(3);
        array.add(4);
        array.add(5);
        Iterator iterator = array.iterator();
        int b = 0;
        for (Integer i : array) {
            assertThat(i, is(array.get(b++)));
        }
        assertThat(1, is(iterator.next()));
        assertThat(2, is(iterator.next()));
        assertThat(3, is(iterator.next()));
        assertThat(4, is(iterator.next()));
        assertThat(5, is(iterator.next()));
        assertThat(false, is(iterator.hasNext()));
    }
}


text:
pyHGEditor
==========

Another notepad software writen in Kivy Python

[![Coverage Status](https://coveralls.io/repos/guihknx/pyHGEditor/badge.png)](https://coveralls.io/r/guihknx/pyHGEditor)


text:
/* global describe, it */
var build = require('../index.js');
var should = require('should');
var File = require('gulp-util').File;
var Buffer = require('buffer').Buffer;

var getFile = function(contents, expected) {
	return {
		file: new File({
			cwd: '/home/tje',
			base: '/home/tje/test',
			path: '/home/tje/test/name.html',
			contents: contents || new Buffer('
And her name was, {{ name }}.
')
		}),
		expected: expected || '
And her name was, Melissa.
'
	};
};

describe('gulp-build', function() {
	it('should compile the template with one variable', function(done) {
		var stream = build({ name: 'Melissa' }),
			fakeFile = getFile();

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.path);
			should.exist(newFile.relative);
			should.exist(newFile.contents);
			Buffer.isBuffer(newFile.contents).should.be.true;
			newFile.contents.toString().should.equal(fakeFile.expected);
			done();
		});

		stream.write(fakeFile.file);
	});

	it('should compile with partials', function(done) {
		var stream = build({ name: 'Figs' }, { partials: [{ name: 'header', tpl: '
Super Bad Ass Cat
' }]});
		var fakeFile = getFile(
			new Buffer('{{> header}}
The most bad ass cat ever is easily, {{name}}.
'),
			'
Super Bad Ass Cat

The most bad ass cat ever is easily, Figs.
'
		);

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.path);
			should.exist(newFile.relative);
			should.exist(newFile.contents);
			Buffer.isBuffer(newFile.contents).should.be.true;
			newFile.contents.toString().should.equal(fakeFile.expected);
			done();
		});

		stream.write(fakeFile.file);
	});

	it('should compile with partials and a layout', function(done) {
		var stream = build({ name: 'Jack' }, {
			partials: [{ name: 'header', tpl: '
The Tests
' }],
			layout: '{{> body}}'
		});

		var fakeFile = getFile(
			new Buffer('{{> header}}
Just some tests, {{name}}!
'),
			'
The Tests

Just some tests, Jack!
'
		);

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.path);
			should.exist(newFile.relative);
			should.exist(newFile.contents);
			Buffer.isBuffer(newFile.contents).should.be.true;
			newFile.contents.toString().should.equal(fakeFile.expected);
			done();
		});

		stream.write(fakeFile.file);
	});

	it('should ignore the layout because of missing {{> body}} tag', function(done) {
		var stream = build({ name: 'Jack' }, { layout: '' });
		var fakeFile = getFile(new Buffer('
Just some tests, {{name}}!
'), '
Just some tests, Jack!
');

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.path);
			should.exist(newFile.relative);
			should.exist(newFile.contents);
			Buffer.isBuffer(newFile.contents).should.be.true;
			newFile.contents.toString().should.equal(fakeFile.expected);
			done();
		});

		stream.write(fakeFile.file);
	});

	it('should compile with helpers', function(done) {
		var stream = build({ name: 'Jack' }, {
			helpers: [
				{
					name: 'add',
					fn: function (a, b) {return a + b;}
				}
			]
		});

		var fakeFile = getFile(
			new Buffer('
1 + 2 is definitely equal to {{add 1 2}}.
'),
			'
1 + 2 is definitely equal to 3.
'
		);

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.path);
			should.exist(newFile.relative);
			should.exist(newFile.contents);
			Buffer.isBuffer(newFile.contents).should.be.true;
			newFile.contents.toString().should.equal(fakeFile.expected);
			done();
		});

		stream.write(fakeFile.file);
	});

	it('should compile with partials that use the provided helpers', function (done) {
		var stream = build({ name: 'Jack' }, {
			helpers: [
				{
					name: 'add',
					fn: function (a, b) {return a + b;}
				}
			],
			partials: [
				{
					name: 'addition',
					tpl: '
1 + 2 is definitely equal to {{add 1 2}}.
'
				}
			]
		});

		var fakeFile = getFile(
			new Buffer('
Fact: {{> addition}}
'),
			'
Fact:
1 + 2 is definitely equal to 3.

'
		);

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.path);
			should.exist(newFile.relative);
			should.exist(newFile.contents);
			Buffer.isBuffer(newFile.contents).should.be.true;
			newFile.contents.toString().should.equal(fakeFile.expected);
			done();
		});

		stream.write(fakeFile.file);
	});

	it('should compile with a layout that use the provided helpers', function(done) {
		var stream = build({ name: 'Jack' }, {
			layout: '

We know that 1 + 2 is {{add 1 2}}.
{{> body}}
',
			helpers: [
				{
					name: 'add',
					fn: function (a, b) {return a + b;}
				}
			]
		});

		var fakeFile = getFile(
			new Buffer('
But what is 1 - 2?
'),
			'

We know that 1 + 2 is 3.

But what is 1 - 2?

'
		);

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.path);
			should.exist(newFile.relative);
			should.exist(newFile.contents);
			Buffer.isBuffer(newFile.contents).should.be.true;
			newFile.contents.toString().should.equal(fakeFile.expected);
			done();
		});

		stream.write(fakeFile.file);
	});

	it('should compile with a layout and partials that use the provided helpers', function(done) {
		var stream = build({ name: 'Jack' }, {
			layout: '

We know that 1 + 2 is {{add 1 2}}.
{{> body}}
',
			helpers: [
				{
					name: 'add',
					fn: function (a, b) {return a + b;}
				},
				{
					name: 'subtract',
					fn: function (a, b) {return a - b;}
				}
			],
			partials: [
				{
					name: 'subtraction',
					tpl: '
Well, it turns out that 1 - 2 is {{subtract 1 2}}.
'
				}
			]
		});

		var fakeFile = getFile(
			new Buffer('
But what is 1 - 2?
{{> subtraction}}'),
			'

We know that 1 + 2 is 3.

But what is 1 - 2?
' +
			'
Well, it turns out that 1 - 2 is -1.

'
		);

		stream.on('data', function(newFile) {
			should.exist(newFile);
			should.exist(newFile.path);
			should.exist(newFile.relative);
			should.exist(newFile.contents);
			Buffer.isBuffer(newFile.contents).should.be.true;
			newFile.contents.toString().should.equal(fakeFile.expected);
			done();
		});

		stream.write(fakeFile.file);
	});
});


text:
package com.qihoo360.replugin.sample.demo1.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.qihoo360.replugin.RePlugin;
import com.qihoo360.replugin.sample.demo1.R;

/**
 * 描述类作用
 * <p>
 * 作者 coder
 * 创建时间 2017/7/5
 */

public class DemoFragment extends Fragment {

    public DemoFragment() {
    }

    private static final String TAG = "DemoFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView() called with: inflater = [" + inflater + "], container = [" + container + "], savedInstanceState = [" + savedInstanceState + "]");
        /**
         * 需要注意不能使用inflater及container因为他们的Context是宿主的
         */
        return LayoutInflater.from(RePlugin.getPluginContext()).inflate(R.layout.main_fragment, container, false);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<shibmd:MetadataProvider xmlns:samlmd="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:shibmd="urn:mace:shibboleth:2.0:metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="InlineMetadata" xsi:schemaLocation="urn:mace:shibboleth:2.0:metadata classpath:/schema/shibboleth-2.0-metadata.xsd urn:oasis:names:tc:SAML:2.0:metadata classpath:/schema/saml-schema-metadata-2.0.xsd " xsi:type="shibmd:InlineMetadataProvider">

    <samlmd:EntitiesDescriptor Name="urn:mace:incommon">

        <samlmd:EntityDescriptor entityID="urn:mace:incommon:internet2.edu">
            <samlmd:IDPSSODescriptor errorURL="https://origin.internet2.edu/error.html" protocolSupportEnumeration="urn:oasis:names:tc:SAML:1.1:protocol urn:mace:shibboleth:1.0">
                <samlmd:NameIDFormat>urn:mace:shibboleth:1.0:nameIdentifier</samlmd:NameIDFormat>
                <samlmd:SingleSignOnService Binding="urn:mace:shibboleth:1.0:profiles:AuthnRequest" Location="https://origin.internet2.edu/shibboleth/HS"/>
            </samlmd:IDPSSODescriptor>
            <samlmd:Organization>
                <samlmd:OrganizationName xml:lang="en">Internet2</samlmd:OrganizationName>
                <samlmd:OrganizationDisplayName xml:lang="en">Internet2</samlmd:OrganizationDisplayName>
                <samlmd:OrganizationURL xml:lang="en"/>
            </samlmd:Organization>
            <samlmd:ContactPerson contactType="technical">
                <samlmd:GivenName>IJ Kim</samlmd:GivenName>
                <samlmd:EmailAddress>ij@internet2.edu</samlmd:EmailAddress>
            </samlmd:ContactPerson>
        </samlmd:EntityDescriptor>

    </samlmd:EntitiesDescriptor>

</shibmd:MetadataProvider>


text:
export COMPOSE_FILE_PATH="${PWD}/target/classes/docker/docker-compose.yml"

if [ -z "${M2_HOME}" ]; then
  export MVN_EXEC="mvn"
else
  export MVN_EXEC="${M2_HOME}/bin/mvn"
fi

start() {
    docker volume create behavior-tutorial-acs-volume
    docker volume create behavior-tutorial-db-volume
    docker volume create behavior-tutorial-ass-volume
    docker-compose -f "$COMPOSE_FILE_PATH" up --build -d
}

start_share() {
    docker-compose -f "$COMPOSE_FILE_PATH" up --build -d behavior-tutorial-share
}

start_acs() {
    docker-compose -f "$COMPOSE_FILE_PATH" up --build -d behavior-tutorial-acs
}

down() {
    if [ -f "$COMPOSE_FILE_PATH" ]; then
        docker-compose -f "$COMPOSE_FILE_PATH" down
    fi
}

purge() {
    docker volume rm -f behavior-tutorial-acs-volume
    docker volume rm -f behavior-tutorial-db-volume
    docker volume rm -f behavior-tutorial-ass-volume
}

build() {
    $MVN_EXEC clean package
}

build_share() {
    docker-compose -f "$COMPOSE_FILE_PATH" kill behavior-tutorial-share
    yes | docker-compose -f "$COMPOSE_FILE_PATH" rm -f behavior-tutorial-share
    $MVN_EXEC clean package -pl behavior-tutorial-share,behavior-tutorial-share-docker
}

build_acs() {
    docker-compose -f "$COMPOSE_FILE_PATH" kill behavior-tutorial-acs
    yes | docker-compose -f "$COMPOSE_FILE_PATH" rm -f behavior-tutorial-acs
    $MVN_EXEC clean package -pl behavior-tutorial-integration-tests,behavior-tutorial-platform,behavior-tutorial-platform-docker
}

tail() {
    docker-compose -f "$COMPOSE_FILE_PATH" logs -f
}

tail_all() {
    docker-compose -f "$COMPOSE_FILE_PATH" logs --tail="all"
}

prepare_test() {
    $MVN_EXEC verify -DskipTests=true -pl behavior-tutorial-platform,behavior-tutorial-integration-tests,behavior-tutorial-platform-docker
}

test() {
    $MVN_EXEC verify -pl behavior-tutorial-platform,behavior-tutorial-integration-tests
}

case "$1" in
  build_start)
    down
    build
    start
    tail
    ;;
  build_start_it_supported)
    down
    build
    prepare_test
    start
    tail
    ;;
  start)
    start
    tail
    ;;
  stop)
    down
    ;;
  purge)
    down
    purge
    ;;
  tail)
    tail
    ;;
  reload_share)
    build_share
    start_share
    tail
    ;;
  reload_acs)
    build_acs
    start_acs
    tail
    ;;
  build_test)
    down
    build
    prepare_test
    start
    test
    tail_all
    down
    ;;
  test)
    test
    ;;
  *)
    echo "Usage: $0 {build_start|build_start_it_supported|start|stop|purge|tail|reload_share|reload_acs|build_test|test}"
esac


text:
namespace DW.ELA.Plugin.Inara.Model
{
    using DW.ELA.Utility.Json;
    using Newtonsoft.Json;

    public sealed class ApiOutputEvent
    {
        [JsonProperty("eventData")]
        public object EventData { get; internal set; }

        /// <summary>
        /// Gets status of event processing as returned by API
        /// </summary>
        [JsonProperty("eventStatus")]
        public int? EventStatus { get; internal set; }

        /// <summary>
        /// Gets error codes as returned by API
        /// </summary>
        [JsonProperty("eventStatusText")]
        public string EventStatusText { get; internal set; }

        public override string ToString() => Serialize.ToJson(this);

    }
}


text:
<?php

declare(strict_types=1);

namespace App\Nova;

use App\Models\DuesTransaction as AppModelsDuesTransaction;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\BelongsToMany;
use Laravel\Nova\Fields\Currency;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\MorphMany;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Http\Requests\NovaRequest;

/**
 * A Nova resource for dues transactions.
 *
 * @extends \App\Nova\Resource<\App\Models\DuesTransaction>
 */
class DuesTransaction extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = AppModelsDuesTransaction::class;

    /**
     * The relationships that should be eager loaded on index queries.
     *
     * @var array<string>
     */
    public static $with = ['payment', 'package', 'user'];

    /**
     * Get the displayble label of the resource.
     */
    public static function label(): string
    {
        return 'Dues Transactions';
    }

    /**
     * Get the displayble singular label of the resource.
     */
    public static function singularLabel(): string
    {
        return 'Dues Transaction';
    }

    /**
     * The logical group associated with the resource.
     *
     * @var string
     */
    public static $group = 'Dues';

    /**
     * The number of results to display in the global search.
     *
     * @var int
     */
    public static $globalSearchResults = 2;

    /**
     * Get the fields displayed by the resource.
     */
    public function fields(NovaRequest $request): array
    {
        return [
            ID::make(),

            BelongsTo::make('Paid By', 'user', User::class)
                ->searchable(),

            BelongsTo::make('Dues Package', 'package', DuesPackage::class),

            Text::make('Status')
                ->resolveUsing(static fn (string $str): string => ucfirst($str))
                ->exceptOnForms(),

            Currency::make('Payment Due', function (): ?float {
                // @phan-suppress-next-line PhanPluginNonBoolBranch
                if ($this->is_paid) {
                    return null;
                }

                if ($this->package === null) {
                    return null;
                }

                if (! $this->package->is_active) {
                    return null;
                }

                return $this->package->cost;
            })
                ->onlyOnDetail(),

            BelongsToMany::make('Merchandise', 'jankForNova')
                ->fields(new MerchandisePivotFields()),

            MorphMany::make('Payments', 'payment', Payment::class)
                ->onlyOnDetail(),

            self::metadataPanel(),
        ];
    }

    /**
     * Get the filters available for the resource.
     *
     * @return array<\Laravel\Nova\Filters\Filter>
     */
    public function filters(NovaRequest $request): array
    {
        return $request->user()->can('read-teams-membership') ? [
            new Filters\DuesTransactionTeam(),
            new Filters\DuesTransactionPaymentStatus(),
        ] : [
            new Filters\DuesTransactionPaymentStatus(),
        ];
    }

    /**
     * Get the actions available for the resource.
     *
     * @return array<\Laravel\Nova\Actions\Action>
     *
     * @phan-suppress PhanTypeMismatchArgumentProbablyReal
     */
    public function actions(NovaRequest $request): array
    {
        return [
            (new Actions\AddPayment())->canSee(static function (Request $request): bool {
                $transaction = AppModelsDuesTransaction::find($request->resourceId);

                if ($transaction !== null && is_a($transaction, AppModelsDuesTransaction::class)) {
                    if ($transaction->user->id === $request->user()->id) {
                        return false;
                    }

                    if ($transaction->is_paid) {
                        return false;
                    }

                    if (! $transaction->package->is_active) {
                        return false;
                    }

                    if (! $transaction->user->signed_latest_agreement) {
                        return false;
                    }
                }

                return $request->user()->can('create-payments');
            })->canRun(
                static fn (NovaRequest $r, AppModelsDuesTransaction $t): bool => $r->user()->can(
                    'create-payments'
                ) && ($t->user()->first()->id !== $r->user()->id)
            )->confirmButtonText('Add Payment'),
        ];
    }

    // This hides the edit button from indexes. This is here to hide the edit button on the merchandise pivot.
    public function authorizedToUpdateForSerialization(NovaRequest $request): bool
    {
        return $request->user()->can('update-dues-transactions') && $request->viaResource !== 'merchandise';
    }

    /**
     * Get the search result subtitle for the resource.
     */
    public function subtitle(): ?string
    {
        return $this->user->full_name.' | '.$this->package->name.' | '.ucfirst($this->status);
    }
}


text:
package com.twitter.server

import com.twitter.finagle.tracing.{Trace, SpanId, TraceId}
import com.twitter.logging.{Level => TwLevel, StringHandler}
import java.util.logging.Logger
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class LogFormatTest extends FunSuite {
  def testStringHandler(f: (Logger, StringHandler) => Unit) {
    val handler = new StringHandler
    handler.setFormatter(new LogFormatter)

    val logger = Logger.getLogger(this.getClass.getSimpleName)
    logger.setUseParentHandlers(false)
    logger.addHandler(handler)

    f(logger, handler)
  }

  test("LogFormat contains trace ID if set") {
    testStringHandler { (log, handler) =>
      Trace.letId(TraceId(None, None, SpanId(1), None)) {
        log.info("test")
        assert(handler.get.contains("TraceId:0000000000000001"))
      }
    }
  }

  test("LogFormat omits trace ID if not set") {
    testStringHandler { (log, handler) =>
      log.info("test")
      assert(!handler.get.contains("TraceId"))
    }
  }

  test("com.twitter.logging.Levels are known") {
    testStringHandler { (log, handler) =>
      log.log(TwLevel.ERROR, "anError")
      assert(handler.get.startsWith("E"), handler.get)
    }
    testStringHandler { (log, handler) =>
      log.log(TwLevel.CRITICAL, "anCritical")
      assert(handler.get.startsWith("E"), handler.get)
    }
  }
}