text:
View specs are a way to add documentation and validation to components, inspired by Clojure's [Spec](https://clojure.org/about/spec).

## Benefits

1. Documentation - components "explain how to use themselves" when props are declared, with optional per-prop docstrings.

2. Debugging - Runtime validation of props and children to ensure correct usage and provide helpful error messages

3. Productivity - Efficient pruning of props that are passed down to child components.

## Usage

**defview** accepts a methods map, where we can include `:spec/props` and `:spec/children` keys. `:spec/props` should be a map which pairs keys with 'specs' that describe the prop:

```clj
(defview greeting
  {:spec/props {:name :String}}
  [this]
  [:div (str "Hello, " (get this :name) ".")])
```

Above, we used the built-in `:String` spec. A spec may be any of the following:

1. The keyword of a registered spec. The built-in specs are:
   ```clj
   :Boolean :String :Number :Function :Map :Vector :Element :Hiccup :SVG :Object :Keyword
   ```
2. A set of permissible values:
    ```clj
    {:spec/props {:flavour #{:vanilla :chocolate}}}
    ```
3. A predicate function:
    ```clj
    {:spec/props {:age #(> % 13)}}
    ```
3. A map containing a `:spec` key, which itself is a spec, alongside additional options.
    ```clj
    {:spec/props {:age {:spec #(> % 13)
                        :required true}}}
    ```

### Spec options

With the map form, we can add metadata like `:doc` and `:required`.

```clj
(defview greeting
  {:spec/props {:name {:spec     :String
                       :doc      "The name of a person to be greeted by this component."
                       :required true}}}
  [this]
  [:div (str "Hello, " (get this :name) ".")])
```

| key | info |
| --- | --- |
| **:doc** (string) | docstring that describes what the prop is for, usage instructions, etc. |
| **:required** (boolean) | key *must* be present |
| **:pass-through** (boolean) | key will be passed on to child component (via `re-view.core/pass-props`)|

### Defining specs

For specs that we wish to re-use in multiple places, we call `defspecs` with a map of spec bindings:

```clj
(defspecs {::label {:spec :String
                    :doc "Label for a form input"}})
```

Now we can use the `::label` spec:

```clj
{:spec/props {:label ::label}}
```

### Specifying keys

Above, we've repeated ourselves, because the `::label` spec refers to the `:label` key in a props map. Under `:props/keys`, we can specify a set of registered specs, which will be paired with their equivalent non-namespaced prop keys:

```clj
{:spec/props {:props/keys #{::label}}
;; means the component expects a `:label` prop, which conforms to the `::label` spec
```

This is more concise.

Specs in `:props/keys` are matched to _simple_ (non-namespaced) keywords in props. `::label` matches `:label`, and so on.

Lastly, we can add `:spec/children` to spec the additional arguments passed to views. This should be a vector of specs, plus the special `:&` keyword, which behaves like the `&` in ordinary Clojure argument lists.

```clj
;; spec for a single :Element child
{:spec/children [:Element]}

;; spec for two children, a :Number and :Element
{:spec/children [:Number :Element]}

;; spec for any number of :Element children
{:spec/children [:& :Element]}

;; spec for a :Number followed by any number of :Element children
{:spec/children [:Number :& :Element]}
```

To recap, we can include the following keys in a component's method map:

| key | info |
| --- | --- |
| **:spec/props** | A map of the form `{<prop-key> <spec>}` |
| **:spec/children** | A vector of specs, aligned to the child args accepted by the component |

In the `:spec/props` map, we may include the special keys:

| key | info |
| --- | --- |
| **:props/keys** | A set of registered specs (keywords) of permissible props for the component |
| **:props/keys-req** | A set of registered specs representing _required_ props for the component |

**Why not just use Clojure Spec?**

While there are similarities between view specs and Clojure Spec, they do not solve precisely the same problems, and view specs were designed with particular requirements in mind:

1. Compiled bundle size: View specs support _runtime_ behaviour (eg. managing props flow, specifying prop defaults), so whatever 'spec' code we choose will be included in app bundles. Clojure Spec has many dependencies and greatly increases bundle sizes; this problem is even more extreme with self-hosted ClojureScript, which Re-View is designed to support. `re-view.view-spec` is ~130 LOC.
2. Documentation: Clojure Spec does not yet support docstrings.
3. Ease of learning: We'd like view specs to be as simple to learn and use as React prop-types. Clojure Spec's great power comes at the cost of a steeper learning curve.

One can certainly use Clojure Spec _in addition_ to view specs, for more inspection and testing during development.

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include <string>
#include <vector>

#include "mediafire_sdk/http/shared_buffer.hpp"
#include "mediafire_sdk/http/headers.hpp"
#include "mediafire_sdk/api/response_base.hpp"

#include "boost/date_time/posix_time/ptime.hpp"

