text:
(function(){
  //Loading async.. need promises
  var $src = document.querySelector("script[data-modules]");
  var mods = $src.dataset["modules"].split(",");

  load(mods);

  function load(mods) {
    if (mods.length > 0) {
      var url = mods.shift().trim();

      if(url.indexOf(".json") !== -1){
        load_json(url, mods);
      }else{
        load_js(url);
        load(mods);
      }
    }
  }

  function load_js(url) {
    var script = document.createElement("script");
    script.type ="text/javascript"
    script.src = url;
    $src.parentElement.appendChild(script)
  }

  function load_json(url, mods) {
    var handleJSON = function handleJSON(data){
      if (data) {
        for(var i=0; i < data.length; i++){
          load_js(data[i]);
        }
      }else{
        console.log("Got no data from: " + url);
      }
      //continue processing mods.
      load(mods);
    }

    getJSON(url, handleJSON);
  }

  //From: https://mathiasbynens.be/notes/xhr-responsetype-json
  function getJSON(url, successHandler, errorHandler) {
    var xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        successHandler && successHandler(xhr.response);
      } else {
        errorHandler && errorHandler(status);
      }
    };
    xhr.send();
  };
})();


text:
layout: tagpage
tag: Environmental Health
header: no

---

redpajama_set_name: RedPajamaGithub


text:
#import "NSObject.h"

@class GEOProxyClient, NSLock, NSMutableSet;

@interface GEOProxyClientRegistry : NSObject
{
    NSLock *_lock;
    GEOProxyClient *_currentComposite;
    NSMutableSet *_currentSet;
}

+ (id)sharedRegistry;
- (id)compositeClient;
- (void)removeClient:(id)arg1;
- (void)addClient:(id)arg1;
- (void)_updateComposite;
- (void)dealloc;
- (void)enableRegistry;

@end


text:
$uiViewScrollProvider

service in module ui.router.state

Description

Provider that returns the ui.router.state.$uiViewScroll service function.

Methods

useAnchorScroll()

Reverts back to using the core $anchorScroll service for
scrolling based on the url anchor.


text:
from django.contrib import admin
from permissions.models import ObjectPermission, PrincipalRoleRelation, Role, Permission

class ObjectPermissionAdmin(admin.ModelAdmin):
    list_display = ('pk', 'role', 'permission', 'content')
    list_filter = ('role', 'permission')
    search_fields = ('content_id', 'role__codename')

admin.site.register(ObjectPermission, ObjectPermissionAdmin)

class PermissionAdmin(admin.ModelAdmin):
    list_display = ('codename', 'name', 'types')
    search_fields = ('codename', 'name')

    def types(self, obj):
        return ','.join([x.name for x in obj.content_types.all()])

admin.site.register(Permission, PermissionAdmin)

class RoleAdmin(admin.ModelAdmin):
    list_display = ('codename', 'name', 'perms')
    search_fields = ('codename', 'name')
    filter_horizontal = ('global_permissions',)

    def perms(self, obj):
        return ','.join([x.codename for x in obj.global_permissions.all()])

admin.site.register(Role, RoleAdmin)

class PrincipalRoleRelationAdmin(admin.ModelAdmin):
    # list_display = ('pk', 'role', 'user', 'group', 'content')
    list_display = ('pk', 'role', 'user', 'group', 'content_type', 'content_id')
    list_filter = ('role', 'group')
    search_fields = ('user__username', 'user__first_name', 'user__last_name', 'content_id')
    raw_id_fields = ('role', 'user', 'group')

admin.site.register(PrincipalRoleRelation, PrincipalRoleRelationAdmin)


text:
package com.lucafontanili.designpatterns.behavioral.memento;

public class Memento {

    private final String state;

    public Memento(String state) {
	this.state = state;
    }

    public String getState() {
	return this.state;
    }

    @Override
    public String toString() {
	return new StringBuilder(32).append("[state=").append(getState()).append("]").toString();
    }
}


text:
<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UsersTableSeeder::class);
        $this->call(PropertyTypesTableSeeder::class);
        $this->call(PropertyStateTableSeeder::class);
        $this->call(FeaturesTableSeeder::class);
        $this->call(CurrenciesTableSeeder::class);
    }
}


text:
#include <cassert>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <algorithm>

#include "line_finder.h"
#include "max_set_list.h"

using std::string;
using std::vector;

using std::cerr;
using std::cout;
using std::endl;

SetOfRegions::SetOfRegions(const vector<SphericalPoint> &geodesic_in)
      : geodesic(geodesic_in)
{
}

SetOfRegions SetOfRegions::create_from_crossing_counts(
      const std::vector<unsigned> &crossings, const Point &p1,
      const Point &p2)
{
   vector<SphericalPoint> geodesic;
   assert(p1.has_lon_lat && p2.has_lon_lat);
   geodesic.push_back(SphericalPoint(p1));
   geodesic.push_back(SphericalPoint(p2));
   double lon1 = (p1.lon >= 0 ? p1.lon - 180 : p1.lon + 180);
   double lon2 = (p2.lon >= 0 ? p2.lon - 180 : p2.lon + 180);
   geodesic.push_back(SphericalPoint(lon1, -p1.lat));
   geodesic.push_back(SphericalPoint(lon2, -p2.lat));

   SetOfRegions result(geodesic);
   for (unsigned i = 0; i < crossings.size(); i++)
      if (crossings[i] > 0)
         result.ids.push_back(i);
   return std::move(result);
}

/// For each state, returns the number of times its boundary crosses the vertical line determined by the x-coordinate.
/// If the line touches the state in a corner, this counts as two crossings.
/// @result Vector whose i-th value is the number of crossings with the i-th state.
vector<unsigned> get_horizontal_line_crossing_cnts(
      double y, const std::vector<RegionData> &regs)
{
   vector<unsigned> line;
   for (const RegionData &reg : regs)
   {
      unsigned crosses = 0;
      for (const vector<Point> &bdry : reg.boundaries)
      {
         assert(bdry.size() > 0);
         Point prev = *(bdry.end() - 1);
         for (const Point &cur : bdry)
         {
            if ((prev.y <= y && cur.y >= y) || (prev.y >= y && cur.y <= y))
               crosses++;
            prev = cur;
         }
      }
      line.push_back(crosses);
   }
   assert(line.size() == regs.size());
   cout << "y: " << y << " Regions: ";
   for (unsigned i = 0; i < line.size(); i++)
   {
      if (line[i] > 0)
         cout << regs[i].name << ": " << line[i] << "x  ";
   }
   cout << endl;
   return std::move(line);
}

class PointAngle
{
public:
   static const double kEps;

   PointAngle(const vector<RegionData> &regs, const Point &center_in,
              unsigned reg_id_in, unsigned polygon_id_in, unsigned pt_id_in)
         : center(&center_in), reg_id(reg_id_in), polygon_id(polygon_id_in),
               pt_id(pt_id_in)
   {
      const vector<Point> &polygon = regs[reg_id].boundaries[polygon_id];
      pt = &polygon[pt_id];
      prev = (pt_id != 0 ? &polygon[pt_id - 1] : &polygon[polygon.size() - 1]);
      next = (pt_id != polygon.size() - 1 ? &polygon[pt_id + 1] : &polygon[0]);

      if ((pt->y == center->y && pt->x == center->x)
            || (prev->y == center->y && prev->x == center->x)
            || (next->y == center->y && next->x == center->x))
      {
         polygon_contains_center = true;  // the polygon is always crossed -> the point can be ignored later
         return;
      }

      angle = atan2(pt->y - center->y, pt->x - center->x);
      angle = normalize_angle(angle);  // normalization may be useless here, but is needed in the latter occurrences

      double prev_angle = atan2(prev->y - center->y, prev->x - center->x);
      prev_angle_diff = normalize_angle(prev_angle - angle);

      double next_angle = atan2(next->y - center->y, next->x - center->x);
      next_angle_diff = normalize_angle(next_angle - angle);

      if (prev_angle_diff == M_PI || next_angle_diff == M_PI)
      {
         polygon_contains_center = true;  // the polygon is always crossed -> the point can be ignored later
         return;
      }

      /*cout << reg_id << ", " << polygon_id << ", " << pt_id << " prev_angle_diff: "
       << prev_angle_diff << " next_angle_diff: " << next_angle_diff
       << " this: " << pt->x << ", " << pt->y << " prev: " << prev->x << ", "
       << prev->y << endl;*/

      if (prev_angle_diff >= 0.0 && next_angle_diff > 0)
         event = kEnter;
      else if (prev_angle_diff < 0.0 && next_angle_diff <= 0)
         event = kLeave;
      else
         event = kNoChange;

      fill_alt_angle();
   }

   bool operator<(const PointAngle &other) const
   {
      return (alt_angle < other.alt_angle);
   }

   const Point *center;
   const Point *pt;
   const Point *prev;
   const Point *next;
   unsigned reg_id;
   unsigned polygon_id;
   unsigned pt_id;
   bool polygon_contains_center = false;
   double angle;
   double alt_angle;

   double prev_angle_diff;
   double next_angle_diff;

   enum EventType
   {
      kEnter = 0,
      kLeave,
      kNoChange
   };

   EventType event = kNoChange;

private:
   static double
   normalize_angle(double alpha);

   void
   fill_alt_angle();
};

const double PointAngle::kEps = 0.000000001;

