text:
<?php

namespace Ilbeygi\UserPermission\Controller;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Ilbeygi\UserPermission\Models\RoleName;
use Ilbeygi\UserPermission\Models\Route;
use Ilbeygi\UserPermission\Models\Role;

class PermissionController extends Controller
{
    /**
     * index of permissions.
     *
     * @return view() function
     */
    public function index()
    {
    	$rolenames = RoleName::orderBy('id','desc')->paginate(12);
    	return view('userPermission.userRoleGroup',compact('rolenames'));
    }

    /**
     * insert role names in database.
     *
     * @return back() function
     */
    public function store(Request $request)
    {
    	$this->validate($request,[
    		'role_name' => 'required|min:3'
    	]);
    	$rolename = new RoleName;
    	$rolename->role_name = $request->role_name;
    	if($rolename->save())
    		session()->flash('status','The user group has been added successfully   .');
    	else
    		session()->flash('status','The user group was not created successfully. Please try again.');
    	return back();
    }

    /**
     * show index access.
     *
     * @return void
     */
    public function accessIndex($id)
    {
    	$routes = Route::all();
    	$roles = Role::where('role_names_id',$id)->paginate(40);
    	return view('userPermission.addPermissions',compact('roles','routes','id'));
    }

    /**
     * store access.
     *
     * @return void
     */
    public function accessStore(Request $request)
    {
        $this->validate($request,[
                'role_names_id' => 'required',
                'access' => 'required'
            ]);

        if (!empty($request->access)) {
            foreach ($request->access as $access) {
                if (Role::where('routes_id',$access)->where('role_names_id',$request->role_names_id)->first()) {
                    continue;
                }else{
                    $role = new Role;
                    $role->routes_id = $access;
                    $role->role_names_id = $request->role_names_id;
                    $role->save();
                }
            }
        }

        session()->flash('status','Permissions have been added successfully.');
        return back();

    }

    /**
     * delete access.
     *
     * @return void
     */
    public function accessDelete($id)
    {
        Role::destroy($id);
        return back();
    }

    /**
     * store Route.
     *
     * @return void
     */
    public function routeStore(Request $request)
    {
        $this->validate($request,[
            'route_name' => 'required',
            'route' => 'required'
        ]);

        $route = new Route;
        $route->route = $request->route;
        $route->route_name = $request->route_name;
        if ($route->save()) {
            session()->flash('status','new route have been added successfully.');
        }else{
            session()->flash('status','Sorry, there was a problem registering the new route , Please try again.');
        }
        return back();
    }

}


text:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var sww = require('./lib/sww.js');