namespace mf {
namespace api {
/** API action path "upload" */
namespace upload {
/** API action "upload/check" */
namespace check {
/** API path "/api/upload/check" */
namespace v0 {

enum class Resumable
{
    /** API value "no" */
    NotResumable,
    /** API value "yes" */
    Resumable
};

enum class HashAlreadyInSystem
{
    /** API value "no" */
    No,
    /** API value "yes" */
    Yes
};

enum class HashAlreadyInAccount
{
    /** API value "no" */
    HashNewToAccount,
    /** API value "yes" */
    HashExistsInAccount
};

enum class HashAlreadyInFolder
{
    /** API value "no" */
    HashNewToFolder,
    /** API value "yes" */
    HashExistsInFolder
};

enum class FilenameInFolder
{
    /** API value "no" */
    No,
    /** API value "yes" */
    Yes
};

enum class FileExistsWithDifferentHash
{
    /** API value "no" */
    No,
    /** API value "yes" */
    Yes
};

enum class StorageLimitExceeded
{
    /** API value "no" */
    No,
    /** API value "yes" */
    Yes
};

enum class ActionOnDuplicate
{
    /** API value "skip" */
    Skip,
    /** API value "keep" */
    Keep,
    /** API value "replace" */
    Replace
};

enum class VersionControl
{
    /** API value "keep_revision" */
    KeepRevision,
    /** API value "none" */
    Required
};

enum class AllUnitsReady
{
    /** API value "no" */
    No,
    /** API value "yes" */
    Yes
};

/**
 * @class ResponseData
 * @brief Response data from API request "upload/check"
 *
 * This data is only available if the API request was successful.
 */
class ResponseData
{
public:
    ResponseData() :
        hash_exists(HashAlreadyInSystem::No),
        hash_in_account(HashAlreadyInAccount::HashNewToAccount),
        hash_in_folder(HashAlreadyInFolder::HashNewToFolder),
        file_exists(FilenameInFolder::No),
        hash_different(FileExistsWithDifferentHash::No),
        available_space(0),
        used_storage_size(0),
        storage_limit(0),
        storage_limit_exceeded(StorageLimitExceeded::No)
    {}
    struct ResumableData
    {
        /** API response field "number_of_units" */
        uint32_t number_of_units;

        /** API response field "all_units_ready" */
        AllUnitsReady all_units_ready;

        /** API response field "unit_size" */
        uint64_t unit_size;

        /** API response field "bitmap.count" */
        boost::optional<uint32_t> bitmap_count;

        /** API response field "bitmap.words" */
        std::vector<uint16_t> words;
    };
    /** API response field "response.hash_exists" */
    HashAlreadyInSystem hash_exists;

    /** API response field "response.in_account" */
    HashAlreadyInAccount hash_in_account;

    /** API response field "response.in_folder" */
    HashAlreadyInFolder hash_in_folder;

    /** API response field "response.file_exists" */
    FilenameInFolder file_exists;

    /** API response field "response.different_hash" */
    FileExistsWithDifferentHash hash_different;

    /** API response field "response.duplicate_quickkey" */
    boost::optional<std::string> duplicate_quickkey;

    /** API response field "response.available_space" */
    uint64_t available_space;

    /** API response field "response.used_storage_size" */
    uint64_t used_storage_size;

    /** API response field "response.storage_limit" */
    uint64_t storage_limit;

    /** API response field "response.storage_limit_exceeded" */
    StorageLimitExceeded storage_limit_exceeded;

    /** API response field "response.resumable_upload" */
    boost::optional<ResumableData> resumable;
};

/**
 * @class Response
 * @brief Response from API request "upload/check"
 */
class Response : public ResponseBase
{
public:
    /** Parsed API response on successful parse. */
    boost::optional<ResponseData> response_data;
};

class Impl;

/**
 * @class Request
 * @brief Make API request "upload/check"
 */
class Request
{
public:

    // Enums in class namespace for usage with templates
    using Resumable = ::mf::api::upload::check::v0::Resumable;
    using HashAlreadyInSystem = ::mf::api::upload::check::v0::HashAlreadyInSystem;
    using HashAlreadyInAccount = ::mf::api::upload::check::v0::HashAlreadyInAccount;
    using HashAlreadyInFolder = ::mf::api::upload::check::v0::HashAlreadyInFolder;
    using FilenameInFolder = ::mf::api::upload::check::v0::FilenameInFolder;
    using FileExistsWithDifferentHash = ::mf::api::upload::check::v0::FileExistsWithDifferentHash;
    using StorageLimitExceeded = ::mf::api::upload::check::v0::StorageLimitExceeded;
    using ActionOnDuplicate = ::mf::api::upload::check::v0::ActionOnDuplicate;
    using VersionControl = ::mf::api::upload::check::v0::VersionControl;
    using AllUnitsReady = ::mf::api::upload::check::v0::AllUnitsReady;

    /**
     * API request "upload/check"
     *
     * @param filename API parameter "filename"
     */
    explicit Request(
            std::string filename
        );

    /**
     * Optional API parameter "hash"
     *
     * @param hash Set parameter "hash" in API request.
     */
    void SetHash(std::string hash);

    /**
     * Optional API parameter "size"
     *
     * @param filesize Set parameter "size" in API request.
     */
    void SetFilesize(uint64_t filesize);

