text:
@interface ServerMenuItem : UIMenuItem {
	NSIndexPath *_indexPath;
    NSMutableString *_category;
}

@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, strong) NSMutableString *category;

@end

@implementation ServerMenuItem
@synthesize indexPath = _indexPath, category = _category;

@end

@interface SickBeardServersViewController () {
    NSMutableArray *_servers;
}

@end

@implementation SickBeardServersViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _servers = [NSMutableArray array];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self refreshServers];
}

- (void)refreshServers
{
    [_servers removeAllObjects];
    [_servers addObjectsFromArray:[SSBSickBeard getServers]];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)handleLongItemPress:(UILongPressGestureRecognizer *)longPressRecognizer
{
    if (longPressRecognizer.state == UIGestureRecognizerStateBegan)
	{
		NSIndexPath *pressedIndexPath = [self.tableView indexPathForRowAtPoint:[longPressRecognizer locationInView:self.tableView]];

		if (pressedIndexPath && (pressedIndexPath.row != NSNotFound) && (pressedIndexPath.section != NSNotFound))
		{
			[self becomeFirstResponder];

            UIMenuController *menuController = [UIMenuController sharedMenuController];
            ServerMenuItem *setDefaultMenuItem = [[ServerMenuItem alloc] initWithTitle:@"Set as default" action:@selector(setDefaultServer:)];
            setDefaultMenuItem.indexPath = pressedIndexPath;

            menuController.menuItems = [NSArray arrayWithObject:setDefaultMenuItem];
            [menuController setTargetRect:[self.tableView rectForRowAtIndexPath:pressedIndexPath] inView:self.tableView];
            [menuController setMenuVisible:YES animated:YES];
        }
    }
}