self.ServiceWorkerWare = sww.ServiceWorkerWare;
self.StaticCacher = sww.StaticCacher;
self.SimpleOfflineCache = sww.SimpleOfflineCache;

},{"./lib/sww.js":5}],2:[function(require,module,exports){
'use strict';

// Inspired by expressjs and shed (https://github.com/wibblymat/shed)
function Router(options) {
  this.options = options;
  this.stack = [];
}

Router.prototype.ALL_METHODS = 'all';
Router.prototype.methods = ['get', 'post', 'put', 'delete', 'head',
  Router.prototype.ALL_METHODS];

/**
 * Add a new route to the stack.
 * @param method (String) http verb to handle the request
 * @param path (Regexp) string or regexp to match urls
 * @param handler (Function) payload to be executed if url matches.
 */
Router.prototype.add = function r_add(method, path, handler) {
  var pathRegexAndTags, pathRegex, namedPlaceholders;

  method = this._sanitizeMethod(method);

  // Parse simle string path into regular expression for path matching
  pathRegexAndTags = this._parseSimplePath(path);
  pathRegex = pathRegexAndTags.regexp;
  namedPlaceholders = pathRegexAndTags.tags;

  this.stack.push({
    method: method,
    path: pathRegex,
    namedPlaceholders: namedPlaceholders,
    handler: handler
  });
};

/**
 * Create the utility methods .get .post ... etc.
 */
Router.prototype.methods.forEach(function(method) {
  Router.prototype[method] = function(path, handler) {
    return this.add(method, path, handler);
  };
});

Router.prototype.proxyMethods = function r_proxyPrototype(obj) {
  var self = this;
  this.methods.forEach(function(method) {
    obj[method] = function(path, mw) {
      if (typeof mw.onFetch !== 'function' && typeof mw !== 'function') {
        throw new Error('This middleware cannot handle fetch request');
      }
      var handler = typeof mw.onFetch !== 'undefined' ?
        mw.onFetch.bind(mw) : mw;
      self.add(method, path, handler);
    };
  });
};

/**
 * Matches the given url and methods with the routes stored in
 * the stack.
 */
Router.prototype.match = function r_match(method, url) {
  method = this._sanitizeMethod(method);
  var matches = [];

  var _this = this;
  this.stack.forEach(function eachRoute(route) {
    if (!(method === route.method || route.method === _this.ALL_METHODS)) {
      return;
    }

    var groups = _this._routeMatch(url, route);
    if (groups) {
      route.handler.__params = groups;
      matches.push(route.handler);
    }
  });

  return matches;
};

/**
 * Performs a matching test for url against a route.
 * @param {String} the url to test
 * @param {route} the route to match against
 * @return {Object} an object with the portions of the url matching the named
 * placeholders or null if there is no match.
 */
Router.prototype._routeMatch = function (url, route) {
  var groups = url.match(route.path);
  if (!groups) { return null; }
  return this._mapParameters(groups, route.namedPlaceholders);
};

/**
 * Assign names from named placeholders in a route to the matching groups
 * for an URL against that route.
 * @param {Array} groups from a successful match
 * @param {Array} names for those groups
 * @return a map of names of named placeholders and values for those matches.
 */
Router.prototype._mapParameters = function (groups, placeholderNames) {
  return placeholderNames.reduce(function (params, name, index) {
    params[name] = groups[index + 1];
    return params;
  }, Object.create(null));
};

Router.prototype._sanitizeMethod = function(method) {
  var sanitizedMethod = method.toLowerCase().trim();
  if (this.methods.indexOf(sanitizedMethod) === -1) {
    throw new Error('Method "' + method + '" is not supported');
  }
  return sanitizedMethod;
};

/**
 * Simple path-to-regex translation based on the Express "string-based path"
 * syntax.
 */
Router.prototype._parseSimplePath = function(path) {
  // Check for named placeholder crowding
  if (/\:[a-zA-Z0-9]+\:[a-zA-Z0-9]+/g.test(path)) {
    throw new Error('Invalid usage of named placeholders');
  }

  // Check for mixed placeholder crowdings
  var mixedPlaceHolders =
    /(\*\:[a-zA-Z0-9]+)|(\:[a-zA-Z0-9]+\:[a-zA-Z0-9]+)|(\:[a-zA-Z0-9]+\*)/g;
  if (mixedPlaceHolders.test(path.replace(/\\\*/g,''))) {
    throw new Error('Invalid usage of named placeholders');
  }

  // Try parsing the string and converting special characters into regex
  try {
    // Parsing anonymous placeholders with simple backslash-escapes
    path = path.replace(/(.|^)[*]+/g, function(m,escape) {
      return escape==='\\' ? '\\*' : (escape+'(?:.*?)');
    });

    // Parsing named placeholders with backslash-escapes
    var tags = [];
    path = path.replace(/(.|^)\:([a-zA-Z0-9]+)/g, function (m, escape, tag) {
      if (escape === '\\') { return ':' + tag; }
      tags.push(tag);
      return escape + '(.+?)';
    });

    return { regexp: RegExp(path + '$'), tags: tags };
  }

  // Failed to parse final path as a RegExp
  catch (ex) {
    throw new Error('Invalid path specified');
  }
};

module.exports = Router;

},{}],3:[function(require,module,exports){
/* global Promise, caches */
'use strict';

var debug = 0 ? console.log.bind(console, '[SimpleOfflineCache]') :
 function(){};

// Default Match options, not exposed.
var DEFAULT_MATCH_OPTIONS = {
  ignoreSearch: false,
  ignoreMethod: false,
  ignoreVary: false
};
var DEFAULT_MISS_POLICY = 'fetch';
// List of different policies
var MISS_POLICIES = [
  DEFAULT_MISS_POLICY
];

var DEFAULT_CACHE_NAME = 'offline';

/**
 * Constructor for the middleware that serves the content of a
 * cache specified by it's name.
 * @param {string} cacheName Name of the cache that will be serving the content
 * @param {object} [options] Object use to setup the cache matching alternatives
 * @param {string} [missPolicy] Name of the policy to follow if a request miss
 *                 when hitting the cache.
 */
function SimpleOfflineCache(cacheName, options, missPolicy) {
  this.cacheName = cacheName || DEFAULT_CACHE_NAME;
  this.options = options || DEFAULT_MATCH_OPTIONS;
  this.missPolicy = missPolicy || DEFAULT_MISS_POLICY;
  if (MISS_POLICIES.indexOf(this.missPolicy) === -1) {
    console.warn('Policy ' + missPolicy + ' not supported');
    this.missPolicy = DEFAULT_MISS_POLICY;
  }
}

SimpleOfflineCache.prototype.onFetch = function soc_onFetch(request, response) {
  // If another middleware layer already have a response, the simple cache
  // just pass through the response and does nothing.
  if (response) {
    return Promise.resolve(response);
  }

  var clone = request.clone();
  var _this = this;
  debug('Handing fetch event: ' + clone.url);
  return this.ensureCache().then(function(cache) {
    return cache.match(clone, _this.options).then(function(res) {
      if (res) {
        return res;
      }

      // So far we just support one policy
      switch(_this.missPolicy) {
        case DEFAULT_MISS_POLICY:
          return fetch(request);
      }
    });
  });
};

SimpleOfflineCache.prototype.ensureCache = function soc_ensureCache() {
  if (!this.cacheRequest) {
    this.cacheRequest = caches.open(this.cacheName);
  }
  return this.cacheRequest;
};

module.exports = SimpleOfflineCache;

},{}],4:[function(require,module,exports){
/* globals caches, Promise, Request */
'use strict';

function StaticCacher(fileList) {
  if (!Array.isArray(fileList) || fileList.length === 0) {
    throw new Error('Invalid file list');
  }
  this.files = fileList;
}

StaticCacher.prototype.onInstall = function sc_onInstall() {
  var self = this;
  return this.getDefaultCache().then(function(cache) {
    return self.addAll(cache, self.files);
  });
};

StaticCacher.prototype.getDefaultCache = function sc_getDefaultCache() {
  if (!this.cacheRequest) {
    this.cacheRequest = caches.open('offline');
  }
  return this.cacheRequest;
};

StaticCacher.prototype.addAll = function(cache, urls) {
  if (!cache) {
    throw new Error('Need a cache to store things');
  }
  // Polyfill until chrome implements it
  if (typeof cache.addAll !== 'undefined') {
    return cache.addAll(urls);
  }

  var promises = [];
  var self = this;
  urls.forEach(function(url) {
    promises.push(self.fetchAndCache(new Request(url), cache));
  });

  return Promise.all(promises);
};

StaticCacher.prototype.fetchAndCache =
function sc_fetchAndCache(request, cache) {

  return fetch(request.clone()).then(function(response) {
    if (parseInt(response.status) < 400) {
      cache.put(request.clone(), response.clone());
    }
    return response;
  });
};

module.exports = StaticCacher;

},{}],5:[function(require,module,exports){
/* global fetch, BroadcastChannel, clients, Promise, Request, Response */
'use strict';

var debug = 1 ? console.log.bind(console, '[ServiceWorkerWare]') : function(){};

var StaticCacher = require('./staticcacher.js');
var SimpleOfflineCache = require('./simpleofflinecache.js');
var Router = require('./router.js');

var ERROR = 'error';
var CONTINUE = 'continue';
var TERMINATE = 'terminate';
var TERMINATION_TOKEN = {};

function DEFAULT_FALLBACK_MW(request) {
  return fetch(request);
}

function ServiceWorkerWare(options) {
  options = options || {};
  if (typeof options === 'function' || options.onFetch) {
    options = { fallbackMiddleware: options };
  }
  options.autoClaim = ('autoClaim' in options) ? options.autoClaim : true;
  this.middleware = [];
  this.router = new Router({});
  this.router.proxyMethods(this);

  this.fallbackMw = options.fallbackMiddleware || DEFAULT_FALLBACK_MW;
  this.autoClaim = options.autoClaim;
}

ServiceWorkerWare.prototype.init = function sww_init() {
  // lifecycle events
  addEventListener('install', this);
  addEventListener('activate', this);
  addEventListener('beforeevicted', this);
  addEventListener('evicted', this);

  // network events
  addEventListener('fetch', this);

  // misc events
  addEventListener('message', this);

  // push notifications
  addEventListener('push', this);

  // XXX: Add default configuration
};

/**
 * Handle and forward all events related to SW
 */
ServiceWorkerWare.prototype.handleEvent = function sww_handleEvent(evt) {

  debug('Event received: ' + evt.type);
  switch(evt.type) {
    case 'install':
      this.onInstall(evt);
      break;
    case 'fetch':
      this.onFetch(evt);
      break;
    case 'activate':
      this.onActivate(evt);
      break;
    case 'push':
    case 'message':
    case 'beforeevicted':
    case 'evicted':
      this.forwardEvent(evt);
      break;
    default:
      debug('Unhandled event ' + evt.type);
  }
};

ServiceWorkerWare.prototype.onFetch = function sww_onFetch(evt) {
  var steps = this.router.match(evt.request.method, evt.request.url);

  // Push the fallback middleware at the end of the list.
  // XXX bug 1165860: Decorating fallback MW with `stopIfResponse` until
  // 1165860 lands
  steps.push((function(req, res) {
    if (res) {
      return Promise.resolve(res);
    }
    return this.fallbackMw(req, res);
  }).bind(this));

  evt.respondWith(this.executeMiddleware(steps, evt.request));

};

/**
 * Run the middleware pipeline and inform if errors preventing respondWith()
 * to swallow the error.
 *
 * @param {Array} the middleware pipeline
 * @param {Request} the request for the middleware
 */
ServiceWorkerWare.prototype.executeMiddleware = function (middleware, request) {
  var response = this.runMiddleware(middleware, 0, request, null);
  response.catch(function (error) { console.error(error); });
  return response;
};

/**
 * Pass through the middleware pipeline, executing each middleware in a
 * sequence according to the result from each execution.
 *
 * Each middleware will be passed with the request and response from the
 * previous one in the pipeline. The response from the latest one will be
 * used to answer from the service worker. The middleware will receive,
 * as the last parameter, a function to stop the pipeline and answer
 * immediately.
 *
 * A middleware run can lead to continuing execution, interruption of the
 * pipeline or error. The next action to be performed is calculated according
 * the conditions of the middleware execution and its return value.
 * See normalizeMwAnswer() for details.
 *
 * @param {Array} middleware pipeline.
 * @param {Number} middleware to execute in the pipeline.
 * @param {Request} the request for the middleware.
 * @param {Response} the response for the middleware.
 */
ServiceWorkerWare.prototype.runMiddleware =
function (middleware, current, request, response) {
  if (current >= middleware.length) {
    return Promise.resolve(response);
  }

  var mw = middleware[current];
  if (request) { request.parameters = mw.__params; }
  var endWith = ServiceWorkerWare.endWith;
  var answer = mw(request, response, endWith);
  var normalized =
    ServiceWorkerWare.normalizeMwAnswer(answer, request, response);

  return normalized.then(function (info) {
    switch (info.nextAction) {
      case TERMINATE:
        return Promise.resolve(info.response);

      case ERROR:
        return Promise.reject(info.error);

      case CONTINUE:
        var next = current + 1;
        var request = info.request;
        var response = info.response;
        return this.runMiddleware(middleware, next, request, response);
    }
  }.bind(this));
};

/**
 * A function to force interruption of the pipeline.
 *
 * @param {Response} the response object that will be used to answer from the
 * service worker.
 */
ServiceWorkerWare.endWith = function (response) {
  if (arguments.length === 0) {
    throw new Error('Type error: endWith() must be called with a value.');
  }
  return [TERMINATION_TOKEN, response];
};

/**
 * A middleware is supposed to return a promise resolving in a pair of request
 * and response for the next one or to indicate that it wants to answer
 * immediately.
 *
 * To allow flexibility, the middleware is allowed to return other values
 * rather than the promise. For instance, it is allowed to return only a
 * request meaning the next middleware will be passed that request but the
 * previous response untouched.
 *
 * The function takes into account all the scenarios to compute the request
 * and response for the next middleware or the intention to terminate
 * immediately.
 *
 * @param {Any} non normalized answer from the middleware.
 * @param {Request} request passed as parameter to the middleware.
 * @param {Response} response passed as parameter to the middleware.
 */
ServiceWorkerWare.normalizeMwAnswer = function (answer, request, response) {
  if (!answer || !answer.then) {
    answer = Promise.resolve(answer);
  }
  return answer.then(function (value) {
    var nextAction = CONTINUE;
    var error, nextRequest, nextResponse;
    var isArray = Array.isArray(value);

    if (isArray && value[0] === TERMINATION_TOKEN) {
      nextAction = TERMINATE;
      nextRequest = request;
      nextResponse = value[1] || response;
    }
    else if (value === null) {
      nextRequest = request;
      nextResponse = null;
    }
    else if (isArray && value.length === 2) {
      nextRequest = value[0];
      nextResponse = value[1];
    }
    else if (value instanceof Response) {
      nextRequest = request;
      nextResponse = value;
    }
    else if (value instanceof Request) {
      nextRequest = value;
      nextResponse = response;
    }
    else {
      var msg = 'Type error: middleware must return a Response, ' +
                'a Request, a pair [Response, Request] or a Promise ' +
                'resolving to one of these types.';
      nextAction = ERROR;
      error = new Error(msg);
    }

    return {
      nextAction: nextAction,
      request: nextRequest,
      response: nextResponse,
      error: error
    };
  });
};

/**
 * Walk all the middleware installed asking if they have prerequisites
 * (on the way of a promise to be resolved) when installing the SW.
 */
ServiceWorkerWare.prototype.onInstall = function sww_oninstall(evt) {
  var installation = this.getFromMiddleware('onInstall');
  evt.waitUntil(installation);

};

/**
 * Walk all the installed middleware asking if they have prerequisites
 * (on the way of a promise to be resolved) when SW activates.
 */
ServiceWorkerWare.prototype.onActivate = function sww_activate(evt) {
  var activation = this.getFromMiddleware('onActivate');
  if (this.autoClaim) {
    activation =
      activation.then(function claim() { return self.clients.claim(); });
  }
  evt.waitUntil(activation);

};

/**
 * Returns a promise gathering the results for executing the same method for
 * all the middleware.
 * @param {Function} the method to be executed.
 * @param {Promise} a promise resolving once all the results have been gathered.
 */
ServiceWorkerWare.prototype.getFromMiddleware =
function sww_getFromMiddleware(method) {
  var tasks = this.middleware.reduce(function (tasks, mw) {
    if (typeof mw[method] === 'function') {
      tasks.push(mw[method]());
    }
    return tasks;
  }, []);
  return Promise.all(tasks);
};

/**
 * Register a new middleware layer, they will treat the request in
 * the order that this layers have been defined.
 * A middleware layer can behave in the ServiceWorker in two ways:
 *  - Listening to SW lifecycle events (install, activate, message).
 *  - Handle a request.
 * To handle each case (or both) the middleware object should provide
 * the following methods:
 * - on<SW LiveCiclyeEvent>: for listening to SW lifeciclye events
 * - onFetch: for handling fetch urls
 */
ServiceWorkerWare.prototype.use = function sww_use() {
  // If the first parameter is not a function we will understand that
  // is the path to handle, and the handler will be the second parameter
  if (arguments.length === 0) {
    throw new Error('No arguments given');
  }
  var mw = arguments[0];
  var path = '*';
  var method = this.router.ALL_METHODS;
  if (typeof mw === 'string') {
    path = arguments[0];
    mw = arguments[1];
    var kind = typeof mw;
    if (!mw || !(kind === 'object' || kind === 'function')) {
      throw new Error('No middleware specified');
    }
    if (Router.prototype.methods.indexOf(arguments[2]) !== -1) {
      method = arguments[2];
    }
  }

  this.middleware.push(mw);
  // Add to the router just if middleware object is able to handle onFetch
  // or if we have a simple function
  var handler = null;
  if (typeof mw.onFetch === 'function') {
    handler = mw.onFetch.bind(mw);
  } else if (typeof mw === 'function') {
    handler = mw;
  }
  if (handler) {
    this.router.add(method, path, handler);
  }
  // XXX: Attaching the broadcastMessage to mw that implements onMessage.
  // We should provide a way to get a reference to the SWW object and do
  // the broadcast from there
  if (typeof mw.onMessage === 'function') {
    mw.broadcastMessage = this.broadcastMessage;
  }
};

/**
 * Forward the event received to any middleware layer that has a 'on<Event>'
 * handler
 */
ServiceWorkerWare.prototype.forwardEvent = function sww_forwardEvent(evt) {
  this.middleware.forEach(function(mw) {
    var handlerName = 'on' + evt.type.replace(/^[a-z]/,
      function(m){
         return m.toUpperCase();
      }
    );
    if (typeof mw[handlerName] !== 'undefined') {
      mw[handlerName].call(mw, evt);
    }
  });
};

/**
 * Broadcast a message to all worker clients
 * @param msg Object the message
 * @param channel String (Used just in Firefox Nightly) using broadcastchannel
 * api to deliver the message, this parameter can be undefined as we listen for
 * a channel undefined in the client.
 */
ServiceWorkerWare.prototype.broadcastMessage = function sww_broadcastMessage(
  msg, channel) {
  // XXX: Until https://bugzilla.mozilla.org/show_bug.cgi?id=1130685 is fixed
  // we can use BroadcastChannel API in Firefox Nightly
  if (typeof BroadcastChannel === 'function') {
    var bc = new BroadcastChannel(channel);
    bc.postMessage(msg);
    bc.close();
    return Promise.resolve();
  } else {
    // This is suppose to be the way of broadcasting a message, unfortunately
    // it's not working yet in Chrome Canary
    return clients.matchAll().then(function(consumers) {
      consumers.forEach(function(client) {
        client.postMessage(msg);
      });
    });
  }
};

ServiceWorkerWare.decorators = {

  ifNoResponse: function (mw) {
    return function (req, res, endWith) {
      if (res) { return [req, res]; }
      return mw(req, res, endWith);
    };
  },

  stopAfter: function (mw) {
    return function (req, res, endWith) {
      var answer = mw(req, res, endWith);
      var normalized = ServiceWorkerWare.normalizeMwAnswer(answer, req, res);

      return normalized.then(function (info) {
        if (info.nextAction === 'error') {
          return Promise.reject(info.error);
        }
        return endWith(info.response);
      });
    };
  }
};

module.exports = {
  ServiceWorkerWare: ServiceWorkerWare,
  StaticCacher: StaticCacher,
  SimpleOfflineCache: SimpleOfflineCache
};

},{"./router.js":2,"./simpleofflinecache.js":3,"./staticcacher.js":4}]},{},[1]);

redpajama_set_name: RedPajamaGithub


text:
require 'rails_helper'