    /**
     * Optional API parameter "folder_key"
     *
     * @param target_parent_folderkey Set parameter "folder_key" in API request.
     */
    void SetTargetParentFolderkey(std::string target_parent_folderkey);

    /**
     * Optional API parameter "filedrop_key"
     *
     * @param target_filedrop Set parameter "filedrop_key" in API request.
     */
    void SetTargetFiledrop(std::string target_filedrop);

    /**
     * Optional API parameter "path"
     *
     * @param path Set parameter "path" in API request.
     */
    void SetPath(std::string path);

    /**
     * Optional API parameter "resumable"
     *
     * @param resumable Set parameter "resumable" in API request.
     */
    void SetResumable(Resumable resumable);

    // Remaining functions are for use by API library only. --------------------

    /** Requester/SessionMaintainer expected type. */
    using ResponseType = Response;

    /** Requester/SessionMaintainer expected type. */
    using ResponseDataType = ResponseData;

    /** Requester/SessionMaintainer expected type. */
    typedef std::function< void( const ResponseType & data)> CallbackType;

    /** Requester/SessionMaintainer expected type. */
    void SetCallback( CallbackType callback_function );

    /** Requester expected method. */
    void HandleContent(
            const std::string & url,
            const mf::http::Headers & headers,
            const std::string & content
        );

    /** Requester expected method. */
    void HandleError(
            const std::string & url,
            std::error_code ec,
            const std::string & error_string
        );

    /** Requester expected method. */
    std::string Url(const std::string & hostname) const;

    /** Requester optional method. */
    mf::http::SharedBuffer::Pointer GetPostData();

    /** SessionMaintainer expected method. */
    void SetSessionToken(
            std::string session_token,
            std::string time,
            int secret_key
        );
private:
    std::shared_ptr<Impl> impl_;
};
}  // namespace v0

}  // namespace check
}  // namespace upload
}  // namespace api
}  // namespace mf


text:
==============================
 Managers - djcelery.managers
==============================

.. contents::
    :local:
.. currentmodule:: djcelery.managers

.. automodule:: djcelery.managers
    :members:
    :undoc-members:


text:
class Haplotype;
class VariantGroup;
class AlignmentDB;

struct Variant
{
    static void write_vcf_header(FILE* fp,
                                 const std::vector<std::string>& header_lines = std::vector<std::string>());

    static std::string make_vcf_header_key_value(const std::string& key, const std::string& value);

    static std::string make_vcf_tag_string(const std::string& tag,
                                           const std::string& id,
                                           int count,
                                           const std::string& type,
                                           const std::string& description);

    Variant() { }
    Variant(const std::string& line) { read_vcf(line); }

    // generate a unique identifier for this variant
    std::string key() const
    {
        std::stringstream out;
        out << ref_name << ':' << ref_position << ':' << ref_seq << ':' << alt_seq;
        return out.str();
    }

    void write_vcf(FILE* fp) const
    {
        assert(fp != NULL);
        const char* gt_def = "GT";
        const char* gt_str = genotype.empty() ? "." : genotype.c_str();

        fprintf(fp, "%s\t%zu\t%s\t", ref_name.c_str(), ref_position + 1, ".");
        fprintf(fp, "%s\t%s\t%.1lf\t", ref_seq.c_str(), alt_seq.c_str(), quality);
        fprintf(fp, "%s\t%s\t%s\t%s\n", filter.empty() ? "PASS" : filter.c_str(), info.c_str(), gt_def, gt_str);
    }

    void read_vcf(const std::string& line)
    {
        std::stringstream ss(line);
        std::string dummy;
        ss >> ref_name;
        ss >> ref_position;
        ss >> dummy; // ID, not used
        ss >> ref_seq;
        ss >> alt_seq;
        ss >> quality;
        ss >> filter;
        ss >> info;
        ss >> dummy; // GT tag
        ss >> genotype;

        // VCF is 1-based but we internally represent a variant as 0-based
        ref_position -= 1;

        assert(!ref_name.empty());
        assert(!ref_seq.empty());
        assert(!alt_seq.empty());
        //assert(ref_position >= 0);
        assert(quality >= 0.0f);
    }

    template<typename T>
    void add_info(const std::string& key, T value)
    {
        std::stringstream ss;
        ss << key << "=" << value;
        if(info.empty()) {
            info = ss.str();
        } else {
            info.append(1, ';');
            info.append(ss.str());
        }
    }

    bool is_snp() const { return ref_seq.length() == 1 && alt_seq.length() == 1; }

    std::string ref_name;
    size_t ref_position;
    std::string ref_seq;
    std::string alt_seq;
    double quality;
    std::string filter;
    std::string info;
    std::string genotype;
};

inline bool sortByPosition(const Variant& a, const Variant& b)
{
    return a.ref_name == b.ref_name ?
        a.ref_position < b.ref_position :
        a.ref_name < b.ref_name;
}

class VariantKeyComp
{
    public:
        inline bool operator()(const Variant& a, const Variant& b) const
        {
            return a.key() < b.key();
        }
};