- (void)setDefaultServer:(UIMenuController *)menuController
{
    ServerMenuItem *setDefaultMenuItem = [[[UIMenuController sharedMenuController] menuItems] objectAtIndex:0];
    SSBSickBeardServer *server = [_servers objectAtIndex:setDefaultMenuItem.indexPath.row];
    [server setAsDefault];

    [self refreshServers];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [_servers count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"ServerCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongItemPress:)];
    [cell addGestureRecognizer:longPress];

    SSBSickBeardServer *server = [_servers objectAtIndex:indexPath.row];
    cell.textLabel.text = server.friendlyName;

    if (server.isDefault) {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - Default server", server.host];
    }
    else {
        cell.detailTextLabel.text = server.host;
    }

    if (server.https) {
        cell.imageView.image = [UIImage imageNamed:@"899-key"];
    }
    else {
        cell.imageView.image = [UIImage imageNamed:@"1008-desktop"];
    }

    if ([server.identifier isEqualToString:[SSBSickBeard getActiveServer].identifier]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        SSBSickBeardServer *server = [_servers objectAtIndex:indexPath.row];

        if ([server.identifier isEqualToString:[SSBSickBeard getActiveServer].identifier]) {
            [SSBSickBeard setActiveServer:nil];
        }

        [server remove];
        [_servers removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SSBSickBeardServer *server = [_servers objectAtIndex:indexPath.row];
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
    [SSBSickBeard setActiveServer:server];
    [self refreshServers];
}

@end


text:
/* $Id: portfwd.c $ */
/** @file
 * NAT Network - port-forwarding rules.
 */

/*
 * Copyright (C) 2013-2015 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

#define LOG_GROUP LOG_GROUP_NAT_SERVICE

#include "winutils.h"
#include "portfwd.h"

#ifndef RT_OS_WINDOWS
#include <arpa/inet.h>
#include <netdb.h>
#include <poll.h>
#else
# include "winpoll.h"
#endif
#include <stdio.h>
#include <string.h>

#include "proxy.h"
#include "proxy_pollmgr.h"
#include "pxremap.h"

#include "lwip/netif.h"

struct portfwd_msg {
    struct fwspec *fwspec;
    int add;
};

static int portfwd_chan_send(struct portfwd_msg *);
static int portfwd_rule_add_del(struct fwspec *, int);
static int portfwd_pmgr_chan(struct pollmgr_handler *, SOCKET, int);

static struct pollmgr_handler portfwd_pmgr_chan_hdl;

void
portfwd_init(void)
{
    portfwd_pmgr_chan_hdl.callback = portfwd_pmgr_chan;
    portfwd_pmgr_chan_hdl.data = NULL;
    portfwd_pmgr_chan_hdl.slot = -1;
    pollmgr_add_chan(POLLMGR_CHAN_PORTFWD, &portfwd_pmgr_chan_hdl);

    /* add preconfigured forwarders */
    fwtcp_init();
    fwudp_init();
}

static int
portfwd_chan_send(struct portfwd_msg *msg)
{
    ssize_t nsent;

    nsent = pollmgr_chan_send(POLLMGR_CHAN_PORTFWD, &msg, sizeof(msg));
    if (nsent < 0) {
        free(msg);
        return -1;
    }

    return 0;
}

static int
portfwd_rule_add_del(struct fwspec *fwspec, int add)
{
    struct portfwd_msg *msg;

    msg = (struct portfwd_msg *)malloc(sizeof(*msg));
    if (msg == NULL) {
        return -1;
    }

    msg->fwspec = fwspec;
    msg->add = add;

    return portfwd_chan_send(msg);
}

int
portfwd_rule_add(struct fwspec *fwspec)
{
    return portfwd_rule_add_del(fwspec, 1);
}

int
portfwd_rule_del(struct fwspec *fwspec)
{
    return portfwd_rule_add_del(fwspec, 0);
}

/**
 * POLLMGR_CHAN_PORTFWD handler.
 */
static int
portfwd_pmgr_chan(struct pollmgr_handler *handler, SOCKET fd, int revents)
{
    void *ptr = pollmgr_chan_recv_ptr(handler, fd, revents);
    struct portfwd_msg *msg = (struct portfwd_msg *)ptr;

    if (msg->fwspec->stype == SOCK_STREAM) {
        if (msg->add) {
            fwtcp_add(msg->fwspec);
        }
        else {
            fwtcp_del(msg->fwspec);
        }
    }
    else { /* SOCK_DGRAM */
        if (msg->add) {
            fwudp_add(msg->fwspec);
        }
        else {
            fwudp_del(msg->fwspec);
        }
    }

    free(msg->fwspec);
    free(msg);

    return POLLIN;
}

int
fwspec_set(struct fwspec *fwspec, int sdom, int stype,
           const char *src_addr_str, uint16_t src_port,
           const char *dst_addr_str, uint16_t dst_port)
{
    struct addrinfo hints;
    struct addrinfo *ai;
    int status;

    LWIP_ASSERT1(sdom == PF_INET || sdom == PF_INET6);
    LWIP_ASSERT1(stype == SOCK_STREAM || stype == SOCK_DGRAM);

    fwspec->sdom = sdom;
    fwspec->stype = stype;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = (sdom == PF_INET) ? AF_INET : AF_INET6;
    hints.ai_socktype = stype;
    hints.ai_flags = AI_NUMERICHOST;

    status = getaddrinfo(src_addr_str, NULL, &hints, &ai);
    if (status != 0) {
        LogRel(("\"%s\": %s\n", src_addr_str, gai_strerror(status)));
        return -1;
    }
    LWIP_ASSERT1(ai != NULL);
    LWIP_ASSERT1(ai->ai_addrlen <= sizeof(fwspec->src));
    memcpy(&fwspec->src, ai->ai_addr, ai->ai_addrlen);
    freeaddrinfo(ai);
    ai = NULL;

    status = getaddrinfo(dst_addr_str, NULL, &hints, &ai);
    if (status != 0) {
        LogRel(("\"%s\": %s\n", dst_addr_str, gai_strerror(status)));
        return -1;
    }
    LWIP_ASSERT1(ai != NULL);
    LWIP_ASSERT1(ai->ai_addrlen <= sizeof(fwspec->dst));
    memcpy(&fwspec->dst, ai->ai_addr, ai->ai_addrlen);
    freeaddrinfo(ai);
    ai = NULL;

    if (sdom == PF_INET) {
        fwspec->src.sin.sin_port = htons(src_port);
        fwspec->dst.sin.sin_port = htons(dst_port);
    }
    else { /* PF_INET6 */
        fwspec->src.sin6.sin6_port = htons(src_port);
        fwspec->dst.sin6.sin6_port = htons(dst_port);
    }

    return 0;
}

int
fwspec_equal(struct fwspec *a, struct fwspec *b)
{
    LWIP_ASSERT1(a != NULL);
    LWIP_ASSERT1(b != NULL);

    if (a->sdom != b->sdom || a->stype != b->stype) {
        return 0;
    }

    if (a->sdom == PF_INET) {
        return a->src.sin.sin_port == b->src.sin.sin_port
            && a->dst.sin.sin_port == b->dst.sin.sin_port
            && a->src.sin.sin_addr.s_addr == b->src.sin.sin_addr.s_addr
            && a->dst.sin.sin_addr.s_addr == b->dst.sin.sin_addr.s_addr;
    }
    else { /* PF_INET6 */
        return a->src.sin6.sin6_port == b->src.sin6.sin6_port
            && a->dst.sin6.sin6_port == b->dst.sin6.sin6_port
            && IN6_ARE_ADDR_EQUAL(&a->src.sin6.sin6_addr, &b->src.sin6.sin6_addr)
            && IN6_ARE_ADDR_EQUAL(&a->dst.sin6.sin6_addr, &b->dst.sin6.sin6_addr);
    }
}

/**
 * Set fwdsrc to the IP address of the peer.
 *
 * For port-forwarded connections originating from hosts loopback the
 * source address is set to the address of one of lwIP interfaces.
 *
 * Currently we only have one interface so there's not much logic
 * here.  In the future we might need to additionally consult fwspec
 * and routing table to determine which netif is used for connections
 * to the specified guest.
 */
int
fwany_ipX_addr_set_src(ipX_addr_t *fwdsrc, const struct sockaddr *peer)
{
    int mapping;

    if (peer->sa_family == AF_INET) {
        const struct sockaddr_in *peer4 = (const struct sockaddr_in *)peer;
        ip_addr_t peerip4;

        peerip4.addr = peer4->sin_addr.s_addr;
        mapping = pxremap_inbound_ip4(&fwdsrc->ip4, &peerip4);
    }
    else if (peer->sa_family == AF_INET6) {
        const struct sockaddr_in6 *peer6 = (const struct sockaddr_in6 *)peer;
        ip6_addr_t peerip6;

        memcpy(&peerip6, &peer6->sin6_addr, sizeof(ip6_addr_t));
        mapping = pxremap_inbound_ip6(&fwdsrc->ip6, &peerip6);
    }
    else {
        mapping = PXREMAP_FAILED;
    }

    return mapping;
}

redpajama_set_name: RedPajamaGithub


text:
package problema;

import java.util.Collections;
import java.util.List;

public class Imovel {

  public static List<Imovel> buscar(Integer nroQuartos, Integer nroVagasCarro,
      Double vlrMaximoCondominio, Double vlrMaximoAluguel, Boolean comFoto,
      Boolean apartamento) {
    // ... código necessário para buscar os imóveis
    return Collections.emptyList();
  }
// ...
  public static void main(String[] args) {
    List<Imovel> imoveis = Imovel.buscar(2, 2, 800.0, 500.0, false, true);
  }
}
// https://github.com/marciojrtorres/tecnicas-praticas-codificacao/blob/master/poucos-parametros/src/problema/Imovel.java
// https://git.io/JO5PU


text:
class java::util::zip::GZIPInputStream : public ::java::util::zip::InflaterInputStream
{

public:
  GZIPInputStream(::java::io::InputStream *);
  GZIPInputStream(::java::io::InputStream *, jint);
  virtual void close();
  virtual jint read(JArray< jbyte > *, jint, jint);
private:
  void readHeader();
  void readFooter();
public:
  static const jint GZIP_MAGIC = 35615;
public: // actually package-private
  static const jint FTEXT = 1;
  static const jint FHCRC = 2;
  static const jint FEXTRA = 4;
  static const jint FNAME = 8;
  static const jint FCOMMENT = 16;
public: // actually protected
  ::java::util::zip::CRC32 * __attribute__((aligned(__alignof__( ::java::util::zip::InflaterInputStream)))) crc;
  jboolean eos;
private:
  jboolean readGZIPHeader;
public:
  static ::java::lang::Class class$;
};

#endif // __java_util_zip_GZIPInputStream__


text:
#include "modules/audio_coding/neteq/tools/neteq_input.h"

#include <sstream>

namespace webrtc {
namespace test {

std::string NetEqInput::PacketData::ToString() const {
  std::stringstream ss;
  ss << "{"
     << "time_ms: " << static_cast<int64_t>(time_ms) << ", "
     << "header: {"
     << "pt: " << static_cast<int>(header.payloadType) << ", "
     << "sn: " << header.sequenceNumber << ", "
     << "ts: " << header.timestamp << ", "
     << "ssrc: " << header.ssrc << "}, "
     << "payload bytes: " << payload.size() << "}";
  return ss.str();
}

}  // namespace test
}  // namespace webrtc


text:
package com.amazonaws.services.iot.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Returned by ListAuditMitigationActionsTask, this object contains information that describes a mitigation action that
 * has been started.
 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AuditMitigationActionExecutionMetadata implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The unique identifier for the task that applies the mitigation action.
     *

     */
    private String taskId;
    /**
     *

     * The unique identifier for the findings to which the task and associated mitigation action are applied.
     *

     */
    private String findingId;
    /**
     *

     * The friendly name of the mitigation action being applied by the task.
     *

     */
    private String actionName;
    /**
     *

     * The unique identifier for the mitigation action being applied by the task.
     *

     */
    private String actionId;
    /**
     *

     * The current status of the task being executed.
     *

     */
    private String status;
    /**
     *

     * The date and time when the task was started.
     *

     */
    private java.util.Date startTime;
    /**
     *

     * The date and time when the task was completed or canceled. Blank if the task is still running.
     *

     */
    private java.util.Date endTime;
    /**
     *

     * If an error occurred, the code that indicates which type of error occurred.
     *

     */
    private String errorCode;
    /**
     *

     * If an error occurred, a message that describes the error.
     *

     */
    private String message;

    /**
     *

     * The unique identifier for the task that applies the mitigation action.
     *

     *
     * @param taskId
     *        The unique identifier for the task that applies the mitigation action.
     */

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    /**
     *

     * The unique identifier for the task that applies the mitigation action.
     *

     *
     * @return The unique identifier for the task that applies the mitigation action.
     */

    public String getTaskId() {
        return this.taskId;
    }

    /**
     *

     * The unique identifier for the task that applies the mitigation action.
     *

     *
     * @param taskId
     *        The unique identifier for the task that applies the mitigation action.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AuditMitigationActionExecutionMetadata withTaskId(String taskId) {
        setTaskId(taskId);
        return this;
    }

    /**
     *

     * The unique identifier for the findings to which the task and associated mitigation action are applied.
     *

     *
     * @param findingId
     *        The unique identifier for the findings to which the task and associated mitigation action are applied.
     */

    public void setFindingId(String findingId) {
        this.findingId = findingId;
    }

    /**
     *

     * The unique identifier for the findings to which the task and associated mitigation action are applied.
     *

     *
     * @return The unique identifier for the findings to which the task and associated mitigation action are applied.
     */

    public String getFindingId() {
        return this.findingId;
    }

    /**
     *

     * The unique identifier for the findings to which the task and associated mitigation action are applied.
     *

     *
     * @param findingId
     *        The unique identifier for the findings to which the task and associated mitigation action are applied.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AuditMitigationActionExecutionMetadata withFindingId(String findingId) {
        setFindingId(findingId);
        return this;
    }

    /**
     *

     * The friendly name of the mitigation action being applied by the task.
     *

     *
     * @param actionName
     *        The friendly name of the mitigation action being applied by the task.
     */

    public void setActionName(String actionName) {
        this.actionName = actionName;
    }

    /**
     *

     * The friendly name of the mitigation action being applied by the task.
     *

     *
     * @return The friendly name of the mitigation action being applied by the task.
     */

    public String getActionName() {
        return this.actionName;
    }

    /**
     *

     * The friendly name of the mitigation action being applied by the task.
     *

     *
     * @param actionName
     *        The friendly name of the mitigation action being applied by the task.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AuditMitigationActionExecutionMetadata withActionName(String actionName) {
        setActionName(actionName);
        return this;
    }

    /**
     *

     * The unique identifier for the mitigation action being applied by the task.
     *

     *
     * @param actionId
     *        The unique identifier for the mitigation action being applied by the task.
     */

    public void setActionId(String actionId) {
        this.actionId = actionId;
    }

    /**
     *

     * The unique identifier for the mitigation action being applied by the task.
     *

     *
     * @return The unique identifier for the mitigation action being applied by the task.
     */

    public String getActionId() {
        return this.actionId;
    }

    /**
     *

     * The unique identifier for the mitigation action being applied by the task.
     *

     *
     * @param actionId
     *        The unique identifier for the mitigation action being applied by the task.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AuditMitigationActionExecutionMetadata withActionId(String actionId) {
        setActionId(actionId);
        return this;
    }

    /**
     *

     * The current status of the task being executed.
     *

     *
     * @param status
     *        The current status of the task being executed.
     * @see AuditMitigationActionsExecutionStatus
     */

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     *

     * The current status of the task being executed.
     *

     *
     * @return The current status of the task being executed.
     * @see AuditMitigationActionsExecutionStatus
     */

    public String getStatus() {
        return this.status;
    }

    /**
     *

     * The current status of the task being executed.
     *

     *
     * @param status
     *        The current status of the task being executed.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AuditMitigationActionsExecutionStatus
     */

    public AuditMitigationActionExecutionMetadata withStatus(String status) {
        setStatus(status);
        return this;
    }

    /**
     *

     * The current status of the task being executed.
     *

     *
     * @param status
     *        The current status of the task being executed.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see AuditMitigationActionsExecutionStatus
     */

    public AuditMitigationActionExecutionMetadata withStatus(AuditMitigationActionsExecutionStatus status) {
        this.status = status.toString();
        return this;
    }

    /**
     *

     * The date and time when the task was started.
     *

     *
     * @param startTime
     *        The date and time when the task was started.
     */

    public void setStartTime(java.util.Date startTime) {
        this.startTime = startTime;
    }

    /**
     *

     * The date and time when the task was started.
     *

     *
     * @return The date and time when the task was started.
     */

    public java.util.Date getStartTime() {
        return this.startTime;
    }

    /**
     *

     * The date and time when the task was started.
     *

     *
     * @param startTime
     *        The date and time when the task was started.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AuditMitigationActionExecutionMetadata withStartTime(java.util.Date startTime) {
        setStartTime(startTime);
        return this;
    }

    /**
     *

     * The date and time when the task was completed or canceled. Blank if the task is still running.
     *

     *
     * @param endTime
     *        The date and time when the task was completed or canceled. Blank if the task is still running.
     */

    public void setEndTime(java.util.Date endTime) {
        this.endTime = endTime;
    }

    /**
     *

     * The date and time when the task was completed or canceled. Blank if the task is still running.
     *

     *
     * @return The date and time when the task was completed or canceled. Blank if the task is still running.
     */

    public java.util.Date getEndTime() {
        return this.endTime;
    }

    /**
     *

     * The date and time when the task was completed or canceled. Blank if the task is still running.
     *

     *
     * @param endTime
     *        The date and time when the task was completed or canceled. Blank if the task is still running.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AuditMitigationActionExecutionMetadata withEndTime(java.util.Date endTime) {
        setEndTime(endTime);
        return this;
    }

    /**
     *

     * If an error occurred, the code that indicates which type of error occurred.
     *

     *
     * @param errorCode
     *        If an error occurred, the code that indicates which type of error occurred.
     */

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    /**
     *

     * If an error occurred, the code that indicates which type of error occurred.
     *

     *
     * @return If an error occurred, the code that indicates which type of error occurred.
     */

    public String getErrorCode() {
        return this.errorCode;
    }

    /**
     *

     * If an error occurred, the code that indicates which type of error occurred.
     *

     *
     * @param errorCode
     *        If an error occurred, the code that indicates which type of error occurred.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AuditMitigationActionExecutionMetadata withErrorCode(String errorCode) {
        setErrorCode(errorCode);
        return this;
    }

    /**
     *

     * If an error occurred, a message that describes the error.
     *

     *
     * @param message
     *        If an error occurred, a message that describes the error.
     */

    public void setMessage(String message) {
        this.message = message;
    }

    /**
     *

     * If an error occurred, a message that describes the error.
     *

     *
     * @return If an error occurred, a message that describes the error.
     */

    public String getMessage() {
        return this.message;
    }

    /**
     *

     * If an error occurred, a message that describes the error.
     *

     *
     * @param message
     *        If an error occurred, a message that describes the error.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AuditMitigationActionExecutionMetadata withMessage(String message) {
        setMessage(message);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getTaskId() != null)
            sb.append("TaskId: ").append(getTaskId()).append(",");
        if (getFindingId() != null)
            sb.append("FindingId: ").append(getFindingId()).append(",");
        if (getActionName() != null)
            sb.append("ActionName: ").append(getActionName()).append(",");
        if (getActionId() != null)
            sb.append("ActionId: ").append(getActionId()).append(",");
        if (getStatus() != null)
            sb.append("Status: ").append(getStatus()).append(",");
        if (getStartTime() != null)
            sb.append("StartTime: ").append(getStartTime()).append(",");
        if (getEndTime() != null)
            sb.append("EndTime: ").append(getEndTime()).append(",");
        if (getErrorCode() != null)
            sb.append("ErrorCode: ").append(getErrorCode()).append(",");
        if (getMessage() != null)
            sb.append("Message: ").append(getMessage());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof AuditMitigationActionExecutionMetadata == false)
            return false;
        AuditMitigationActionExecutionMetadata other = (AuditMitigationActionExecutionMetadata) obj;
        if (other.getTaskId() == null ^ this.getTaskId() == null)
            return false;
        if (other.getTaskId() != null && other.getTaskId().equals(this.getTaskId()) == false)
            return false;
        if (other.getFindingId() == null ^ this.getFindingId() == null)
            return false;
        if (other.getFindingId() != null && other.getFindingId().equals(this.getFindingId()) == false)
            return false;
        if (other.getActionName() == null ^ this.getActionName() == null)
            return false;
        if (other.getActionName() != null && other.getActionName().equals(this.getActionName()) == false)
            return false;
        if (other.getActionId() == null ^ this.getActionId() == null)
            return false;
        if (other.getActionId() != null && other.getActionId().equals(this.getActionId()) == false)
            return false;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
            return false;
        if (other.getStartTime() == null ^ this.getStartTime() == null)
            return false;
        if (other.getStartTime() != null && other.getStartTime().equals(this.getStartTime()) == false)
            return false;
        if (other.getEndTime() == null ^ this.getEndTime() == null)
            return false;
        if (other.getEndTime() != null && other.getEndTime().equals(this.getEndTime()) == false)
            return false;
        if (other.getErrorCode() == null ^ this.getErrorCode() == null)
            return false;
        if (other.getErrorCode() != null && other.getErrorCode().equals(this.getErrorCode()) == false)
            return false;
        if (other.getMessage() == null ^ this.getMessage() == null)
            return false;
        if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getTaskId() == null) ? 0 : getTaskId().hashCode());
        hashCode = prime * hashCode + ((getFindingId() == null) ? 0 : getFindingId().hashCode());
        hashCode = prime * hashCode + ((getActionName() == null) ? 0 : getActionName().hashCode());
        hashCode = prime * hashCode + ((getActionId() == null) ? 0 : getActionId().hashCode());
        hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
        hashCode = prime * hashCode + ((getStartTime() == null) ? 0 : getStartTime().hashCode());
        hashCode = prime * hashCode + ((getEndTime() == null) ? 0 : getEndTime().hashCode());
        hashCode = prime * hashCode + ((getErrorCode() == null) ? 0 : getErrorCode().hashCode());
        hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode());
        return hashCode;
    }

    @Override
    public AuditMitigationActionExecutionMetadata clone() {
        try {
            return (AuditMitigationActionExecutionMetadata) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.iot.model.transform.AuditMitigationActionExecutionMetadataMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package org.eclipse.microprofile.jwt.tck.container.jaxrs;

import java.io.IOException;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.eclipse.microprofile.jwt.Claims;
import org.eclipse.microprofile.jwt.tck.TCKConstants;
import org.eclipse.microprofile.jwt.tck.util.MpJwtTestVersion;
import org.eclipse.microprofile.jwt.tck.util.TokenUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.testng.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.testng.Assert;
import org.testng.Reporter;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static org.eclipse.microprofile.jwt.tck.TCKConstants.TEST_GROUP_CDI_PROVIDER;

/**
 * Tests of injection JsonWebToken claims using the {@linkplain javax.enterprise.inject.Instance} interface.
 */
public class ProviderInjectionTest extends Arquillian {

    /**
     * The test generated JWT token string
     */
    private static String token;
    // Time claims in the token
    private static Long iatClaim;
    private static Long authTimeClaim;
    private static Long expClaim;

    /**
     * The base URL for the container under test
     */
    @ArquillianResource
    private URL baseURL;

    /**
     * Create a CDI aware base web application archive
     * @return the base base web application archive
     * @throws IOException - on resource failure
     */
    @Deployment(testable=true)
    public static WebArchive createDeployment() throws IOException {
        URL publicKey = ProviderInjectionTest.class.getResource("/publicKey.pem");
        WebArchive webArchive = ShrinkWrap
            .create(WebArchive.class, "ProviderInjectionTest.war")
            .addAsManifestResource(new StringAsset(MpJwtTestVersion.MPJWT_V_1_0.name()), MpJwtTestVersion.MANIFEST_NAME)
            .addAsResource(publicKey, "/publicKey.pem")
            .addClass(ProviderInjectionEndpoint.class)
            .addClass(TCKApplication.class)
            .addAsWebInfResource("beans.xml", "beans.xml")
            ;
        System.out.printf("WebArchive: %s\n", webArchive.toString(true));
        return webArchive;
    }

    @BeforeClass(alwaysRun=true)
    public static void generateToken() throws Exception {
        HashMap<String, Long> timeClaims = new HashMap<>();
        token = TokenUtils.generateTokenString("/Token1.json", null, timeClaims);
        iatClaim = timeClaims.get(Claims.iat.name());
        authTimeClaim = timeClaims.get(Claims.auth_time.name());
        expClaim = timeClaims.get(Claims.exp.name());
    }

    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected token issuer claim is as expected")
    public void verifyIssuerClaim() throws Exception {
        Reporter.log("Begin verifyIssuerClaim");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedIssuer";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.iss.name(), TCKConstants.TEST_ISSUER)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected raw token claim is as expected")
    public void verifyInjectedRawToken() throws Exception {
        Reporter.log("Begin verifyInjectedRawToken\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedRawToken";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.raw_token.name(), token)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected jti claim is as expected")
    public void verifyInjectedJTI() throws Exception {
        Reporter.log("Begin verifyInjectedJTI\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedJTI";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.jti.name(), "a-123")
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected aud claim is as expected")
    public void verifyInjectedAudience() throws Exception {
        Reporter.log("Begin verifyInjectedAudience\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedAudience";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.aud.name(), "s6BhdRkqt3")
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected iat claim is as expected")
    public void verifyInjectedIssuedAt() throws Exception {
        Reporter.log("Begin verifyInjectedIssuedAt\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedIssuedAt";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.iat.name(), iatClaim)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected sub claim is as expected")
    public void verifyInjectedOptionalSubject() throws Exception {
        Reporter.log("Begin verifyInjectedOptionalSubject\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedOptionalSubject";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.sub.name(), "24400320")
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected raw token claim is as expected")
    public void verifyInjectedOptionalAuthTime() throws Exception {
        Reporter.log("Begin verifyInjectedOptionalAuthTime\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedOptionalAuthTime";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected custom claim is missing as expected")
    public void verifyInjectedOptionalCustomMissing() throws Exception {
        Reporter.log("Begin verifyInjectedOptionalCustomMissing\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedOptionalCustomMissing";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            ;
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected customString claim is as expected")
    public void verifyInjectedCustomString() throws Exception {
        Reporter.log("Begin verifyInjectedCustomString\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomString";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam("value", "customStringValue")
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected customInteger claim is as expected")
    public void verifyInjectedCustomInteger() throws Exception {
        Reporter.log("Begin verifyInjectedCustomInteger\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomInteger";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam("value", 123456789)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected customDouble claim is as expected")
    public void verifyInjectedCustomDouble() throws Exception {
        Reporter.log("Begin verifyInjectedCustomDouble\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomDouble";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam("value", 3.141592653589793)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }

    // Duplicate tests that use Token2.json to verify that @RequestScope or @Dependent scoping is in use

    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected token issuer claim is as expected")
    public void verifyIssuerClaim2() throws Exception {
        Reporter.log("Begin verifyIssuerClaim");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedIssuer";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.iss.name(), TCKConstants.TEST_ISSUER)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected raw token claim is as expected")
    public void verifyInjectedRawToken2() throws Exception {
        Reporter.log("Begin verifyInjectedRawToken\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedRawToken";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.raw_token.name(), token)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected jti claim is as expected")
    public void verifyInjectedJTI2() throws Exception {
        Reporter.log("Begin verifyInjectedJTI\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedJTI";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.jti.name(), "a-123")
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected aud claim is as expected")
    public void verifyInjectedAudience2() throws Exception {
        Reporter.log("Begin verifyInjectedAudience\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedAudience";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.aud.name(), "s6BhdRkqt3")
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected iat claim is as expected")
    public void verifyInjectedIssuedAt2() throws Exception {
        Reporter.log("Begin verifyInjectedIssuedAt\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedIssuedAt";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.iat.name(), iatClaim)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected sub claim is as expected")
    public void verifyInjectedOptionalSubject2() throws Exception {
        Reporter.log("Begin verifyInjectedOptionalSubject\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedOptionalSubject";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.sub.name(), "24400320")
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected raw token claim is as expected")
    public void verifyInjectedOptionalAuthTime2() throws Exception {
        Reporter.log("Begin verifyInjectedOptionalAuthTime\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedOptionalAuthTime";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected customString claim is as expected")
    public void verifyInjectedCustomString2() throws Exception {
        Reporter.log("Begin verifyInjectedCustomString\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomString";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam("value", "customStringValue")
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected customInteger claim is as expected")
    public void verifyInjectedCustomInteger2() throws Exception {
        Reporter.log("Begin verifyInjectedCustomInteger\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomInteger";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam("value", 123456789)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
    @RunAsClient
    @Test(groups = TEST_GROUP_CDI_PROVIDER,
        description = "Verify that the injected customDouble claim is as expected")
    public void verifyInjectedCustomDouble2() throws Exception {
        Reporter.log("Begin verifyInjectedCustomDouble\n");
        String uri = baseURL.toExternalForm() + "endp/verifyInjectedCustomDouble";
        WebTarget echoEndpointTarget = ClientBuilder.newClient()
            .target(uri)
            .queryParam("value", 3.141592653589793)
            .queryParam(Claims.auth_time.name(), authTimeClaim);
        Response response = echoEndpointTarget.request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer " + token).get();
        Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
        String replyString = response.readEntity(String.class);
        JsonReader jsonReader = Json.createReader(new StringReader(replyString));
        JsonObject reply = jsonReader.readObject();
        Reporter.log(reply.toString());
        Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
    }
}


text:
As per the [grand plan][1]:
[Goals][2] articulates the purpose and technical goals of project as a whole.
[Components][3] enumerates the components needed to fulfill the project requirements.
[Functionality][4] attempts to outline the functional requirements of Curate.
[Personas][5] attempts to describe prospective users of Curate.
[Stories][6] is a first draft of user stories for Curate.
Well-articulated stories will be moved to their own github issues.

[Coding Rules and Procedures][7] outlines our proposal for coding standards and collaboration practices.

[1]: https://github.com/ndlib/planning#the-process
[2]: https://github.com/ndlib/planning/blob/master/Curate/Goals.md
[3]: https://github.com/ndlib/planning/blob/master/Curate/Components.md
[4]: https://github.com/ndlib/planning/blob/master/Curate/Functionality.md
[5]: https://github.com/ndlib/planning/blob/master/Curate/Personas.md
[6]: https://github.com/ndlib/planning/blob/master/Curate/Stories.md
[7]: https://github.com/ndlib/planning/blob/master/Curate/Coding_Rules_and_Procedures.md


text:
using ConsoleApplication.Graphs;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication.Similarity
{
    public class EdgeSimillarityStrategy : ISimilarityCalculationStrategy
    {
        public double CalculateSimilarity(Path first, Path second)
        {
            var firstEdges = TransformPathToEdgeCollecetion(first);
            var secondEdges = TransformPathToEdgeCollecetion(second);

            return firstEdges.Count(edge => secondEdges.Contains(edge));
        }

        public IEnumerable<Fragment> FindSimilarFragments(Path first, Path second)
        {
            var firstEdges = TransformPathToEdgeCollecetion(first);
            var secondEdges = TransformPathToEdgeCollecetion(second);

            return firstEdges
                .Where(edge => secondEdges.Contains(edge))
                .Select(edge => new Fragment(edge));
        }

        private HashSet<Edge> TransformPathToEdgeCollecetion(Path path)
        {
            var edges = new HashSet<Edge>(new EdgeEqualityComparer());
            for (var n = 0; n < path.Count - 1; n++)
                edges.Add(new Edge(path.Nodes[n], path.Nodes[n + 1], 0));
            return edges;
        }
    }
}


text:
pypif.obj.common.software module
================================

.. automodule:: pypif.obj.common.software
    :members:
    :undoc-members:
    :show-inheritance:


text:
package online.zhaopei.myproject.domain.gjpayment;

import java.io.Serializable;
import java.util.Date;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

import online.zhaopei.myproject.common.adapter.DateAdapter;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class BodyMaster implements Serializable {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -4001147269292461151L;

	@XmlElement(name = "SEQNO")
	private String seqNo;

	@XmlElement(name = "GUID")
	private String guid;

	@XmlElement(name = "MANAGERCUSTOMSCODE")
	private String managerCustomsCode;

	@XmlElement(name = "PAYTIME")
	@XmlJavaTypeAdapter(DateAdapter.class)
	private Date payTime;

	@XmlElement(name = "ORDERID")
	private String orderId;

	@XmlElement(name = "PAYENTERPRISECODE")
	private String payEnterpriseCode;

	@XmlElement(name = "PAYENTERPRISENAME")
	private String payEnterpriseName;

	@XmlElement(name = "PAYNUMBER")
	private String payNumber;

	@XmlElement(name = "ECPCODE")
	private String ecpCode;

	@XmlElement(name = "ECPNAME")
	private String ecpName;

	@XmlElement(name = "PAYMENTTYPE")
	private String paymentType;

	@XmlElement(name = "MONETARYTYPE")
	private String monetaryType;

	@XmlElement(name = "FEE")
	private Double fee;

	@XmlElement(name = "CUSTOMERFLAG")
	private String customerFlag;

	@XmlElement(name = "IDTYPE")
	private String idType;

	@XmlElement(name = "CUSTOMERID")
	private String customerId;

	@XmlElement(name = "IETYPE")
	private String ieType;

	@XmlElement(name = "REMARK")
	private String remark;

	@XmlElement(name = "PAYUSER")
	private String payUser;

	@XmlElement(name = "PAYECODE")
	private String payECode;

	@XmlElement(name = "CBECODEINSP")
	private String cbeCodeInsp;

	@XmlElement(name = "COININSP")
	private String coinInsp;

	@XmlElement(name = "CBECODE")
	private String cbeCode;

	@XmlElement(name = "cbeName")
	private String cbeName;

	public String getSeqNo() {
		return seqNo;
	}

	public void setSeqNo(String seqNo) {
		this.seqNo = seqNo;
	}

	public String getGuid() {
		return guid;
	}

	public void setGuid(String guid) {
		this.guid = guid;
	}

	public String getManagerCustomsCode() {
		return managerCustomsCode;
	}

	public void setManagerCustomsCode(String managerCustomsCode) {
		this.managerCustomsCode = managerCustomsCode;
	}

	public Date getPayTime() {
		return payTime;
	}

	public void setPayTime(Date payTime) {
		this.payTime = payTime;
	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public String getPayEnterpriseCode() {
		return payEnterpriseCode;
	}

	public void setPayEnterpriseCode(String payEnterpriseCode) {
		this.payEnterpriseCode = payEnterpriseCode;
	}

	public String getPayEnterpriseName() {
		return payEnterpriseName;
	}

	public void setPayEnterpriseName(String payEnterpriseName) {
		this.payEnterpriseName = payEnterpriseName;
	}

	public String getPayNumber() {
		return payNumber;
	}

	public void setPayNumber(String payNumber) {
		this.payNumber = payNumber;
	}

	public String getEcpCode() {
		return ecpCode;
	}

	public void setEcpCode(String ecpCode) {
		this.ecpCode = ecpCode;
	}

	public String getEcpName() {
		return ecpName;
	}

	public void setEcpName(String ecpName) {
		this.ecpName = ecpName;
	}

	public String getPaymentType() {
		return paymentType;
	}

	public void setPaymentType(String paymentType) {
		this.paymentType = paymentType;
	}

	public String getMonetaryType() {
		return monetaryType;
	}

	public void setMonetaryType(String monetaryType) {
		this.monetaryType = monetaryType;
	}

	public Double getFee() {
		return fee;
	}

	public void setFee(Double fee) {
		this.fee = fee;
	}

	public String getCustomerFlag() {
		return customerFlag;
	}

	public void setCustomerFlag(String customerFlag) {
		this.customerFlag = customerFlag;
	}

	public String getIdType() {
		return idType;
	}

	public void setIdType(String idType) {
		this.idType = idType;
	}

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	public String getIeType() {
		return ieType;
	}

	public void setIeType(String ieType) {
		this.ieType = ieType;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public String getPayUser() {
		return payUser;
	}

	public void setPayUser(String payUser) {
		this.payUser = payUser;
	}

	public String getPayECode() {
		return payECode;
	}

	public void setPayECode(String payECode) {
		this.payECode = payECode;
	}

	public String getCbeCodeInsp() {
		return cbeCodeInsp;
	}

	public void setCbeCodeInsp(String cbeCodeInsp) {
		this.cbeCodeInsp = cbeCodeInsp;
	}

	public String getCoinInsp() {
		return coinInsp;
	}

	public void setCoinInsp(String coinInsp) {
		this.coinInsp = coinInsp;
	}

	public String getCbeCode() {
		return cbeCode;
	}

	public void setCbeCode(String cbeCode) {
		this.cbeCode = cbeCode;
	}

	public String getCbeName() {
		return cbeName;
	}

	public void setCbeName(String cbeName) {
		this.cbeName = cbeName;
	}
}


text:
from datetime import date, datetime
import decimal
import os
import pytz
import re
import tempfile
import traceback

from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.core.exceptions import PermissionDenied
from django.core.files.storage import get_storage_class
from django.core.mail import mail_admins
from django.core.servers.basehttp import FileWrapper
from django.db import IntegrityError
from django.db import transaction
from django.db.models.signals import pre_delete
from django.http import HttpResponse, HttpResponseNotFound, \
    StreamingHttpResponse
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from django.utils import timezone
from modilabs.utils.subprocess_timeout import ProcessTimedOut
from pyxform.errors import PyXFormError
from pyxform.xform2json import create_survey_element_from_xml
import sys
import common_tags

from odk_logger.models import Attachment
from odk_logger.models import Instance
from odk_logger.models.instance import InstanceHistory
from odk_logger.models.instance import get_id_string_from_xml_str
from odk_logger.models import XForm
from odk_logger.models.xform import XLSFormError
from odk_logger.xform_instance_parser import InstanceInvalidUserError, \
    IsNotCrowdformError, DuplicateInstance, clean_and_parse_xml, \
    get_uuid_from_xml, get_deprecated_uuid_from_xml, \
    get_submission_date_from_xml
from odk_viewer.models.parsed_instance import _remove_from_mongo
from odk_viewer.models.parsed_instance import xform_instances

from odk_viewer.models import ParsedInstance, DataDictionary
from utils.model_tools import queryset_iterator, set_uuid
from xml.dom import Node

OPEN_ROSA_VERSION_HEADER = 'X-OpenRosa-Version'
HTTP_OPEN_ROSA_VERSION_HEADER = 'HTTP_X_OPENROSA_VERSION'
OPEN_ROSA_VERSION = '1.0'
DEFAULT_CONTENT_TYPE = 'text/xml; charset=utf-8'
DEFAULT_CONTENT_LENGTH = settings.DEFAULT_CONTENT_LENGTH

uuid_regex = re.compile(r'<formhub><uuid>([^<]+)</uuid></formhub>',
                        re.DOTALL)

mongo_instances = settings.MONGO_DB.instances

@transaction.commit_manually
def create_instance(username, xml_file, media_files,
                    status=u'submitted_via_web', uuid=None,
                    date_created_override=None, request=None):
    """
    I used to check if this file had been submitted already, I've
    taken this out because it was too slow. Now we're going to create
    a way for an admin to mark duplicate instances. This should
    simplify things a bit.
    Submission cases:
        If there is a username and no uuid, submitting an old ODK form.
        If there is no username and a uuid, submitting a touchform.
        If there is a username and a uuid, submitting a new ODK form.
    """
    try:
        if username:
            username = username.lower()
        xml = xml_file.read()
        is_touchform = False
        # check alternative form submission ids
        if not uuid:
            # parse UUID from uploaded XML
            split_xml = uuid_regex.split(xml)

            # check that xml has UUID, then it is a crowdform
            if len(split_xml) > 1:
                uuid = split_xml[1]
        else:
            # is a touchform
            is_touchform = True

        if not username and not uuid:
            raise InstanceInvalidUserError()

        if uuid:
            # try find the fomr by its uuid which is the ideal condition
            if XForm.objects.filter(uuid=uuid).count() > 0:
                xform = XForm.objects.get(uuid=uuid)
                xform_username = xform.user.username

                if xform_username != username and not xform.is_crowd_form \
                        and not is_touchform:
                    raise IsNotCrowdformError()

                username = xform_username
        # else, since we have a username, the Instance creation logic will
        # handle checking for the forms existence by its id_string
        if username and request and request.user.is_authenticated():
            id_string = get_id_string_from_xml_str(xml)
            xform = XForm.objects.get(
                id_string=id_string, user__username=username)
            if not xform.is_crowd_form and not is_touchform \
                    and xform.user.profile.require_auth \
                    and xform.user != request.user:
                raise PermissionDenied(
                    _(u"%(request_user)s is not allowed to make submissions "
                      u"to %(form_user)s's %(form_title)s form." % {
                          'request_user': request.user,
                          'form_user': xform.user,
                          'form_title': xform.title}))

        user = get_object_or_404(User, username=username)
        existing_instance_count = Instance.objects.filter(
            xml=xml, user=user).count()

        if existing_instance_count == 0:
            proceed_to_create_instance = True
        else:
            existing_instance = Instance.objects.filter(xml=xml, user=user)[0]
            if existing_instance.xform and\
                    not existing_instance.xform.has_start_time:
                proceed_to_create_instance = True
            else:
                # Ignore submission as a duplicate IFF
                #  * a submission's XForm collects start time
                #  * the submitted XML is an exact match with one that
                #    has already been submitted for that user.
                proceed_to_create_instance = False
                raise DuplicateInstance()

        # get new and depracated uuid's
        new_uuid = get_uuid_from_xml(xml)
        duplicate_instances = Instance.objects.filter(uuid=new_uuid)
        if duplicate_instances:
            for f in media_files:
                Attachment.objects.get_or_create(
                    instance=duplicate_instances[0],
                    media_file=f, mimetype=f.content_type)
            # ensure we have saved the extra attachments
            transaction.commit()
            raise DuplicateInstance()

        if proceed_to_create_instance:
            # check if its an edit submission
            old_uuid = get_deprecated_uuid_from_xml(xml)
            instances = Instance.objects.filter(uuid=old_uuid)
            if not date_created_override:
                date_created_override = get_submission_date_from_xml(xml)
            if instances:
                instance = instances[0]
                InstanceHistory.objects.create(
                    xml=instance.xml, xform_instance=instance, uuid=old_uuid)
                instance.xml = xml
                instance.uuid = new_uuid
                instance.save()
            else:
                # new submission
                instance = Instance.objects.create(
                    xml=xml, user=user, status=status)
            for f in media_files:
                Attachment.objects.get_or_create(
                    instance=instance, media_file=f, mimetype=f.content_type)

            # override date created if required
            if date_created_override:
                if not timezone.is_aware(date_created_override):
                    # default to utc?
                    date_created_override = timezone.make_aware(
                        date_created_override, timezone.utc)
                instance.date_created = date_created_override
                instance.save()

            if instance.xform is not None:
                pi, created = ParsedInstance.objects.get_or_create(
                    instance=instance)
            if not created:
                pi.save(async=False)
        # commit all changes
        transaction.commit()
        return instance
    except Exception:
        transaction.rollback()
        raise
    return None

def report_exception(subject, info, exc_info=None):
    if exc_info:
        cls, err = exc_info[:2]
        message = _(u"Exception in request:"
                    u" %(class)s: %(error)s")\
            % {'class': cls.__name__, 'error': err}
        message += u"".join(traceback.format_exception(*exc_info))
    else:
        message = u"%s" % info

    if settings.DEBUG or settings.TESTING_MODE:
        sys.stdout.write("Subject: %s\n" % subject)
        sys.stdout.write("Message: %s\n" % message)
    else:
        mail_admins(subject=subject, message=message)

def round_down_geopoint(num):
    if num:
        decimal_mult = 1000000
        return str(decimal.Decimal(int(num * decimal_mult)) / decimal_mult)
    return None

def response_with_mimetype_and_name(
        mimetype, name, extension=None, show_date=True, file_path=None,
        use_local_filesystem=False, full_mime=False):
    if extension is None:
        extension = mimetype
    if not full_mime:
        mimetype = "application/%s" % mimetype
    if file_path:
        try:
            if not use_local_filesystem:
                default_storage = get_storage_class()()
                wrapper = FileWrapper(default_storage.open(file_path))
                response = StreamingHttpResponse(wrapper, mimetype=mimetype)
                response['Content-Length'] = default_storage.size(file_path)
            else:
                wrapper = FileWrapper(open(file_path))
                response = StreamingHttpResponse(wrapper, mimetype=mimetype)
                response['Content-Length'] = os.path.getsize(file_path)
        except IOError:
            response = HttpResponseNotFound(
                _(u"The requested file could not be found."))
    else:
        response = HttpResponse(mimetype=mimetype)
    response['Content-Disposition'] = disposition_ext_and_date(
        name, extension, show_date)
    return response

def disposition_ext_and_date(name, extension, show_date=True):
    if name is None:
        return 'attachment;'
    if show_date:
        name = "%s_%s" % (name, date.today().strftime("%Y_%m_%d"))
    return 'attachment; filename=%s.%s' % (name, extension)

def store_temp_file(data):
    tmp = tempfile.TemporaryFile()
    ret = None
    try:
        tmp.write(data)
        tmp.seek(0)
        ret = tmp
    finally:
        tmp.close()
    return ret

def publish_form(callback):
    try:
        return callback()
    except (PyXFormError, XLSFormError) as e:
        return {
            'type': 'alert-error',
            'text': e
        }
    except IntegrityError as e:
        return {
            'type': 'alert-error',
            'text': _(u'Form with this id or SMS-keyword already exists.'),
        }
    except ValidationError as e:
        # on clone invalid URL
        return {
            'type': 'alert-error',
            'text': _(u'Invalid URL format.'),
        }
    except AttributeError as e:
        # form.publish returned None, not sure why...
        return {
            'type': 'alert-error',
            'text': e
        }
    except ProcessTimedOut as e:
        # catch timeout errors
        return {
            'type': 'alert-error',
            'text': _(u'Form validation timeout, please try again.'),
        }
    except Exception, e:
        report_exception("ERROR: XLSForm publishing Exception", e)
        return {
            'type': 'alert-error',
            'text': e
        }

def publish_xls_form(xls_file, user, id_string=None):
    """ Creates or updates a DataDictionary with supplied xls_file,
        user and optional id_string - if updating
    """
    # get or create DataDictionary based on user and id string
    if id_string:
        dd = DataDictionary.objects.get(
            user=user, id_string=id_string)
        dd.xls = xls_file
        dd.save()
        return dd
    else:
        return DataDictionary.objects.create(
            user=user,
            xls=xls_file
        )

def publish_xml_form(xml_file, user, id_string=None):
    xml = xml_file.read()
    survey = create_survey_element_from_xml(xml)
    form_json = survey.to_json()
    if id_string:
        dd = DataDictionary.objects.get(user=user, id_string=id_string)
        dd.xml = xml
        dd.json = form_json
        dd._mark_start_time_boolean()
        set_uuid(dd)
        dd._set_uuid_in_xml()
        dd.save()
        return dd
    else:
        dd = DataDictionary(user=user, xml=xml, json=form_json)
        dd._mark_start_time_boolean()
        set_uuid(dd)
        dd._set_uuid_in_xml(file_name=xml_file.name)
        dd.save()
        return dd

class BaseOpenRosaResponse(HttpResponse):
    status_code = 201

    def __init__(self, *args, **kwargs):
        super(BaseOpenRosaResponse, self).__init__(*args, **kwargs)

        self[OPEN_ROSA_VERSION_HEADER] = OPEN_ROSA_VERSION
        tz = pytz.timezone(settings.TIME_ZONE)
        dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z')
        self['Date'] = dt
        self['X-OpenRosa-Accept-Content-Length'] = DEFAULT_CONTENT_LENGTH
        self['Content-Type'] = DEFAULT_CONTENT_TYPE

class OpenRosaResponse(BaseOpenRosaResponse):
    status_code = 201

    def __init__(self, *args, **kwargs):
        super(OpenRosaResponse, self).__init__(*args, **kwargs)
        # wrap content around xml
        self.content = '''<?xml version='1.0' encoding='UTF-8' ?>
<OpenRosaResponse xmlns="http://openrosa.org/http/response">
        <message nature="">%s</message>
</OpenRosaResponse>''' % self.content

class OpenRosaResponseNotFound(OpenRosaResponse):
    status_code = 404

class OpenRosaResponseBadRequest(OpenRosaResponse):
    status_code = 400

class OpenRosaResponseNotAllowed(OpenRosaResponse):
    status_code = 405

def inject_instanceid(xml_str, uuid):
    if get_uuid_from_xml(xml_str) is None:
        xml = clean_and_parse_xml(xml_str)
        children = xml.childNodes
        if children.length == 0:
            raise ValueError(_("XML string must have a survey element."))

        # check if we have a meta tag
        survey_node = children.item(0)
        meta_tags = [
            n for n in survey_node.childNodes
            if n.nodeType == Node.ELEMENT_NODE
            and n.tagName.lower() == "meta"]
        if len(meta_tags) == 0:
            meta_tag = xml.createElement("meta")
            xml.documentElement.appendChild(meta_tag)
        else:
            meta_tag = meta_tags[0]

        # check if we have an instanceID tag
        uuid_tags = [
            n for n in meta_tag.childNodes
            if n.nodeType == Node.ELEMENT_NODE
            and n.tagName == "instanceID"]
        if len(uuid_tags) == 0:
            uuid_tag = xml.createElement("instanceID")
            meta_tag.appendChild(uuid_tag)
        else:
            uuid_tag = uuid_tags[0]
        # insert meta and instanceID
        text_node = xml.createTextNode(u"uuid:%s" % uuid)
        uuid_tag.appendChild(text_node)
        return xml.toxml()
    return xml_str

def update_mongo_for_xform(xform, only_update_missing=True):
    instance_ids = set(
        [i.id for i in Instance.objects.only('id').filter(xform=xform)])
    sys.stdout.write("Total no of instances: %d\n" % len(instance_ids))
    mongo_ids = set()
    user = xform.user
    userform_id = "%s_%s" % (user.username, xform.id_string)
    if only_update_missing:
        sys.stdout.write("Only updating missing mongo instances\n")
        mongo_ids = set(
            [rec[common_tags.ID] for rec in mongo_instances.find(
                {common_tags.USERFORM_ID: userform_id},
                {common_tags.ID: 1})])
        sys.stdout.write("Total no of mongo instances: %d\n" % len(mongo_ids))
        # get the difference
        instance_ids = instance_ids.difference(mongo_ids)
    else:
        # clear mongo records
        mongo_instances.remove({common_tags.USERFORM_ID: userform_id})
    # get instances
    sys.stdout.write(
        "Total no of instances to update: %d\n" % len(instance_ids))
    instances = Instance.objects.only('id').in_bulk(
        [id for id in instance_ids])
    total = len(instances)
    done = 0
    for id, instance in instances.items():
        (pi, created) = ParsedInstance.objects.get_or_create(instance=instance)
        pi.save(async=False)
        done += 1
        # if 1000 records are done, flush mongo
        if (done % 1000) == 0:
            sys.stdout.write(
                'Updated %d records, flushing MongoDB...\n' % done)
        settings.MONGO_CONNECTION.admin.command({'fsync': 1})
        progress = "\r%.2f %% done..." % ((float(done) / float(total)) * 100)
        sys.stdout.write(progress)
        sys.stdout.flush()
    # flush mongo again when done
    settings.MONGO_CONNECTION.admin.command({'fsync': 1})
    sys.stdout.write(
        "\nUpdated %s\n------------------------------------------\n"
        % xform.id_string)

def mongo_sync_status(remongo=False, update_all=False, user=None, xform=None):
    qs = XForm.objects.only('id_string', 'user').select_related('user')
    if user and not xform:
        qs = qs.filter(user=user)
    elif user and xform:
        qs = qs.filter(user=user, id_string=xform.id_string)
    else:
        qs = qs.all()

    total = qs.count()
    found = 0
    done = 0
    total_to_remongo = 0
    report_string = ""
    for xform in queryset_iterator(qs, 100):
        # get the count
        user = xform.user
        instance_count = Instance.objects.filter(xform=xform).count()
        userform_id = "%s_%s" % (user.username, xform.id_string)
        mongo_count = mongo_instances.find(
            {common_tags.USERFORM_ID: userform_id}).count()

        if instance_count != mongo_count or update_all:
            line = "user: %s, id_string: %s\nInstance count: %d\t"\
                   "Mongo count: %d\n---------------------------------"\
                   "-----\n" % (
                       user.username, xform.id_string, instance_count,
                       mongo_count)
            report_string += line
            found += 1
            total_to_remongo += (instance_count - mongo_count)

            # should we remongo
            if remongo or (remongo and update_all):
                if update_all:
                    sys.stdout.write(
                        "Updating all records for %s\n--------------------"
                        "---------------------------\n" % xform.id_string)
                else:
                    sys.stdout.write(
                        "Updating missing records for %s\n----------------"
                        "-------------------------------\n"
                        % xform.id_string)
                update_mongo_for_xform(
                    xform, only_update_missing=not update_all)
        done += 1
        sys.stdout.write(
            "%.2f %% done ...\r" % ((float(done) / float(total)) * 100))
    # only show stats if we are not updating mongo, the update function
    # will show progress
    if not remongo:
        line = "Total # of forms out of sync: %d\n" \
            "Total # of records to remongo: %d\n" % (
            found, total_to_remongo)
        report_string += line
    return report_string

def remove_xform(xform):
    # disconnect parsed instance pre delete signal
    pre_delete.disconnect(_remove_from_mongo, sender=ParsedInstance)

    # delete instances from mongo db
    query = {
        ParsedInstance.USERFORM_ID:
        "%s_%s" % (xform.user.username, xform.id_string)}
    xform_instances.remove(query, j=True)

    # delete xform, and all related models
    xform.delete()

    # reconnect parsed instance pre delete signal?
    pre_delete.connect(_remove_from_mongo, sender=ParsedInstance)


text:
<?php

namespace Dothiv\ValueObject;

use JMS\Serializer\Annotation as Serializer;

/**
 * The clock service abstracts the current date.
 */
class ClockValue extends AbstractValueObject implements ValueObjectInterface
{

    /**
     * @var \DateTime
     */
    private $clock;

    /**
     * @param string $clockExpr
     */
    public function __construct($clockExpr)
    {
        $this->clock = $clockExpr instanceof \DateTime ? $clockExpr : new \DateTime($clockExpr);
    }

    /**
     * @return \DateTime
     */
    public function getNow()
    {
        return clone $this->clock;
    }

    /**
     * {@inheritdoc}
     */
    public function toScalar()
    {
        return $this->__toString();
    }

    /**
     * {@inheritdoc}
     * @Serializer\HandlerCallback("json", direction = "serialization")
     */
    public function __toString()
    {
        return $this->clock->format(DATE_W3C);
    }

}


text:
dvgrab -autosplit -rewind -showstatus -size=0 -timestamp tape-

# the file names will be like: "tape-2013.08.06_12-02-17.dv"


text:
import settings from "./_settings";

export default () => {
    return settings;
}


text:
An AWS Lambda function to receive GitHub webhooks from API gateway and relay them to an EC2 instance.

## Usage

1. Create a Security Group for the Lambda function
  - Inbound: None
  - Outbound: Only allow HTTPS/HTTP to the receiving instance

1. Create a Lambda function:
  - Runtime: Python 2.7
  - Handler: hook.lambda_handler
  - Role: Basic With VPC
  - Memory: 128MB
  - Timeout: 30sec
  - VPC: The VPC of the receiving instance
  - Subnets: At least 2 private subnets within the VPC
  - Security Groups: The Security Group configured previously

1. Install dependencies locally:

  `$ pip install -r requirements.txt -t lambdawebhook/lib/`

1. Create a ZIP archive of the `lambdawebhook` directory:

  `$ cd lambdawebhook`
  `$ zip -r lambdawebhook.zip *`

1. Upload the zipped code to the Lambda function created previously

1. Create an API in API gateway

1. Create a resource for `/github`

1. Create a POST method for `/github`
  - Integration type: Lambda Function
  - Lambda Region: The region of the Lamba function created previously
  - Lambda Function: The Lambda function created previously

1. Integration Request -> Mapping Templates:
  - Content-Type: `application/json`
  - Mapping Template (replace `secret` and `jenkins_url` as appropriate for your configuration):

          {
              "x_github_delivery": "$util.escapeJavaScript($input.params().header.get('X-GitHub-Delivery'))",
              "x_github_event": "$util.escapeJavaScript($input.params().header.get('X-GitHub-Event'))",
              "x_hub_signature": "$util.escapeJavaScript($input.params().header.get('X-Hub-Signature'))",
              "secret": "some_secret",
              "jenkins_url": "https://jenkins/github-webhook/",
              "payload": "$util.base64Encode($input.body)"
          }

1. Method Response:
  - HTTP Status: `400`

1. Integration Response -> Add integration response:
  - Lambda Error Regex: `400 Client Error: Bad Request`
  - Method response status: `400`
  - Mapping Templates:
    - Content-Type: `application/json`
    - Template:

            {
                "message": $input.json('$.errorMessage')
            }

1. Deploy API

1. Configure the webhook and secret for the GitHub repository using the API URL provided in the previous step, and `secret` set above.

1. Test by pushing some code to the repository.

## Development

Linting (flake8) and testing (unittest) are executed using `tox` in the root directory of this repository:

    $ pip install tox
    $ tox


text:
@{

# Script module or binary module file associated with this manifest.
RootModule = 'JobSetManager.psm1'

# Version number of this module.
ModuleVersion = '0.3.2'

# Supported PSEditions
CompatiblePSEditions = @('Desktop','Core')

# ID used to uniquely identify this module
GUID = 'ff451c16-973e-4b8f-b26e-fc53666bdc82'

# Author of this module
Author = 'Mike Campbell'

# Company or vendor of this module
CompanyName = 'Exact Solutions'

# Copyright statement for this module
Copyright = '2019'

# Description of the functionality provided by this module
Description = 'add on module for poshrsjob, ThreadJob, or BackgroundJobs to manage complex interdependent Jobs'

# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''

# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''

# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''

# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''

# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''

# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()

# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()

# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()

# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()

# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()

# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @(
    'Add-JSMJobAttempt'
    'Add-JSMJobCompletion'
    'Add-JSMJobFailure'
    'Add-JSMProcessingStatusEntry'
    'Clear-JSMJobAttempt'
    'Clear-JSMJobCompletion'
    'Clear-JSMFailedJob'
    'Clear-JSMProcessingStatusEntry'
    'Get-JSMJobAttempt'
    'Get-JSMJobCompletion'
    'Get-JSMJobCurrent'
    'Get-JSMJobDiagram'
    'Get-JSMJobFailure'
    'Get-JSMJobPending'
    'Get-JSMProcessingStatusEntry'
    'Get-JSMJobSetDiagram'
    'Get-JSMJobNext'
    'Get-JSMJobRequired'
    'Get-JSMStopwatch'
    'Get-JSMVariable'
    'Get-JSMVariableValue'
    'Invoke-JSMProcessingLoop'
    'New-JSMVariable'
    'Start-JSMJobFailureProcess'
    'Start-JSMNewJobCompletionProcess'
    'Start-JSMPeriodicReportProcess'
    'Remove-JSMJobCompletion'
    'Remove-JSMFailedJob'
    'Remove-JSMVariable'
    'Set-JSMJobAttempt'
    'Set-JSMPeriodicReportSetting'
    'Set-JSMVariable'
    'Start-JSMStopwatch'
    'Start-JSMJob'
    'Test-JSMJobCondition'
    'Test-JSMJobResult'
    'Test-JSMStopWatchPeriod'
)

# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
#CmdletsToExport = '*'

# Variables to export from this module
#VariablesToExport = '*'

# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
#AliasesToExport = '*'

# DSC resources to export from this module
# DscResourcesToExport = @()

# List of all modules packaged with this module
# ModuleList = @()

# List of all files packaged with this module
# FileList = @()

# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{

    PSData = @{

        # Tags applied to this module. These help with module discovery in online galleries.
        # Tags = @()

        # A URL to the license for this module.
        # LicenseUri = ''

        # A URL to the main website for this project.
        ProjectUri = 'https://github.com/exactmike/JobSetManager'

        # A URL to an icon representing this module.
        # IconUri = ''

        # ReleaseNotes of this module
        # ReleaseNotes = ''

    } # End of PSData hashtable

} # End of PrivateData hashtable

# HelpInfo URI of this module
# HelpInfoURI = ''

# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''

}