describe D11TeamSeasonSquadStat, type: :model do
  let(:d11_team) { FactoryGirl.create(:d11_team) }
  let(:season) { FactoryGirl.create(:season) }

  before { @d11_team_season_squad_stat = FactoryGirl.create(:d11_team_season_squad_stat, d11_team: d11_team, season: season) }

  subject { @d11_team_season_squad_stat }

  it { is_expected.to respond_to(:season) }
  it { is_expected.to respond_to(:value) }
  it { is_expected.to respond_to(:max_bid) }

  it { is_expected.to be_valid }

  describe '#season' do
    subject { @d11_team_season_squad_stat.season }
    it { is_expected.to eq season }
  end

  describe '#value' do
    specify { expect(subject.value).to eq 0 }
  end

  describe '#max_bid' do
    specify { expect(subject.max_bid).to eq 450 }
  end

  describe "#summarize_stats" do
    let!(:season) { FactoryGirl.create(:season) }
    let!(:premier_league) { FactoryGirl.create(:premier_league, season: season) }
    let!(:match_day) { FactoryGirl.create(:match_day, premier_league: premier_league, match_day_number: 1) }
    let!(:match) { FactoryGirl.create(:match, match_day: match_day) }
    let!(:d11_league) { FactoryGirl.create(:d11_league, season: season) }
    let!(:d11_match_day) { FactoryGirl.create(:d11_match_day, d11_league: d11_league, match_day_number: 1) }
    let!(:d11_match) { FactoryGirl.create(:d11_match, d11_match_day: d11_match_day) }

    context "for defenders" do
      let!(:position) { FactoryGirl.create(:position, defender: true) }
      let!(:player_match_stat1) { FactoryGirl.create(:player_match_stat, d11_team: d11_match.home_d11_team, match: match, position: position, lineup: :starting_lineup, goals: 1, goal_assists: 1, own_goals: 1, goals_conceded: 1, yellow_card_time: 40, red_card_time: 80, man_of_the_match: true, rating: 700, substitution_off_time: 90 ) }
      let!(:player_match_stat2) { FactoryGirl.create(:player_match_stat, d11_team: d11_match.home_d11_team, match: match, position: position, lineup: :substitute, goals: 2, goal_assists: 2, own_goals: 2, goals_conceded: 2, yellow_card_time: 40, red_card_time: 80, shared_man_of_the_match: true, rating: 800, substitution_on_time: 5) }
      let!(:player_match_stat3) { FactoryGirl.create(:player_match_stat, d11_team: d11_match.home_d11_team, match: match, position: position, lineup: :starting_lineup, goals_conceded: 0, rating: 600) }
      let!(:player_match_stat4) { FactoryGirl.create(:player_match_stat, d11_team: d11_match.home_d11_team, match: match, position: position, lineup: :did_not_participate) }
      let!(:d11_team_season_squad_stat) { FactoryGirl.create(:d11_team_season_squad_stat, d11_team: d11_match.home_d11_team, season: season) }

      specify { expect(d11_team_season_squad_stat.team_goals).to eq 3 }
      specify { expect(d11_team_season_squad_stat.goals).to eq 3 }
      specify { expect(d11_team_season_squad_stat.goal_assists).to eq 3 }
      specify { expect(d11_team_season_squad_stat.own_goals).to eq 3 }
      specify { expect(d11_team_season_squad_stat.goals_conceded).to eq 3 }
      specify { expect(d11_team_season_squad_stat.clean_sheets).to eq 1 }
      specify { expect(d11_team_season_squad_stat.rating).to eq 700 }
      specify { expect(d11_team_season_squad_stat.points).to eq 10 }
      specify { expect(d11_team_season_squad_stat.yellow_cards).to eq 2 }
      specify { expect(d11_team_season_squad_stat.red_cards).to eq 2 }
      specify { expect(d11_team_season_squad_stat.man_of_the_match).to eq 1 }
      specify { expect(d11_team_season_squad_stat.shared_man_of_the_match).to eq 1 }
      specify { expect(d11_team_season_squad_stat.games_started).to eq 2 }
      specify { expect(d11_team_season_squad_stat.games_substitute).to eq 1 }
      specify { expect(d11_team_season_squad_stat.games_did_not_participate).to eq 1 }
      specify { expect(d11_team_season_squad_stat.substitutions_on).to eq 1 }
      specify { expect(d11_team_season_squad_stat.substitutions_off).to eq 1 }
      specify { expect(d11_team_season_squad_stat.minutes_played).to eq 265 }
    end

    context "for non-defenders" do
      let!(:player_match_stat1) { FactoryGirl.create(:player_match_stat, d11_team: d11_match.home_d11_team, match: match, lineup: :starting_lineup, goals: 1, goal_assists: 1, own_goals: 1, goals_conceded: 1, yellow_card_time: 40, red_card_time: 80, man_of_the_match: true, rating: 700, substitution_off_time: 90 ) }
      let!(:player_match_stat2) { FactoryGirl.create(:player_match_stat, d11_team: d11_match.home_d11_team, match: match, lineup: :substitute, goals: 2, goal_assists: 2, own_goals: 2, goals_conceded: 2, yellow_card_time: 40, red_card_time: 80, shared_man_of_the_match: true, rating: 800, substitution_on_time: 5) }
      let!(:player_match_stat3) { FactoryGirl.create(:player_match_stat, d11_team: d11_match.home_d11_team, match: match, lineup: :starting_lineup, goals_conceded: 0, rating: 600) }
      let!(:player_match_stat4) { FactoryGirl.create(:player_match_stat, d11_team: d11_match.home_d11_team, match: match, lineup: :did_not_participate) }
      let!(:d11_team_season_squad_stat) { FactoryGirl.create(:d11_team_season_squad_stat, d11_team: d11_match.home_d11_team, season: season) }

      specify { expect(d11_team_season_squad_stat.team_goals).to eq 2 }
      specify { expect(d11_team_season_squad_stat.goals).to eq 3 }
      specify { expect(d11_team_season_squad_stat.goal_assists).to eq 3 }
      specify { expect(d11_team_season_squad_stat.own_goals).to eq 3 }
      specify { expect(d11_team_season_squad_stat.goals_conceded).to eq 0 }
      specify { expect(d11_team_season_squad_stat.clean_sheets).to eq 0 }
      specify { expect(d11_team_season_squad_stat.rating).to eq 700 }
      specify { expect(d11_team_season_squad_stat.points).to eq 7 }
      specify { expect(d11_team_season_squad_stat.yellow_cards).to eq 2 }
      specify { expect(d11_team_season_squad_stat.red_cards).to eq 2 }
      specify { expect(d11_team_season_squad_stat.man_of_the_match).to eq 1 }
      specify { expect(d11_team_season_squad_stat.shared_man_of_the_match).to eq 1 }
      specify { expect(d11_team_season_squad_stat.games_started).to eq 2 }
      specify { expect(d11_team_season_squad_stat.games_substitute).to eq 1 }
      specify { expect(d11_team_season_squad_stat.games_did_not_participate).to eq 1 }
      specify { expect(d11_team_season_squad_stat.substitutions_on).to eq 1 }
      specify { expect(d11_team_season_squad_stat.substitutions_off).to eq 1 }
      specify { expect(d11_team_season_squad_stat.minutes_played).to eq 265 }
    end
  end

  it_should_behave_like "d11 team squad stats summary"

  context "when season is nil" do
    before { @d11_team_season_squad_stat.season = nil }
    it { is_expected.not_to be_valid }
  end

  context "when player_season_infos exist" do
    let!(:season) { FactoryGirl.create(:season) }
    let!(:d11_team) { FactoryGirl.create(:d11_team) }
    let!(:player1) { FactoryGirl.create(:player) }
    let!(:player_season_info1) { FactoryGirl.create(:player_season_info, player: player1, season: season, d11_team: d11_team, value: 50) }
    let!(:player2) { FactoryGirl.create(:player) }
    let!(:player_season_info2) { FactoryGirl.create(:player_season_info, player: player2, season: season, d11_team: d11_team, value: 155) }

    specify { expect(subject.value).to eq 205 }
    specify { expect(subject.max_bid).to eq 255 }
  end

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Xemio.GameLibrary.Content.Formats;

namespace Xemio.GameLibrary.Content
{
    public abstract class ContentReader<T> : IContentReader
    {
        #region Properties
        /// <summary>
        /// Gets the serializer.
        /// </summary>
        protected SerializationManager SerializationManager
        {
            get { return XGL.Components.Require<SerializationManager>(); }
        }
        #endregion

        #region Methods
        /// <summary>
        /// Reads an instance.
        /// </summary>
        /// <param name="reader">The reader.</param>
        public abstract T Read(IFormatReader reader);
        #endregion

        #region IContentReader Member
        /// <summary>
        /// Gets the type.
        /// </summary>
        public Type Id
        {
            get { return typeof(T); }
        }
        /// <summary>
        /// Gets a value indicating whether to bypass the current content format.
        /// </summary>
        public virtual bool BypassFormat
        {
            get { return false; }
        }
        /// <summary>
        /// Reads an instance.
        /// </summary>
        /// <param name="reader">The reader.</param>
        object IContentReader.Read(IFormatReader reader)
        {
            return this.Read(reader);
        }
        #endregion
    }
}


text:
cask 'navicat-for-oracle' do
  version '12.1.3'
  sha256 '3b2e3c8d56099ceaffbe1f6a536537b245c2d916216a4265925770c8cf8b49e5'

  url "http://download.navicat.com/download/navicat#{version.major_minor.no_dots}_ora_en.dmg"
  appcast 'https://www.navicat.com/products/navicat-for-oracle-release-note'
  name 'Navicat for Oracle'
  homepage 'https://www.navicat.com/products/navicat-for-oracle'

  app 'Navicat for Oracle.app'
end


text:
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */

#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "ifcpp/model/GlobalDefines.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingObject.h"

namespace IFC4X3
{
	// TYPE IfcLampTypeEnum = ENUMERATION OF	(COMPACTFLUORESCENT	,FLUORESCENT	,HALOGEN	,HIGHPRESSUREMERCURY	,HIGHPRESSURESODIUM	,LED	,METALHALIDE	,OLED	,TUNGSTENFILAMENT	,USERDEFINED	,NOTDEFINED);
	class IFCQUERY_EXPORT IfcLampTypeEnum : virtual public BuildingObject
	{
	public:
		enum IfcLampTypeEnumEnum
		{
			ENUM_COMPACTFLUORESCENT,
			ENUM_FLUORESCENT,
			ENUM_HALOGEN,
			ENUM_HIGHPRESSUREMERCURY,
			ENUM_HIGHPRESSURESODIUM,
			ENUM_LED,
			ENUM_METALHALIDE,
			ENUM_OLED,
			ENUM_TUNGSTENFILAMENT,
			ENUM_USERDEFINED,
			ENUM_NOTDEFINED
		};

		IfcLampTypeEnum() = default;
		IfcLampTypeEnum( IfcLampTypeEnumEnum e ) { m_enum = e; }
		virtual uint32_t classID() const { return 185388416; }
		virtual shared_ptr<BuildingObject> getDeepCopy( BuildingCopyOptions& options );
		virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
		static shared_ptr<IfcLampTypeEnum> createObjectFromSTEP( const std::string& arg, const std::map<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream );
		IfcLampTypeEnumEnum m_enum;
	};
}


text:
package unittest.io.pivotal.gemfire.spark.connector

import com.gemstone.gemfire.cache.Region
import io.pivotal.gemfire.spark.connector._
import io.pivotal.gemfire.spark.connector.internal.rdd.{GemFireRDDWriter, GemFirePairRDDWriter}
import org.apache.spark.{TaskContext, SparkContext}
import org.apache.spark.rdd.RDD
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{FunSuite, Matchers}
import collection.JavaConversions._
import scala.reflect.ClassTag
import org.mockito.Matchers.{eq => mockEq, any => mockAny}

class GemFireRDDFunctionsTest extends FunSuite with Matchers with MockitoSugar {

  test("test PairRDDFunction Implicit") {
    import io.pivotal.gemfire.spark.connector._
    val mockRDD = mock[RDD[(Int, String)]]
    // the implicit make the following line valid
    val pairRDD: GemFirePairRDDFunctions[Int, String] = mockRDD
    pairRDD shouldBe a [GemFirePairRDDFunctions[_, _]]
  }

  test("test RDDFunction Implicit") {
    import io.pivotal.gemfire.spark.connector._
    val mockRDD = mock[RDD[String]]
    // the implicit make the following line valid
    val nonPairRDD: GemFireRDDFunctions[String] = mockRDD
    nonPairRDD shouldBe a [GemFireRDDFunctions[_]]
  }

  def createMocks[K, V](regionPath: String)
    (implicit kt: ClassTag[K], vt: ClassTag[V], m: Manifest[Region[K, V]]): (String, GemFireConnectionConf, GemFireConnection, Region[K, V]) = {
    val mockConnection = mock[GemFireConnection]
    val mockConnConf = mock[GemFireConnectionConf]
    val mockRegion = mock[Region[K, V]]
    when(mockConnConf.getConnection).thenReturn(mockConnection)
    when(mockConnection.getRegionProxy[K, V](regionPath)).thenReturn(mockRegion)
    // mockRegion shouldEqual mockConn.getRegionProxy[K, V](regionPath)
    (regionPath, mockConnConf, mockConnection, mockRegion)
  }