class VariantKeyEqualityComp
{
    public:
        inline bool operator()(const Variant& a, const Variant& b) const
        {
            return a.key() == b.key();
        }
};

// Read a collection of variants from a VCF file
std::vector<Variant> read_variants_from_file(const std::string& filename);
std::vector<Variant> read_variants_for_region(const std::string& filename,
                                              const std::string& contig,
                                              int region_start,
                                              int region_end);

// Remove variants that are in the vector fewer than min_count times
void filter_variants_by_count(std::vector<Variant>& variants, int min_count);

// Remove snps or indels
void filter_out_non_snp_variants(std::vector<Variant>& variants);

// Expand the HMMInputSequence to contain alternatives representing
// methylated versions with the same basic sequence. The output includes
// the unmethylated version of the sequence over the nucleotide alphabet
std::vector<HMMInputSequence> generate_methylated_alternatives(const HMMInputSequence& sequence,
                                                               const std::vector<std::string>& methylation_types);

// Score the variants contained within the input group using the nanopolish HMM
void score_variant_group(VariantGroup& variant_group,
                         Haplotype base_haplotype,
                         const std::vector<HMMInputData>& input,
                         const int max_haplotypes,
                         const int ploidy,
                         const bool genotype_all_input_variants,
                         const uint32_t alignment_flags,
                         const std::vector<std::string>& methylation_types);

// Call genotypes for the variants in this group using a simple model
std::vector<Variant> simple_call(VariantGroup& variant_group,
                                 const int ploidy,
                                 const bool genotype_all_input_variants);

// Call genotypes for the variants in this group using support from nearby variants
std::vector<Variant> multi_call(VariantGroup& variant_group,
                                std::vector<const VariantGroup*> neighbor_groups,
                                const int ploidy,
                                const bool genotype_all_input_variants);

// Score a single variant, stopping when the absolute value of the score relative
// to the reference meets a threshold
Variant score_variant_thresholded(const Variant& input_variant,
                                  Haplotype base_haplotype,
                                  const std::vector<HMMInputData>& input,
                                  const uint32_t alignment_flags,
                                  const uint32_t score_threshold,
                                  const std::vector<std::string>& methylation_types);

// Annotate each SNP variant in the input set with the fraction of reads supporting every possible base at the position
void annotate_variants_with_all_support(std::vector<Variant>& input, const AlignmentDB& alignments, int min_flanking_sequence, const uint32_t alignment_flags);

#endif


text:
package org.cinnamon.core.repository;

import javax.persistence.EntityManager;

import org.cinnamon.core.domain.UserActivity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author 동성
 * @since 2015. 1. 28.
 */
@Repository("configuration.userActivityRepository")
public class UserActivityRepository {

	@Autowired
	EntityManager em;

	public void persist(UserActivity userActivity) {
		em.persist(userActivity);
	}

}


text:
//
//   Copyright 2015 Blu Age Corporation - Plano, Texas
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
using System;
using System.Runtime.Serialization;

namespace Summer.Batch.Extra.Ebcdic.Exception
{
    /// <summary>
    ///  Exception thrown by EbcdicReader and EbcdicWriter when the format of a field is missing or unknown.
    /// </summary>
    [Serializable]
    public class UnexpectedFieldTypeException : EbcdicException
    {
        private readonly char _fieldType;

        /// <summary>
        /// Custom constructor with a message
        /// </summary>
        /// <param name="message"></param>
        public UnexpectedFieldTypeException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Custom constructor with a message and an inner exception
        /// </summary>
        /// <param name="message"></param>
        /// <param name="cause"></param>
        public UnexpectedFieldTypeException(string message, System.Exception cause)
            : base(message, cause)
        {
        }

        /// <summary>
        /// Custom constructor with a filedType
        /// </summary>
        /// <param name="fieldType"></param>
        public UnexpectedFieldTypeException(char fieldType)
            : base("Unexpected field encountered: " + fieldType)
        {
            _fieldType = fieldType;
        }

        /// <summary>
        /// Constructor for deserialization.
        /// </summary>
        /// <param name="info">the info holding the serialization data</param>
        /// <param name="context">the serialization context</param>
        public UnexpectedFieldTypeException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
            _fieldType = info.GetChar("FieldType");
        }

        /// <summary>
        /// override on getMessage
        /// </summary>
        public override string Message
        {
            get { return "Unexpected field encountered: " + _fieldType; }
        }

        /// <summary>
        /// Sets the <see cref="SerializationInfo"/> with information about the exception.
        /// </summary>
        /// <param name="info">
        /// The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.
        /// </param>
        /// <param name="context">
        /// The <see cref="StreamingContext"/> that contains contextual information about the source or destination.
        /// </param>
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info,context);
            info.AddValue("FieldType",_fieldType);
        }
    }
}


text:
/*
  Rewrite the PrintCalendar class in Listing 6.12 to display a calendar for a
  specified month using the Calendar and GregorianCalendar classes. Your
  program receives the month and year from the command line. For example:

  java E13_04 5 2016

  You can also run the program without the year. In this case, the year is the
  current year. If you run the program without specifying a month and a year,
  the month is the current month.
*/