double PointAngle::normalize_angle(double alpha)
{
   while (alpha < -M_PI)
      alpha += 2 * M_PI;
   while (alpha >= M_PI)
      alpha -= 2 * M_PI;
   return alpha;
}

void PointAngle::fill_alt_angle()
{
   alt_angle = angle;
   if (alt_angle < 0)
      alt_angle += M_PI;
   switch (event)
   {
      case kEnter:
         alt_angle -= kEps;
         break;
      case kLeave:
         alt_angle += kEps;
         break;
      case kNoChange:
         break;
   }
}

void find_lines_from_center(MaxSetList *set_list, const Point &center,
                            const vector<RegionData> &regs)
{
   vector<unsigned> cross_cnts = get_horizontal_line_crossing_cnts(center.y,
                                                                   regs);
   vector<unsigned> cross_cnts_orig = cross_cnts;

   vector<PointAngle> event_list;
   vector<bool> always_crossed(regs.size(), false);

   for (unsigned reg_id = 0; reg_id < regs.size(); reg_id++)
   {
      const RegionData &reg = regs[reg_id];
      vector<PointAngle> new_events;
      for (unsigned bdry_id = 0; bdry_id < reg.boundaries.size(); bdry_id++)
      {
         const vector<Point> &bdry = reg.boundaries[bdry_id];
         assert(bdry.size() > 0);
         for (unsigned pt_id = 0; pt_id < bdry.size(); pt_id++)
         {
            PointAngle new_event = PointAngle(regs, center, reg_id, bdry_id,
                                              pt_id);
            if (new_event.polygon_contains_center)
            {
               assert(cross_cnts[reg_id] > 0);
               always_crossed[reg_id] = true;
               break;
            }
            if (new_event.event != PointAngle::kNoChange)
               new_events.push_back(std::move(new_event));
         }
         if (always_crossed[reg_id])
            break;
      }
      if (!always_crossed[reg_id])
         event_list.insert(event_list.end(), new_events.begin(),
                           new_events.end());
   }

   std::sort(event_list.begin(), event_list.end());

   /*  SetOfRegions
    new_reg = SetOfRegions::create_from_crossing_counts (cross_cnts, center, Point::create_gnomonic_from_spherical(center.lon));
    set_list->add_set (std::move (new_reg));*/

   for (const PointAngle &event : event_list)
   {
      int reg_id = event.reg_id;
      /*cout << event.reg_id << ", " << event.polygon_id << ", " << event.pt_id
       << " prev_angle_diff: " << event.prev_angle_diff
       << " next_angle_diff: " << event.next_angle_diff << " this: "
       << event.pt->x << ", " << event.pt->y << " prev: " << event.prev->x
       << ", " << event.prev->y << endl;
       cout << "Event " << std::setprecision (10) << event.angle << " "
       << event.alt_angle << endl;*/
      if (!always_crossed[reg_id])
      {
         if (event.event == PointAngle::kEnter)
         {
            cross_cnts[reg_id] += 2;
            SetOfRegions new_reg = SetOfRegions::create_from_crossing_counts(
                  cross_cnts, center, *event.pt);
            set_list->add_set(std::move(new_reg));
         }
         else if (event.event == PointAngle::kLeave)
         {
            assert(cross_cnts[reg_id] >= 2);
            cross_cnts[reg_id] -= 2;
         }
      }
   }
   assert(cross_cnts.size() == cross_cnts_orig.size());
   for (unsigned i = 0; i < cross_cnts.size(); i++)
      assert(cross_cnts[i] == cross_cnts_orig[i]);
}

void find_lines(MaxSetList *set_list, const vector<RegionData> &regs)
{
   for (const RegionData &reg : regs)
   {
      cout << "Starting " << reg.name << endl;
      for (const vector<Point> &bdry : reg.boundaries)
      {
         assert(bdry.size() > 0);
         for (const Point &center : bdry)
            find_lines_from_center(set_list, center, regs);
      }
   }
}


text:
/**
 @mainpage A strict JSON parser and generator for Objective-C

 JSON (JavaScript Object Notation) is a lightweight data-interchange
 format. This framework provides two apis for parsing and generating
 JSON. One standard object-based and a higher level api consisting of
 categories added to existing Objective-C classes.

 This framework does its best to be as strict as possible, both in what it
 accepts and what it generates. For example, it does not support trailing commas
 in arrays or objects. Nor does it support embedded comments, or
 anything else not in the JSON specification. This is considered a feature.

 Learn more on the http://code.google.com/p/json-framework project site.

 @page page_working_with_scalars Working with scalars

 Strictly speaking correctly formed JSON text must have exactly
 one top-level container. (Either an Array or an Object.) Scalars,
 i.e. nulls, numbers, booleans and strings, are not valid JSON on their own.
 It can be quite convenient to pretend that such fragments are valid
 JSON however, and this framework lets you do so.

 A scalar is also referred to as a "fragment".

*/

//#import <JSON/SBJSON.h>
//#import <JSON/NSObject+SBJSON.h>
//#import <JSON/NSString+SBJSON.h>


text:
class FormatterConfigCopierForm(Form):
	'''FormatterConfigCopier

	'''

	def __init__(self, data = None, items = None, post = None, **args):

		super().__init__(data, items, **args)
		set = self.add('FieldSet', {
			'id' : 'configset',
			'title' : '',
			'css' : ['i-form-row i-margin-large']
		})

		fielder = IN.fielder

		entity_type = args['entity_type']
		entity_bundle = args['entity_bundle']
		view_mode = args['view_mode']

		entity_class = Entity.entity_class(entity_type, entity_bundle)
		view_modes =  entity_class.Entitier.view_modes()

		# remove current from modes
		if view_mode in view_modes:
			view_modes.remove(view_mode)

		set.add('HTMLSelect', {
			'id' : 'view_mode',
			'title' : s('Copy configuration from view mode'),
			'options' : view_modes,
			'required' :  True,
			'validation_rule' : [
				'Not', [['Empty', '']], 'The view mode is required!'
			],
			'value' : post.get('view_mode', None),
			'multiple' : False,
		})

		set.add('TextDiv', {
			'value' : s('Copy to view mode <b>{view_mode}</b>', {'view_mode' : view_mode}),
		})

		set = self.add('FieldSet', {
			'id' : 'actionset',
			'title' : '',
			'css' : ['i-form-row i-margin-large']
		})

		set.add('Submit', {
			'value' : s('Copy configuration'),
			'css' : ['i-button i-button-primary']
		})

@IN.register('FormatterConfigCopierForm', type = 'Former')
class FormatterConfigCopierFormFormer(FormFormer):
	'''FormatterConfigCopierForm Former'''

	def submit_prepare(self, form, post):

		super().submit_prepare(form, post)

		if form.has_errors:
			return

	def submit(self, form, post):
		'''Save the entity and return entity id'''

		if form.has_errors:
			return

		# custom commands
		form.result_commands = []

		args = form.args

		entity_type = args['entity_type']
		entity_bundle = args['entity_bundle']
		view_mode = args['view_mode']
		from_view_mode = form['configset']['view_mode'].value

		fielder = IN.fielder

		if entity_bundle not in fielder.entity_field_config[entity_type]:

			form.result_commands.append({
				'method' : 'notify',
				'args' : [{
					'message' : s('No fields found on this bundle!'),
					'status'  : 'warning',
					'timeout' : 5000,
					'pos'     : 'bottom-left',
				}]
			})

			return

		for field_name in fielder.entity_field_config[entity_type][entity_bundle].keys():
			display_config = fielder.field_display_config(entity_type, entity_bundle, from_view_mode, field_name)

			config = {
				'field_formatter' : display_config.get('field_formatter', ''),
				'field_formatter_config' : display_config.get('field_formatter_config', {}),
			}

			try:
				fielder.set_field_formatter_config(entity_type, entity_bundle, view_mode, field_name, config)
			except Exception as e:
				IN.logger.debug()
				form.has_errors = True
				form.error_message = ' '.join((s('Error while copying configuration!'), str(e)))
				return

		form.result_commands.append({
			'method' : 'closeAjaxModal',
			'args' : [],
		})

		form.result_commands.append({
			'method' : 'notify',
			'args' : [{
				'message' : s('Configuration copied!'),
				'status'  : 'info',
				'timeout' : 5000,
				'pos'     : 'bottom-left',
			}]
		})


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/dialogflow/v2/intent.proto

namespace Google\Cloud\Dialogflow\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * The request message for [Intents.GetIntent][google.cloud.dialogflow.v2.Intents.GetIntent].
 *
 * Generated from protobuf message google.cloud.dialogflow.v2.GetIntentRequest
 */
class GetIntentRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The name of the intent.
     * Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
     *
     * Generated from protobuf field string name = 1;
     */
    private $name = '';
    /**
     * Optional. The language to retrieve training phrases, parameters and rich
     * messages for. If not specified, the agent's default language is used.
     * [More than a dozen
     * languages](https://dialogflow.com/docs/reference/language) are supported.
     * Note: languages must be enabled in the agent, before they can be used.
     *
     * Generated from protobuf field string language_code = 2;
     */
    private $language_code = '';
    /**
     * Optional. The resource view to apply to the returned intent.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.IntentView intent_view = 3;
     */
    private $intent_view = 0;

    public function __construct() {
        \GPBMetadata\Google\Cloud\Dialogflow\V2\Intent::initOnce();
        parent::__construct();
    }

    /**
     * Required. The name of the intent.
     * Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
     *
     * Generated from protobuf field string name = 1;
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. The name of the intent.
     * Format: `projects/<Project ID>/agent/intents/<Intent ID>`.
     *
     * Generated from protobuf field string name = 1;
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

    /**
     * Optional. The language to retrieve training phrases, parameters and rich
     * messages for. If not specified, the agent's default language is used.
     * [More than a dozen
     * languages](https://dialogflow.com/docs/reference/language) are supported.
     * Note: languages must be enabled in the agent, before they can be used.
     *
     * Generated from protobuf field string language_code = 2;
     * @return string
     */
    public function getLanguageCode()
    {
        return $this->language_code;
    }

    /**
     * Optional. The language to retrieve training phrases, parameters and rich
     * messages for. If not specified, the agent's default language is used.
     * [More than a dozen
     * languages](https://dialogflow.com/docs/reference/language) are supported.
     * Note: languages must be enabled in the agent, before they can be used.
     *
     * Generated from protobuf field string language_code = 2;
     * @param string $var
     * @return $this
     */
    public function setLanguageCode($var)
    {
        GPBUtil::checkString($var, True);
        $this->language_code = $var;

        return $this;
    }

    /**
     * Optional. The resource view to apply to the returned intent.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.IntentView intent_view = 3;
     * @return int
     */
    public function getIntentView()
    {
        return $this->intent_view;
    }

    /**
     * Optional. The resource view to apply to the returned intent.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.IntentView intent_view = 3;
     * @param int $var
     * @return $this
     */
    public function setIntentView($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\Dialogflow\V2\IntentView::class);
        $this->intent_view = $var;

        return $this;
    }

}


text:
CREATE VIEW {{ schema_geotrek }}.v_cities AS
SELECT code AS "Code",
       name AS "Name",
       CASE
           WHEN published IS FALSE THEN 'No'
           WHEN published IS TRUE THEN 'Yes'
       END AS "Published",
       geom
FROM public.zoning_city
;

-- Zones

CREATE VIEW {{ schema_geotrek }}.v_districts AS
SELECT id,
       name AS "Name",
       CASE
           WHEN published IS FALSE THEN 'No'
           WHEN published IS TRUE THEN 'Yes'
       END AS "Published",
       geom
FROM public.zoning_district
;


text:
from django.conf import settings
from socialregistration.compat.urls import *
from socialregistration.contrib.tumblr.views import TumblrRedirect, \
    TumblrCallback, TumblrSetup

urlpatterns = patterns('',
    url('^redirect/$', TumblrRedirect.as_view(), name='redirect'),
    url('^callback/$', TumblrCallback.as_view(), name='callback'),
    url('^setup/$', TumblrSetup.as_view(), name='setup'),
)


text:
#include <aws/dynamodb/model/BatchStatementError.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace DynamoDB
{
namespace Model
{

BatchStatementError::BatchStatementError() :
    m_code(BatchStatementErrorCodeEnum::NOT_SET),
    m_codeHasBeenSet(false),
    m_messageHasBeenSet(false)
{
}

BatchStatementError::BatchStatementError(JsonView jsonValue) :
    m_code(BatchStatementErrorCodeEnum::NOT_SET),
    m_codeHasBeenSet(false),
    m_messageHasBeenSet(false)
{
  *this = jsonValue;
}

BatchStatementError& BatchStatementError::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Code"))
  {
    m_code = BatchStatementErrorCodeEnumMapper::GetBatchStatementErrorCodeEnumForName(jsonValue.GetString("Code"));

    m_codeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Message"))
  {
    m_message = jsonValue.GetString("Message");

    m_messageHasBeenSet = true;
  }

  return *this;
}

JsonValue BatchStatementError::Jsonize() const
{
  JsonValue payload;

  if(m_codeHasBeenSet)
  {
   payload.WithString("Code", BatchStatementErrorCodeEnumMapper::GetNameForBatchStatementErrorCodeEnum(m_code));
  }

  if(m_messageHasBeenSet)
  {
   payload.WithString("Message", m_message);

  }

  return payload;
}

} // namespace Model
} // namespace DynamoDB
} // namespace Aws


text:
package com.github.lzenczuk.crawler.node.http.model;

import com.github.lzenczuk.crawler.node.http.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * @author lzenczuk 04/04/2016
 */
public class HttpResponse {

    private final String errorMessage;

    private final org.apache.http.HttpResponse apacheHttpResponse;

    public HttpResponse(org.apache.http.HttpResponse apacheHttpResponse) {
        this.errorMessage = null;
        this.apacheHttpResponse = apacheHttpResponse;
    }

    public HttpResponse(String errorMessage) {
        this.errorMessage = errorMessage;
        this.apacheHttpResponse = null;
    }

    public boolean isError(){
        return errorMessage!=null;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public Integer getStatusCode() {
        return apacheHttpResponse.getStatusLine().getStatusCode();
    }

    public String getProtocolVersion() {
        return apacheHttpResponse.getProtocolVersion().toString();
    }

    public String getReasonPhrase() {
        return apacheHttpResponse.getStatusLine().getReasonPhrase();
    }

    public Optional<InputStream> getEntityStream(){

        if(apacheHttpResponse ==null || apacheHttpResponse.getEntity()==null) return Optional.empty();

        try {
            return Optional.of(apacheHttpResponse.getEntity().getContent());
        } catch (IOException e) {
            return Optional.empty();
        }
    }
}


text:
import 'reflect-metadata';
import { expect } from 'chai'
import * as sinon from 'sinon';
import Dispatcher from '../../../src/service/dispatcher/dispatcher';
import CommandCollection from '../../../src/command/commandCollection';

describe('Dispatcher tests', () => {

    let dispatcher: Dispatcher;
    let sandbox: sinon.SinonSandbox;

    beforeEach(() => {
        dispatcher = new Dispatcher();
        sandbox = sinon.sandbox.create();
    })

    afterEach(() => {
        sandbox.restore();
    });

    describe("Test addCommand method", () => {
        it("Add command should work correctly", () => {
            let command: any = {
                getName: () => {
                    return 'name';
                },
                getAliases: () => {
                    return [
                        'first-alias',
                        'second-alias'
                    ]
                }
            }

            let commandNameSpy = sandbox.spy(command, 'getName');

            let commandAliasesSpy = sandbox.spy(command, 'getAliases');
            let commandsMapSpy = sandbox.spy(CommandCollection.prototype, 'set');

            dispatcher.addCommand(command);

            expect(commandNameSpy.calledOnce).to.be.true;
            expect(commandAliasesSpy.calledOnce).to.be.true;
            expect(commandsMapSpy.callCount).to.equal(3);
            expect(commandsMapSpy.getCall(0).calledWith('name', command)).to.be.true
            expect(commandsMapSpy.getCall(1).calledWith('first-alias', command)).to.be.true
            expect(commandsMapSpy.getCall(2).calledWith('second-alias', command)).to.be.true
        })

        it("Add command should not add aliases when it is not given", () => {
            let command: any = {
                getName: () => {
                    return 'name';
                },
                getAliases: () => {
                    return []
                }
            }
            let commandNameSpy = sandbox.spy(command, 'getName');
            let commandAliasesSpy = sandbox.spy(command, 'getAliases');
            let commandsMapSpy = sandbox.spy(CommandCollection.prototype, 'set');

            dispatcher.addCommand(command);

            expect(commandNameSpy.calledOnce).to.be.true;
            expect(commandsMapSpy.calledOnce).to.be.true;
            expect(commandAliasesSpy.calledOnce).to.be.true;
            expect(commandsMapSpy.firstCall.calledWith('name', command)).to.be.true
        })
    })

    describe("Test dispatch method", () => {
        it("Dispatcher should dispatch command correctly", () => {
            let command: any = {
                execute: () => { }
            }

            let commandParameters: any = {
                user: 'user'
            }

            let commandExecuteSpy = sandbox.spy(command, 'execute');
            let commandsMapStub = sandbox.stub(CommandCollection.prototype, 'get').returns(command);

            dispatcher.dispatch('command-name', commandParameters);

            expect(commandsMapStub.calledOnce).to.be.true;
            expect(commandsMapStub.calledWith('command-name')).to.be.true;
            expect(commandExecuteSpy.calledOnce).to.be.true;
            expect(commandExecuteSpy.calledWith(commandParameters)).to.be.true;
        })

        it("Dispatcher should not dispatch command when command does not exist", () => {
            let commandParameters: any = {
                user: 'user'
            }

            let commandsMapStub = sandbox.stub(CommandCollection.prototype, 'get').returns(undefined);

            dispatcher.dispatch('command-name', commandParameters);

            expect(commandsMapStub.calledOnce).to.be.true;
            expect(commandsMapStub.calledWith('command-name')).to.be.true;
        })
    })
})


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="br.ifcibirama.dell_pc.javaisfun.Metodos2"
    android:background="@android:color/white"
    >
    <ImageButton
        android:id="@+id/imageButton20"
        android:layout_width="42dp"
        android:layout_height="38dp"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:background="@android:color/transparent"
        android:onClick="next"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.976"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:srcCompat="@drawable/proximo"
        tools:layout_editor_absoluteX="326dp"
        tools:layout_editor_absoluteY="513dp" />

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="28dp"
        android:layout_height="31dp"
        android:background="@android:color/transparent"
        app:srcCompat="@drawable/back"
        android:onClick="TextDialog"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintHorizontal_bias="0.023"
        app:layout_constraintVertical_bias="0.015"
        android:contentDescription="@string/menu" />