  test("test GemFirePairRDDWriter") {
    val (regionPath, mockConnConf, mockConnection, mockRegion) = createMocks[String, String]("test")
    val writer = new GemFirePairRDDWriter[String, String](regionPath, mockConnConf)
    val data = List(("1", "one"), ("2", "two"), ("3", "three"))
    writer.write(null, data.toIterator)
    val expectedMap: Map[String, String] = data.toMap
    verify(mockRegion).putAll(expectedMap)
  }

  test("test GemFireNonPairRDDWriter") {
    val (regionPath, mockConnConf, mockConnection, mockRegion) = createMocks[Int, String]("test")
    val writer = new GemFireRDDWriter[String, Int, String](regionPath, mockConnConf)
    val data = List("a", "ab", "abc")
    val f: String => (Int, String) = s => (s.length, s)
    writer.write(f)(null, data.toIterator)
    val expectedMap: Map[Int, String] = data.map(f).toMap
    verify(mockRegion).putAll(expectedMap)
  }

  test("test PairRDDFunctions.saveToGemfire") {
    verifyPairRDDFunction(useOpConf = false)
  }

  test("test PairRDDFunctions.saveToGemfire w/ opConf") {
    verifyPairRDDFunction(useOpConf = true)
  }

  def verifyPairRDDFunction(useOpConf: Boolean): Unit = {
    import io.pivotal.gemfire.spark.connector._
    val (regionPath, mockConnConf, mockConnection, mockRegion) = createMocks[String, String]("test")
    val mockRDD = mock[RDD[(String, String)]]
    val mockSparkContext = mock[SparkContext]
    when(mockRDD.sparkContext).thenReturn(mockSparkContext)
    val result =
      if (useOpConf)
        mockRDD.saveToGemfire(regionPath, mockConnConf, Map(RDDSaveBatchSizePropKey -> "5000"))
      else
        mockRDD.saveToGemfire(regionPath, mockConnConf)
    verify(mockConnection, times(1)).validateRegion[String, String](regionPath)
    result === Unit
    verify(mockSparkContext, times(1)).runJob[(String, String), Unit](
      mockEq(mockRDD), mockAny[(TaskContext, Iterator[(String, String)]) => Unit])(mockAny(classOf[ClassTag[Unit]]))

    // Note: current implementation make following code not compilable
    //       so not negative test for this case
    //  val rdd: RDD[(K, V)] = ...
    //  rdd.saveToGemfire(regionPath, s => (s.length, s))
  }

  test("test RDDFunctions.saveToGemfire") {
    verifyRDDFunction(useOpConf = false)
  }

  test("test RDDFunctions.saveToGemfire w/ opConf") {
    verifyRDDFunction(useOpConf = true)
  }

  def verifyRDDFunction(useOpConf: Boolean): Unit = {
    import io.pivotal.gemfire.spark.connector._
    val (regionPath, mockConnConf, mockConnection, mockRegion) = createMocks[Int, String]("test")
    val mockRDD = mock[RDD[(String)]]
    val mockSparkContext = mock[SparkContext]
    when(mockRDD.sparkContext).thenReturn(mockSparkContext)
    val result =
      if (useOpConf)
        mockRDD.saveToGemfire(regionPath, s => (s.length, s), mockConnConf, Map(RDDSaveBatchSizePropKey -> "5000"))
      else
        mockRDD.saveToGemfire(regionPath, s => (s.length, s), mockConnConf)
    verify(mockConnection, times(1)).validateRegion[Int, String](regionPath)
    result === Unit
    verify(mockSparkContext, times(1)).runJob[String, Unit](
      mockEq(mockRDD), mockAny[(TaskContext, Iterator[String]) => Unit])(mockAny(classOf[ClassTag[Unit]]))

    // Note: current implementation make following code not compilable
    //       so not negative test for this case
    //  val rdd: RDD[T] = ...   // T is not a (K, V) tuple
    //  rdd.saveToGemfire(regionPath)
  }

}


text:
package octolink.entity;

import gameframework.base.Drawable;
import gameframework.base.DrawableImage;
import gameframework.game.GameEntity;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;

public class Path implements Terrain, Drawable, GameEntity {

	public static final int RENDERING_SIZE = 24;
	private DrawableImage image;
	protected Point position;

	public Path(Canvas defaultCanvas, Point pos) {
		image = new DrawableImage("images/path.gif", defaultCanvas);
		position = pos;
	}

	public Point getPosition() {
		return position;
	}

	@Override
	public void draw(Graphics g) {
		g.drawImage(image.getImage(), (int) getPosition().getX(),
				(int) getPosition().getY(), RENDERING_SIZE, RENDERING_SIZE,
				null);
	}

	public Rectangle getBoundingBox() {
		return (new Rectangle((int) position.getX(), (int) position.getY(),
				RENDERING_SIZE, RENDERING_SIZE));
	}

}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>What is Imagination?</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" type="text/css" href="css/main.css">

IMAGINATION EXPLAINED

-words words words words.

- Jean-Paul Sartre

-words words words words.

- 3h

-words words words words.

- 3h

-words words words words.

- Jean-Paul Sartre

-words words words words.

- Jean-Paul Sartre

<?
//HELPFUL
//http://www.emoticode.net/php/embed-tumblr-posts-into-website.html

//load the tumblr information into a variable
$xml = simplexml_load_file('http://cutleryjam.tumblr.com/api/read');
//save a path to all the posts for easy reference later
$posts = $xml->xpath("/tumblr/posts/post");
//declare an empty array for our posts
$post_array = array();

//this is some wierd php syntax
//it takes every post from our variable $posts
//and do this for each one
foreach($posts as $post) {?>

<?php if ($post['type'] == 'photo') {  ?>

    <? $postDate = date("jS D M, H:i",strtotime($post['date']));?>

    <?php $stringDate = str_replace(' ', '', $postDate);?>
	<?php $stringDate = str_replace(',', '.', $stringDate);?>

    <?php $newphotourl = $post->{'photo-url'}; ?>

    <?php echo '
'; ?>

    <? echo $postDate.'

'; ?>

    <?php $caption = $post->{'photo-caption'}; ?>
    <?php echo $caption.'
'; ?>

  <?php } ?>

<?}?>


text:
import threading

class SharedCounter:
    '''
    A counter object that can be shared by multiple threads.
    '''
    def __init__(self, initial_value = 0):
        self._value = initial_value
        self._value_lock = threading.Lock()

    def incr(self,delta=1):
        '''
	Increment the counter with locking
	'''
        with self._value_lock:
             self._value += delta

    def decr(self,delta=1):
        '''
        Decrement the counter with locking
        '''
        with self._value_lock:
             self._value -= delta

def test(c):
    for n in range(1000000):
        c.incr()
    for n in range(1000000):
        c.decr()

if __name__ == '__main__':
    c = SharedCounter()
    t1 = threading.Thread(target=test, args=(c,))
    t2 = threading.Thread(target=test, args=(c,))
    t3 = threading.Thread(target=test, args=(c,))
    t1.start()
    t2.start()
    t3.start()
    print('Running test')
    t1.join()
    t2.join()
    t3.join()

    assert c._value == 0
    print('Looks good!')


text:
Meteor.publish('presenter', function(presenterId) {
    return presenterId && Presentations.find({presenterId: presenterId});
});

Meteor.publish('viewer', function(sessionId) {
	return sessionId && Presentations.find(
		{sessionId: sessionId},
		{fields: {page: 1, sessionId: 1, realtimeUrl: 1}}
	);
});


text:
<?php

// SymfonyWebConfiguratorBundle::final.html.twig
return array (
);


text:
using System;
using System.Collections.Generic;
using SuperSocket.ClientEngine;
using WebSocket4Net;

namespace OsEngine.Market.Services
{
    public class WsSource
    {
        private WebSocket _wsClient;

        private WsSource() { }

        public WsSource(string uri)
        {
            _wsClient = new WebSocket(uri);

            _wsClient.AutoSendPingInterval = 3;
            _wsClient.EnableAutoSendPing = true;
            SubscribeEvents();
        }

        public WsSource(string uri, List<KeyValuePair<string, string>> headers)
        {
            _wsClient = new WebSocket(uri, customHeaderItems: headers);

            SubscribeEvents();
        }

        private void SubscribeEvents()
        {
            _wsClient.Opened += WsClientOnOpened;
            _wsClient.DataReceived += WsClientOnDataReceived;
            _wsClient.MessageReceived += WsClientOnMessageReceived;
            _wsClient.Error += WsClientOnError;
            _wsClient.Closed += WsClientOnClosed;
        }

        private void UnsubscribeEvents()
        {
            if (_wsClient != null)
            {
                _wsClient.Opened -= WsClientOnOpened;
                _wsClient.DataReceived -= WsClientOnDataReceived;
                _wsClient.MessageReceived -= WsClientOnMessageReceived;
                _wsClient.Error -= WsClientOnError;
                _wsClient.Closed -= WsClientOnClosed;
            }
        }

        private void WsClientOnOpened(object sender, EventArgs e)
        {
            MessageEvent?.Invoke(WsMessageType.Opened, "");
        }

        private void WsClientOnDataReceived(object sender, DataReceivedEventArgs e)
        {
            ByteDataEvent?.Invoke(WsMessageType.ByteData, e.Data);
        }

        private void WsClientOnMessageReceived(object sender, MessageReceivedEventArgs e)
        {
            MessageEvent?.Invoke(WsMessageType.StringData, e.Message);
        }

        private void WsClientOnError(object sender, ErrorEventArgs e)
        {
            MessageEvent?.Invoke(WsMessageType.Error, e.Exception.Message);
        }

        private void WsClientOnClosed(object sender, EventArgs e)
        {
            MessageEvent?.Invoke(WsMessageType.Closed, "");
        }

        public void Start()
        {
            _wsClient?.Open();
        }

        private void Stop()
        {
            _wsClient?.Close();
            UnsubscribeEvents();
        }

        public void Dispose()
        {
            Stop();
            _wsClient?.Dispose();
            _wsClient = null;
            MessageEvent?.Invoke(WsMessageType.Closed, "");
        }

        public void SendMessage(string message)
        {
            _wsClient.Send(message);
        }

        public event Action<WsMessageType, string> MessageEvent;

        public event Action<WsMessageType, byte[]> ByteDataEvent;
    }

    public enum WsMessageType
    {
        Opened,
        Closed,
        StringData,
        ByteData,
        Error
    }
}


text:
package co.com.codesoftware.beans.admin;

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

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import co.com.codesoftware.logica.UsuarioLogic;
import co.com.codesoftware.servicio.usuario.PerfilEntity;
import co.com.codesoftware.servicio.usuario.UsuarioEntity;
import co.com.codesoftware.utilities.ErrorEnum;
import co.com.codesoftware.utilities.GeneralBean;

@ManagedBean
@ViewScoped
public class PerfilesBean implements GeneralBean {

	private UsuarioEntity objetoSesion;
	private List<PerfilEntity> listaPerifiles;
	// Perfil seleccionado
	private PerfilEntity perfilSelec;
	private String[] permisosAdm;
	private String[] permisosInv;
	private String[] permisosPara;
	private String[] permisosFact;
	private List<PerfilBean> listPermAdm;
	private List<PerfilBean> listPermInv;
	private List<PerfilBean> listPermPara;
	private List<PerfilBean> listFactura;