import java.util.Calendar;
import java.util.GregorianCalendar;

public class E13_04 {
  public static void main(String[] args) {
    if (!isValidInput(args)) {
      System.out.println("Usage: java E13_04 [month(1-12)] [year(4 digits)]");
      System.exit(1);
    }

    // create a GregorianCalendar for the current date in order to handle
    // default input values
    GregorianCalendar g = new GregorianCalendar();
    int month = 0;
    int year = 0;

    // if input is ordinary (month year)
    if (args.length == 2) {
      month = Integer.parseInt(args[0]) - 1; // decrement input month by 1
      year = Integer.parseInt(args[1]);
    // if input is month only
  } else if (args.length == 1 && args[0].length() == 1 ||
                                 args[0].length() == 2) {
      month = Integer.parseInt(args[0]) - 1; // decrement input month by 1
      year = g.get(Calendar.YEAR);
    // if input is year only
    } else if (args.length == 1 && args[0].length() == 4) {
      month = g.get(Calendar.MONTH);
      year = Integer.parseInt(args[0]);
    // if input is default (blank)
    } else {
      month = g.get(Calendar.MONTH);
      year = g.get(Calendar.YEAR);
    }

    g = new GregorianCalendar(year, month, 1);
    PrintCalendar.printMonth(g);
  }

  public static boolean isValidInput(String[] args) {
    if (args.length > 2) {
      return false;
    }

    if (args.length == 2) {
      if (!args[0].matches("[1-9]") && !args[0].matches("1[012]")) {
        return false;
      }
      if (!args[1].matches("\\d\\d\\d\\d")) {
        return false;
      }
    }

    if (args.length == 1) {
      if (!args[0].matches("[1-9]") && !args[0].matches("1[012]") &&
          !args[0].matches("\\d\\d\\d\\d")) {
        return false;
      }
    }

    return true;
  }
}


text:
package org.apache.oozie.executor.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.oozie.ErrorCode;
import org.apache.oozie.client.CoordinatorAction;
import org.apache.oozie.util.ParamChecker;

/**
 * Get the status of Coordinator actions for a given Coordinator job
 */
public class CoordJobGetActionsStatusJPAExecutor implements JPAExecutor<List<CoordinatorAction.Status>> {

    private String coordJobId = null;

    public CoordJobGetActionsStatusJPAExecutor(String coordJobId) {
        ParamChecker.notNull(coordJobId, "coordJobId");
        this.coordJobId = coordJobId;
    }