    <TextView
        android:id="@+id/textView61"
        android:layout_width="328dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif-condensed"
        android:text="Os métodos são partes do código que executam alguma função especifica, também chamadas de funções, eles possuem uma estrutura específica e característica, podem ser utilizados inúmeras vezes no código."
        android:textAlignment="center"
        android:textColor="@color/cinzinha"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.15" />

    <TextView
        android:id="@+id/textView62"
        android:layout_width="272dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif-condensed"
        android:text="Sabendo todos elementos das lições anteriores você pode agora entender a estrutura de um método."
        android:textAlignment="center"
        android:textColor="@color/cinzinha"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.399" />

    <TextView
        android:id="@+id/textView63"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif-condensed"
        android:text="[modificador] tipo_retorno identificador ([argumentos]) {"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.562" />

    <TextView
        android:id="@+id/textView64"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif-condensed"
        android:text="//Corpo do método"
        android:textColor="@android:color/holo_red_dark"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.175"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.631" />

    <TextView
        android:id="@+id/textView65"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif-condensed"
        android:text="}"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.023"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.724" />

    <TextView
        android:id="@+id/textView73"
        android:layout_width="293dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif-condensed"
        android:text="Estes estão situados dentro das Classes e nelas, operam funções padrões ou variadas."
        android:textAlignment="center"
        android:textColor="@color/cinzinha"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.509"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.855" />
</android.support.constraint.ConstraintLayout>


text:
package org.apache.cordova.indicator;

import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.ProgressDialog;
import android.util.Log;
import android.os.CountDownTimer;
import android.content.DialogInterface;
import android.view.WindowManager;

import org.apache.cordova.indicator.AndroidProgressHUD;

public class ProgressIndicator extends CordovaPlugin {

    private ProgressDialog progressIndicator = null;
    private AndroidProgressHUD activityIndicator = null;
    private String text = null;
    private boolean showLock = false;
    private Integer progress = 0;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (this.cordova.getActivity().isFinishing()) {
            return true;
        }
        if (action.equals("show")) {
            String type = args.getString(0); //bar
            String title = args.getString(1);
            String text = args.getString(2);
            Integer pro = args.getInt(3);
            show(type, title, text, pro);
            callbackContext.success();
        } else if (action.equals("hide")) {
            hide();
            callbackContext.success();
        }else if (action.equals("showSimple")){
            boolean dim = args.getBoolean(0);
            this.showSimple(dim);
        }else if (action.equals("showSimpleWithLabel")){
            boolean dim = args.getBoolean(0);
            String text = args.getString(1);
            this.showSimpleWithLabel(dim, text);
        }else if (action.equals("showDeterminateBar")){
            boolean dim = args.getBoolean(0);
            Integer timeout = args.getInt(1);
            this.showBar(dim, timeout);
        }else if (action.equals("showProgressBar")){
            String title = args.getString(0);
            String message = args.getString(1);
            this.showProgressBar(title, message);
        }
        else if (action.equals("showDeterminateBarWithLabel")){
            boolean dim = args.getBoolean(0);
            Integer timeout = args.getInt(1);
            String message = args.getString(2);
            this.showBarWithLabel(dim, timeout, message);
        } else if (action.equals("setProgress")) {
            this.setProgress(args.getDouble(0));
        } else if (action.equals("setTitle")) {
            this.setTitle(args.getString(0));
        } else if (action.equals("setMessage")) {
            this.setMessage(args.getString(0));
        }

        return true;
    }

    /**
     * This show the ProgressDialog
     *
     * @param text - Message to display in the Progress Dialog
     */
    public void show(String type, String title, String text, Integer pro) {

    }

    /**
     * This hide the ProgressDialog
     */
    public void hide() {
        if (progressIndicator != null) {
            progressIndicator.dismiss();
            progressIndicator = null;
        }
        if (activityIndicator != null) {
            activityIndicator.dismiss();
            activityIndicator = null;
        } else {
            this.showLock = false;
        }
    }

    public void showSimple(Boolean dim){
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                if (activityIndicator != null){
                    activityIndicator.dismiss();
                }
                activityIndicator = AndroidProgressHUD.show(
                        ProgressIndicator.this.cordova.getActivity(), null, true, false, null);
            }
        });
    }

    public void showSimpleWithLabel(Boolean dim, String text){
        this.text = text;
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                if (activityIndicator != null){
                    activityIndicator.dismiss();
                }
                activityIndicator = AndroidProgressHUD.show(
                        ProgressIndicator.this.cordova.getActivity(), ProgressIndicator.this.text, true, false, null);
            }
        });
    }

    public void showBar(Boolean dim, Integer timeout){
        progressIndicator = new ProgressDialog(this.cordova.getActivity());
        progressIndicator.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressIndicator.setIndeterminate(false);
        if(dim) {
            WindowManager.LayoutParams lp = progressIndicator.getWindow().getAttributes();
            lp.dimAmount = 0.8f;
            progressIndicator.getWindow().setAttributes(lp);
        }
        progressIndicator.setCancelable(false);
        progressIndicator.show();
        final CountDownTimer mCountDownTimer;
        progress = 0;
        mCountDownTimer=new CountDownTimer(timeout, timeout/100) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.v("Log_tag", "Tick of Progress"+ progress + millisUntilFinished);
                progress++;
                if(progressIndicator != null) {
                    progressIndicator.setProgress(progress);
                }else{
                    this.cancel();
                }
            }
            @Override
            public void onFinish() {
                progress++;
                progressIndicator.setProgress(progress);
                progressIndicator.dismiss();
            }
        };
        mCountDownTimer.start();
    }

    public void showBarWithLabel(Boolean dim, Integer timeout, String message){
        progressIndicator = new ProgressDialog(this.cordova.getActivity());
        progressIndicator.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressIndicator.setIndeterminate(false);
        progressIndicator.setMessage(message);
        progressIndicator.setCancelable(false);
        progressIndicator.show();
        CountDownTimer mCountDownTimer;
        progress = 0;
        mCountDownTimer=new CountDownTimer(timeout, timeout/100) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.v("Log_tag", "Tick of Progress"+ progress + millisUntilFinished);
                progress++;
                if (progressIndicator != null) {
                    progressIndicator.setProgress(progress);
                }else{
                    this.cancel();
                }
            }
            @Override
            public void onFinish() {
                progress++;
                progressIndicator.setProgress(progress);
                progressIndicator.dismiss();
            }
        };
        mCountDownTimer.start();
    }

    public void showProgressBar(final String title, final String message){
        final CordovaInterface cordova = this.cordova;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                progressIndicator = new ProgressDialog(cordova.getActivity());
                progressIndicator.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressIndicator.setIndeterminate(false);
                progressIndicator.setTitle(title);
                progressIndicator.setMessage(message);
                progressIndicator.setCancelable(false);
                progressIndicator.show();
            }
        };
        this.cordova.getActivity().runOnUiThread(runnable);
    }

    /**
     * Set the value of the progress bar when progress style is "HORIZONTAL"
     *
     * @param rawArgs
     */
    private void setProgress(final Double rawArgs) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (progressIndicator != null) {
                    int value = (int) (rawArgs * 100);
                    progressIndicator.setProgress(value);
                }
            };
        };
        this.cordova.getActivity().runOnUiThread(runnable);
    }

    /**
     * Set the title of the progress dialog
     *
     * @param rawArgs
     */
    private void setTitle(final String title) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (progressIndicator != null) {
                    progressIndicator.setTitle(title.replaceAll("^\"|\"$", ""));
                }
            };
        };
        this.cordova.getActivity().runOnUiThread(runnable);
    }

    /**
     * Set the message of the progress dialog
     *
     * @param rawArgs
     */
    private void setMessage(final String message) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (progressIndicator != null) {
                    progressIndicator.setMessage(message.replaceAll("^\"|\"$", ""));
                }
            };
        };
        this.cordova.getActivity().runOnUiThread(runnable);
    }

}


text:
PageRank implementation in Erlang

## Tasks

### Compiling

```sh
rebar3 compile
```

### Generating Documentation

```sh
rebar3 edoc
```


text:
import React, { Component, PropTypes } from 'react'
import ReactDOM, { render } from 'react-dom'
import cx from 'classname'
import autobind from 'autobind-decorator'

export default class RevealPhase extends Component {
  constructor(props) {
    super(props)
    this.state = {
      showAnswer: {},
      revealing: 0
    }

    this.believedLies = props.gameState.lies.filter(l => l.believers.length !== 0)
    this.timeout = 5000
    this.emittedDisplay = false
  }

  componentDidMount() {
    this.moveScreen = () => {
      return setTimeout(() => {
        this.setState({
          revealing: this.state.revealing + 1
        })
        this.moveScreen()
      }, this.timeout)
    }

    this.moveScreen()
  }

  componentWillUnmount() {
    clearTimeout(this.moveScreen)
  }

  render() {
    const { revealing } = this.state
    const { gameState, engine } = this.props
    const {
      lies,
      currentQuestion,
      gameCode,
      players
    } = gameState

    // Showing the final score
    if (!this.emittedDisplay && revealing > this.believedLies.length + 1) {
      this.moveScreen = () => null
      engine.displayActionComplete({ gameCode })
      this.emittedDisplay = true
    }

    // Showing a lie
    if (revealing > this.believedLies.length) {
      return (

Game Code: {gameCode}

          <DisplayScore players={players} lies={lies}/>

(Look at your gamepad screen!)

      )
    }

    // Showing the correct answer
    if (revealing === this.believedLies.length) {
      this.timeout = 5000
    }

    return (

Game Code: {gameCode}

{currentQuestion.question}

{this.showAnswer}

    )
  }

