text:
#ifndef EX_SORT_GRBY_H
#define EX_SORT_GRBY_H

/* -*-C++-*-
******************************************************************************
*
* File:         ex_sort_grby.h
* Description:  Class declarations for ex_sort_grby_tcb and ex_sort_grby_tdb
*               The sort groupby operator assumes that its input comes grouped
*               already, therefore it needs no internal table
* Created:
* Language:     C++
*
*
*
*
******************************************************************************
*/

// External forward declarations
//
class ExSimpleSQLBuffer;

// This file should only be included by ex_sort_grby.c

//
// Task Definition Block
//
#include "ComTdbSortGrby.h"

// -----------------------------------------------------------------------
// Classes defined in this file
// -----------------------------------------------------------------------
class ex_sort_grby_tdb;

// -----------------------------------------------------------------------
// Classes referenced in this file
// -----------------------------------------------------------------------
class ex_tcb;

// -----------------------------------------------------------------------
// ex_sort_grby_tdb
// -----------------------------------------------------------------------
class ex_sort_grby_tdb : public ComTdbSortGrby
{
public:

  // ---------------------------------------------------------------------
  // Constructor is only called to instantiate an object used for
  // retrieval of the virtual table function pointer of the class while
  // unpacking. An empty constructor is enough.
  // ---------------------------------------------------------------------
  ex_sort_grby_tdb()
  {}

  virtual ~ex_sort_grby_tdb()
  {}

  // ---------------------------------------------------------------------
  // Build a TCB for this TDB. Redefined in the Executor project.
  // ---------------------------------------------------------------------
  virtual ex_tcb *build(ex_globals *globals);

private:
  // ---------------------------------------------------------------------
  // !!!!!!! IMPORTANT -- NO DATA MEMBERS ALLOWED IN EXECUTOR TDB !!!!!!!!
  // *********************************************************************
  // The Executor TDB's are only used for the sole purpose of providing a
  // way to supplement the Compiler TDB's (in comexe) with methods whose
  // implementation depends on Executor objects. This is done so as to
  // decouple the Compiler from linking in Executor objects unnecessarily.
  //
  // When a Compiler generated TDB arrives at the Executor, the same data
  // image is "cast" as an Executor TDB after unpacking. Therefore, it is
  // a requirement that a Compiler TDB has the same object layout as its
  // corresponding Executor TDB. As a result of this, all Executor TDB's
  // must have absolutely NO data members, but only member functions. So,
  // if you reach here with an intention to add data members to a TDB, ask
  // yourself two questions:
  //
  // 1. Are those data members Compiler-generated?
  //    If yes, put them in the ComTdbSortGrby instead.
  //    If no, they should probably belong to someplace else (like TCB).
  //
  // 2. Are the classes those data members belong defined in the executor
  //    project?
  //    If your answer to both questions is yes, you might need to move
  //    the classes to the comexe project.
  // ---------------------------------------------------------------------
};

//
// Task control block for ex_sort_grby_tcb
//
class ex_sort_grby_tcb : public ex_tcb
{
  friend class   ex_sort_grby_tdb;
  friend class   ex_sort_grby_private_state;

protected:
  const ex_tcb * childTcb_;

  ex_queue_pair  qparent_;
  ex_queue_pair  qchild_;

  ExSimpleSQLBuffer *pool_;

  queue_index    processedInputs_;

  atp_struct *workAtp_;

public:
  // Constructor
  ex_sort_grby_tcb(const ex_sort_grby_tdb & sort_grby_tdb,
		   const ex_tcb &    child_tcb , // child queue pair
		   ex_globals * glob
		   );

  ~ex_sort_grby_tcb();

  enum sort_grby_step {
    SORT_GRBY_EMPTY,
    SORT_GRBY_NEW_GROUP,
    SORT_GRBY_FIRST_GROUP_ROW,
    SORT_GRBY_STARTED,
    SORT_GRBY_FINALIZE,
    SORT_GRBY_FINALIZE_CANCEL,
    SORT_GRBY_FINALIZE_EOF,
    SORT_GRBY_DONE,
    SORT_GRBY_CANCELLED,
    SORT_GRBY_LOCAL_ERROR,
    SORT_GRBY_CHILD_ERROR,
    SORT_GRBY_NEVER_STARTED,

    // next few states are for rollup sortgroupby tcb
    SORT_GRBY_ROLLUP_GROUPS_INIT,
    SORT_GRBY_ROLLUP_GROUP_START,
    SORT_GRBY_ROLLUP_GROUP,
    SORT_GRBY_ROLLUP_FINAL_GROUP_START,
    SORT_GRBY_ROLLUP_FINAL_GROUP
    };

  void freeResources();  // free resources

  virtual short work();  // when scheduled to do work

  ex_sort_grby_tdb & sort_grby_tdb() const
  {return (ex_sort_grby_tdb &) tdb;}

  // return a pair of queue pointers to the parent node. Needed only during
  // construction of nodes.
  ex_queue_pair getParentQueue() const
  {
    return (qparent_);
  }

  virtual ex_tcb_private_state * allocatePstates(
       Lng32 &numElems,      // inout, desired/actual elements
       Lng32 &pstateLength); // out, length of one element

  AggrExpr * aggrExpr() const { return sort_grby_tdb().aggrExpr(); }

  inline ex_expr * grbyExpr() const { return sort_grby_tdb().grbyExpr_; };
  inline ex_expr * moveExpr() const { return sort_grby_tdb().moveExpr_; };
  inline ex_expr * havingExpr() const { return sort_grby_tdb().havingExpr_; };

  inline Lng32 recLen() {return sort_grby_tdb().recLen_;};

  virtual Int32 numChildren() const { return 1; }
  virtual const ex_tcb* getChild(Int32 pos) const
  {
    ex_assert((pos >= 0), "");
    if (pos == 0)
      return childTcb_;
    else
      return NULL;
  }

protected:
  // code contained in the next 4 methods was previously part of mainline
  // sort groupby code.
  // That has now been extracted into these methods so it could be
  // used by regular and rollup sortgroupby tcbs.
  short handleCancel(sort_grby_step &step, short &rc);
  short handleError(sort_grby_step &step, short &rc);
  short handleFinalize(sort_grby_step &step, short &rc);
  short handleDone(sort_grby_step &step, short &rc,
                   NABoolean noAssert = FALSE);

};

/////////////////////////////////////////////////////////////////////
// Task control block for ex_sort_grby_rollup_tcb
/////////////////////////////////////////////////////////////////////
class ex_sort_grby_rollup_tcb : public ex_sort_grby_tcb
{
  friend class   ex_sort_grby_tdb;
  friend class   ex_sort_grby_private_state;

public:
  // Constructor
  ex_sort_grby_rollup_tcb(const ex_sort_grby_tdb & sort_grby_tdb,
                          const ex_tcb &    child_tcb , // child queue pair
                          ex_globals * glob
                          );

  virtual short work();  // when scheduled to do work

private:
  short rollupAggrInit();

  // this method does 3 things:
  //  1) moves rollup nulls to return buffer
  //  2) evaluates grouping function for rollup nulls
  //  3) moves grouping function result to return buffer
  short processRollupGrbyNulls(Int16 groupNum);

  // move values from child row to rollup array
  short rollupGrbyMoveValue(ex_queue_entry * centry);

  // evaluate aggregate for all regular and rollup entries
  short rollupAggrEval(ex_queue_entry * centry);

  // array of entries where rollup aggrs and group values will be computed
  char ** rollupGroupAggrArr_;

  sort_grby_step step_;

  Int16 rollupColumnNum_;
  Int16 startGroupNum_;
  Int16 endGroupNum_;
  Int16 currGroupNum_;

  NABoolean allDone_;
};

///////////////////////////////////////////////////////////////////
class ex_sort_grby_private_state : public ex_tcb_private_state
{
  friend class ex_sort_grby_tcb;
  friend class ex_sort_grby_rollup_tcb;

public:

  ex_sort_grby_private_state();
  ~ex_sort_grby_private_state();

private:

  ex_sort_grby_tcb::sort_grby_step step_;

  queue_index index_;        // index into down queue
  Int64 matchCount_;         // number of rows returned for this parent row
  NABoolean     oneRowAggr_;
};

#endif


text:
Padrino.configure_apps do
  # enable :sessions
  set :session_secret, ENV['SESSION_SECRET'] || 'cd89a4ebe8801dfd0c7d657bad04ec6c220e342286ffb7b423ee38d9608a8a04'
  set :protection, except: :path_traversal
  set :protect_from_csrf, true
end

# Mounts the core application for this project
Padrino.mount('Wkanki::App', app_file: Padrino.root('app/app.rb')).to('/')

redpajama_set_name: RedPajamaGithub


text:
void flash_erase_page(uint32_t address);
void flash_program_word(uint32_t address, uint32_t data);
uint32_t flash_get_status_flags(void);

#endif // __FLASH_H__


text:
package com.github.dynamo.model.music;

import java.io.Serializable;