    @Override
    public String getName() {
        return "CoordJobGetActionsStatusJPAExecutor";
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<CoordinatorAction.Status> execute(EntityManager em) throws JPAExecutorException {
        try {
            Query q = em.createNamedQuery("GET_COORD_ACTIONS_STATUS");
            q.setParameter("jobId", coordJobId);
            List<String> coordStatusResultList = q.getResultList();
            List<CoordinatorAction.Status> coordStatus = new ArrayList<CoordinatorAction.Status>();
            for (String a : coordStatusResultList) {
                coordStatus.add(CoordinatorAction.Status.valueOf(a));
            }
            return coordStatus;
        }
        catch (Exception e) {
            throw new JPAExecutorException(ErrorCode.E0603, e.getMessage(), e);
        }
    }
}


text:
package command

import (
	"fmt"
	"strings"

	"github.com/hashicorp/consul/command/base"
	"github.com/hashicorp/serf/coordinate"
)

// RTTCommand is a Command implementation that allows users to query the
// estimated round trip time between nodes using network coordinates.
type RTTCommand struct {
	base.Command
}

func (c *RTTCommand) Help() string {
	helpText := `
Usage: consul rtt [options] node1 [node2]

  Estimates the round trip time between two nodes using Consul's network
  coordinate model of the cluster.

  At least one node name is required. If the second node name isn't given, it
  is set to the agent's node name. Note that these are node names as known to
  Consul as "consul members" would show, not IP addresses.

  By default, the two nodes are assumed to be nodes in the local datacenter
  and the LAN coordinates are used. If the -wan option is given, then the WAN
  coordinates are used, and the node names must be suffixed by a period and
  the datacenter (eg. "myserver.dc1").

  It is not possible to measure between LAN coordinates and WAN coordinates
  because they are maintained by independent Serf gossip areas, so they are
  not compatible.

` + c.Command.Help()

	return strings.TrimSpace(helpText)
}

func (c *RTTCommand) Run(args []string) int {
	var wan bool

	f := c.Command.NewFlagSet(c)

	f.BoolVar(&wan, "wan", false, "Use WAN coordinates instead of LAN coordinates.")

	if err := c.Command.Parse(args); err != nil {
		return 1
	}

	// They must provide at least one node.
	nodes := f.Args()
	if len(nodes) < 1 || len(nodes) > 2 {
		c.UI.Error("One or two node names must be specified")
		c.UI.Error("")
		c.UI.Error(c.Help())
		return 1
	}

	// Create and test the HTTP client.
	client, err := c.Command.HTTPClient()
	if err != nil {
		c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err))
		return 1
	}
	coordClient := client.Coordinate()

	var source string
	var coord1, coord2 *coordinate.Coordinate
	if wan {
		source = "WAN"

		// Default the second node to the agent if none was given.
		if len(nodes) < 2 {
			agent := client.Agent()
			self, err := agent.Self()
			if err != nil {
				c.UI.Error(fmt.Sprintf("Unable to look up agent info: %s", err))
				return 1
			}

			node, dc := self["Config"]["NodeName"], self["Config"]["Datacenter"]
			nodes = append(nodes, fmt.Sprintf("%s.%s", node, dc))
		}

		// Parse the input nodes.
		parts1 := strings.Split(nodes[0], ".")
		parts2 := strings.Split(nodes[1], ".")
		if len(parts1) != 2 || len(parts2) != 2 {
			c.UI.Error("Node names must be specified as <node name>.<datacenter> with -wan")
			return 1
		}
		node1, dc1 := parts1[0], parts1[1]
		node2, dc2 := parts2[0], parts2[1]

		// Pull all the WAN coordinates.
		dcs, err := coordClient.Datacenters()
		if err != nil {
			c.UI.Error(fmt.Sprintf("Error getting coordinates: %s", err))
			return 1
		}

		// See if the requested nodes are in there. We only compare
		// coordinates in the same areas.
		var area1, area2 string
		for _, dc := range dcs {
			for _, entry := range dc.Coordinates {
				if dc.Datacenter == dc1 && entry.Node == node1 {
					area1 = dc.AreaID
					coord1 = entry.Coord
				}
				if dc.Datacenter == dc2 && entry.Node == node2 {
					area2 = dc.AreaID
					coord2 = entry.Coord
				}

				if area1 == area2 && coord1 != nil && coord2 != nil {
					goto SHOW_RTT
				}
			}
		}

		// Nil out the coordinates so we don't display across areas if
		// we didn't find anything.
		coord1, coord2 = nil, nil
	} else {
		source = "LAN"

		// Default the second node to the agent if none was given.
		if len(nodes) < 2 {
			agent := client.Agent()
			node, err := agent.NodeName()
			if err != nil {
				c.UI.Error(fmt.Sprintf("Unable to look up agent info: %s", err))
				return 1
			}
			nodes = append(nodes, node)
		}

		// Pull all the LAN coordinates.
		entries, _, err := coordClient.Nodes(nil)
		if err != nil {
			c.UI.Error(fmt.Sprintf("Error getting coordinates: %s", err))
			return 1
		}

		// See if the requested nodes are in there.
		for _, entry := range entries {
			if entry.Node == nodes[0] {
				coord1 = entry.Coord
			}
			if entry.Node == nodes[1] {
				coord2 = entry.Coord
			}

			if coord1 != nil && coord2 != nil {
				goto SHOW_RTT
			}
		}
	}

	// Make sure we found both coordinates.
	if coord1 == nil {
		c.UI.Error(fmt.Sprintf("Could not find a coordinate for node %q", nodes[0]))
		return 1
	}
	if coord2 == nil {
		c.UI.Error(fmt.Sprintf("Could not find a coordinate for node %q", nodes[1]))
		return 1
	}

SHOW_RTT:

	// Report the round trip time.
	dist := fmt.Sprintf("%.3f ms", coord1.DistanceTo(coord2).Seconds()*1000.0)
	c.UI.Output(fmt.Sprintf("Estimated %s <-> %s rtt: %s (using %s coordinates)", nodes[0], nodes[1], dist, source))
	return 0
}

func (c *RTTCommand) Synopsis() string {
	return "Estimates network round trip time between nodes"
}


text:
package jfrn.aljavaportatil.application;

import java.io.IOException;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import jfrn.aljavaportatil.view.IntroductionController;

public class IntroductionApp extends Application {

	private Stage stage;
	private AnchorPane rootLayout;

	@Override
	public void start(Stage primaryStage) throws Exception {
		stage = primaryStage;
		stage.setTitle("Aljava Portátil - JFRN v1.0");
		stage.setResizable(false);

		stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            public void handle(WindowEvent t) {
                Platform.exit();
                System.exit(0);
            }
        });

		initRootLayout();
	}

	private void initRootLayout() throws IOException {
		FXMLLoader loader = new FXMLLoader();
				loader.setLocation(IntroductionApp.class.getResource("/jfrn/aljavaportatil/view/IntroductionView.fxml"));
		rootLayout = (AnchorPane) loader.load();

		Scene scene = new Scene(rootLayout);
		stage.setScene(scene);

		IntroductionController controller = loader.getController();
		controller.setIntroductionApp(this);

		stage.show();
	}

	public static void main( String[] args ) {
		launch(args);
	}

}


text:
"""Look ahead mechanism in regular expressions.

use (?=)
"""
import re

pattern = re.compile(r'(?=fox)')
result = pattern.search("The quick brown fox")
print result