  get showAnswer() {
    const { revealing } = this.state
    const { gameState } = this.props
    const {
      lies,
      currentQuestion,
      gameCode,
      players
    } = gameState

    if (revealing < this.believedLies.length) {
      return this.revealLie(this.believedLies[revealing])
    }
    return this.revealRealAnswer(currentQuestion)
  }

  revealRealAnswer(currentQuestion) {
    let scrubs = currentQuestion.believers.map((player, key) => {
      return (

          { player }

      );
    });

    return (

            Correct Answer:

          { currentQuestion.answer }

{ scrubs }

    );
  }

  revealLie(lie) {
    let scrubs = lie.believers.map((player, key) => {
      return (

          { player }

      );
    });

    return (

          { lie.lie }

            By: { lie.liar }

          { scrubs }

    );
  }

  angle() {
    let randomAngle = Math.floor((Math.random() * 14) - 7);
    return {
      transform: 'rotate('+ randomAngle +'deg)'
    }
  }

  playerId(playerName) {
    let players = this.props.gameState.players;

    for(let i = 0; i < players.length; i++) {
      if(players[i].displayName === playerName) return i + 1
    }
    return 0
  }

  revealTimer() {
    console.log('revealTimer called')
    setTimeout(() => {
      const incReveal = this.state.revealing + 1
      console.log('set timeout triggered')
      this.setState({
        revealing: incReveal
      })
    }, 2000)
  }
}