	@PostConstruct
	public void init() {
		this.objetoSesion = (UsuarioEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
				.get("dataSession");
		try {
			UsuarioLogic objLogic = new UsuarioLogic();
			listaPerifiles = objLogic.obtenerPerfiles();
			this.perfilSelec = (PerfilEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
					.get("perfilSelected");
			if (this.perfilSelec != null) {
				this.setPermisosAplicacion();
				permisosAdm = this.perfilSelec.getPermisos().split("\\.");
				permisosInv = this.perfilSelec.getPermisos().split("\\.");
				permisosFact = this.perfilSelec.getPermisos().split("\\.");
				permisosPara = this.perfilSelec.getPermisos().split("\\.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Funcion con la cual asigno los permisos de la aplicacion
	 */
	public void setPermisosAplicacion() {
		if (listPermAdm == null) {
			listPermAdm = new ArrayList<>();
		}
		// Permisos de Administracion
		listPermAdm.add(new PerfilBean("RESOLUCION. DE FACT.", "Adm1"));
		listPermAdm.add(new PerfilBean("SEDES", "Adm2"));
		listPermAdm.add(new PerfilBean("CONTEO", "Adm3"));
		listPermAdm.add(new PerfilBean("PARAMETROS", "Adm4"));
		listPermAdm.add(new PerfilBean("USUARIOS", "Adm5"));
		listPermAdm.add(new PerfilBean("PROVEEDORES", "Adm6"));
		listPermAdm.add(new PerfilBean("CLIENTES", "Adm7"));
		listPermAdm.add(new PerfilBean("PERFILES", "Adm8"));
		listPermAdm.add(new PerfilBean("SOCIOS", "Adm9"));
		listPermAdm.add(new PerfilBean("PARAM PRODUCTOS", "Adm10"));
		// Permisos de Inventario
		if (listPermInv == null) {
			this.listPermInv = new ArrayList<>();
		}
		listPermInv.add(new PerfilBean("FACTURA DE COMPRA", "Inv1"));
		listPermInv.add(new PerfilBean("CONS. FACTURA COMPRA", "Inv2"));
		listPermInv.add(new PerfilBean("CONS. TEMP. FACTURA COMPRA", "Inv3"));
		listPermInv.add(new PerfilBean("INSERTAR PRODUCTOS", "Inv4"));
		listPermInv.add(new PerfilBean("PARAM. PRECIO", "Inv5"));
		listPermInv.add(new PerfilBean("CONSULTA GENERAL", "Inv6"));
		listPermInv.add(new PerfilBean("SOLICITUDES PROD", "Inv7"));
		listPermInv.add(new PerfilBean("CARGUE PRODUCTOS TODO", "Inv8"));
		listPermInv.add(new PerfilBean("CARGUE PRODUCTOS", "Inv9"));
		listPermInv.add(new PerfilBean("APORTES SOCIOS", "Inv10"));
		listPermInv.add(new PerfilBean("CONS PROD X SEDE", "Inv11"));
		// Permisos de parametros
		if (listPermPara == null) {
			this.listPermPara = new ArrayList<>();
		}
		listPermPara.add(new PerfilBean("ASOCIACION CATEGORIAS", "Per1"));
		listPermPara.add(new PerfilBean("ADM. PRECIOS MASIVOS", "Per2"));
		listPermPara.add(new PerfilBean("REPORTE BASICO", "Per3"));
		listPermPara.add(new PerfilBean("COMPRAS Y VENTAS", "Per4"));
		// Permisos de facturacion
		if(listFactura == null){
			this.listFactura = new ArrayList<>();
		}
		listFactura.add(new PerfilBean("NOTA CREDITO", "Fact1"));
		listFactura.add(new PerfilBean("NOTA DEBITO", "Fact2"));
		listFactura.add(new PerfilBean("ACCESO PEDIDOS", "FcCr7"));
		listFactura.add(new PerfilBean("CAMBIO PRECIO PEDIDO", "FcCr8"));
		listFactura.add(new PerfilBean("ACCESO FACTURACIÓN", "FcCr1"));
		listFactura.add(new PerfilBean("GENERAR REMISION SAFC", "FcCr13"));
		listFactura.add(new PerfilBean("COTIZACIONES", "FcCr12"));
		listFactura.add(new PerfilBean("REMISIONAR SAFC", "FcCr14"));
		listFactura.add(new PerfilBean("REMISIONES", "Fact3"));
		listFactura.add(new PerfilBean("PAGO REMISIONES", "Fact4"));
		listFactura.add(new PerfilBean("CONSULTA FACTURAS", "Fact5"));
	}

	/**
	 * Funcion con la cual obtengo los permisos y los envia a la base de datos
	 */
	public void enviarPermisos() {
		String perAdm = "";
		if ((this.permisosAdm == null || this.permisosAdm.length == 0)
				&& (this.permisosInv == null || this.permisosInv.length == 0)
				&& (this.permisosPara == null || this.permisosPara.length == 0)) {
			this.messageBean("Por Favor seleccione un permiso al menos", ErrorEnum.ERROR);
		} else {
			if (this.permisosAdm != null) {
				for (String item : this.permisosAdm) {
					perAdm += "." + item + ".";
				}
			}
			if (this.permisosInv != null) {
				for (String item : this.permisosInv) {
					perAdm += "." + item + ".";
				}
			}
			if (this.permisosPara != null) {
				for (String item : this.permisosPara) {
					perAdm += "." + item + ".";
				}
			}
			if(this.permisosFact!=null){
				for(String item : this.permisosFact){
					perAdm += "." + item +".";
				}

			}
			UsuarioLogic objLogic = new UsuarioLogic();
			this.perfilSelec.setPermisos(perAdm);
			String valida = objLogic.actualizaPerfiles(this.perfilSelec);
			if ("Ok".equalsIgnoreCase(valida)) {
				this.messageBean("Perfil actualizado correctamente", ErrorEnum.SUCCESS);
			} else {
				this.messageBean(valida, ErrorEnum.ERROR);
			}
		}
	}

	/**
	 * Funcion con la cual redirecciono a la pagina con la cual edito los
	 * perfiles
	 *
	 * @param objEntity
	 * @return
	 */
	public String actualizaPerfil(PerfilEntity objEntity) {
		String ruta = "";
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("perfilSelected", objEntity);
		ruta = "/ACTION/ADMIN/actualizarPerifl.jsf";
		return ruta;
	}

	public UsuarioEntity getObjetoSesion() {
		return objetoSesion;
	}

	public void setObjetoSesion(UsuarioEntity objetoSesion) {
		this.objetoSesion = objetoSesion;
	}

	public List<PerfilEntity> getListaPerifiles() {
		return listaPerifiles;
	}

	public void setListaPerifiles(List<PerfilEntity> listaPerifiles) {
		this.listaPerifiles = listaPerifiles;
	}

	public PerfilEntity getPerfilSelec() {
		return perfilSelec;
	}

	public void setPerfilSelec(PerfilEntity perfilSelec) {
		this.perfilSelec = perfilSelec;
	}

	public String[] getPermisosAdm() {
		return permisosAdm;
	}

	public void setPermisosAdm(String[] permisosAdm) {
		this.permisosAdm = permisosAdm;
	}

	public List<PerfilBean> getListPermAdm() {
		return listPermAdm;
	}

	public void setListPermAdm(List<PerfilBean> listPermAdm) {
		this.listPermAdm = listPermAdm;
	}

	public List<PerfilBean> getListPermInv() {
		return listPermInv;
	}

	public void setListPermInv(List<PerfilBean> listPermInv) {
		this.listPermInv = listPermInv;
	}

	public String[] getPermisosInv() {
		return permisosInv;
	}

	public void setPermisosInv(String[] permisosInv) {
		this.permisosInv = permisosInv;
	}

	public String[] getPermisosPara() {
		return permisosPara;
	}

	public void setPermisosPara(String[] permisosPara) {
		this.permisosPara = permisosPara;
	}

	public List<PerfilBean> getListPermPara() {
		return listPermPara;
	}

	public void setListPermPara(List<PerfilBean> listPermPara) {
		this.listPermPara = listPermPara;
	}

	public List<PerfilBean> getListFactura() {
		return listFactura;
	}

	public void setListFactura(List<PerfilBean> listFactura) {
		this.listFactura = listFactura;
	}

	public String[] getPermisosFact() {
		return permisosFact;
	}

	public void setPermisosFact(String[] permisosFact) {
		this.permisosFact = permisosFact;
	}

}


text:
> Java的标准库中未能提供足够的方法来操作其核心类。Apache Commons Lang 提供了这些额外的方法。
Lang provides a host of helper utilities for the java.lang API, notably String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization and System properties. Additionally it contains basic enhancements to java.util.Date and a series of utilities dedicated to help with building methods, such as hashCode, toString and equals.

* #### 1. StringUtils

##### 1.1 public static boolean isBlank(CharSequence cs):
检查字符串是否为空 --- "",null,或只存在空格
使用示例:
```java
 StringUtils.isBlank(null)      = true // null算作空
 StringUtils.isBlank("")        = true //""算作空
 StringUtils.isBlank(" ")       = true // 只存在空格也算空
 StringUtils.isBlank("bob")     = false
 StringUtils.isBlank("  bob  ") = false
 ```

##### 1.2 public static boolean isNotBlank(CharSequence cs):
与1.1用法相反,判断字符串是否为非空 --- 非"", 非null,或不只是 存在空格
 ```java
  StringUtils.isNotBlank(null)      = false
  StringUtils.isNotBlank("")        = false
  StringUtils.isNotBlank(" ")       = false
  StringUtils.isNotBlank("bob")     = true
  StringUtils.isNotBlank("  bob  ") = true
 ```

##### 1.3 public static boolean isEmpty(CharSequence cs):

检查字符串是否为空 --- "",null
使用示例:
```java
 StringUtils.isEmpty(null)      = true // null算作空
 StringUtils.isEmpty("")        = true //""算作空
 StringUtils.isEmpty(" ")       = false
 StringUtils.isEmpty("bob")     = false
 StringUtils.isEmpty("  bob  ") = false
```

##### 1.4 public static boolean isNotEmpty(CharSequence cs):
与1.3用法相反,检查字符串是否为空 --- 非"",非null.
```java
 StringUtils.isNotEmpty(null)      = false
 StringUtils.isNotEmpty("")        = false
 StringUtils.isNotEmpty(" ")       = true
 StringUtils.isNotEmpty("bob")     = true
 StringUtils.isNotEmpty("  bob  ") = true
```

##### 1.5 public static String trim(String str):
移除字符串首尾两端的空格、制表符等"空白符";
若想指定要移除的字符,请使用strip(String, String)方法
```java
 StringUtils.trim(null)          = null
 StringUtils.trim("")            = ""
 StringUtils.trim("     ")       = ""
 StringUtils.trim("abc")         = "abc"
 StringUtils.trim("    abc    ") = "abc"
```

##### 1.6 public static String trimToNull(String str):
移除字符串首尾两端的空格、制表符等"空白符"。
若trim过后该字符串成为了空字符串(""),则返回NULL;
```java
StringUtils.trimToNull(null)          = null
StringUtils.trimToNull("")            = null
StringUtils.trimToNull("     ")       = null
StringUtils.trimToNull("abc")         = "abc"
StringUtils.trimToNull("    abc    ") = "abc"
```

##### 1.7 public static String trimToEmpty(String str):
移除字符串首尾两端的空格、制表符等"空白符"。
若trim过后该字符串成为了空字符串("")或NULL,则返回空字符串("");
```java
 StringUtils.trimToEmpty(null)          = ""
 StringUtils.trimToEmpty("")            = ""
 StringUtils.trimToEmpty("     ")       = ""
 StringUtils.trimToEmpty("abc")         = "abc"
 StringUtils.trimToEmpty("    abc    ") = "abc"
```

##### 1.8 public static String chop(String str):
移除字符串中的最后一个字符。
如果字符串以"\r\n"结尾,则会将"\r\n"全部移除。
```java
 StringUtils.chop(null)          = null
 StringUtils.chop("")            = ""
 StringUtils.chop("abc \r")      = "abc "
 StringUtils.chop("abc\n")       = "abc"
 StringUtils.chop("abc\r\n")     = "abc"
 StringUtils.chop("abc")         = "ab"
 StringUtils.chop("abc\nabc")    = "abc\nab"
 StringUtils.chop("a")           = ""
 StringUtils.chop("\r")          = ""
 StringUtils.chop("\n")          = ""
 StringUtils.chop("\r\n")        = ""
 ```

##### 1.9 public static String repeat(String str,int repeat):
> str : 要复写的字符串;
repeat : 复写的次数;

复写一个字符串repeat次以形成一个新的字符串:

```java
 StringUtils.repeat(null, 2) = null
 StringUtils.repeat("", 0)   = ""
 StringUtils.repeat("", 2)   = ""
 StringUtils.repeat("a", 3)  = "aaa"
 StringUtils.repeat("ab", 2) = "abab"
 StringUtils.repeat("a", -2) = ""
 ```
##### 1.10 public static String repeat(String str,String separator,int repeat):
> str : 要复写的字符串;
separator : 分隔符;
repeat : 复写的次数;

```java
 StringUtils.repeat(null, null, 2) = null
 StringUtils.repeat(null, "x", 2)  = null
 StringUtils.repeat("", null, 0)   = ""
 StringUtils.repeat("", "", 2)     = ""
 StringUtils.repeat("", "x", 3)    = "xxx"
 StringUtils.repeat("?", ", ", 3)  = "?, ?, ?"
 ```

 ##### 1.11 public static String repeat(char ch,int repeat):
 > ch : 要复写的字符;
 repeat : 复写的次数;

 复写一个字符repeat次以形成一个新的字符串:

 ```java
 StringUtils.repeat('e', 0)  = ""
 StringUtils.repeat('e', 3)  = "eee"
 StringUtils.repeat('e', -2) = ""
  ```
##### 1.12 public static int length(CharSequence cs):
获取一个字符串的长度,若字符串为NULL,长度视作0
```java
StringUtils.length(null)  = 0
StringUtils.length("")    = 0
StringUtils.length("abc") = 3
···

##### 1.13 public static String upperCase(String str):
将一个字符串转换为大写,NULL将仍返回为NULL
···java
 StringUtils.upperCase(null)  = null
 StringUtils.upperCase("")    = ""
 StringUtils.upperCase("aBc") = "ABC"
```

##### 1.14 public static String lowerCase(String str):
将一个字符串转换为小写,NULL将仍返回为NULL
```java
  StringUtils.lowerCase(null)  = null
  StringUtils.lowerCase("")    = ""
  StringUtils.lowerCase("aBc") = "abc"
```


text:
package main

import (
	"flag"
	"fmt"
	"github.com/GeoNet/delta/meta"
	"github.com/GeoNet/kit/gloria_pb"
	"github.com/golang/protobuf/proto"
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"strings"
)

var (
	thirdPartySites = []string{"DUNT", "FALE", "LDRZ", "LYTT", "NIUM", "OUSD"}
)

func main() {

	//Meta Loading Code grabbed from rinexml
	var verbose bool
	flag.BoolVar(&verbose, "verbose", false, "make noise")

	var output string
	flag.StringVar(&output, "output", "output", "output directory")

	var network string
	flag.StringVar(&network, "network", "../../network", "base network directory")

	var install string
	flag.StringVar(&install, "install", "../../install", "base install directory")

	flag.Usage = func() {
		fmt.Fprint(os.Stderr, "\n")
		fmt.Fprint(os.Stderr, "Build a set of ProtoBuf files for Gloria from delta meta information\n")
		fmt.Fprint(os.Stderr, "\n")
		fmt.Fprint(os.Stderr, "Usage:\n")
		fmt.Fprint(os.Stderr, "\n")
		fmt.Fprintf(os.Stderr, "  %s [options]\n", os.Args[0])
		fmt.Fprint(os.Stderr, "\n")
		fmt.Fprint(os.Stderr, "Options:\n")
		fmt.Fprint(os.Stderr, "\n")
		flag.PrintDefaults()
		fmt.Fprint(os.Stderr, "\n")
	}

	flag.Parse()

	var firmwareHistoryList meta.FirmwareHistoryList
	if err := meta.LoadList(filepath.Join(install, "firmware.csv"), &firmwareHistoryList); err != nil {
		fmt.Fprintf(os.Stderr, "error: unable to load firmware history: %v\n", err)
		os.Exit(-1)
	}

	firmwareHistory := make(map[string]map[string][]meta.FirmwareHistory)
	for _, i := range firmwareHistoryList {
		if _, ok := firmwareHistory[i.Model]; !ok {
			firmwareHistory[i.Model] = make(map[string][]meta.FirmwareHistory)
		}
		firmwareHistory[i.Model][i.Serial] = append(firmwareHistory[i.Model][i.Serial], i)
	}

	for j := range firmwareHistory {
		for k := range firmwareHistory[j] {
			sort.Sort(meta.FirmwareHistoryList(firmwareHistory[j][k]))
		}
	}

	var installedAntennaList meta.InstalledAntennaList
	if err := meta.LoadList(filepath.Join(install, "antennas.csv"), &installedAntennaList); err != nil {
		fmt.Fprintf(os.Stderr, "error: unable to load antenna installs: %v\n", err)
		os.Exit(-1)
	}

	installedAntenna := make(map[string][]meta.InstalledAntenna)
	for _, i := range installedAntennaList {
		installedAntenna[i.Mark] = append(installedAntenna[i.Mark], i)
	}
	for i := range installedAntenna {
		sort.Sort(sort.Reverse(meta.InstalledAntennaList(installedAntenna[i])))
	}

	var deployedReceiverList meta.DeployedReceiverList
	if err := meta.LoadList(filepath.Join(install, "receivers.csv"), &deployedReceiverList); err != nil {
		fmt.Fprintf(os.Stderr, "error: unable to load receiver installs: %v\n", err)
		os.Exit(-1)
	}

	deployedReceivers := make(map[string][]meta.DeployedReceiver)
	for _, i := range deployedReceiverList {
		deployedReceivers[i.Mark] = append(deployedReceivers[i.Mark], i)
	}
	for i := range deployedReceivers {
		sort.Sort(sort.Reverse(meta.DeployedReceiverList(deployedReceivers[i])))
	}

	var installedRadomeList meta.InstalledRadomeList
	if err := meta.LoadList(filepath.Join(install, "radomes.csv"), &installedRadomeList); err != nil {
		fmt.Fprintf(os.Stderr, "error: unable to load radome installs: %v\n", err)
		os.Exit(-1)
	}

	installedRadomes := make(map[string][]meta.InstalledRadome)
	for _, i := range installedRadomeList {
		installedRadomes[i.Mark] = append(installedRadomes[i.Mark], i)
	}
	for i := range installedRadomes {
		sort.Sort(meta.InstalledRadomeList(installedRadomes[i]))
	}

	var markList meta.MarkList
	if err := meta.LoadList(filepath.Join(network, "marks.csv"), &markList); err != nil {
		fmt.Fprintf(os.Stderr, "error: unable to load mark list: %v\n", err)
		os.Exit(-1)
	}

	var monumentList meta.MonumentList
	if err := meta.LoadList(filepath.Join(network, "monuments.csv"), &monumentList); err != nil {
		fmt.Fprintf(os.Stderr, "error: unable to load monuments list: %v\n", err)
		os.Exit(-1)
	}
	monuments := make(map[string]meta.Monument)
	for _, m := range monumentList {
		monuments[m.Mark] = m
	}

	var marks = gloria_pb.Marks{Marks: make(map[string]*gloria_pb.Mark)}

	for _, m := range markList {

		mark_pb := gloria_pb.Mark{
			Code: m.Code,
			Point: &gloria_pb.Point{
				Latitude:  m.Latitude,
				Longitude: m.Longitude,
				Elevation: m.Elevation,
			},
			DomesNumber:      monuments[m.Code].DomesNumber,
			DeployedReceiver: make([]*gloria_pb.DeployedReceiver, 0),
			InstalledAntenna: make([]*gloria_pb.InstalledAntenna, 0),
			InstalledRadome:  make([]*gloria_pb.InstalledRadome, 0),
			Span: &gloria_pb.Span{
				Start: m.Start.Unix(),
				End:   m.End.Unix(),
			},
		}

		// Higher download priority marks are scheduled for download first.
		// Download rate can be restricted here as well.
		switch {
		case m.Igs:
			mark_pb.Download = &gloria_pb.Download{Priority: 1000}
			mark_pb.Distribution = &gloria_pb.Distribution{Igs: true}
		case m.Network == "LI":
			mark_pb.Download = &gloria_pb.Download{Priority: 100}
			mark_pb.Distribution = &gloria_pb.Distribution{Linz: true}
		default:
			mark_pb.Download = &gloria_pb.Download{Priority: 0}
		}

		if m.Code == "SBAM" || m.Code == "SCTB" || m.Code == "AHAM" { // scott base sites
			mark_pb.Download.Rate = 1024 // Rate unit is bytes per second
		}

		for _, tps := range thirdPartySites {
			if tps == m.Code {
				mark_pb.Download.ThirdParty = true
			}
		}

		if m.Network == "LI" {
			mark_pb.Comment = `This station is part of the LINZ PositioNZ and GeoNet
cGNSS networks and is jointly funded by Land Information
New Zealand and GNS Science. This data is licenced for
re-use under the Creative Commons Attribution 4.0
International licence. For more detail please refer
to https://www.linz.govt.nz/linz-copyright`

		} else {
			mark_pb.Comment = `These data are supplied by GeoNet. GeoNet is core
funded by EQC, LINZ and MBIE and is operated by
GNS Science on behalf of stakeholders and all New
Zealanders. The data policy, disclaimer, licence and
contact information can be found at www.geonet.org.nz`

		}

		recList := deployedReceivers[m.Code]
		for _, rec := range recList {
			rec_pb := gloria_pb.DeployedReceiver{
				Receiver: &gloria_pb.Receiver{
					Model:        rec.Model,
					SerialNumber: rec.Serial,
					Firmware:     make([]*gloria_pb.Firmware, 0),
				},
				Span: &gloria_pb.Span{
					Start: rec.Start.Unix(),
					End:   rec.End.Unix(),
				},
			}

			firmList := firmwareHistory[rec.Model][rec.Serial]
			for _, firm := range firmList {
				firm_pb := gloria_pb.Firmware{
					Version: firm.Version,
					Span: &gloria_pb.Span{
						Start: firm.Start.Unix(),
						End:   firm.End.Unix(),
					},
				}
				rec_pb.Receiver.Firmware = append(rec_pb.Receiver.Firmware, &firm_pb)
			}
			mark_pb.DeployedReceiver = append(mark_pb.DeployedReceiver, &rec_pb)
		}

		antList := installedAntenna[m.Code]
		for _, ant := range antList {
			ant_pb := gloria_pb.InstalledAntenna{
				Antenna: &gloria_pb.Antenna{
					Model:        ant.Model,
					SerialNumber: ant.Serial,
				},
				Offset: &gloria_pb.Offset{
					Vertical: ant.Vertical,
					North:    ant.North,
					East:     ant.East,
				},
				Span: &gloria_pb.Span{
					Start: ant.Start.Unix(),
					End:   ant.End.Unix(),
				},
			}
			mark_pb.InstalledAntenna = append(mark_pb.InstalledAntenna, &ant_pb)
		}

		radList := installedRadomes[m.Code]
		for _, rad := range radList {
			rad_pb := gloria_pb.InstalledRadome{
				Radome: &gloria_pb.Radome{
					Model: rad.Model,
				},
				Span: &gloria_pb.Span{
					Start: rad.Start.Unix(),
					End:   rad.End.Unix(),
				},
			}
			mark_pb.InstalledRadome = append(mark_pb.InstalledRadome, &rad_pb)
		}

		b, err := proto.Marshal(&mark_pb)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: unable to marsh xml: %v\n", err)
			os.Exit(-1)
		}

		pbfile := filepath.Join(output, strings.ToLower(m.Code)+".pb")
		if err := os.MkdirAll(filepath.Dir(pbfile), 0755); err != nil {
			fmt.Fprintf(os.Stderr, "error: unable to create dir: %v\n", err)
			os.Exit(-1)
		}
		if err := ioutil.WriteFile(pbfile, b, 0644); err != nil {
			fmt.Fprintf(os.Stderr, "error: unable to write file: %v\n", err)
			os.Exit(-1)
		}

		marks.Marks[m.Code] = &mark_pb
	}

	b, err := proto.Marshal(&marks)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: unable to marshal marks index protobuf: %v\n", err)
		os.Exit(-1)
	}
	if err := ioutil.WriteFile(filepath.Join(output, "mark-index.pb"), b, 0644); err != nil {
		fmt.Fprintf(os.Stderr, "error: unable to write file: %v\n", err)
		os.Exit(-1)
	}
}


text:
Are you sure you want to delete this article ?

		{{article.data.title}}

<button class="btn btn-primary" ng-click="article.ok()">OK</button>
<button class="btn btn-warning" ng-click="article.cancel()">Cancel</button>


text:
package com.android21buttons.fragmenttestrule;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

public class FragmentTestRuleTest {

    @Test
    public void createFragment() throws Exception {
        FragmentTestRule<?, Fragment> testRule = new FragmentTestRule<>(FragmentActivity.class, Fragment.class);

        assertThat(testRule.createFragment(), is(notNullValue()));
    }

    @Test
    public void getFragmentNoCreate() throws Exception {
        FragmentTestRule<?, Fragment> testRule = new FragmentTestRule<>(FragmentActivity.class, Fragment.class);

        assertThat(testRule.getFragment(), is(nullValue()));
    }
}


text:
@implementation UIImage (Image)

+(instancetype)originalImagewithName:(NSString *)name{
    UIImage *image = [UIImage imageNamed:name];
    return  [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

-(instancetype)cicrleImage{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    [path addClip];
    [self drawAtPoint:CGPointZero];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return  image;
}
@end


text:
@interface MLFeedCell ()
@property (weak, nonatomic) IBOutlet UILabel *title;
@property (weak, nonatomic) IBOutlet UILabel *content;
@property (weak, nonatomic) IBOutlet UIImageView *map;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *date;

@end
@implementation MLFeedCell

- (void)awakeFromNib {
    // Initialization code
}

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

    // Configure the view for the selected state
}
- (void)setFeedEntity:(MLFeedEntity *)feedEntity {
    _feedEntity = feedEntity;
    _title.text = _feedEntity.title;
    _content.text = _feedEntity.content;
    _map.image = [UIImage imageNamed:_feedEntity.imageName];
    [_map sizeToFit];
    _name.text = _feedEntity.username;
    _date.text = _feedEntity.time;
}

@end


text:
@implementation ScenarioTestCase

+ (id)defaultTestSuite
{
    NSString* selfClassName = NSStringFromClass(self);
    if ([selfClassName isEqualToString:@"ScenarioTestCase"] || [selfClassName isEqualToString:@"SwiftBehaveTest"]) {
        // don't execute swift-behave framework test classes
        return nil;
    }

    XCTestSuite* suite = [[XCTestSuite alloc] initWithName:NSStringFromClass(self)];
    for (Scenario* scenario in [self scenarios]) {
        [self addScenarioWithName:scenario.scenarioName steps:scenario.steps environment:scenario.environment testSuite:suite];
    }
    return suite;
}

+ (NSArray*)scenarios
{
    return @[];
}

+ (void)addScenarioWithName:(NSString*)scenarioName steps:(NSArray*)steps environment:(NSDictionary<NSString*,NSString*>* _Nonnull)environment testSuite:(XCTestSuite*)suite
{
    for (NSInvocation* invocation in [self testInvocations]) {

        // here goes the tricky part: replace the selector within the invocation
        // with a newly created instance method with a name derived from the
        // scenario name.
        SEL selector = [self addInstanceMethodForScenario:scenarioName];
        invocation.selector = selector;

        XCTestCase* test = [[self alloc] initWithInvocation:invocation name:scenarioName steps:steps environment:environment];
        [suite addTest:test];
    }
}

+ (NSString*)storyfile
{
    // must be overriden in concrete swift-behave sub classes
    return @"OVERRIDE";
}

- (instancetype)initWithInvocation:(NSInvocation*)invocation name:(NSString*)scenarioName steps:(NSArray*)steps environment:(NSDictionary*)environment
{
    self = [super initWithInvocation:invocation];
    if (self) {
        _scenarioName = scenarioName;
        _steps = steps;
        _environment = environment;
    }

    return self;
}

+ (SEL)addInstanceMethodForScenario:(NSString*)scenarioName
{
    IMP implementation = imp_implementationWithBlock(^(ScenarioTestCase* self) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self performSelector:NSSelectorFromString(@"testScenario")];
#pragma clang diagnostic pop
    });

    NSArray* selectorComponents = [scenarioName componentsSeparatedByString:@" "];
    NSString* selectorName = [selectorComponents componentsJoinedByString:@"_"];

    SEL selector = NSSelectorFromString(selectorName);
    const char* types = [@"v@:" UTF8String];
    class_addMethod(self, selector, implementation, types);
    return selector;
}

@end


text:
Model attributes are basic pieces of information about a model.  For example, a model called `Person` might have attributes named `firstName`, `lastName`, `phoneNumber`, `age`, `birthDate` and `emailAddress`.

<!---
FUTURE: address sql vs. no sql and stuff like:
"""
In most cases, this data is _homogenous_, meaning each record has the same attributes,
"""
-->

### Defining attributes

A model's `attributes` [setting](https://sailsjs.com/documentation/concepts/models-and-orm/model-settings) allows you to provide a set of attributes, each defined as a dictionary (a plain JavaScript object):

```javascript
// api/models/User.js
{
  attributes: {
    emailAddress: { type: 'string', required: true, },
    karma: { type: 'number', },
    isSubscribedToNewsletter: { type: 'boolean', defaultsTo: true, },
  },
}
```

Within each attribute, there are one or more keys—or options—which are used to provide additional direction to Sails and Waterline.  These attribute keys tell the model how to go about ensuring type safety, enforcing high-level validation rules, and (if you have automigrations enabled) how it should go about setting up tables or collections in your database.

##### Default attributes

You can also define default attributes that will appear in _all_ of your models, by defining `attributes` as a [default model setting](https://sailsjs.com/documentation/concepts/models-and-orm/model-settings) (e.g. in `config/models.js`).  For example, new Sails apps come with three default attributes out of the box: `id`, `createdAt`, and `updatedAt`.

These attributes will be available in all models unless they are overridden or disabled.  To override a default attribute, define an attribute with the same name in the model definition.  To _disable_ a default attribute, define it as `false`.  For instance, to disable the default `updatedAt` attribute for a particular model:

```javascript
// api/models/ProductCategory.js
module.exports = {
  attributes: {
    updatedAt: false,
    label: { type: 'string', required: true },
  }
}
```

### Type safety

##### Type

Except for [associations](https://sailsjs.com/documentation/concepts/models-and-orm/associations), every attribute must declare a `type`.

This is the type of data that will be stored for this attribute and used for logical type safety checks of queries and results.  Here is a list of the data types supported by Sails and Waterline:

- string
- number
- boolean
- json
- ref

##### Required

If an attribute is `required: true`, then a value must always be specified for it when calling `.create()`.  This prevents the attribute value from being created as or updated to `null` or empty string ("").

##### Default values

In addition to the five data types, there are a couple of other basic guarantees that you can define for an attribute; one of these is the ability to assign it a default value.

The default value (`defaultsTo`) of an attribute only applies on `.create()`, and only when the key is omitted entirely.

```javascript
attributes: {
  phoneNumber: {
    type: 'string',
    defaultsTo: '111-222-3333'
  }
}
```

##### Allow Null

The `string`, `number`, and `boolean` data types do _not_ accept `null` as a value when creating or updating records.  In order to allow a `null` value to be set, you can toggle the `allowNull` flag on the attribute. Note that the `allowNull` flag is only valid on the data types listed above. It is _not_ valid on attributes with types `json` or `ref`, any associations, or any primary key attributes.

```javascript
attributes: {
  phoneNumber: {
    type: 'string',
    allowNull: true
  }
}
```

### Validations

In addition to basic type safety checks, Sails offers several different high-level validation rules.  For example, the `isIn` rule verifies that any new value stored for this attribute must _exactly match_ one of a few different hard-coded constants:

```javascript
unsubscribeReason: {
  type: 'string',
  isIn: ['boring', 'too many emails', 'recipes too difficult', 'other'],
  required: true
}
```

For a complete list of high-level validation rules, see [Validations](https://sailsjs.com/documentation/concepts/models-and-orm/validations).

<!--

FUTURE: need ot move primary key out to the top-level (it's a model setting now)

commented-out content at: https://gist.github.com/rachaelshaw/f10d70c73780d5087d4c936cdefd5648#1
-->

### columnName

Inside an attribute definition, you can specify a `columnName` to force Sails/Waterline to store data for that attribute in a specific column in the configured datastore (i.e. database).  Be aware that this is not necessarily SQL-specific—it will also work for MongoDB fields, etc.

While the `columnName` property is primarily designed for working with existing/legacy databases, it can also be useful in situations where your database is being shared by other applications, or those in which you don't have access permissions to change the schema.

To store/fetch your model's `numberOfWheels` attribute into/from the `number_of_round_rotating_things` column:
```javascript
  // An attribute in one of your models:
  // ...
  numberOfWheels: {
    type: 'number',
    columnName: 'number_of_round_rotating_things'
  }
  // ...
```

Now for a more comprehensive example.

Let's say you have a `User` model in your Sails app that looks like this:

```javascript
// api/models/User.js
module.exports = {
  datastore: 'shinyNewMySQLDatabase',
  attributes: {
    name: {
      type: 'string'
    },
    password: {
      type: 'string'
    },
    email: {
      type: 'string',
      unique: true
    }
  }
};
```

Everything works great, but instead of using an existing MySQL database sitting on a server somewhere that happens to house your app's intended users...

```javascript
// config/datastores.js
module.exports = {
  // ...

  // Existing users are in here!
  rustyOldMySQLDatabase: {
    adapter: 'sails-mysql',
    url: 'mysql://ofh:Gh19R!?@db.eleven.sameness.foo/jonas'
  },
  // ...
};
```

... let's say there's a table called `our_users` in the old MySQL database that looks like this:

| the_primary_key | email_address | full_name | seriously_hashed_password|
|------|---|----|---|
| 7 | mike@sameness.foo | Mike McNeil | ranchdressing |
| 14 | nick@sameness.foo | Nick Crumrine | thousandisland |

In order to use this from Sails, you'd change your `User` model to look like this:

```javascript
// api/models/User.js
module.exports = {
  datastore: 'rustyOldMySQLDatabase',
  tableName: 'our_users',
  attributes: {
    id: {
      type: 'number',
      unique: true,
      columnName: 'the_primary_key'
    },
    name: {
      type: 'string',
      columnName: 'full_name'
    },
    password: {
      type: 'string',
      columnName: 'seriously_hashed_password'
    },
    email: {
      type: 'string',
      unique: true,
      columnName: 'email_address'
    }
  }
};
```

> You might have noticed that we also used the [`tableName`](https://sailsjs.com/documentation/concepts/models-and-orm/model-settings#?tablename) property in this example.  This allows us to control the name of the table that will be used to house our data.

### Encryption at rest

##### encrypt

Setting `encrypt` allows you to decide whether this attribute should be automatically encrypted. If set to `true`, when a record is retrieved, it will still contain the encrypted value for this attribute unless [`.decrypt()`](https://sailsjs.com/documentation/reference/waterline-orm/queries/decrypt) is used.

```javascript
attributes: {
  ssn: {
    type: 'string',
    encrypt: true
  }
}
```
> If you're using `encrypt: true` for an attribute, you won't be able to look up records by the unencrypted value.

### Automigrations

These settings are used to indicate how Sails should create the physical-level (e.g. PostgreSQL, MySQL or MongoDB) database field for an attribute when an app is lifted.

> When a model’s `migrate` property is set to `safe`, these settings will be ignored and the database columns will remain unchanged.

##### columnType

Indicates the type of physical-level column data type to use for an attribute when Sails creates the database table. This allows you to specify types that are tied directly to how your underlying database will create them. For example, you may have an attribute that sets its `type` property to `number` and to store that in the database you want to use the column type `float`. Your attribute definition would look like:

```javascript
attributes: {
  placeInLine: {
    type: 'number',
    columnType: 'float'
  }
}
```

> * Column types are entirely database-dependent.  Be sure that the `columnType` you select corresponds to a data type that is valid for your database!  If you don’t specify a `columnType`, the adapter will choose one for you based on the attribute’s `type`.
> * The `columnType` value is used verbatim in the statement that creates the database column, so you can use it to specify additional options, e.g. `varchar(255) CHARACTER SET utf8mb4`.
> * If you intend to store binary data in a Sails model, you’ll want to set the `type` of the attribute to `ref`, and then use the appropriate `columnType` for your chosen database (e.g. `mediumblob` for MySQL or `bytea` for PostgreSQL).  Keep in mind that whatever you attempt to store will have to fit in memory before being transferred to the database, as there is currently no mechanism in Sails for streaming binary data to a datastore adapter.  As an alternative to storing blobs in a database, you might consider streaming them to disk or to a remote filesystem like S3, using the [`.upload()` method](https://sailsjs.com/documentation/concepts/file-uploads).
> * Keep in mind that custom column options like `CHARACTER SET utf8mb4` in MySQL can affect a column’s storage size. This is especially relevant when used in conjunction with the `unique` property, where you may have to specify a smaller column size to avoid errors.  See the [`unique` property](https://sailsjs.com/documentation/concepts/models-and-orm/attributes#?unique) docs below for more info.

##### autoIncrement

Sets up the attribute as an auto-increment key.  When a new record is added to the model, if a value for this attribute is not specified, it will be generated by incrementing the most recent record's value by one. Note: attributes that specify `autoIncrement` should always be of `type: 'number'`. Also bear in mind that the level of support varies across different datastores. For instance, MySQL will not allow more than one auto-incrementing column per table.

```javascript
attributes: {
  placeInLine: {
    type: 'number',
    autoIncrement: true
  }
}
```

##### unique

Ensures no two records will be allowed with the same value for the target attribute. This is an adapter-level constraint, so in most cases this will result in a unique index on the attribute being created in the underlying datastore.

```javascript
attributes: {
  username: {
    type: 'string',
    unique: true
  }
}
```

Depending on your database, when using `unique: true`, you may also need set `required: true`.

> When using `unique: true` on an attribute with the `utf8mb4` character set in a MySQL database, you will need to set the column size manually via the [`columnType` property](https://sailsjs.com/documentation/concepts/models-and-orm/attributes#?columntype) to avoid a possible 'index too long' error.  For example: `columnType: varchar(100) CHARACTER SET utf8mb4`.

<!--

commented-out content at: https://gist.github.com/rachaelshaw/f10d70c73780d5087d4c936cdefd5648#2

commented-out content at: https://gist.github.com/rachaelshaw/f10d70c73780d5087d4c936cdefd5648#3

FUTURE: move enum to validations page

commented-out content at: https://gist.github.com/rachaelshaw/f10d70c73780d5087d4c936cdefd5648#4

commented-out content at: https://gist.github.com/rachaelshaw/f10d70c73780d5087d4c936cdefd5648#5

-->

<docmeta name="displayName" value="Attributes">


text:
package org.apache.log4j.jmx;

//import java.lang.reflect.Constructor;
import java.util.Iterator;
import javax.management.DynamicMBean;
import javax.management.AttributeList;
import javax.management.Attribute;
import javax.management.RuntimeOperationsException;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.log4j.Logger;

public abstract class AbstractDynamicMBean implements DynamicMBean,
                                                      MBeanRegistration {

  String dClassName;
  MBeanServer server;

  /**
   * Enables the to get the values of several attributes of the Dynamic MBean.
   */
  public
  AttributeList getAttributes(String[] attributeNames) {

    // Check attributeNames is not null to avoid NullPointerException later on
    if (attributeNames == null) {
      throw new RuntimeOperationsException(
			   new IllegalArgumentException("attributeNames[] cannot be null"),
			   "Cannot invoke a getter of " + dClassName);
    }

    AttributeList resultList = new AttributeList();

    // if attributeNames is empty, return an empty result list
    if (attributeNames.length == 0)
      return resultList;

    // build the result attribute list
    for (int i=0 ; i<attributeNames.length ; i++){
      try {
	Object value = getAttribute((String) attributeNames[i]);
	resultList.add(new Attribute(attributeNames[i],value));
      } catch (Exception e) {
	e.printStackTrace();
      }
    }
    return(resultList);
  }

  /**
   * Sets the values of several attributes of the Dynamic MBean, and returns the
   * list of attributes that have been set.
   */
  public AttributeList setAttributes(AttributeList attributes) {

    // Check attributes is not null to avoid NullPointerException later on
    if (attributes == null) {
      throw new RuntimeOperationsException(
                    new IllegalArgumentException("AttributeList attributes cannot be null"),
		    "Cannot invoke a setter of " + dClassName);
    }
    AttributeList resultList = new AttributeList();

    // if attributeNames is empty, nothing more to do
    if (attributes.isEmpty())
      return resultList;

    // for each attribute, try to set it and add to the result list if successfull
    for (Iterator i = attributes.iterator(); i.hasNext();) {
      Attribute attr = (Attribute) i.next();
      try {
	setAttribute(attr);
	String name = attr.getName();
	Object value = getAttribute(name);
	resultList.add(new Attribute(name,value));
      } catch(Exception e) {
	e.printStackTrace();
      }
    }
    return(resultList);
  }

  protected
  abstract
  Logger getLogger();

  public
  void postDeregister() {
    getLogger().debug("postDeregister is called.");
  }

  public
  void postRegister(java.lang.Boolean registrationDone) {
  }

  public
  void preDeregister() {
    getLogger().debug("preDeregister called.");
  }

  public
  ObjectName preRegister(MBeanServer server, ObjectName name) {
    getLogger().debug("preRegister called. Server="+server+ ", name="+name);
    this.server = server;
    return name;
  }

}


text:
/* ===========================================================
 * trumbowyg.upload.js v1.2
 * Upload plugin for Trumbowyg
 * http://alex-d.github.com/Trumbowyg
 * ===========================================================
 * Author : Alexandre Demode (Alex-D)
 *          Twitter : @AlexandreDemode
 *          Website : alex-d.fr
 * Mod by : Aleksandr-ru
 *          Twitter : @Aleksandr_ru
 *          Website : aleksandr.ru
 */

(function ($) {
    'use strict';
    //console.log(window.location.origin);
    var defaultOptions = {
        serverPath: "procMedia",
        fileFieldName: 'fileToUpload',
        data: [],
        headers: {},
        xhrFields: {},
        urlPropertyName: 'file',
        statusPropertyName: 'success',
        success: undefined,
        error: undefined
    };

    function getDeep(object, propertyParts) {
        var mainProperty = propertyParts.shift(),
            otherProperties = propertyParts;

        if (object !== null) {
            if (otherProperties.length === 0) {
                return object[mainProperty];
            }

            if (typeof object === 'object') {
                return getDeep(object[mainProperty], otherProperties);
            }
        }
        return object;
    }

    addXhrProgressEvent();

    $.extend(true, $.trumbowyg, {
        langs: {
            // jshint camelcase:false
            en: {
                upload: 'Upload',
                file: 'File',
                uploadError: 'Error'
            },
            sk: {
                upload: 'Nahrať',
                file: 'Súbor',
                uploadError: 'Chyba'
            },
            fr: {
                upload: 'Envoi',
                file: 'Fichier',
                uploadError: 'Erreur'
            },
            cs: {
                upload: 'Nahrát obrázek',
                file: 'Soubor',
                uploadError: 'Chyba'
            },
            zh_cn: {
                upload: '上传',
                file: '文件',
                uploadError: '错误'
            },
            ru: {
                upload: 'Загрузка',
                file: 'Файл',
                uploadError: 'Ошибка'
            }
        },
        // jshint camelcase:true

        plugins: {
            upload: {
                init: function (trumbowyg) {
                    trumbowyg.o.plugins.upload = $.extend(true, {}, defaultOptions, trumbowyg.o.plugins.upload || {});
                    var btnDef = {
                        fn: function () {
                            trumbowyg.saveRange();

                            var file,
                                prefix = trumbowyg.o.prefix;

                            var $modal = trumbowyg.openModalInsert(
                                // Title
                                trumbowyg.lang.upload,

                                // Fields
                                {
                                    file: {
                                        type: 'file',
                                        required: true,
                                        attributes: {
                                            accept: 'image/*'
                                        }
                                    },
                                    alt: {
                                        label: 'description',
                                        value: trumbowyg.getRangeText()
                                    }
                                },

                                // Callback
                                function (values) {
                                    var data = new FormData();
                                    data.append(trumbowyg.o.plugins.upload.fileFieldName, file);

                                    trumbowyg.o.plugins.upload.data.map(function (cur) {
                                        data.append(cur.name, cur.value);
                                    });

                                    if ($('.' + prefix + 'progress', $modal).length === 0) {
                                        $('.' + prefix + 'modal-title', $modal)
                                            .after(
                                                $('<div/>', {
                                                    'class': prefix + 'progress'
                                                }).append(
                                                    $('<div/>', {
                                                        'class': prefix + 'progress-bar'
                                                    })
                                                )
                                            );
                                    }

                                    $.ajax({
                                        url: trumbowyg.o.plugins.upload.serverPath,
                                        headers: trumbowyg.o.plugins.upload.headers,
                                        xhrFields: trumbowyg.o.plugins.upload.xhrFields,
                                        type: 'POST',
                                        data: data,
                                        cache: false,
                                        dataType: 'json',
                                        processData: false,
                                        contentType: false,

                                        progressUpload: function (e) {
                                            $('.' + prefix + 'progress-bar').stop().animate({
                                                width: Math.round(e.loaded * 100 / e.total) + '%'
                                            }, 200);
                                        },

                                        success: function (data) {
                                            if (trumbowyg.o.plugins.upload.success) {
                                                trumbowyg.o.plugins.upload.success(data, trumbowyg, $modal, values);
                                            } else {
                                                if (!!getDeep(data, trumbowyg.o.plugins.upload.statusPropertyName.split('.'))) {
                                                    var url = getDeep(data, trumbowyg.o.plugins.upload.urlPropertyName.split('.'));
                                                    trumbowyg.execCmd('insertImage', url);
                                                    $('img[src="' + url + '"]:not([alt])', trumbowyg.$box).attr('alt', values.alt);
                                                    setTimeout(function () {
                                                        trumbowyg.closeModal();
                                                    }, 250);
                                                    trumbowyg.$c.trigger('tbwuploadsuccess', [trumbowyg, data, url]);
                                                } else {
                                                    trumbowyg.addErrorOnModalField(
                                                        $('input[type=file]', $modal),
                                                        trumbowyg.lang[data.message]
                                                    );
                                                    trumbowyg.$c.trigger('tbwuploaderror', [trumbowyg, data]);
                                                }
                                            }
                                        },

                                        error: trumbowyg.o.plugins.upload.error || function () {
                                            trumbowyg.addErrorOnModalField(
                                                $('input[type=file]', $modal),
                                                trumbowyg.lang.uploadError
                                            );
                                            trumbowyg.$c.trigger('tbwuploaderror', [trumbowyg]);
                                        }
                                    });
                                }
                            );

                            $('input[type=file]').on('change', function (e) {
                                try {
                                    // If multiple files allowed, we just get the first.
                                    file = e.target.files[0];
                                } catch (err) {
                                    // In IE8, multiple files not allowed
                                    file = e.target.value;
                                }
                            });
                        }
                    };

                    trumbowyg.addBtnDef('upload', btnDef);
                }
            }
        }
    });

    function addXhrProgressEvent() {
        if (!$.trumbowyg && !$.trumbowyg.addedXhrProgressEvent) {   // Avoid adding progress event multiple times
            var originalXhr = $.ajaxSettings.xhr;
            $.ajaxSetup({
                xhr: function () {
                    var req = originalXhr(),
                        that = this;
                    if (req && typeof req.upload === 'object' && that.progressUpload !== undefined) {
                        req.upload.addEventListener('progress', function (e) {
                            that.progressUpload(e);
                        }, false);
                    }

                    return req;
                }
            });
            $.trumbowyg.addedXhrProgressEvent = true;
        }
    }
})(jQuery);


text:
from random import choice
from django.shortcuts import redirect

paises = ['Colombia', 'Peru', 'Mexico']

def de_donde_vengo(request):
    return choice(paises)

class PaisMiddleware():
    def process_request(self, request):
	pais = de_donde_vengo(request)
	if pais == 'Mexico':
	    return redirect('http://localhost:8000/tracks/Debaser/')