"""
Match any word followed by a comma.
The example below is not the same as re.compile(r"\w+,")
For this will result in ['me,', 'myself,']
"""
patt = re.compile(r"\w+(?=,)")
res = patt.findall("Me, myself, and I")
print res

"""Use alternation (|) to match
any word followed by comma or a dot.
"""
p = re.compile(r'\w+(?=,|\.)')
results = p.findall("Here they are: Tom, Dick, and Harry.")
print results


text:
<?php

namespace Drupal\commerce_payment\Event;

use Drupal\commerce_order\Entity\OrderInterface;
use Symfony\Component\EventDispatcher\Event;

/**
 * Defines the event for filtering the available payment gateways.
 *
 * @see \Drupal\commerce_payment\Event\PaymentEvents
 */
class FilterPaymentGatewaysEvent extends Event {

  /**
   * The payment gateways.
   *
   * @var \Drupal\commerce_payment\Entity\PaymentGatewayInterface[]
   */
  protected $paymentGateways;

  /**
   * The order.
   *
   * @var \Drupal\commerce_order\Entity\OrderInterface
   */
  protected $order;

  /**
   * Constructs a new FilterPaymentGatewaysEvent object.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentGatewayInterface[] $payment_gateways
   *   The payment gateways.
   * @param \Drupal\commerce_order\Entity\OrderInterface $order
   *   The order.
   */
  public function __construct(array $payment_gateways, OrderInterface $order) {
    $this->paymentGateways = $payment_gateways;
    $this->order = $order;
  }

  /**
   * Gets the payment gateways.
   *
   * @return \Drupal\commerce_payment\Entity\PaymentGatewayInterface[]
   *   The payment gateways.
   */
  public function getPaymentGateways() {
    return $this->paymentGateways;
  }

  /**
   * Sets the payment gateways.
   *
   * @param \Drupal\commerce_payment\Entity\PaymentGatewayInterface[] $payment_gateways
   *   The payment gateways.
   *
   * @return $this
   */
  public function setPaymentGateways(array $payment_gateways) {
    $this->paymentGateways = $payment_gateways;
    return $this;
  }

  /**
   * Gets the order.
   *
   * @return \Drupal\commerce_order\Entity\OrderInterface
   *   The order.
   */
  public function getOrder() {
    return $this->order;
  }

}


text:
package storage::hp::p2000::xmlapi::mode::health;

use base qw(centreon::plugins::templates::hardware);

use strict;
use warnings;

sub set_system {
    my ($self, %options) = @_;

    $self->{regexp_threshold_numeric_check_section_option} =
        '^(?:sensor|fan\.speed)$';

    $self->{cb_hook1} = 'init_health';

    $self->{thresholds} = {
        # disk, enclosure, vdisk, saslink, fan
        default => [
            ['ok', 'OK'],
            ['degraded', 'WARNING'],
            ['failed|fault', 'CRITICAL'],
            ['unknown', 'UNKNOWN'],
            ['not available', 'OK']
        ],
        fru => [
            ['ok', 'OK'],
            ['absent', 'WARNING'],
            ['fault', 'CRITICAL'],
            ['not available', 'UNKNOWN']
        ],
        sensor => [
            ['ok', 'OK'],
            ['warning|not installed|unavailable', 'WARNING'],
            ['error|unrecoverable', 'CRITICAL'],
            ['unknown|unsupported', 'UNKNOWN']
        ]
    };

    $self->{components_exec_load} = 0;
    $self->{components_path} = 'storage::hp::p2000::xmlapi::mode::components';
    $self->{components_module} = ['disk', 'enclosure', 'fan', 'fru', 'psu', 'saslink', 'sensor', 'vdisk'];
}

sub init_health {
    my ($self, %options) = @_;

    $self->{custom} = $options{custom};
}

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options, no_absent => 1, force_new_perfdata => 1);
    bless $self, $class;

    $options{options}->add_options(arguments => {});

    return $self;
}

1;

__END__

=head1 MODE

Check health status of storage.

=over 8

=item B<--component>

Which component to check (Default: '.*').
Can be: 'disk', 'enclosure', 'fan', 'fru', 'psu', 'saslink', 'sensor', 'vdisk'.

=item B<--filter>

Exclude some parts (comma seperated list) (Example: --filter=fru --filter=enclosure)
Can also exclude specific instance: --filter=disk,1

=item B<--no-component>

Return an error if no compenents are checked.
If total (with skipped) is 0. (Default: 'critical' returns).

=item B<--threshold-overload>

Set to overload default threshold values (syntax: section,[instance,]status,regexp)
It used before default thresholds (order stays).
Example: --threshold-overload='disk,OK,unknown'

=item B<--warning>

Set warning threshold for 'sensor', 'fan.speed' (syntax: type,instance,threshold)
Example: --warning='sensor,temperature.*,30'

=item B<--critical>

Set warning threshold for 'sensor', 'fan.speed' (syntax: type,instance,threshold)
Example: --warning='sensor,temperature.*,30'

=back

=cut


text:
/**
 * generated by Xtext 2.10.0
 */