const DisplayScore = ({ players, lies }) => {
  const sortedPlayers = [...players].sort((a, b) =>
    a.score  {
    for (let i = 0; i < players.length; i++) {
      if (players[i].displayName === playerName) return i + 1
    }
    return 0
  }

  const playerLie = (playerName) => {
    for (let i = 0; i < lies.length; i++) {
      if (lies[i].liar === playerName) return lies[i].lie
    }
    return 0
  }

  const playerList = sortedPlayers.map(player => {
    return (

{playerLie(player.displayName)}

{player.displayName}

{player.score}

    )
  })

  return
{playerList}

}


text:
import os
import sys

from conary import conarycfg
from conary.deps import deps
from conary.lib import log
from conary.lib import options

from rmake import compat, errors
from rmake.compat import cvccmd as cvc
from rmake.cmdline import query

(NO_PARAM,  ONE_PARAM)  = (options.NO_PARAM, options.ONE_PARAM)
(OPT_PARAM, MULT_PARAM) = (options.OPT_PARAM, options.MULT_PARAM)
(NORMAL_HELP, VERBOSE_HELP)  = (options.NORMAL_HELP, options.VERBOSE_HELP)

CG_MISC = 'Miscellaneous Commands'
CG_BUILD = 'Job Manipulation'
CG_INFO = 'Information Display'

# helper function to get list of commands we support
_commands = []
def register(cmd):
    _commands.append(cmd)

class rMakeCommand(options.AbstractCommand):
    defaultGroup = 'Common Options'
    commandGroup = CG_MISC

    docs = {'config'             : (VERBOSE_HELP,
                                    "Set config KEY to VALUE", "'KEY VALUE'"),
            'server-config'      : (VERBOSE_HELP,
                            "Set server config KEY to VALUE", "'KEY VALUE'"),
            'config-file'        : (VERBOSE_HELP,
                                    "Read PATH config file", "PATH"),
            'context'            : (VERBOSE_HELP,
                                    "Set the configuration context to use"),
            'server-config-file' : (VERBOSE_HELP,
                                    "Read PATH config file", "PATH"),
            'conary-config-file'  : (VERBOSE_HELP,
                                    "Read PATH conary config file", "PATH"),
            'build-config-file'  : (VERBOSE_HELP,
                                    "Read PATH config file", "PATH"),
            'rmake-config-file'  : (VERBOSE_HELP,
                                    "Read PATH config file", "PATH"),
            'skip-default-config': (VERBOSE_HELP,
                                    "Don't read default configs"),
            'verbose'            : (VERBOSE_HELP,
                                    "Display more detailed information where available") }

    def addParameters(self, argDef):
        d = {}
        d["context"] = ONE_PARAM
        d["config"] = MULT_PARAM
        d["server-config"] = MULT_PARAM
        d["server-config-file"] = MULT_PARAM
        d["build-config-file"] = MULT_PARAM
        d["conary-config-file"] = MULT_PARAM
        d["skip-default-config"] = NO_PARAM
        d["verbose"] = NO_PARAM
        argDef[self.defaultGroup] = d

    def _getContext(self, buildConfig, conaryConfig, argSet):
        context = conaryConfig.context
        if buildConfig.context:
            context = buildConfig.context
        if os.path.exists('CONARY'):
            conaryState = compat.ConaryVersion().ConaryStateFromFile('CONARY',
                                                           parseSource=False)
            if conaryState.hasContext():
                context = conaryState.getContext()

        context = os.environ.get('CONARY_CONTEXT', context)
        context = argSet.pop('context', context)
        return context

    def _setContext(self, buildConfig, conaryConfig, argSet):
        context = self._getContext(buildConfig, conaryConfig, argSet)
        usedContext = False
        if conaryConfig and context:
            if conaryConfig.hasSection(context):
                usedContext = True
                conaryConfig.setContext(context)

        buildConfig.useConaryConfig(conaryConfig)
        if context and buildConfig.hasSection(context):
            buildConfig.setContext(context)
            usedContext = True
        if not usedContext and context:
            raise errors.RmakeError('No such context "%s"' % context)

    def processConfigOptions(self, (buildConfig, conaryConfig, pluginManager),
                             cfgMap, argSet):
        """
            Manage any config maps we've set up, converting
            assigning them to the config object.
        """
        configFileList = argSet.pop('build-config-file', [])
        if not isinstance(configFileList, list):
            configFileList = list(configFileList)

        configFileList.extend(argSet.pop('config-file', []))

        for path in configFileList:
            buildConfig.read(path, exception=True)

        configFileList = argSet.pop('conary-config-file', [])
        if not isinstance(configFileList, list):
            configFileList = list(configFileList)
        if configFileList and not conaryConfig:
            conaryConfig = conarycfg.ConaryConfiguration(readConfigFiles=False)
        for path in configFileList:
            conaryConfig.read(path, exception=True)
        self._setContext(buildConfig, conaryConfig, argSet)

        for (arg, data) in cfgMap.items():
            cfgName, paramType = data[0:2]
            value = argSet.pop(arg, None)
            if value is not None:
                if arg.startswith('no-'):
                    value = not value

                buildConfig.configLine("%s %s" % (cfgName, value))

        for line in argSet.pop('config', []):
            buildConfig.configLine(line)

        for line in argSet.pop('server-config', []):
            serverConfig.configLine(line)
        if argSet.pop('verbose', False):
            log.setVerbosity(log.DEBUG)

    def requireParameters(self, args, expected=None, allowExtra=False,
                          appendExtra=False, maxExtra=None):
        args = args[1:] # cut off argv[0]
        command = repr(args[0])
        if isinstance(expected, str):
            expected = [expected]
        if expected is None:
            expected = ['command']
        else:
            expected = ['command'] + expected
        if expected:
            missing = expected[len(args):]
            if missing:
                raise errors.BadParameters('%s missing %s command'
                                           ' parameter(s): %s' % (
                                            command, len(missing),
                                            ', '.join(missing)))
        extra = len(args) - len(expected)
        if not allowExtra and not appendExtra:
            maxExtra = 0
        if maxExtra is not None and extra > maxExtra:
            if maxExtra:
                numParams = '%s-%s' % (len(expected)-1,
                                       len(expected) + maxExtra - 1)
            else:
                 numParams = '%s' % (len(expected)-1)
            raise errors.BadParameters('%s takes %s arguments, received %s' % (command, numParams, len(args)-1))

        if appendExtra:
            # final parameter is list
            return args[:len(expected)-1] + [args[len(expected)-1:]]
        elif allowExtra:
            return args[:len(expected)] + [args[len(expected):]]
        else:
            return args

def _getJobIdOrUUIds(val):
    return [ _getJobIdOrUUId(x) for x in val ]

def _getJobIdOrUUId(val):
    try:
        return int(val)
    except (ValueError, TypeError):
        if isinstance(val, str) and len(val) == 32:
            return val
        else:
            raise errors.ParseError, 'Not a valid jobId or UUID: %s' % val

class BuildCommand(rMakeCommand):
    '''Builds the specified packages or recipes.  '''

    commands = ['build']
    commandGroup = CG_BUILD
    paramHelp = '<troveSpec>[{context}] [<troveSpec>][{context}]*'
    help = 'Build packages or recipes'

    docs = {'flavor' : "flavor to build with",
            'host'   : "host to limit build to",
            'label'  : "label to limit build to",
            'match'  : (options.VERBOSE_HELP,
                        "Only build troves that match the given specification"),
            'no-watch'  : "do not show build status",
            'poll'   : (options.VERBOSE_HELP, 'backwards compatibility option'),
            'prep'   : (options.VERBOSE_HELP,
                            'do not build package, only create chroot'),
            'quiet'  : "show less build info - don't tail logs",
            'commit' : "commit job when it is done",
            'message' : "Message to assign to troves upon commit",
            'macro'   : ('set macro NAME to VALUE', "'NAME VALUE'"),
            'no-clean': 'do not remove build directory even if build is'
                        ' successful',
            'to-file': (options.VERBOSE_HELP,
                        'store job in a file instead of sending it'
                        ' to the server.  This makes it possible for others'
                        ' to start the job.'),
            'binary-search': (options.VERBOSE_HELP,
                              'Search for the binary'
                              'version of group and build the latest'
                              'sources on that branch with the same flavor'),
            'reuse':    ('reuse old chroot if possible instead of removing'
                         ' and recreating'),
            'info'    : ('Gather and display all the information necessary to perform the build'),
            'recurse':  ('recurse groups, building all included sources'),
            'ignore-rebuild-deps': ('Do not rebuild packages if the only'
                                    ' change to them is the packages to be'
                                    ' installed in their chroot.'),
            'ignore-external-rebuild-deps': ('Do not rebuild packages unless'
                                             ' their source has changed or'
                                             ' another package in the job will'
                                             ' be installed in this package\'s'
                                             ' chroot')}

    def addParameters(self, argDef):
        self.addBuildParameters(argDef)
        rMakeCommand.addParameters(self, argDef)
        argDef['flavor'] = ONE_PARAM
        argDef['host'] = MULT_PARAM
        argDef['label'] = MULT_PARAM
        argDef['match'] = MULT_PARAM
        argDef['binary-search'] = NO_PARAM
        argDef['recurse'] = NO_PARAM

    def addBuildParameters(self, argDef):
        argDef['commit'] = NO_PARAM
        argDef['prep'] = NO_PARAM
        argDef['macro'] = MULT_PARAM
        argDef['message'] = '-m', ONE_PARAM
        argDef['no-watch'] = NO_PARAM
        argDef['poll'] = NO_PARAM
        argDef['no-clean'] = NO_PARAM
        argDef['to-file'] = ONE_PARAM
        argDef['quiet'] = NO_PARAM
        argDef['info'] = NO_PARAM

    def addConfigOptions(self, cfgMap, argDef):
        cfgMap['reuse'] = 'reuseRoots', NO_PARAM
        rMakeCommand.addConfigOptions(self, cfgMap, argDef)

    def runCommand(self, client, cfg, argSet, args):
        if self.verbose:
            log.setVerbosity(log.DEBUG)
        else:
            log.setVerbosity(log.INFO)
        command, troveSpecs = self.requireParameters(args, 'troveSpec',
                                                     appendExtra=True)
        if command == 'buildgroup':
            log.warning('"buildgroup" is deprecated and will be removed in a future release - use "build --recurse" instead')
        rebuild = (command == 'rebuild')
        flavorSpec = argSet.pop('flavor', None)
        if flavorSpec:
            flavor = deps.parseFlavor(flavorSpec)
            if flavor is None:
                raise errors.ParseError("Invalid flavor: '%s'" % flavorSpec)
            newFlavor = deps.overrideFlavor(client.buildConfig.buildFlavor,
                                            flavor)
            client.buildConfig.buildFlavor = newFlavor
            newFlavors = []
            for oldFlavor in client.buildConfig.flavor:
                newFlavors.append(deps.overrideFlavor(oldFlavor, flavor))
            client.buildConfig.flavor = newFlavors

        matchSpecs = argSet.pop('match', [])
        hosts = argSet.pop('host', [])
        labels = argSet.pop('label', [])
        recurseGroups = argSet.pop('recurse', False) or command == 'buildgroup'

        if recurseGroups:
            if argSet.pop('binary-search', False):
                recurseGroups = client.BUILD_RECURSE_GROUPS_BINARY
            elif not compat.ConaryVersion().supportsFindGroupSources():
                log.warning('Your conary does not support recursing a group'
                            ' source component, defaulting to searching the'
                            ' binary version')
                recurseGroups = client.BUILD_RECURSE_GROUPS_BINARY
            else:
                recurseGroups = client.BUILD_RECURSE_GROUPS_SOURCE

        self._prep(client, argSet)
        job = client.createBuildJob(troveSpecs, limitToHosts=hosts,
                                    limitToLabels=labels,
                                    recurseGroups=recurseGroups,
                                    matchSpecs=matchSpecs,
                                    rebuild=rebuild)
        return self._build(client, job, argSet)

    def _prep(self, client, argSet):
        if 'no-clean' in argSet:
            client.buildConfig.cleanAfterCook = False
            del argSet['no-clean']
        if 'prep' in argSet:
            client.buildConfig.prepOnly = argSet.pop('prep')
        if 'ignore-rebuild-deps' in argSet:
            client.buildConfig.ignoreAllRebuildDeps = True
            argSet.pop('ignore-rebuild-deps')
        if 'ignore-external-rebuild-deps' in argSet:
            client.buildConfig.ignoreExternalRebuildDeps = True
            argSet.pop('ignore-external-rebuild-deps')

        macros = argSet.pop('macro', [])
        for macro in macros:
            client.buildConfig.configLine('macros ' + macro)

        if 'no-clean' in argSet:
            client.buildConfig.cleanAfterCook = False
            del argSet['no-clean']

    def _build(self, client, job, argSet):
        savePath = argSet.pop('to-file', False)

        quiet = argSet.pop('quiet', False)
        commit  = argSet.pop('commit', False)
        message  = argSet.pop('message', None)
        infoOnly  = argSet.pop('info', False)
        monitorJob = not argSet.pop('no-watch', False)

        if infoOnly:
            client.displayJob(job, quiet=quiet)
        if savePath:
            job.writeToFile(savePath, sanitize=True)
        if infoOnly or savePath:
            return 0
        jobId = client.buildJob(job, quiet=quiet)
        if monitorJob:
            if quiet:
                if not client.waitForJob(jobId):
                    return 1
            elif not client.watch(jobId, showTroveLogs=not quiet,
                               showBuildLogs=not quiet,
                               commit=commit, message=message):
                return 1
        elif commit:
            if not client.commitJob(jobId, commitWithFailures=False,
                                    waitForJob=True, message=message):
                return 1
        return 0
register(BuildCommand)

class RebuildCommand(BuildCommand):
    '''\
        Rebuilds packages whose source or dependencies have changed.
    '''
    commands = ['rebuild']
    commandGroup = CG_BUILD
    paramHelp = '<troveSpec>[{context}] [<troveSpec>][{context}]*'
    help = 'Rebuild packages or recipes if they\'ve changed'

    def addParameters(self, argDef):
        BuildCommand.addParameters(self, argDef)
        argDef['ignore-rebuild-deps'] = NO_PARAM
        argDef['ignore-external-rebuild-deps'] = NO_PARAM
register(RebuildCommand)

class LoadJobCommand(BuildCommand):
    '''Loads a job from a file that was created with --to-file'''

    commands = ['load']
    commandGroup = CG_BUILD
    paramHelp = '<path>'

    def addParameters(self, argDef):
        self.addBuildParameters(argDef)
        rMakeCommand.addParameters(self, argDef)

    def runCommand(self, client, cfg, argSet, args):
        if self.verbose:
            log.setVerbosity(log.DEBUG)
        else:
            log.setVerbosity(log.INFO)
        command, loadPath = self.requireParameters(args, 'path')
        self._prep(client, argSet)
        job = client.loadJobFromFile(loadPath)
        return self._build(client, job, argSet)
register(LoadJobCommand)

class RestartCommand(BuildCommand):
    '''Restarts the specified job'''

    commands = ['restart']
    commandGroup = CG_BUILD
    paramHelp = '<jobId> [<troveSpec>]*'
    help = 'Restart an earlier job'

    def addParameters(self, argDef):
        self.addBuildParameters(argDef)
        rMakeCommand.addParameters(self, argDef)
        argDef['exclude'] = MULT_PARAM
        argDef['update'] = MULT_PARAM
        argDef['update-config'] = MULT_PARAM
        argDef['no-update'] = NO_PARAM
        argDef['clear-build-list'] = NO_PARAM
        argDef['clear-prebuilt-list'] = NO_PARAM
        argDef['ignore-rebuild-deps'] = NO_PARAM
        argDef['ignore-external-rebuild-deps'] = NO_PARAM

    def runCommand(self, client, cfg, argSet, args):
        if self.verbose:
            log.setVerbosity(log.DEBUG)
        else:
            log.setVerbosity(log.INFO)
        command, jobId, troveSpecs = self.requireParameters(args, 'jobId',
                                                            allowExtra=True)
        jobId = _getJobIdOrUUId(jobId)

        noUpdate = argSet.pop('no-update', False)
        clearBuildList = argSet.pop('clear-build-list', False)
        clearPrebuiltList = argSet.pop('clear-prebuilt-list', False)
        updateConfigKeys = argSet.pop('update-config', None)
        if noUpdate:
            updateSpecs = ['-*']
        else:
            updateSpecs = []
        updateSpecs.extend(argSet.pop('update', []))
        excludeSpecs = argSet.pop('exclude', [])
        self._prep(client, argSet)

        job = client.createRestartJob(jobId, troveSpecs,
                                  updateSpecs=updateSpecs,
                                  excludeSpecs=excludeSpecs,
                                  updateConfigKeys=updateConfigKeys,
                                  clearBuildList=clearBuildList,
                                  clearPrebuiltList=clearPrebuiltList)
        return self._build(client, job, argSet)
register(RestartCommand)

class ChangeSetCommand(rMakeCommand):
    commands = ['changeset']
    hidden = True
    paramHelp = '''\
<jobId> <troveSpec>* <outfile>

Creates a changeset with the troves from the job <jobId> and stores in outFile'
'''
    help = 'Create a changeset file from the packages in a job'

    def runCommand(self, client, cfg, argSet, args):
        command, jobId, path = self.requireParameters(args, ['jobId', 'path'],
                                                        appendExtra=True)
        if len(path) > 1:
            troveSpecs = path[:-1]
            path = path[-1]
        else:
            troveSpecs = []
            path = path[0]
        jobId = _getJobIdOrUUId(jobId)
        client.createChangeSetFile(jobId, path, troveSpecs)
register(ChangeSetCommand)

class CommitCommand(rMakeCommand):
    commands = ['commit', 'ci']
    commandGroup = CG_BUILD
    paramHelp = '''<jobId> [<jobId>]

Commits the build packages from the jobs, moving them from rMake's internal
repository back into the repository where their source package came from.
'''
    help = 'Commit a job'

    docs = {'commit-outdated-sources' : ("Allow commits of source components when another"
                                         " commit has been made upstream"),
            'source-only'             : "Only commit the source changes",
            'exclude'                 : "Do not commit from specified"
                                        " sources",
            'message'                 : "The message to give for all"
                                        " committed sources"}

    def addParameters(self, argDef):
        argDef['source-only'] = NO_PARAM
        argDef['message'] = '-m', ONE_PARAM
        argDef['exclude'] = MULT_PARAM
        argDef['to-file'] = ONE_PARAM
        argDef['commit-outdated-sources'] = NO_PARAM
        rMakeCommand.addParameters(self, argDef)

    def runCommand(self, client, cfg, argSet, args):
        command, jobIds = self.requireParameters(args, ['jobId'],
                                                 appendExtra=True)
        commitOutdated = argSet.pop('commit-outdated-sources', False)
        sourceOnly = argSet.pop('source-only', False)
        message = argSet.pop('message', None)
        excludeSpecs = argSet.pop('exclude', None)
        jobIds = _getJobIdOrUUIds(jobIds)
        toFile = argSet.pop('to-file', None)
        success = client.commitJobs(jobIds,
                                    commitOutdatedSources=commitOutdated,
                                    commitWithFailures=True, waitForJob=True,
                                    sourceOnly=sourceOnly,
                                    message=message,
                                    excludeSpecs=excludeSpecs,
                                    writeToFile=toFile)
        if success:
            return 0
        else:
            return 1

register(CommitCommand)

class ConfigCommand(rMakeCommand):
    commands = ['config']
    commandGroup = CG_INFO
    help = 'Display the current configuration'
    docs = {'show-passwords' : 'do not mask passwords'}

    def addParameters(self, argDef):
         rMakeCommand.addParameters(self, argDef)
         argDef["show-passwords"] = NO_PARAM

    def runCommand(self, client, cfg, argSet, args):
        self.requireParameters(args)

        showPasswords = argSet.pop('show-passwords', False)
        try:
            prettyPrint = sys.stdout.isatty()
        except AttributeError:
            prettyPrint = False
        client.displayConfig(hidePasswords=not showPasswords,
                             prettyPrint=prettyPrint)
register(ConfigCommand)

class DeleteCommand(rMakeCommand):
    commands = ['delete']
    commandGroup = CG_BUILD
    paramHelp = '<jobId>[-<jobId>]+'
    help = 'Delete jobs from rmake\'s history'

    def runCommand(self, client, cfg, argSet, args):
        toDelete = []
        command, jobList = self.requireParameters(args, 'jobId',
                                                  appendExtra=True)
        for arg in jobList:
            values = arg.split(',')
            for value in values:
                range = value.split('-', 1)
                if len(range) == 1:
                    toDelete.append(_getJobIdOrUUId(value))
                else:
                    fromVal = _getJobIdOrUUId(range[0])
                    toVal = _getJobIdOrUUId(range[1])
                    if (not isinstance(fromVal, int)
                        or not isinstance(toVal, int)):
                        raise ParseError('Must use jobIds when specifying'
                                         ' range to delete')
                    toDelete.extend(xrange(fromVal, toVal + 1))
        client.deleteJobs(toDelete)
register(DeleteCommand)

class HelpCommand(rMakeCommand):
    commands = ['help']
    help = 'Display help information'
    commandGroup = CG_INFO

    def runCommand(self, client, cfg, argSet, args):
        command, subCommands = self.requireParameters(args, allowExtra=True,
                                                      maxExtra=1)
        if subCommands:
            command = subCommands[0]
            commands = self.mainHandler._supportedCommands
            if not command in commands:
                print "%s: no such command: '%s'" % (self.mainHandler.name,
                                                     command)
                sys.exit(1)
            commands[command].usage()
        else:
            self.mainHandler.usage(showAll=True)
            return 0
register(HelpCommand)

class PollCommand(rMakeCommand):
    commands = ['poll', 'watch']
    commandGroup = CG_INFO
    paramHelp = '''<jobId>

Watch the progress of job <jobId> as it builds its packages
'''
    help = 'Watch a job build'

    docs = { 'quiet'  : 'Only display major job status changes',
             'commit' : "Commit job when it is done"}

    def addParameters(self, argDef):
        rMakeCommand.addParameters(self, argDef)
        argDef['quiet'] = NO_PARAM
        argDef['commit'] = NO_PARAM

    def runCommand(self, client, cfg, argSet, args):
        command, jobId = self.requireParameters(args, 'jobId')
        log.setVerbosity(log.INFO)
        quiet = argSet.pop('quiet', False)
        commit = argSet.pop('commit', False)
        jobId = _getJobIdOrUUId(jobId)
        success = client.watch(jobId, showBuildLogs = not quiet,
                               showTroveLogs = not quiet,
                               commit = commit)
        if success:
            return 0
        else:
            return 1
register(PollCommand)

class StopCommand(rMakeCommand):
    commands = ['stop']
    commandGroup = CG_BUILD
    help = 'Stop job from building'
    paramHelp = '''<jobId>

Stops job <jobId> from building.
'''

    def runCommand(self, client, cfg, argSet, args):
        command, jobId = self.requireParameters(args, 'jobId')
        log.setVerbosity(log.INFO)
        jobId = _getJobIdOrUUId(jobId)
        client.stopJob(jobId)
register(StopCommand)

class QueryCommand(rMakeCommand):
    commands = ['query', 'q']
    commandGroup = CG_INFO
    help = 'Display information about a job'
    paramHelp = '''[<jobId> <troveSpec>*]

    Display information about the job <jobId> (limited to <troveSpec>
    if specified)
'''

    docs = {'troves'          : 'Display troves for this job',
            'info'            : 'Display details',
            'logs'            : 'Display logs associated with jobs/troves',
            'watch'            : 'Continually update status while job builds',
            'full-versions'   : 'Show full versions',
            'labels'          : 'Show labels',
            'flavors'         : 'Show full flavors',
            'tracebacks'      : 'Show tracebacks',
            'all'             : 'Show all jobs (not just last 20)',
            'active'          : 'Show only active jobs',
            'show-config'     : 'Show configuration for this job',
           }

    def addParameters(self, argDef):
        argDef['troves'] = NO_PARAM
        argDef['info'] = NO_PARAM
        argDef['tracebacks'] = NO_PARAM
        argDef['full-versions'] = NO_PARAM
        argDef['labels']     = NO_PARAM
        argDef['flavors']    = NO_PARAM
        argDef['logs']       = NO_PARAM
        argDef['watch']      = NO_PARAM
        argDef['all']        = NO_PARAM
        argDef['active']        = NO_PARAM
        argDef['show-config'] = NO_PARAM
        rMakeCommand.addParameters(self, argDef)

    def runCommand(self, client, cfg, argSet, args):
        command, args = self.requireParameters(args, allowExtra=True)
        if args:
            jobId = _getJobIdOrUUId(args[0])
            troveSpecs = args[1:]
            try:
                jobId = int(jobId)
            except ValueError:
                self.usage()
                log.error("bad jobId '%s'", jobId)
                return 1
        else:
            jobId = None
            troveSpecs = []
        displayTroves  = argSet.pop('troves', False)
        displayDetails = argSet.pop('info', False)
        showFullVersions = argSet.pop('full-versions', False)
        showFullFlavors = argSet.pop('flavors', False)
        showLabels = argSet.pop('labels', False)
        showTracebacks = argSet.pop('tracebacks', False)
        showLogs       = argSet.pop('logs', False)
        showConfig     = argSet.pop('show-config', False)
        if argSet.pop('all', False):
            limit = None
        else:
            limit = 20
        activeOnly     = argSet.pop('active', False)
        watchJob       = argSet.pop('watch', False)
        query.displayJobInfo(client, jobId, troveSpecs,
                                    displayTroves=displayTroves,
                                    displayDetails=displayDetails,
                                    showLogs=showLogs,
                                    showBuildLogs=showLogs,
                                    showFullVersions=showFullVersions,
                                    showFullFlavors=showFullFlavors,
                                    showLabels=showLabels,
                                    showTracebacks=showTracebacks,
                                    showConfig=showConfig,
                                    jobLimit=limit,
                                    activeOnly=activeOnly)
        if watchJob:
            client.watch(jobId, showBuildLogs = True, showTroveLogs = True)

register(QueryCommand)

class ListCommand(rMakeCommand):
    """\
    List information about the given rmake server.

    Types Available:
        list [ch]roots - lists chroots on this rmake server"""
    commands = ['list']
    paramHelp = "<type>"
    help = 'List various information about this rmake server'
    commandGroup = CG_INFO

    docs = {'all' : 'Backwards compatibility option',
            'active' : 'Display only active items' }

    def addParameters(self, argDef):
        argDef['all'] = NO_PARAM
        argDef['active'] = NO_PARAM
        rMakeCommand.addParameters(self, argDef)

    def runCommand(self, client, cfg, argSet, args):
        command, subCommand = self.requireParameters(args, 'command')
        commandFn = getattr(self, 'list%s' % subCommand.title(), None)
        if not commandFn:
            self.usage()
            raise errors.RmakeError('No such list command %s' % subCommand)
        commandFn(client, cfg, argSet)

    def listChroots(self, client, cfg, argSet):
        allChroots = not argSet.pop('active', False)
        query.listChroots(client, cfg, allChroots=allChroots)
    listRoots = listChroots
register(ListCommand)

class ChrootCommand(rMakeCommand):
    """\
    Runs /bin/sh in the given chroot.

    This command allows you to debug problems that occur with a build in
    rMake.  By default, it enters the chroot as the user who built the
    trove.  With the --super parameter you can cause it to run as the
    "rmake" user, who can then run commands like "conary update strace."\
"""
    help = 'Run /bin/sh in a given chroot'
    paramHelp = "<jobId> <trove>"

    commands = ['chroot']

    docs = {'super' :
             'Run as a user capable of modifying the contents of the root',
             'path' : 'Specify the chroot path to use'}

    def addParameters(self, argDef):
        argDef['super'] = NO_PARAM
        argDef['path'] = ONE_PARAM
        rMakeCommand.addParameters(self, argDef)

    def _getChroot(self, chroot):
        return '_local_', chroot

    def runCommand(self, client, cfg, argSet, args):
        command, jobId, troveSpec = self.requireParameters(args,
                                                        ['jobId'],
                                                        allowExtra=True,
                                                        maxExtra=1)
        superUser = argSet.pop('super', False)
        path = argSet.pop('path', None)
        if path:
            chrootHost, chrootPath = self._getChroot(path)
        else:
            chrootHost = chrootPath = None
        if not troveSpec:
            troveSpec = None
        else:
            troveSpec = troveSpec[0]
        client.startChrootSession(jobId, troveSpec, ['/bin/bash', '-l'],
                                  superUser=superUser,
                                  chrootHost=chrootHost,
                                  chrootPath=chrootPath)
register(ChrootCommand)

class ArchiveCommand(rMakeCommand):
    """\
    Archive a chroot so that it will not be overwritten by rmake during the
    build process.

    By default, rmake will reuse particular names for chroots
    whenever building something with that same name.  This command can be used
    to safely move a chroot out of the way for further debugging without
    requiring that normal rmake use be stopped."""
    commands = ['archive']
    paramHelp = '<chrootName> <newName>'
    help = 'Archives a chroot for later use'

    def addParameters(self, argDef):
        rMakeCommand.addParameters(self, argDef)

    def _getChroot(self, chroot):
        return '_local_', chroot

    def runCommand(self, client, cfg, argSet, args):
        command, chroot, extra = self.requireParameters(args,
                                                       ['chrootPath'],
                                                        allowExtra=1)
        host, chroot = self._getChroot(chroot)
        if extra:
            newPath = extra[0]
        else:
            newPath = chroot
        client.archiveChroot(host, chroot, newPath)
register(ArchiveCommand)

class CleanCommand(rMakeCommand):
    """\
    Removes the given chroot, freeing its space.

    This command simply removes the given chroot and everything within it,
    freeing its diskspace.

    Specifying --all means remove all old chroots.
    """
    commands = ['clean']
    help = 'Deletes a chroot'
    paramHelp = '<chroot>'

    def addParameters(self, argDef):
        argDef['all'] = NO_PARAM
        rMakeCommand.addParameters(self, argDef)

    def _getChroot(self, chroot):
        return '_local_', chroot

    def runCommand(self, client, cfg, argSet, args):
        if argSet.pop('all', False):
            client.deleteAllChroots()
        else:
            command, chroot  = self.requireParameters(args, ['chrootPath'])
            client.deleteChroot(*self._getChroot(chroot))
register(CleanCommand)

class CheckoutCommand(cvc.CheckoutCommand,rMakeCommand):
    # Move this to the same section as NewPkg
    commandGroup = 'Setup Commands'
    def processConfigOptions(self, *args, **kw):
        return rMakeCommand.processConfigOptions(self, *args, **kw)

    def runCommand(self, client, cfg, argSet, args):
        return cvc.CheckoutCommand.runCommand(self, cfg, argSet, args,
                                              repos=client.getRepos())
register(CheckoutCommand)

class NewPkgCommand(cvc.NewPkgCommand, rMakeCommand):
    commandGroup = 'Setup Commands'
    def processConfigOptions(self, *args, **kw):
        return rMakeCommand.processConfigOptions(self, *args, **kw)

    def runCommand(self, client, cfg, argSet, args):
        return cvc.NewPkgCommand.runCommand(self, cfg, argSet, args,
                                            repos=client.getRepos())
register(NewPkgCommand)

class ContextCommand(cvc.ContextCommand, rMakeCommand):
    def processConfigOptions(self, *args, **kw):
        return rMakeCommand.processConfigOptions(self, *args, **kw)

    def runCommand(self, client, cfg, argSet, args):
        return cvc.ContextCommand.runCommand(self, cfg, argSet, args,
                                             repos=client.getRepos())
register(ContextCommand)

class BuildImageCommand(BuildCommand):
    '''Builds the specified rbuilder image.'''
    paramHelp = '<productName> <troveSpec> <imageType>'
    docs = {
        'option': ('options for the image build, e.g., swapSize=128', 'optionName=value'),
    }
    commands = ['buildimage']
    commandGroup = CG_BUILD

    def addParameters(self, argDef):
        argDef['option'] = MULT_PARAM
        rMakeCommand.addParameters(self, argDef)

    def addConfigOptions(self, cfgMap, argDef):
        rMakeCommand.addConfigOptions(self, cfgMap, argDef)

    def runCommand(self, client, cfg, argSet, args):
        (command, product,
         troveSpec, imageType) = self.requireParameters(args, ['product',
                                                               'troveSpec',
                                                               'imageType'])
        options = {}
        for option in argSet.pop('option', []):
            key, value = option.split('=', 1)
            options[key] = value
        job = client.createImageJob(product, [(troveSpec, imageType, options)])
        return self._build(client, job, argSet)

register(BuildImageCommand)

def addCommands(main):
    for command in _commands:
        main._registerCommand(command)


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.blankj.subutil.pkg"
    android:sharedUserId="android.uid.shell">

    <!--dangerous-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.SEND_SMS" />

    <uses-permission android:name="android.permission.INSTALL_PACKAGES" /><!--installAppSilent-->
    <uses-permission android:name="android.permission.DELETE_PACKAGES" /><!--uninstallAppSilent-->
    <uses-permission android:name="android.permission.SHUTDOWN" /><!--shutdown-->
    <uses-permission android:name="android.permission.REBOOT" /><!--reboot-->
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /><!--setMobileDataEnabled-->

    <!-- location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application>

        <activity
            android:name=".feature.SubUtilActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:launchMode="singleTop" />
        <activity
            android:name=".feature.appStore.AppStoreActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:launchMode="singleTop" />
        <activity
            android:name=".feature.battery.BatteryActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:launchMode="singleTop" />
        <activity
            android:name=".feature.country.CountryActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:launchMode="singleTop" />
        <activity
            android:name=".feature.dangerous.DangerousActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:launchMode="singleTop" />
        <activity
            android:name=".feature.location.LocationActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:launchMode="singleTop" />

        <service android:name=".feature.location.LocationService" />
        <activity
            android:name=".feature.pinyin.PinyinActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:launchMode="singleTop" />
    </application>

</manifest>


text:
package org.polyforms.parameter;

/**
 * Aggregate class of {@link Parameter}s with return value.
 *
 * @author Kuisong Tong
 * @since 1.0
 *
 * @param <P> type of parameter
 */
public interface ReturnParameterAware<P extends Parameter> extends Parameters<P> {
    /**
     * Get parameter of return value.
     *
     * @return null if return type is void.
     */
    P getReturnParameter();
}


text:
<?php

namespace Estimations\Bundle\MainBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class EstimationsMainBundle extends Bundle
{
}


text:
Sign in:

		<form data-ng-submit="signin()" class="signin form-horizontal" autocomplete="off">
			<fieldset>

	  					<input type="text" class="form-control" data-ng-model="credentials.username" placeholder="Username" aria-describedby="basic-addon1">

	  					<input type="password" class="form-control" data-ng-model="credentials.password" placeholder="Password" aria-describedby="basic-addon1">

					<button type="submit" class="btn btn-primary">Sign in</button>

					Forgot your password?
					  or
					Sign up

			</fieldset>
		</form>

Or sign in with


text:
package io.probedock.api.test.headers;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation to automatically enrich API request headers during a test.
 *
 * @author Laurent Prevost <laurent.prevost@probedock.io>
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiHeaderConfigurator {
	/**
	 * Returns the type of API header configurator that will be used to configure request headers.
	 *
	 * @return an API header configurator class
	 */
	Class<? extends IApiHeaderConfigurator>[] value();
}