public class MusicArtist implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private String name;
	private boolean favorite;
	private boolean blackListed;
	private Long tadbArtistId;
	private String aka;

	public MusicArtist(String name, boolean favorite, boolean blackListed, Long tadbArtistId, String aka) {
		this.name = name;
		this.favorite = favorite;
		this.blackListed = blackListed;
		this.tadbArtistId = tadbArtistId;
		this.aka = aka;
	}

	public String getName() {
		return name;
	}

	public boolean isFavorite() {
		return favorite;
	}

	public void setFavorite(boolean favorite) {
		this.favorite = favorite;
	}

	public boolean isBlackListed() {
		return blackListed;
	}

	public Long getTadbArtistId() {
		return tadbArtistId;
	}

	public void setTadbArtistId(Long tadbArtistId) {
		this.tadbArtistId = tadbArtistId;
	}

	public String getAka() {
		return aka;
	}

	@Override
	public int hashCode() {
		return name.hashCode();
	}

	@Override
	public String toString() {
		return name;
	}

	@Override
	public boolean equals(Object other) {
		return other != null && name.equals( ((MusicArtist)other).getName() );
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <meta content="text/html; charset=ISO-8859-1"
      http-equiv="Content-Type">
    <title>Annotations and Annotation Progress</title>
    <link href="../css/doc.css" rel="stylesheet" type="text/css">

Annotations and annotation progress

Annotations

Annotation
          attributes and values

Simple span
          annotations vs. complex annotations

Annotation categories

Admin annotations,
          SEGMENTs, and annotation progress

Annotations

The basic unit of document enrichment in MAT is the annotation. There are two
      types of annotations in MAT: span

        annotations and spanless

        annotations. Span annotations are anchored to a
      particular contiguous span in the document, and make some implicit
      assertion about it; e.g., the span from character 10 to character
      15 is a noun phrase. Spanless annotations are not anchored to a
      span, and are used to make assertions about the entire document,
      or to make assertions about other annotations; e.g., annotation 1
      and annotation 2 refer to the same entity.

The task specification for each task contains one or more annotation set descriptors, which
      define the annotations available in the task. In MAT 2.0, there's
      very little reason, if any, to have multiple annotation set
      descriptors defined; however, upcoming versions of MAT will
      exploit this capability extensively.

Annotation
      attributes and values

In MAT, annotations have labels, and may have attributes and
      values associated with them. Each attribute has a type and
      an aggregation.

The types are:

"string": this is the default type. The value of such an
        attribute must be a string. When specifying this type, you can
        provide a default; specify that the default is the spanned text;
        or provide an exhaustive list of choices.

"int": the value of this attribute must be an integer. When
        specifying this type, you can provide a default; specify that
        the default is the spanned text (if it can be coerced to an
        integer); provide an exhaustive list of choices; or provide
        minimum and/or maximum values.

"float": the value of this attribute must be a float. When
        specifying this type, you can provide a default; specify that
        the default is the spanned text (if it can be coerced to a
        float); or provide minimum and/or maximum values.

"boolean": the value of this attribute must be a boolean (Java
        boolean, JavaScript true/false, Python True/False). When
        specifying this type, you can provide a default.

"annotation": the value of this attribute must be an
        annotation. When specifying this type, you can specify a set of
        label restrictions, each consisting of a label or a label and
        some attribute/value pairs; any filler of this attribute must
        satisfy one of the label restrictions.

See here
      for examples of defining attributes of various types.

It is possible for any attribute to have a null value (Java and
      JavaScript null, Python None), or not to be present. These
      conditions are intended to be equivalent, and the various document
      libraries mostly treat them that way; however, there may be times
      in Python where an attribute which has never been set will raise a
      KeyError.

The aggregations are:

"none" or null: the default. A singleton value.

"list": a list of values of the type specified. Null list
        elements are not permitted.

"set": a set of values of the type specified. Null set
        elements are not permitted.

MAT does not currently limit the possible combinations of these
      types and aggregations, even if some of them are nonsensical
      (e.g., a set of booleans). However, the annotation UI has not been
      enriched with the ability to edit all 15 possible combinations;
      some of the less common ones (e.g., sets of strings which are not
      restricted by a choice list) have not been implemented yet. We're
      committed to supporting all of them, eventually.

MAT also supports the notion of effective label. An
      effective label is a notional label (e.g., "PERSON") which is
      presented to the user in its notional form, but is implemented as
      an annotation label plus an attribute value of a string attribute
      which is specified to have an exhaustive list of choices. Labels
      of this sort are also known as "ENAMEX-style" labels, after the
      MUC convention of defining "PERSON" as "ENAMEX" + type="PER", and
      "ORGANIZATION" and "LOCATION" analogously.

Simple span
      annotations vs. complex annotations

Simple span annotations are span annotations which have
      either no attributes, or a single attribute/value pair which
      defines the effective label. This notion is important because it
      is the class of annotations which the Carafe engine can build models
      for. While it's possible to use more complex engines with MAT (we
      don't provide details on how to do it, but it's possible), MAT
      "out of the box" has more limited capabilities for annotations
      which are more complex than this (i.e., spanless annotations, or
      annotations with more attributes). In these case, Carafe will
      happily build and apply models for the simple span subset of the
      complex annotations it's given, but this capability isn't enough
      to support the full tag-a-little,
        learn-a-little loop, or the experiment harness.

Here's a complete list of these limitations:

Hand anotation: no limitations.

Automated content tagging in workflows, workspaces, and the
          experiment engine: Carafe will add only simple span
        annotations. Carafe will not add additional attributes beyond
        the effective label attribute (if present), nor spanless
        annotations.

Model building in file mode, workspaces, and the experiment
          engine: Carafe will build models only for simple span
        annotations. Carafe will not build models for additional
        attributes beyond the effective label attribute (if present),
        nor spanless annotations.

Visual document comparison: no limitations.

Visual document alignment and reconciliation: simple
        span annotations only.

Scoring: no limitations.

Workspace import, assignment and folder management: no
        limitations.

Transducing and reporting: no limitations.

Annotation categories

Annotation categories are one way of notifying MAT about the role
      of the various annotations in the MAT task. Annotations in the
      "content" category are, in some sense, what the task is about;
      these are the annotations you'll be adding by hand, or using the Carafe engine to add
      automatically.