package robotcontrol.roc.impl;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

import robotcontrol.roc.DirectedAction;
import robotcontrol.roc.RocPackage;

/**
 *
 * An implementation of the model object 'Directed Action'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link robotcontrol.roc.impl.DirectedActionImpl#getActionName Action Name}

 *
{@link robotcontrol.roc.impl.DirectedActionImpl#getDirection Direction}

 *

 *
 * @generated
 */
public class DirectedActionImpl extends MinimalEObjectImpl.Container implements DirectedAction
{
  /**
   * The cached value of the '{@link #getActionName() Action Name}' containment reference.
   *
   *
   * @see #getActionName()
   * @generated
   * @ordered
   */
  protected EObject actionName;

  /**
   * The cached value of the '{@link #getDirection() Direction}' containment reference.
   *
   *
   * @see #getDirection()
   * @generated
   * @ordered
   */
  protected EObject direction;

  /**
   *
   *
   * @generated
   */
  protected DirectedActionImpl()
  {
    super();
  }

  /**
   *
   *
   * @generated
   */
  @Override
  protected EClass eStaticClass()
  {
    return RocPackage.Literals.DIRECTED_ACTION;
  }

  /**
   *
   *
   * @generated
   */
  public EObject getActionName()
  {
    return actionName;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetActionName(EObject newActionName, NotificationChain msgs)
  {
    EObject oldActionName = actionName;
    actionName = newActionName;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, RocPackage.DIRECTED_ACTION__ACTION_NAME, oldActionName, newActionName);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setActionName(EObject newActionName)
  {
    if (newActionName != actionName)
    {
      NotificationChain msgs = null;
      if (actionName != null)
        msgs = ((InternalEObject)actionName).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - RocPackage.DIRECTED_ACTION__ACTION_NAME, null, msgs);
      if (newActionName != null)
        msgs = ((InternalEObject)newActionName).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - RocPackage.DIRECTED_ACTION__ACTION_NAME, null, msgs);
      msgs = basicSetActionName(newActionName, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, RocPackage.DIRECTED_ACTION__ACTION_NAME, newActionName, newActionName));
  }

  /**
   *
   *
   * @generated
   */
  public EObject getDirection()
  {
    return direction;
  }

  /**
   *
   *
   * @generated
   */
  public NotificationChain basicSetDirection(EObject newDirection, NotificationChain msgs)
  {
    EObject oldDirection = direction;
    direction = newDirection;
    if (eNotificationRequired())
    {
      ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, RocPackage.DIRECTED_ACTION__DIRECTION, oldDirection, newDirection);
      if (msgs == null) msgs = notification; else msgs.add(notification);
    }
    return msgs;
  }

  /**
   *
   *
   * @generated
   */
  public void setDirection(EObject newDirection)
  {
    if (newDirection != direction)
    {
      NotificationChain msgs = null;
      if (direction != null)
        msgs = ((InternalEObject)direction).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - RocPackage.DIRECTED_ACTION__DIRECTION, null, msgs);
      if (newDirection != null)
        msgs = ((InternalEObject)newDirection).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - RocPackage.DIRECTED_ACTION__DIRECTION, null, msgs);
      msgs = basicSetDirection(newDirection, msgs);
      if (msgs != null) msgs.dispatch();
    }
    else if (eNotificationRequired())
      eNotify(new ENotificationImpl(this, Notification.SET, RocPackage.DIRECTED_ACTION__DIRECTION, newDirection, newDirection));
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case RocPackage.DIRECTED_ACTION__ACTION_NAME:
        return basicSetActionName(null, msgs);
      case RocPackage.DIRECTED_ACTION__DIRECTION:
        return basicSetDirection(null, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public Object eGet(int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case RocPackage.DIRECTED_ACTION__ACTION_NAME:
        return getActionName();
      case RocPackage.DIRECTED_ACTION__DIRECTION:
        return getDirection();
    }
    return super.eGet(featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eSet(int featureID, Object newValue)
  {
    switch (featureID)
    {
      case RocPackage.DIRECTED_ACTION__ACTION_NAME:
        setActionName((EObject)newValue);
        return;
      case RocPackage.DIRECTED_ACTION__DIRECTION:
        setDirection((EObject)newValue);
        return;
    }
    super.eSet(featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public void eUnset(int featureID)
  {
    switch (featureID)
    {
      case RocPackage.DIRECTED_ACTION__ACTION_NAME:
        setActionName((EObject)null);
        return;
      case RocPackage.DIRECTED_ACTION__DIRECTION:
        setDirection((EObject)null);
        return;
    }
    super.eUnset(featureID);
  }

  /**
   *
   *
   * @generated
   */
  @Override
  public boolean eIsSet(int featureID)
  {
    switch (featureID)
    {
      case RocPackage.DIRECTED_ACTION__ACTION_NAME:
        return actionName != null;
      case RocPackage.DIRECTED_ACTION__DIRECTION:
        return direction != null;
    }
    return super.eIsSet(featureID);
  }

} //DirectedActionImpl