The other categories above have semantics assigned by MAT. These
      semantics are crucial for using MAT correctly. The annotations in
      the "token" and "zone" categories (known as "structure
      categories") can be inherited from the root task, which is what
      most tasks will do. This is what you should do in most cases,
      since it's unusual to need to define your own structural
      annotations. We attempt to document MAT's dependencies on these
      categories below. The annotations in the "admin" category are
      special; all tasks will have these annotations.

Content annotations

The semantics of the content labels are defined by the task. For
      instance, the sample task is about annotation of named entities,
      and the three content annotation labels shown here have a
      standardized interpretation in named entity annotation, for which
      detailed guidelines have been developed about when to assign each
      of these annotation labels. You may not add annotations named
      SEGMENT or VOTE, since these are reserved names of admin
      annotations.

Good guidelines are crucial for maximizing agreement among human
      annotators when preparing gold-standard corpora. When you develop
      your own task, you should develop similar guidelines; this skill
      is quite sophisticated, and is outside the scope of this
      documentation.

Zone annotations

Zones correspond to large chunks of the document where
      annotations can be found. The default zone annotation in MAT is
      the "zone" label, which has an attribute called "region_type",
      whose value is typically "body" (it's possible for the Carafe
      engine to use the zone attributes as a training feature, but we
      don't use that capability at the moment). The implementation of
      your task provides the Carafe engine with information about the
      default zone annotation; you can change this implementation (and
      you must if you have a custom zone annotation) as described in the
      advanced

        topics. You may not add annotations named SEGMENT or VOTE,
      since these are reserved names of admin annotations.

The simplest zoning of a document is to assign a single zone of
      region_type "body" which encompasses the whole document, and there
      is a zone step available which does this. If you want to get more
      sophisticated (e.g., exclude HTML or XML tags), you'll have to
      consult the advanced
        topics.

Zone tags are also used in the UI to induce the creation of
      untaggable regions, which are regions that have no zone
      annotation. These regions are indicated visually by graying out
      the document text. If the document has any zone annotations at
      all, the UI will create these regions.

Token annotations

Tokens correspond, pretty much, to words. In MAT, token
      annotations are used as the basis for most computation. When you
      hand-annotate your documents, you are encouraged to require that
      token annotations are present, so that the MAT annotation tool can
      determine the possible boundaries of your proposed annotation.
      This is because the Carafe trainer and tagger both use tokens (not
      characters) as the "atoms" of computation, and as a result, any
      annotation whose boundaries do not coincide with token boundaries
      must be modified or discarded during the training phase (because
      the element at the relevant edge doesn't correspond to an "atom"
      as far as Carafe is concerned). Similarly, you must use the same
      automatic tokenization process for training and tagging, for
      obvious reasons.

Carafe is one of many trainable annotation tools which rely on
      tokens as atoms; however, most hand annotation tools don't try to
      ensure in advance that annotation boundaries match token
      boundaries, and the users of such tools have to make
      accommodations later in their workflows.

The MAT toolkit comes with a default English tokenizer, which we
      describe when we talk about steps.
      There's nothing special about this tokenizer; you can replace it
      with your own, as long as you use the same tokenizer throughout
      your task. If you inherit your structure annotations from the core
      task, and use the default tokenizer, you don't have to think about
      this any further. If you don't, your tokenizer and task have to
      make sure of several things:

the task defines an annotation label of category "token"

there is at least one annotation label of this category, named
        "lex" (Carafe expects this name)

the tokenizer outputs annotations with these labels

the spans which bear these labels don't cross the boundaries
        of zone annotations

A sample
      inventory of annotations

As an example, let's take a look at the annotations in the sample

        'Named Entity' task.

          Annotation label

          Category

          Use

          lex

          token

          each lex tag delimits a
            non-whitespace token (the basic element used in the Carafe
            trainer and tagger)

          zone

          zone

          delimits a contiguous zone in
            which content annotations will be found

          PERSON

          content

          a proper name of a person

          LOCATION

          content

          a proper name of a location

          ORGANIZATION

          content

          a proper name of an
            organization

          SEGMENT

          admin

          administrative info about the
            progress of annotation (present in all tasks)

          VOTE

          admin

          administrative info about reconciliation
            (present in all tasks)

Admin annotations,
      SEGMENTs, and annotation progress

The final category of annotations, admin annotations, are crucial to the operation of
      the 2.0 version of MAT. However, both of them work behind the
      scenes for you. If you don't care about the inner bookkeeping that
      MAT uses, you may skip this section; all you really need to know
      is that using the two admin annotations, SEGMENT and VOTE, MAT can
      keep detailed track of how the annotation of various portions of a
      document is progressing.

These admin annotations play a much smaller role in MAT 2.0
        than we originally anticipated. We had originally expected MAT
        2.0 to contain support for partial hand annotation and
        correction (e.g., annotating only certain regions of documents),
        for active learning, and for reconciliation workflows in
        workspaces. However, our exploration of active learning has
        convinced us that there's no evidence that it reduces annotator
        time for document-oriented annotation tasks, and our extensions
        for spanless annotation have forced us to reconsider our
        original strategy for reconciliation. We've issued a
        reconciliation tool for simple span tasks with MAT 2.0, but this
        tool will be replaced in the next version of MAT with a more
        general-purpose reconciliation tool based on the new comparison tool and the new scorer. The new reconciliation
        workflows will still require SEGMENTs and VOTEs, but they'll
        look different than they do now.

This section should be regarded as applying exclusively to MAT
        2.0, with considerable future modifications planned.

The details

There are currently two admin annotations: SEGMENT, which records
      information about the progress of annotation, and VOTE, which is
      used specifically during reconciliation.
      Reconciliation is an advanced topic, and we'll talk about VOTE
      annotations when we talk about reconciliation. Here, we describe
      the role of the SEGMENT annotation.

    SEGMENTs are a disjoint cover of the zone annotations in a document.
    These annotations can capture a number of aspects about the progress
    of annotation:

the extent of the progress

the identity of the annotator

the status of the progress

The SEGMENT is a span annotation. It has two attributes,
      "annotator" and "status". These attributes occur in the following
      configurations of values:

          Value of the annotator
            attribute

          Value of the status attribute

          What it means

          (null)

          "non-gold"

          The segment is untouched. No
            human or automated annotator has modified it.

          "MACHINE"

          "non-gold"

          The segment has been
            annotated by an automated tool, but no human has marked it
            as completed.

          (a user's name)

          "non-gold"

          A user "owns" this segment
            and has modified the segment in some way, but is not
            prepared to mark it as completed. If a user corrects a
            segment which an automated tool has annotated, the user now
            "owns" the segment.

          (a user's name)

          "human gold"

          A user "owns" the segment and
            has marked it as complete.

          (a user's name)

          "reconciled"

          A user "owns" the segment and
            has marked it complete, and the segment has been vetted by
            the reconciliation process.

    (Reconciliation adds a few more attributes to the SEGMENT
    annotation. We'll discuss those later.)

It's possible, then, to have partially annotated documents, with
      multiple segments, some of whose segments are gold and some of
      whose segments are not gold. The 2.0 version of MAT does not yet
      expose this possibility in its UI (except during the
      reconciliation process), but the infrastructure to represent this
      is already there. These attribute values can be rolled up,
      conceptually, to represent documents which are in a variety of
      states of completion. These document status values are used
      extensively in workspaces.

            <meta http-equiv="content-type" content="text/html;
              charset=ISO-8859-1">
            "reconciled"

          documents all of whose
            SEGMENTs have status = "reconciled"

          "gold"

          documents all of whose
            SEGMENTS have status = "reconciled" or status = "human gold"
            (and at least one "human gold" SEGMENT)

          "partially gold"

          documents some (but not all)
            of whose SEGMENTs have status = "reconciled" or status =
            "human gold"

          "uncorrected"

          documents all of whose
            SEGMENTS have annotator = "MACHINE"

          "partially corrected"

          documents some of whose
            SEGMENTs have annotator != "MACHINE" and annotator != null
            (i.e., they've been touched by a human annotator)

          "unannotated"

          documents which have no
            content annotations in any segment and no SEGMENTs which are
            owned by any annotator

All the relevant MAT tools are aware of the SEGMENT annotations.

The predefined zone steps
        ensure that when zones are added, corresponding SEGMENT
        annotations are added as well.

The Carafe engine, by
        default, will only insert annotations into SEGMENTs whose
        annotator = "MACHINE" or annotator = null. If no segments are
        found, it will insert annotations into all the zones; if no
        zones are found, it will insert annotations into the entire
        document. Any SEGMENT into which annotations are inserted will
        be marked annotator = "MACHINE".

The Carafe engine, by
        default, will train on all SEGMENTs which have been which have
        been touched by a human annotator, whether or not they're gold
        (see, however, the --partial_training_on_gold_only option). If
        no SEGMENTs are found, it will use all the zones; if no zones
        are found, it will use the entire document. The scope of the
        training is important; any blank regions are treated as
        implicitly negative information (i.e., the trainer will conclude
        that there's no annotation there on purpose).

The MAT UI ensures that each document that's going to be
        annotated has at least one SEGMENT per zone. It uses "unknown
        human" as the default annotator. As soon as the human annotator
        adds, removes or modifies an annotation, the enclosing SEGMENT
        annotation is marked annotator = "unknown human".  The
        "mark gold" step in the UI marks all SEGMENTs in the document
        status = "human gold".


text:
    OsuCelebrityDEBUG

Current

Spoof

Login with Twitch

{{global.user.name}}

Signout


text:
package com.ibm.watson.assistant.v2.model;

import static org.testng.Assert.*;

import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import com.ibm.watson.assistant.v2.utils.TestUtilities;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;

/** Unit test class for the ResponseGenericChannel model. */
public class ResponseGenericChannelTest {
  final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
  final List<FileWithMetadata> mockListFileWithMetadata =
      TestUtilities.creatMockListFileWithMetadata();

  @Test
  public void testResponseGenericChannel() throws Throwable {
    ResponseGenericChannel responseGenericChannelModel = new ResponseGenericChannel();
    assertNull(responseGenericChannelModel.getChannel());
  }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Protocols.TestTools.StackSdk.Asn1;

namespace Microsoft.Protocols.TestTools.StackSdk.Security.KerberosLib
{
    /*
    EncKrbCredPart  ::= [APPLICATION 29] SEQUENCE {
        ticket-info     [0] SEQUENCE OF KrbCredInfo,
        nonce           [1] UInt32 OPTIONAL,
        timestamp       [2] KerberosTime OPTIONAL,
        usec            [3] Microseconds OPTIONAL,
        s-address       [4] HostAddress OPTIONAL,
        r-address       [5] HostAddress OPTIONAL
    }
    */
    [Asn1Tag(Asn1TagType.Application, 29)]
    public class EncKrbCredPart : Asn1Sequence
    {
        [Asn1Field(0), Asn1Tag(Asn1TagType.Context, 0)]
        public Asn1SequenceOf<KrbCredInfo> ticket_info { get; set; }

        [Asn1Field(1, Optional = true), Asn1Tag(Asn1TagType.Context, 1)]
        public KerbUInt32 nonce { get; set; }

        [Asn1Field(2, Optional = true), Asn1Tag(Asn1TagType.Context, 2)]
        public KerberosTime timestamp { get; set; }

        [Asn1Field(3, Optional = true), Asn1Tag(Asn1TagType.Context, 3)]
        public Microseconds usec { get; set; }

        [Asn1Field(4, Optional = true), Asn1Tag(Asn1TagType.Context, 4)]
        public HostAddress s_address { get; set; }

        [Asn1Field(5, Optional = true), Asn1Tag(Asn1TagType.Context, 5)]
        public HostAddress r_address { get; set; }

        public EncKrbCredPart()
        {
            this.ticket_info = null;
            this.nonce = null;
            this.timestamp = null;
            this.usec = null;
            this.s_address = null;
            this.r_address = null;
        }

        public EncKrbCredPart(
         Asn1SequenceOf<KrbCredInfo> param0,
         KerbUInt32 param1,
         KerberosTime param2,
         Microseconds param3,
         HostAddress param4,
         HostAddress param5)
        {
            this.ticket_info = param0;
            this.nonce = param1;
            this.timestamp = param2;
            this.usec = param3;
            this.s_address = param4;
            this.r_address = param5;
        }
    }
}


text:
namespace Mass.Core.Expressions
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Mass.Core.Functions;

    public class CallExpression : IExpression
    {
        private static int hashcode = typeof(CallExpression).GetHashCode();

        private IExpression expression;
        private IList<IExpression> arguments;

        public CallExpression(IExpression expression, IList<IExpression> arguments)
        {
            this.expression = expression;
            this.arguments = arguments;
        }

        public object Evaluate(Context context)
        {
            IFunction function = (IFunction)this.expression.Evaluate(context);

            IList<object> values = new List<object>();

            foreach (var argument in this.arguments)
                values.Add(argument.Evaluate(context));

            return function.Apply(null, values);
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            if (obj is CallExpression)
            {
                var expr = (CallExpression)obj;

                if (!this.expression.Equals(expr.expression))
                    return false;

                if (this.arguments.Count != expr.arguments.Count)
                    return false;

                for (var k = 0; k < this.arguments.Count; k++)
                    if (!this.arguments[k].Equals(expr.arguments[k]))
                        return false;

                return true;
            }

            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            int result = this.expression.GetHashCode() + hashcode;

            foreach (var argument in this.arguments)
                result += argument.GetHashCode();

            return result;
        }
    }
}


text:
require "cases/helper"

module ActiveRecord
  class Migration
    class SchemaDefinitionsTest < ActiveRecord::TestCase
      attr_reader :connection

      def setup
        @connection = ActiveRecord::Base.connection
      end

      def test_build_create_table_definition_with_block
        td = connection.build_create_table_definition :test do |t|
          t.column :foo, :string
        end

        id_column = td.columns.find { |col| col.name == "id" }
        assert_predicate id_column, :present?
        assert id_column.type
        assert id_column.sql_type

        foo_column = td.columns.find { |col| col.name == "foo" }
        assert_predicate foo_column, :present?
        assert foo_column.type
        assert foo_column.sql_type
      end

      def test_build_create_table_definition_without_block
        td = connection.build_create_table_definition(:test)

        id_column = td.columns.find { |col| col.name == "id" }
        assert_predicate id_column, :present?
        assert id_column.type
        assert id_column.sql_type
      end

      def test_build_create_join_table_definition_with_block
        assert connection.table_exists?(:posts)
        assert connection.table_exists?(:comments)

        join_td = connection.build_create_join_table_definition(:posts, :comments) do |t|
          t.column :another_col, :string
        end

        assert_equal :comments_posts, join_td.name
        assert_equal ["another_col", "comment_id", "post_id"], join_td.columns.map(&:name).sort
      end

      def test_build_create_join_table_definition_without_block
        assert connection.table_exists?(:posts)
        assert connection.table_exists?(:comments)

        join_td = connection.build_create_join_table_definition(:posts, :comments)

        assert_equal :comments_posts, join_td.name
        assert_equal ["comment_id", "post_id"], join_td.columns.map(&:name).sort
      end

      def test_build_create_index_definition
        connection.create_table(:test) do |t|
          t.column :foo, :string
        end
        create_index = connection.build_create_index_definition(:test, :foo)

        assert_match "CREATE INDEX", create_index.ddl
        assert_equal "index_test_on_foo", create_index.index.name
      ensure
        connection.drop_table(:test) if connection.table_exists?(:test)
      end

      if current_adapter?(:Mysql2Adapter)
        def test_build_create_index_definition_for_existing_index
          connection.create_table(:test) do |t|
            t.column :foo, :string
          end
          connection.add_index(:test, :foo)

          create_index = connection.build_create_index_definition(:test, :foo, if_not_exists: true)
          assert_nil create_index
        ensure
          connection.drop_table(:test) if connection.table_exists?(:test)
        end
      end

      unless current_adapter?(:SQLite3Adapter)
        def test_build_change_column_definition
          connection.create_table(:test) do |t|
            t.column :foo, :string
          end

          change_cd = connection.build_change_column_definition(:test, :foo, :integer)
          assert change_cd.ddl

          change_col = change_cd.column
          assert_equal "foo", change_col.name.to_s
          assert change_col.type
          assert change_col.sql_type
        ensure
          connection.drop_table(:test) if connection.table_exists?(:test)
        end

        def test_build_change_column_default_definition
          connection.create_table(:test) do |t|
            t.column :foo, :string
          end

          change_default_cd = connection.build_change_column_default_definition(:test, :foo, "new")
          assert_match "SET DEFAULT 'new'", change_default_cd.ddl
          assert_equal "new", change_default_cd.default

          change_col = change_default_cd.column
          assert_equal "foo", change_col.name.to_s
          assert change_col.type
          assert change_col.sql_type
        ensure
          connection.drop_table(:test) if connection.table_exists?(:test)
        end
      end
    end
  end
end


text:
<?php
namespace Warlords\GameBundle\Controller;

use FOS\UserBundle\Controller\ResettingController as BaseController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\HttpFoundation\Response;

class ResettingController extends BaseController
{

    /**
     * Request reset user password: submit form and send email
     */
    public function sendEmailAction()
    {
        $email = $this->container->get('request')->request->get('email');

        /** @var $user UserInterface */
        $user = $this->container->get('fos_user.user_manager')->findUserByEmail($email);

        if (null === $user) {
            return $this->container->get('templating')->renderResponse('FOSUserBundle:Resetting:request.html.'.$this->getEngine(), array('invalid_email' => $email));
        }

        if ($user->isPasswordRequestNonExpired($this->container->getParameter('fos_user.resetting.token_ttl'))) {
            return $this->container->get('templating')->renderResponse('FOSUserBundle:Resetting:passwordAlreadyRequested.html.'.$this->getEngine());
        }

        if (null === $user->getConfirmationToken()) {
            /** @var $tokenGenerator \FOS\UserBundle\Util\TokenGeneratorInterface */
            $tokenGenerator = $this->container->get('fos_user.util.token_generator');
            $user->setConfirmationToken($tokenGenerator->generateToken());
        }

        $this->container->get('session')->set(static::SESSION_EMAIL, $this->getObfuscatedEmail($user));
        $this->container->get('fos_user.mailer')->sendResettingEmailMessage($user);
        $user->setPasswordRequestedAt(new \DateTime());
        $this->container->get('fos_user.user_manager')->updateUser($user);

        return new RedirectResponse($this->container->get('router')->generate('fos_user_resetting_check_email'));
    }

     public function resetAction($token)
    {
        $user = $this->container->get('fos_user.user_manager')->findUserByConfirmationToken($token);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with "confirmation token" does not exist for value "%s"', $token));
        }

        if (!$user->isPasswordRequestNonExpired($this->container->getParameter('fos_user.resetting.token_ttl'))) {
            return new RedirectResponse($this->container->get('router')->generate('fos_user_resetting_request'));
        }

        $form = $this->container->get('fos_user.resetting.form');
        $formHandler = $this->container->get('fos_user.resetting.form.handler');
        $process = $formHandler->process($user);

        if ($process) {
            $this->setFlash('fos_user_success', 'resetting.flash.success');
            $response = new RedirectResponse($this->container->get('router')->generate('WarlordsGameBundle_profile'));
            $this->authenticateUser($user, $response);

            return $response;
        } else {
            $message = array();
        	foreach ($form->getErrors() as $error) {
                $message[] = $error->getMessage();
        	}
            $children = $form->getChildren();

            foreach ($children as $child) {
                if ($child->hasErrors()) {
                    foreach ($child->getErrors() as $error) {
                        $message[] = $error->getMessage();
                    }
                }
            }

        }
        return $this->container->get('templating')->renderResponse('FOSUserBundle:Resetting:reset.html.'.$this->getEngine(), array(
            'token' => $token,
            'form' => $form->createView(),
            'errors' => $message,
        ));
    }
}


text:
package org.apache.camel.component.mina2;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;

/**
 * @version
 */
public class Mina2ProducerAnotherConcurrentTest extends BaseMina2Test {

    @Test
    public void testSimple() throws Exception {
        String out = template.requestBody("direct:start", "A", String.class);
        assertEquals("Bye A", out);
    }

    @Test
    public void testNoConcurrentProducers() throws Exception {
        doSendMessages(1, 1);
    }

    @Test
    public void testConcurrentProducers() throws Exception {
        doSendMessages(200, 5);
    }

    private void doSendMessages(int files, int poolSize) throws Exception {
        getMockEndpoint("mock:result").expectedMessageCount(files);

        ExecutorService executor = Executors.newFixedThreadPool(poolSize);
        Map<Integer, Future<Object>> responses = new ConcurrentHashMap<Integer, Future<Object>>();
        for (int i = 0; i < files; i++) {
            final int index = i;
            Future<Object> out = executor.submit(new Callable<Object>() {

                public Object call() throws Exception {
                    return template.requestBody("direct:start", index, String.class);
                }
            });
            responses.put(index, out);
        }

        assertMockEndpointsSatisfied();
        assertEquals(files, responses.size());

        for (int i = 0; i < files; i++) {
            Object out = responses.get(i).get();
            assertEquals("Bye " + i, out);
        }
        executor.shutdownNow();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {

            public void configure() throws Exception {
                from("direct:start").to(String.format("mina2:tcp://localhost:%1$s?sync=true", getPort()));

                from(String.format("mina2:tcp://localhost:%1$s?sync=true", getPort())).process(new Processor() {

                    public void process(Exchange exchange) throws Exception {
                        String body = exchange.getIn().getBody(String.class);
                        exchange.getOut().setBody("Bye " + body);
                    }
                }).to("mock:result");
            }
        };
    }
}


text:
export default [{
  name: 'height',
  description: 'The height of the chart.',
  value: 700,
  type: 'number',
  units: 'px',
  category: 'Size',
  getter: function (){
    // get value
    // console.log('getter');
    return this.value;
  },
  setter: function (newValue){
    // Set something
    // console.log('setter');
    return newValue;
  }
}, {
  name: 'width',
  description: 'The widthj of the chart.',
  value: 900,
  units: 'px',
  type: 'number',
  category: 'Size'
}, {
  name: 'transitionDuration',
  description: 'How long should it take to animate on click.',
  value: 750,
  units: 'ms',
  type: 'number',
  category: 'Animation'
}, {
  name: 'introDuration',
  description: 'How long should it take to animate in.',
  value: 2000,
  units: 'ms',
  type: 'number',
  category: 'Animation'
}, {
  name: 'colorRange',
  value: ['#BBE491', '#FB8D34', '#E45621', '#73B0D7'],
  description: 'colors for categories',
  type: 'colorArray',
  category: 'Color'
}];


text:
FROM ubuntu:xenial
MAINTAINER vishh@google.com

RUN apt-get update && apt-get install -y nfs-common=1:1.2.8-9ubuntu12 glusterfs-client=3.7.6-1ubuntu1

ENTRYPOINT ["/bin/mount"]


text:
const RuntimeException = Jymfony.Component.Validator.Exception.RuntimeException;

/**
 * @memberOf Jymfony.Component.Validator.Exception
 */
export default class ValidationFailedException extends RuntimeException {
    /**
     * Constructor.
     *
     * @param {*} value
     * @param {Jymfony.Component.Validator.ConstraintViolationListInterface} violations
     */
    __construct(value, violations) {
        /**
         * @type {Jymfony.Component.Validator.ConstraintViolationListInterface}
         *
         * @private
         */
        this._violations = violations;

        /**
         * @type {*}
         *
         * @private
         */
        this._value = value;

        super.__construct(violations);
    }

    /**
     * Gets the invalid value.
     *
     * @returns {*}
     */
    get value() {
        return this._value;
    }

    /**
     * Gets the violation list.
     *
     * @returns {Jymfony.Component.Validator.ConstraintViolationListInterface}
     */
    get violations() {
        return this._violations;
    }
}


text:
"""
Tests for _common.py functions.  This is a unit test of the function and its
API, not a test of pywbemcli commands.
"""

from __future__ import absolute_import, print_function

import sys
from datetime import datetime
from packaging.version import parse as parse_version
import pytest

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict  # pylint: disable=import-error

from pywbem import CIMProperty, CIMInstance, CIMInstanceName, Uint32, Uint64, \
    Sint32, CIMDateTime, __version__

from pywbemtools.pywbemcli._display_cimobjects import \
    _format_instances_as_rows, _display_instances_as_table

from pywbemtools._output_formatting import DEFAULT_MAX_CELL_WIDTH

from ..pytest_extensions import simplified_test_function

OK = True    # mark tests OK when they execute correctly
RUN = True    # Mark OK = False and current test case being created RUN
FAIL = False  # Any test currently FAILING or not tested yet
SKIP = False  # mark tests that are to be skipped.

DATETIME1_DT = datetime(2014, 9, 22, 10, 49, 20, 524789)
DATETIME1_OBJ = CIMDateTime(DATETIME1_DT)
DATETIME1_STR = '"20140922104920.524789+000"'

# Click (as of 7.1.2) raises UnsupportedOperation in click.echo() when
# the pytest capsys fixture is used. That happens only on Windows.
# See Click issue https://github.com/pallets/click/issues/1590. This
# run condition skips the testcases on Windows.
CLICK_ISSUE_1590 = sys.platform == 'win32'

_PYWBEM_VERSION = parse_version(__version__)
# pywbem 1.0.0b1 or later
PYWBEM_1_0_0B1 = _PYWBEM_VERSION.release >= (1, 0, 0) and \
    _PYWBEM_VERSION.dev is None
# pywbem 1.0.0 (dev, beta, final) or later
PYWBEM_1_0_0 = _PYWBEM_VERSION.release >= (1, 0, 0)

# NOTE: The following methods are testcase parameters.  They define instances
# used in TESTCASES_FMT_INSTANCE_AS_ROWS
def simple_instance(pvalue=None):
    """
    Build a simple instance to test and return that instance. The properties
    in the instance are sorted by (lower cased) property name.

    If the parameter pvalue is provided, it must be a scalar value and an
    instance with a single property with that value is returned.
    """
    if pvalue:
        properties = [CIMProperty("P", pvalue)]
    else:
        properties = [
            CIMProperty("Pbf", value=False),
            CIMProperty("Pbt", value=True),
            CIMProperty("Pdt", DATETIME1_OBJ),
            CIMProperty("Pint32", Uint32(99)),
            CIMProperty("Pint64", Uint64(9999)),
            CIMProperty("Pstr1", u"Test String"),
        ]
    inst = CIMInstance("CIM_Foo", properties)
    return inst

def array_instance(pvalue, ptype):
    """
    Build an instance with a single property named P and the value  and type
    defined. Used to build test instance with array properties because
    type cannot be determined from the data since it is an array.
    """
    properties = [CIMProperty("P", pvalue, type=ptype)]
    return CIMInstance("CIM_Foo", properties)

def simple_instance_unsorted(pvalue=None):
    """
    Build a simple instance to test and return that instance. The properties
    in the instance are not sorted by (lower cased) property name, but
    the property order when sorted is the same as in the instance returned by
    simple_instance().

    If the parameter pvalue is provided, it must be a scalar value and an
    instance with a single property with that value is returned.
    """
    if pvalue:
        properties = [CIMProperty("P", pvalue)]
    else:
        properties = [
            CIMProperty("Pbt", value=True),
            CIMProperty("Pbf", value=False),  # out of order
            CIMProperty("pdt", DATETIME1_OBJ),  # lower cased
            CIMProperty("PInt64", Uint64(9999)),  # out of order when case ins.
            CIMProperty("Pint32", Uint32(99)),
            CIMProperty("Pstr1", u"Test String"),
        ]
    inst = CIMInstance("CIM_Foo", properties)
    return inst

def simple_instance2(pvalue=None):
    """
    Build a simple instance to test and return that instance. The properties
    in the instance are sorted by (lower cased) property name.

    If the parameter pvalue is provided, it must be a scalar value and an
    instance with a single property with that value is returned.
    """
    if pvalue:
        properties = [CIMProperty("P", pvalue)]
    else:
        properties = [
            CIMProperty("Pbf", value=False),
            CIMProperty("Pbt", value=True),
            CIMProperty("Pdt", DATETIME1_OBJ),
            CIMProperty("Pint64", Uint64(9999)),
            CIMProperty("Psint32", Sint32(-2147483648)),
            CIMProperty("Pstr1", u"Test String"),
            CIMProperty("Puint32", Uint32(4294967295)),
        ]
    inst = CIMInstance("CIM_Foo", properties)
    return inst

def simple_array_instance2(pvalue=None):
    """
    Build a simple instance to test and return that instance. The properties
    in the instance are sorted by (lower cased) property name.

    For this test all of the array elements have a single value
    """
    if pvalue:
        properties = [CIMProperty("P", pvalue)]
    else:
        properties = [
            CIMProperty("Pbf", is_array=True, value=[False]),
            CIMProperty("Pbt", is_array=True, value=[True]),
            CIMProperty("Pdt", is_array=True, value=[DATETIME1_OBJ]),
            CIMProperty("Pint64", is_array=True, value=[Uint64(9999)]),
            CIMProperty("Psint32", is_array=True, value=[Sint32(-2147483648)]),
            CIMProperty("Pstr1", is_array=True, value=[u"Test String"]),
            CIMProperty("Puint32", is_array=True, value=[Uint32(4294967295)]),
        ]
    inst = CIMInstance("CIM_Foo", properties)
    return inst

def simple_array_instance21(pvalue=None):
    """
    Build a simple instance to test and return that instance. The properties
    in the instance are sorted by (lower cased) property name.

    For this test all of the array elements have a two values
    """
    if pvalue:
        properties = [CIMProperty("P", pvalue)]
    else:
        properties = [
            CIMProperty("Pbf", is_array=True, value=[False, False]),
            CIMProperty("Pbt", is_array=True, value=[True, True]),
            CIMProperty("Pdt", is_array=True, value=[DATETIME1_OBJ,
                                                     DATETIME1_OBJ]),
            CIMProperty("Pint64", is_array=True, value=[Uint64(9999),
                                                        Uint64(9999)]),
            CIMProperty("Psint32", is_array=True, value=[Sint32(-2147483648),
                                                         Sint32(-2147483648)]),
            CIMProperty("Pstr1", is_array=True, value=[u"Test String",
                                                       u"Test String"]),
            CIMProperty("Puint32", is_array=True, value=[Uint32(4294967295),
                                                         Uint32(4294967295)]),
        ]
    inst = CIMInstance("CIM_Foo", properties)
    return inst

def string_instance(tst_str):
    """
    Build a CIM instance with a single property.
    """
    properties = [CIMProperty("Pstr1", tst_str)]
    inst = CIMInstance("CIM_Foo", properties)
    return inst

# Testcases for _format_instances_as_rows()

    # Each list item is a testcase tuple with these items:
    # * desc: Short testcase description.
    # * kwargs: Keyword arguments for the test function:
    #   * args: Positional args for _format_instances_as_rows().
    #   * kwargs: Keyword args for _format_instances_as_rows().
    #   * exp_rtn: Expected return value of _format_instances_as_rows().
    # * exp_exc_types: Expected exception type(s), or None.
    # * exp_rtn: Expected warning type(s), or None.
    # * condition: Boolean condition for testcase to run, or 'pdb' for debugger

TESTCASES_FORMAT_INSTANCES_AS_ROWS = [
    (
        "Verify simple instance to table",
        dict(
            args=([simple_instance()], None),
            kwargs={},
            exp_rtn=[
                ["false", "true", DATETIME1_STR, "99", "9999",
                 u'"Test String"']],
        ),
        None, None, OK),

    (
        "Verify simple instance to table with quote_strings=False",
        dict(
            args=(),
            kwargs=dict(
                insts=[simple_instance()],
                max_cell_width=DEFAULT_MAX_CELL_WIDTH,
                quote_strings=False),
            exp_rtn=[
                ["false", "true", DATETIME1_STR, "99", "9999",
                 u'Test String']],
        ),
        None, None, OK),

    (
        "Verify simple instance str array to table with quote_strings=False",
        dict(
            args=(),
            kwargs=dict(
                insts=[simple_instance(pvalue=["abc", 'def'])],
                max_cell_width=DEFAULT_MAX_CELL_WIDTH,
                quote_strings=False),
            exp_rtn=[
                ['"abc", "def"']],
        ),
        None, None, OK),
    (

        "Verify simple instance int array with quote_strings=True",
        dict(
            args=(),
            kwargs=dict(
                insts=[array_instance(pvalue=[Uint32(12345), Uint32(67891)],
                                      ptype='uint32')],
                max_cell_width=DEFAULT_MAX_CELL_WIDTH,
                quote_strings=True),
            exp_rtn=[
                ['12345, 67891']],
        ),
        None, None, OK),

    (
        "Verify simple instance int array with col limit,quote_strings=True",
        dict(
            args=(),
            kwargs=dict(
                insts=[array_instance(pvalue=[Uint32(12345), Uint32(67891)],
                                      ptype='uint32')],
                max_cell_width=6,
                quote_strings=True),
            exp_rtn=[
                ['12345,\n67891']],
        ),
        None, None, OK),

    (
        "Verify simple instance int array with quote_strings=False",
        dict(
            args=(),
            kwargs=dict(
                insts=[array_instance(pvalue=[Uint32(12345), Uint32(67891)],
                                      ptype='uint32')],
                max_cell_width=DEFAULT_MAX_CELL_WIDTH,
                quote_strings=False),
            exp_rtn=[
                ['12345, 67891']],
        ),
        None, None, OK),

    (
        "Verify simple instance int array with col limit,quote_strings=False",
        dict(
            args=(),
            kwargs=dict(
                insts=[array_instance(pvalue=[Uint32(12345), Uint32(67891)],
                                      ptype='uint32')],
                max_cell_width=6,
                quote_strings=False),
            exp_rtn=[
                ['12345,\n67891']],
        ),
        None, None, OK),

    (
        "Verify simple instance to table with col limit",
        dict(
            args=([simple_instance()], 30),
            kwargs={},
            exp_rtn=[
                ["false", "true", DATETIME1_STR, "99", "9999",
                 u'"Test String"']],
        ),
        None, None, OK),

    (
        "Verify simple instance to table, unsorted",
        dict(
            args=([simple_instance_unsorted()],
                  DEFAULT_MAX_CELL_WIDTH,),
            kwargs={},
            exp_rtn=[
                ["false", "true", DATETIME1_STR, "99", "9999",
                 u'"Test String"']],
        ),
        None, None, OK),

    (
        "Verify instance with 2 keys and 2 non-keys, unsorted",
        dict(
            args=(),
            kwargs=dict(
                insts=[
                    CIMInstance(
                        "CIM_Foo",
                        properties=[
                            CIMProperty("P2", value="V2"),
                            CIMProperty("p1", value="V1"),
                            CIMProperty("Q2", value="K2"),
                            CIMProperty("q1", value="K1"),
                        ],
                        path=CIMInstanceName(
                            "CIM_Foo",
                            keybindings=[
                                CIMProperty("Q2", value="K2"),
                                CIMProperty("q1", value="K1"),
                            ]
                        ),
                    ),
                ],
                max_cell_width=DEFAULT_MAX_CELL_WIDTH,
            ),
            exp_rtn=[
                ['"K1"', '"K2"', '"V1"', '"V2"'],
            ],
        ),
        None, None, OK),

    (
        "Verify 2 instances with different sets of properties",
        dict(
            args=(),
            kwargs=dict(
                insts=[
                    CIMInstance(
                        "CIM_Foo",
                        properties=[
                            CIMProperty("P2", value="VP2a"),
                            CIMProperty("p1", value="VP1a"),
                            CIMProperty("P3", value="VP3a"),
                        ],
                    ),
                    CIMInstance(
                        "CIM_FooSub",
                        properties=[
                            CIMProperty("P2", value="VP2b"),
                            CIMProperty("p1", value="VP1b"),
                            CIMProperty("N1", value="VN1b"),
                        ],
                    ),
                ],
                max_cell_width=DEFAULT_MAX_CELL_WIDTH,
            ),
            exp_rtn=[
                ['', '"VP1a"', '"VP2a"', '"VP3a"'],
                ['"VN1b"', '"VP1b"', '"VP2b"', ''],
            ],
        ),
        None, None, OK),

    (
        "Verify 2 instances where second one has path",
        dict(
            args=(),
            kwargs=dict(
                insts=[
                    CIMInstance(
                        "CIM_Foo",
                        properties=[
                            CIMProperty("P2", value="VP2a"),
                            CIMProperty("p1", value="VP1a"),
                        ],
                    ),
                    CIMInstance(
                        "CIM_FooSub",
                        properties=[
                            CIMProperty("P2", value="VP2b"),
                            CIMProperty("p1", value="VP1b"),
                            CIMProperty("Q2", value="K2b"),
                            CIMProperty("q1", value="K1b"),
                        ],
                        path=CIMInstanceName(
                            "CIM_Foo",
                            keybindings=[
                                CIMProperty("q2", value="K2b"),
                                CIMProperty("Q1", value="K1b"),
                            ]
                        ),
                    ),
                ],
                max_cell_width=DEFAULT_MAX_CELL_WIDTH,
            ),
            exp_rtn=[
                ['', '', '"VP1a"', '"VP2a"'],
                ['"K1b"', '"K2b"', '"VP1b"', '"VP2b"'],
            ],
        ),
        None, None, OK),

    (
        "Verify simple instance with one string all components overflow line1",
        dict(
            args=([simple_instance(pvalue="A B C D")],
                  4),
            kwargs={},
            exp_rtn=[
                ['"A "\n"B "\n"C "\n"D"']],
        ),
        None, None, OK),

    (
        "Verify simple instance with one string all components overflow line2",
        dict(
            args=([simple_instance(pvalue="ABCD")],
                  4),
            kwargs={},
            exp_rtn=[
                ['"AB"\n"CD"']],
        ),
        None, None, OK),

    (
        "Verify simple instance with one string overflows line",
        dict(
            args=([simple_instance(pvalue="A B C D")],
                  8),
            kwargs={},
            exp_rtn=[
                ['"A B C "\n"D"']],
        ),
        None, None, OK),

    (
        "Verify simple instance withone unit32 max val",
        dict(
            args=([simple_instance(pvalue=Uint32(4294967295))],
                  8),
            kwargs={},
            exp_rtn=[
                ['4294967295']],
        ),
        None, None, OK),

    (
        "Verify simple instance with one string fits on line",
        dict(
            args=([simple_instance(pvalue="A B C D")],
                  12),
            kwargs={},
            exp_rtn=[
                ['"A B C D"']],
        ),
        None, None, OK),

    (
        "Verify datetime property, folded",
        dict(
            args=([simple_instance(pvalue=DATETIME1_OBJ)],
                  20),
            kwargs={},
            exp_rtn=[
                ['"20140922104920.524"\n"789+000"']],
        ),
        None, None, OK),

    (
        "Verify datetime property not folded",
        dict(
            args=([simple_instance(pvalue=DATETIME1_OBJ)],
                  30),
            kwargs={},
            exp_rtn=[
                ['"20140922104920.524789+000"']],
        ),
        None, None, OK),

    (
        "Verify integer property where len too small",
        dict(
            args=([simple_instance(pvalue=Uint32(999999))],
                  4),
            kwargs={},
            exp_rtn=[['999999']],
        ),
        None, None, OK),

    (
        "Verify char16 property",
        dict(
            args=([CIMInstance('P', [CIMProperty('P',
                                                 type='char16',
                                                 value='f')])],
                  4),
            kwargs={},
            exp_rtn=[[u"'f'"]],
        ),
        None, None, OK),

    (
        "Verify properties with no value",
        dict(
            args=([CIMInstance('P', [CIMProperty('P', value=None,
                                                 type='char16'),
                                     CIMProperty('Q', value=None,
                                                 type='uint32'),
                                     CIMProperty('R', value=None,
                                                 type='string'), ])],
                  4),
            kwargs={},
            exp_rtn=[[u'', u'', u'']],
        ),
        None, None, OK),

    (
        "Verify format of instance with reference property as row entry",
        dict(
            args=([CIMInstance("TST_REFPROP",
                               [CIMProperty(
                                   'P',
                                   type='reference',
                                   reference_class="blah",
                                   value=CIMInstanceName(
                                       "REF_CLN",
                                       keybindings=OrderedDict(k1='v1')))])],
                  30),
            kwargs={},
            exp_rtn=[
                [u'"/:REF_CLN.k1=\\"v1\\""']],
        ),
        None, None, OK),
]

@pytest.mark.parametrize(
    "desc, kwargs, exp_exc_types, exp_warn_types, condition",
    TESTCASES_FORMAT_INSTANCES_AS_ROWS)
@simplified_test_function
def test_format_instances_as_rows(testcase, args, kwargs, exp_rtn):
    """
    Test the output of the common _format_instances_as_rows() function
    """

    # The code to be tested
    act_rtn = _format_instances_as_rows(*args, **kwargs)

    # Ensure that exceptions raised in the remainder of this function
    # are not mistaken as expected exceptions
    assert testcase.exp_exc_types is None
    # result is list of lists.  we want to test each item in inner list

    assert len(act_rtn) == len(exp_rtn), \
        "Unexpected number of lines in test desc: {}:\n" \
        "Expected line cnt={}:\n" \
        "{}\n\n" \
        "Actual line cnt={}:\n" \
        "{}\n". \
        format(testcase.desc, len(act_rtn), '\n'.join(act_rtn),
               len(exp_rtn), '\n'.join(exp_rtn))

    assert exp_rtn == act_rtn, \
        "Unequal values for test desc: {}:\n" \
        "Expected = {}:\n" \
        "Actual   = {}:\n". \
        format(testcase.desc, exp_rtn, act_rtn)

# Testcases for _display_instances_as_table()

    # Each list item is a testcase tuple with these items:
    # * desc: Short testcase description.
    # * kwargs: Keyword arguments for the test function:
    #   * args: Positional args for _display_instances_as_table().
    #   * kwargs: Keyword args for _display_instances_as_table().
    #   * exp_stdout: Expected output on stdout.
    # * exp_exc_types: Expected exception type(s), or None.
    # * exp_warn_types: Expected warning type(s), or None.
    # * condition: Boolean condition for testcase to run, or 'pdb' for debugger

TESTCASES_DISPLAY_INSTANCES_AS_TABLE = [
    (
        "Verify print of simple instance to table",
        dict(
            args=([simple_instance()], None, 'simple'),
            kwargs={},
            exp_stdout="""\
Instances: CIM_Foo
Pbf    Pbt    Pdt                     Pint32    Pint64  Pstr1
-----  -----  --------------------  --------  --------  -------------
false  true   "20140922104920.524"        99      9999  "Test String"
              "789+000"
""",

        ),
        None, None, not CLICK_ISSUE_1590
    ),
    (
        "Verify print of simple instance to table with col limit",
        dict(
            args=([simple_instance2()], 80, 'simple'),
            kwargs={},
            exp_stdout="""\
Instances: CIM_Foo
Pbf    Pbt    Pdt            Pint64      Psint32  Pstr1        Puint32
-----  -----  -----------  --------  -----------  --------  ----------
false  true   "201409221"      9999  -2147483648  "Test "   4294967295
              "04920.524"                         "String"
              "789+000"
""",
        ),
        None, None, not CLICK_ISSUE_1590
    ),

    (
        "Verify print of simple array instance to table with col limit",
        dict(
            args=([simple_array_instance2()], 80, 'simple'),
            kwargs={'ctx_options': None},
            exp_stdout="""\
Instances: CIM_Foo
Pbf    Pbt    Pdt            Pint64      Psint32  Pstr1        Puint32
-----  -----  -----------  --------  -----------  --------  ----------
false  true   "201409221"      9999  -2147483648  "Test "   4294967295
              "04920.524"                         "String"
              "789+000"
""",
        ),
        None, None, not CLICK_ISSUE_1590
    ),

    (
        "Verify print of simple array instance21 to table with col limit",
        dict(
            args=([simple_array_instance21()], 220, 'simple'),
            kwargs={'ctx_options': None},
            exp_stdout="""\
Instances: CIM_Foo
Pbf           Pbt         Pdt                                                       Pint64      Psint32                   Pstr1                         Puint32
------------  ----------  --------------------------------------------------------  ----------  ------------------------  ----------------------------  ----------------------
false, false  true, true  "20140922104920.524789+000", "20140922104920.524789+000"  9999, 9999  -2147483648, -2147483648  "Test String", "Test String"  4294967295, 4294967295
""",   # noqa: E501
        ),
        None, None, not CLICK_ISSUE_1590
    ),

    # The following test fails apparently in an issue in the capsys so marked
    # fail until we sort out issu es when a second instance is added. Did same
    # ctest above with very largeell size and another with single instance
    # and that works.  TODO
    (
        "Verify print of simple array instance21 to table with col limit",
        dict(
            args=([simple_array_instance21()], 80, 'simple'),
            kwargs={'ctx_options': None},
            exp_stdout="""\
Instances: CIM_Foo
Pbf    Pbt    Pdt          Pint64      Psint32  Pstr1        Puint32
-----  -----  ---------  --------  -----------  --------  ----------
false  true   "2014092"      9999  -2147483648  "Test "   4294967295
              "2104920"                         "String"
              ".524789"
              "+000"
false  true   "2014092"      9999  -2147483648  "Test "   4294967295
              "2104920"                         "String"
              ".524789"
              "+000"
""",
        ),
        None, None, FAIL  # WAS not CLICK_ISSUE_1590
    ),

    (
        "Verify print of instance with reference property",
        dict(
            args=([CIMInstance("CIM_Foo",
                               [CIMProperty(
                                   'P',
                                   type='reference',
                                   reference_class="blah",
                                   value=CIMInstanceName(
                                       "REF_CLN",
                                       keybindings=OrderedDict(k1='v1',
                                                               k2=32)))])],
                  80, 'simple'),
            kwargs={'ctx_options': None},
            exp_stdout="""\
Instances: CIM_Foo
P
---------------------------
"/:REF_CLN.k1=\\"v1\\",k2=32"
""",
        ),
        None, None, not CLICK_ISSUE_1590 and PYWBEM_1_0_0B1
    ),
]

# NOTE: The following test cannot use simplified test function because it uses
# pytest capsys to capture date.

@pytest.mark.parametrize(
    "desc, kwargs, exp_exc_types, exp_warn_types, condition",
    TESTCASES_DISPLAY_INSTANCES_AS_TABLE)
def test_display_instances_as_table(
        desc, kwargs, exp_exc_types, exp_warn_types, condition, capsys):
    """
    Test the output of the print_insts_as_table function. This primarily
    tests for overall format and the ability of the function to output to
    stdout. The previous test tests the row formatting and handling of
    multiple instances.
    """
    if not condition:
        pytest.skip("Testcase condition not satisfied")

    # This logic only supports successful testcases without warnings
    assert exp_exc_types is None
    assert exp_warn_types is None

    args = kwargs['args']
    kwargs_ = kwargs['kwargs']
    exp_stdout = kwargs['exp_stdout']
    # The code to be tested
    _display_instances_as_table(*args, **kwargs_)

    stdout, _ = capsys.readouterr()

    assert exp_stdout == stdout, \
        "Unexpected output in test case: {}\n" \
        "Actual:\n" \
        "{}\n" \
        "Expected:\n" \
        "{}\n" \
        "End\n".format(desc, stdout, exp_stdout)


text:
@interface YQCalendarWeekLabel : UIView

@end


text:
<?php

namespace GotChosen\SiteBundle\Command;

use Doctrine\Bundle\DoctrineBundle\Registry;
use GotChosen\SiteBundle\Entity\User;
use GotChosen\SiteBundle\Repository\UserRepository;
use JMS\I18nRoutingBundle\Router\I18nRouter;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Routing\RequestContext;

class ResendRegConfirmCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('gotchosen:resend:regconfirm')
            ->addOption('send')
            ->setDescription('Resend registration confirmation notices.');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // set translator locale, otherwise all of our translations are ignored.
        $this->getContainer()->get('translator')->setLocale('en');

        /** @var Registry $doctrine */
        $doctrine = $this->getContainer()->get('doctrine');
        $em = $doctrine->getManager();

        $mailer = $this->getContainer()->get('gotchosen.mail.no_spool_mailer');

        $doSend = $input->getOption('send');

        $conn = $em->getConnection();

        $stmt = $conn->prepare(
            "SELECT username, email, confirmation_token FROM User
             WHERE enabled = 0 AND createdDate > ?
             AND status = 'unconfirmed'
             AND confirmation_token IS NOT NULL
             AND confirmation_token <> ''"
        );
        $stmt->bindValue(1, "2013-10-03 00:00:00");
        $stmt->execute();

        $count = 0;
        while ( $user = $stmt->fetch() ) {
            $count++;
            $output->writeln($user['username']);
            if ( $doSend ) {
                $this->sendConfirmation($mailer, $user);
                $output->writeln(' - sent');
            }
        }
        $output->writeln("{$count} users found");
    }

    protected function sendConfirmation($mailer, $user)
    {
        /** @var I18NRouter $router */
        $router = $this->getContainer()->get('router');
        $templating = $this->getContainer()->get('templating');

        $router->setContext(new RequestContext('', 'GET', 'www.gotchosen.com', 'https'));

        $params = ['token' => $user['confirmation_token']];
        $url = $router->generate('fos_user_registration_confirm', $params, true);
        $rendered = $templating->render('FOSUserBundle:Registration:email.txt.twig', array(
            'user' => $user,
            'confirmationUrl' =>  $url
        ));

        // Render the email, use the first line as the subject, and the rest as the body
        $renderedLines = explode("\n", trim($rendered));
        $subject = $renderedLines[0];
        $body = implode("\n", array_slice($renderedLines, 1));

        $message = \Swift_Message::newInstance()
            ->setSubject($subject)
            ->setFrom('noreply@gotchosen.com', 'GotChosen')
            ->setTo($user['email'])
            ->setBody($body);

        // We're going to bulk send these over Mailgun instead of Mandrill
        $headers = $message->getHeaders();
        $headers->addTextHeader('X-Gc-Type', 'mass');

        $mailer->send($message);
    }
}


text:
namespace spv {

void SpvBuildLogger::tbdFunctionality(const std::string& f)
{
    if (std::find(std::begin(tbdFeatures), std::end(tbdFeatures), f) == std::end(tbdFeatures))
        tbdFeatures.push_back(f);
}

void SpvBuildLogger::missingFunctionality(const std::string& f)
{
    if (std::find(std::begin(missingFeatures), std::end(missingFeatures), f) == std::end(missingFeatures))
        missingFeatures.push_back(f);
}

std::string SpvBuildLogger::getAllMessages() const {
    std::ostringstream messages;
    for (auto it = tbdFeatures.cbegin(); it != tbdFeatures.cend(); ++it)
        messages << "TBD functionality: " << *it << "\n";
    for (auto it = missingFeatures.cbegin(); it != missingFeatures.cend(); ++it)
        messages << "Missing functionality: " << *it << "\n";
    for (auto it = warnings.cbegin(); it != warnings.cend(); ++it)
        messages << "warning: " << *it << "\n";
    for (auto it = errors.cbegin(); it != errors.cend(); ++it)
        messages << "error: " << *it << "\n";
    return messages.str();
}

} // end spv namespace


text:
require File.expand_path('../../common', __FILE__)

describe 'Action' do
  before do
    @storage = stub('Storage')
    @downloader = stub('Downloader', :storage => @storage)
    @gzipped_hello = "\u001F\x8B\b\u0000^\u007F\x90N\u0000\u0003\xF3H\xCD\xC9\xC9\a\u0000\x82\x89\xD1\xF7\u0005\u0000\u0000\u0000"
  end

  should 'accept valid constructor parameters' do
    action = GetThemAll::Action.new(@downloader, :destination_folder => '/tmp')
    action.destination_folder.should == '/tmp'
  end

  should 'raise an error on unknown constructor parameter' do
    proc{
      GetThemAll::Action.new(@downloader, :unknown => 42)
    }.should.raise(RuntimeError)
  end

  describe 'with an exsiting action' do
    before do
      @action = GetThemAll::Action.new(@downloader, :destination_folder => '/tmp')
    end

    # it "can decompress gzipped data" do
    #   str = @action.gunzip( @gzipped_hello )
    #   str.should == "Hello"
    # end

    # it "can read uncompressed request content" do
    #   request = stub('Request',
    #       :headers => {'content-encoding' => ['text/html']},
    #       :content => "Some data"
    #     )
    #
    #   @action.get_content(request).should == "Some data"
    # end

    # it "can read compressed request content" do
    #   request = stub('Request',
    #       :headers => {'content-encoding' => ['gzip']},
    #       :content => @gzipped_hello
    #     )
    #
    #   @action.get_content(request).should == "Hello"
    # end

  end

end


text:
<?php

namespace Kdyby\Events;

/**
 * @author Filip Procházka <filip@prochazka.su>
 */
class EventArgsList extends EventArgs
{

	/**
	 * @var array
	 */
	private $args;

	/**
	 * @param array $args
	 */
	public function __construct(array $args)
	{
		$this->args = $args;
	}

	/**
	 * @return array
	 */
	public function getArgs()
	{
		return $this->args;
	}

}


text:
using System;

namespace SharperArchitecture.Common.Expressions
{
    public class SubExpressionInfo
    {
        public string Path { get; set; }

        public Type MemberType { get; set; }

        public string MemberName { get; set; }

        public System.Linq.Expressions.Expression Expression { get; set; }
    }
}


text:
package org.elasticsearch.search.aggregations.bucket.significant.heuristics;

import org.elasticsearch.common.xcontent.ToXContent;

public interface SignificanceHeuristicBuilder extends ToXContent {
}


text:
UpdatePasswordInfoBar::UpdatePasswordInfoBar(
    std::unique_ptr<UpdatePasswordInfoBarDelegate> delegate)
    : ConfirmInfoBar(std::move(delegate)) {}

UpdatePasswordInfoBar::~UpdatePasswordInfoBar() {}

bool UpdatePasswordInfoBar::Register(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

int UpdatePasswordInfoBar::GetIdOfSelectedUsername() const {
  return Java_UpdatePasswordInfoBar_getSelectedUsername(
      base::android::AttachCurrentThread(), java_infobar_.obj());
}

base::android::ScopedJavaLocalRef<jobject>
UpdatePasswordInfoBar::CreateRenderInfoBar(JNIEnv* env) {
  using base::android::ConvertUTF16ToJavaString;
  using base::android::ScopedJavaLocalRef;
  UpdatePasswordInfoBarDelegate* update_password_delegate =
      static_cast<UpdatePasswordInfoBarDelegate*>(delegate());
  ScopedJavaLocalRef<jstring> ok_button_text = ConvertUTF16ToJavaString(
      env, GetTextFor(ConfirmInfoBarDelegate::BUTTON_OK));
  ScopedJavaLocalRef<jstring> cancel_button_text = ConvertUTF16ToJavaString(
      env, GetTextFor(ConfirmInfoBarDelegate::BUTTON_CANCEL));
  ScopedJavaLocalRef<jstring> branding_text =
      ConvertUTF16ToJavaString(env, update_password_delegate->GetBranding());

  std::vector<base::string16> usernames;
  if (update_password_delegate->ShowMultipleAccounts()) {
    for (auto password_form : update_password_delegate->GetCurrentForms())
      usernames.push_back(password_form->username_value);
  } else {
    usernames.push_back(
        update_password_delegate->get_username_for_single_account());
  }

  base::android::ScopedJavaLocalRef<jobject> infobar;
  infobar.Reset(Java_UpdatePasswordInfoBar_show(
      env, reinterpret_cast<intptr_t>(this), GetEnumeratedIconId(),
      base::android::ToJavaArrayOfStrings(env, usernames).obj(),
      ok_button_text.obj(), cancel_button_text.obj(), branding_text.obj(),
      update_password_delegate->ShowMultipleAccounts(),
      update_password_delegate->is_smartlock_branding_enabled()));

  java_infobar_.Reset(env, infobar.obj());
  return infobar;
}

void UpdatePasswordInfoBar::OnLinkClicked(JNIEnv* env,
                                          const JavaParamRef<jobject>& obj) {
  GetDelegate()->LinkClicked(NEW_FOREGROUND_TAB);
}


text:
module Namespaced
  class Model
    include Mongoid::Document
    include Mongoid::Timestamps::Short
    #include ActiveModel::ForbiddenAttributesProtection

    field :name

    include Mongoid::Elasticsearch
    elasticsearch! index_options: {
      'namespaced/model' => {
        mappings: {
          properties: {
            name: {
              type: 'string'
            }
          }
        }
      }
    }
  end
end


text:
<?php include "templates/include/header.php" ?>

Category_3 Archive

    <?php foreach ( $results['articles'] as $article ) { ?>

<a href=".?action=viewArticle&articleId=<?php echo $article->id?>"> <?php echo htmlspecialchars( $article->title )?>

                    <?php echo htmlspecialchars( $article->summary )?>

                   <?php echo date('j F Y', $article->publicationDate)?> | <?php echo ( $article->category )?>

    <?php } ?>

<?php echo $results['totalRows']?> article<?php echo ( $results['totalRows'] != 1 ) ? 's' : '' ?> in total.

Return to Homepage

<?php include "templates/include/footer.php" ?>


text:
using Concordion.Integration;

namespace Concordion.Spec.Concordion.Extension.Resource
{
    [ConcordionTest]
    public class ResourceExtensionTest : AbstractExtensionTestCase
    {
        public void addResourceExtension()
        {
            Extension = new ResourceExtension();
        }

        public void addDynamicResourceExtension()
        {
            Extension = new DynamicResourceExtension();
        }

        protected override void ConfigureTestRig()
        {
            TestRig.WithResource(new Api.Resource(ResourceExtension.SourcePath), "0101");
        }

        public int getMeaningOfLife()
        {
            return 42;
        }
    }
}


text:
package com.davidstemmer.screenplay.util;

import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Created by weefbellington on 10/11/15.
 */
public class CollectionUtils {
    public static  <T, C extends Collection<T>>
    C fromIterator(Iterator iter, C retValue) {
        while (iter.hasNext()) {
            retValue.add((T)iter.next());
        }
        return retValue;
    }

    public static  <T, C extends Collection<T>>
    C difference(C first, C second, C retValue) {
        Set<T> diff = new LinkedHashSet<>(first);
        diff.removeAll(second);
        retValue.addAll(diff);
        return retValue;
    }

    public static <T> ArrayDeque<T> emptyQueue(Class<T> clazz) {
        return new ArrayDeque<>();
    }
}


text:
<?php

namespace PhRest\Bootstrap;

/**
 * Trait TLive
 * @package PhRest\Bootstrap
 */
trait TLive {

    /**
     * @return bool
     */
    public function isLive() {
        return true;
    }

    /**
     * @return bool
     */
    public function isTest() {
        return false;
    }

}


text:
using System.Reactive.Linq;
using System.Threading.Tasks;
using Toggl.Core.Services;
using Toggl.Core.UI.Navigation;
using Toggl.Core.UI.Services;
using Toggl.Shared;
using Toggl.Shared.Extensions;

namespace Toggl.Core.UI.ViewModels.Calendar
{
    [Preserve(AllMembers = true)]
    public sealed class CalendarPermissionDeniedViewModel : ViewModel
    {
        private readonly IPermissionsChecker permissionsChecker;
        private readonly IRxActionFactory rxActionFactory;

        public ViewAction EnableAccess { get; }

        public CalendarPermissionDeniedViewModel(INavigationService navigationService, IPermissionsChecker permissionsChecker, IRxActionFactory rxActionFactory)
            : base(navigationService)
        {
            Ensure.Argument.IsNotNull(permissionsChecker, nameof(permissionsChecker));
            Ensure.Argument.IsNotNull(rxActionFactory, nameof(rxActionFactory));

            this.permissionsChecker = permissionsChecker;

            EnableAccess = rxActionFactory.FromAction(enableAccess);
        }

        public override void ViewAppeared()
        {
            base.ViewAppeared();
            closeIfPermissionIsGranted();
        }

        private void enableAccess()
        {
            View.OpenAppSettings();
        }

        private async Task closeIfPermissionIsGranted()
        {
            var authorized = await permissionsChecker.CalendarPermissionGranted;
            if (authorized)
                Close();
        }
    }
}


text:
package com.github.anba.es6draft.ast;

/**
 * Extension: Object Spread Initializer
 */
public final class SpreadProperty extends PropertyDefinition {
    private final Expression expression;

    public SpreadProperty(long beginPosition, long endPosition, Expression expression) {
        super(beginPosition, endPosition);
        this.expression = expression;
    }

    /**
     * Returns the spread expression node.
     *
     * @return the spread expression
     */
    public Expression getExpression() {
        return expression;
    }

    @Override
    public PropertyName getPropertyName() {
        throw new AssertionError();
    }

    @Override
    public <R, V> R accept(NodeVisitor<R, V> visitor, V value) {
        return visitor.visit(this, value);
    }

    @Override
    public <V> int accept(IntNodeVisitor<V> visitor, V value) {
        return visitor.visit(this, value);
    }

    @Override
    public <V> void accept(VoidNodeVisitor<V> visitor, V value) {
        visitor.visit(this, value);
    }
}


text:
<!DOCTYPE html>

    <title>Basic usage</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" >

    <link href="../../content/shared/styles/examples-offline.css" rel="stylesheet">
    <link href="../../../styles/kendo.dataviz.min.css" rel="stylesheet">

    Back


text:
SRBase
======
[![views](https://sourcegraph.com/api/repos/github.com/emerssso/SRBase/.counters/views.svg)](https://sourcegraph.com/github.com/emerssso/SRBase) [![Build Status](https://travis-ci.org/emerssso/SRBase.svg?branch=master)](https://travis-ci.org/emerssso/SRBase) [![Coverage Status](https://coveralls.io/repos/emerssso/SRBase/badge.svg)](https://coveralls.io/r/emerssso/SRBase)

SR Base is an Android application compatible with Android versions 4.3+.
It may be compatible with older 4.0+ versions as well, but they have not been tested.

This app is intended to help in recording Service Record  (SR) information for multi-day
service jobs, and produce a nicely formatted summary suitable for entry on work reports.
It's designed to have as simple and quick a UI as possible so that things load quickly on-the-go.
This is based on my father's work requirements, but if it works for you as well, great!
Let me know if there is some feature you would like to see, and I'll try to work it in.

If someone wiser in the way of Android development stumbles upon this app and sees some
modifications/improvements/optimizations, let me know! I started this as a learning project
to see how Android development has changed since I first wrote apps for Gingerbread, and
I feel like there's definitely room for improvement.

This app is available for use from Google Play at: <https://play.google.com/store/apps/details?id=com.gmail.emerssso.srbase>.

This app is Copyright Conner Kasten, 2014, and distributed under the Apache Licence, Version 2.0.
That license is available at <http://www.apache.org/licenses/LICENSE-2.0>.


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@android:color/background_light">

  <ListView
      android:id="@+id/ll_options"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
  </ListView>

</RelativeLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout android:id="@+id/alliance_details"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content" />

</RelativeLayout>


text:
import * as tokens from '../core/tokens';
import providersDecoratorFactory from './providers-decorator-factory';

const Provider = providersDecoratorFactory(tokens.providers.provider);

export default Provider;


text:
// Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms.

#region Using Statements
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
#endregion

namespace WaveEngine.AI.PathFinding
{
    /// <summary>
    /// Represents an adjacency Matrix
    /// </summary>
    /// <typeparam name="T">Type of nodes in the adjacency matrixc</typeparam>
    public class AdjacencyMatrix<T>
    {
        #region Variables

        /// <summary>
        /// The adjacencty matrix
        /// </summary>
        private Dictionary<T, List<Adjacency<T>>> adjacenctyMatrix;
        #endregion

        #region Properties

        /// <summary>
        /// Gets the nodes count.
        /// </summary>
        /// <value>
        /// The nodes count.
        /// </value>
        public int NodesCount
        {
            get
            {
                return this.adjacenctyMatrix.Keys.Count;
            }
        }
        #endregion

        #region Initialize

        /// <summary>
        /// Initializes a new instance of the <see cref="AdjacencyMatrix{T}" /> class.
        /// </summary>
        public AdjacencyMatrix()
        {
            this.adjacenctyMatrix = new Dictionary<T, List<Adjacency<T>>>();
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Adds the adjacent.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="adjacent">The adjacent.</param>
        /// <param name="weight">The weight.</param>
        public void AddAdjacent(T node, T adjacent, int weight)
        {
            this.AddNodeIfNeeded(adjacent);

            this.AddNodeIfNeeded(node);

            this.AddAdjacency(node, adjacent, weight);

            this.AddAdjacency(adjacent, node, weight);
        }

        /// <summary>
        /// Removes the node.
        /// </summary>
        /// <param name="node">The node.</param>
        public void RemoveNode(T node)
        {
            this.adjacenctyMatrix.Remove(node);

            foreach (T key in this.adjacenctyMatrix.Keys)
            {
                this.adjacenctyMatrix[key].RemoveAll(c => c.Node.Equals(node));
            }
        }

        /// <summary>
        /// Gets the adjacents.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <returns>Adjacents of the node</returns>
        public List<Adjacency<T>> GetAdjacents(T node)
        {
            if (this.adjacenctyMatrix.ContainsKey(node))
            {
                return this.adjacenctyMatrix[node];
            }
            else
            {
                return new List<Adjacency<T>>();
            }
        }

        /// <summary>
        /// Gets the bigger arist.
        /// </summary>
        /// <returns>The bigger arist</returns>
        public int GetBiggerArist()
        {
            int biggerArist = int.MinValue;
            foreach (var key in this.adjacenctyMatrix.Keys)
            {
                foreach (var adjacent in this.adjacenctyMatrix[key])
                {
                    if (adjacent.Weight > biggerArist)
                    {
                        biggerArist = adjacent.Weight;
                    }
                }
            }

            return biggerArist;
        }
        #endregion

        #region Private Methods

        /// <summary>
        /// Checks the less than zero node.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <exception cref="ArgumentException">When node is less than zero</exception>
        private void CheckLessThanZeroNode(int node)
        {
            if (node < 0)
            {
                throw new ArgumentException(string.Format("Node index {0} can not be less than zero.", node));
            }
        }

        /// <summary>
        /// Adds the node if needed.
        /// </summary>
        /// <param name="node">The node.</param>
        private void AddNodeIfNeeded(T node)
        {
            if (!this.adjacenctyMatrix.ContainsKey(node))
            {
                this.adjacenctyMatrix.Add(node, new List<Adjacency<T>>());
            }
        }

        /// <summary>
        /// Adds the adjacency.
        /// </summary>
        /// <param name="node">The node.</param>
        /// <param name="adjacent">The adjacent.</param>
        /// <param name="weight">The weight.</param>
        private void AddAdjacency(T node, T adjacent, int weight)
        {
            var adjacencies = this.adjacenctyMatrix[node];

            var adjacentToUpdate = adjacencies.Where(a => a.Node.Equals(adjacent)).FirstOrDefault();

            if (adjacentToUpdate != null)
            {
                adjacentToUpdate.Weight = weight;
            }
            else
            {
                this.adjacenctyMatrix[node].Add(new Adjacency<T>() { Node = adjacent, Weight = weight });
            }
        }
        #endregion
    }
}


text:
require 'csv'

class Report
  attr :file
  def initialize(file)
    @file = file
  end

  def to_hash
    @hash = begin
      hash = {}
      CSV.open(file) do |csv|
        csv.each do |row|
          label = row.shift
          hash[label] = row
        end
      end
      hash
    end
  end

  def compare(report)
    us = to_hash
    them = report.to_hash
    common_labels = us.keys & them.keys
    my_labels = us.keys - common_labels
    their_labels = them.keys - common_labels
    results = [['Test', report.file, file, report.file + ' vs ' + file]]
    results += common_labels.map do |label|
      my_time = us[label].first.to_f
      their_time = them[label].first.to_f
      [label, their_time, my_time, their_time / my_time]
    end
    results += my_labels.map do |label|
      my_time = us[label].first.to_f
      [label, nil, my_time, nil]
    end
    results += their_labels.map do |label|
      their_time = them[label].first.to_f
      [label, their_time, nil, nil]
    end
    results
  end
end


text:
/*
Given a collection of candidate numbers (C) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
*/

#include <algorithm>
#include <vector>
#include <stdio.h>

using namespace std;

class Solution
{
public:
    vector<vector<int> > combinationSum2(vector<int>& candidates, int target)
    {
        std::sort(candidates.begin(), candidates.end());
        vector<vector<int> > result;
        vector<int> array;
        solve(candidates, target, 0, 0, array, result);
        return result;
    }

    void solve(vector<int>& candidates, int target, int sum, int index,
               vector<int>& array, vector<vector<int> >& result)
    {
        for (int i = index; i < candidates.size(); ++i)
        {
            if (sum + candidates[i] > target)
            {
                return;
            }
            if (i > index && candidates[i - 1] == candidates[i])
            {
                continue;
            }
            array.push_back(candidates[i]);
            if (sum + candidates[i] == target)
            {
                result.push_back(array);
            }
            solve(candidates, target, sum + candidates[i], i + 1, array, result);
            array.pop_back();
        }
    }
};

int main(int argc, char* argv[])
{
    vector<int> array = {1, 1};
    Solution s;
    vector<vector<int> >&& result = s.combinationSum2(array, 2);
    for (auto v : result)
    {
        for (auto i : v)
        {
            printf("%d ", i);
        }
        printf("\n");
    }
    return 0;
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. K. Small, Man. s. e. fl. 216. 1933

#### Original name
null

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:text="音乐列表"
        android:textSize="20sp"
        android:gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/lv_dialog_musiclist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>