text:
/* global window, localStorage */
/* eslint no-underscore-dangle: 0 */
import Graphics from '../common/Graphics';
import Entity from './Entity';
import DataObject from '../model/DataObject';
import EnergyShield from './misc/EnergyShield';
import JetEngine from './misc/JetEngine';
import QuadTree from '../common/QuadTree';
import EventEmitter from '../sync/EventEmitter';
import Util from '../common/Util';
import {
  GROUP_EFFECTS,
  GROUP_ENTITIES,
  GROUP_ENTITIES_BUILDINGS,
} from '../common/Const';

const ns = window.fivenations;

let phaserGame;
let singleton;

const entities = [];

/**
 * Creates a function that can be used to filter entities
 * @param {array} entities Array of entities the can be filtered further
 * @return {function}
 */
function createSelector(targetEntities) {
  const playerRegExp = /:player\(([1-9+])\)/;
  /**
   * returns array of entities with the exposing the activity API against them
   * @param {mixed}
   * @return {array} [Array of entities]
   */
  return function $(filter) {
    let targets;

    if (typeof filter === 'function') {
      targets = targetEntities.filter(filter);
    } else if (typeof filter === 'string') {
      if (filter === ':selected') {
        targets = targetEntities.filter(entity => entity.isSelected());
      } else if (filter === ':not(hibernated)') {
        targets = targetEntities.filter(entity => !entity.isHibernated());
      } else if (filter === ':user') {
        targets = targetEntities.filter(entity =>
          entity.isEntityControlledByUser());
      } else if (filter === ':user:selected') {
        targets = targetEntities.filter((entity) => {
          if (!entity.isEntityControlledByUser()) return false;
          if (!entity.isSelected()) return false;
          if (entity.hasNoUserControl()) return false;
          return true;
        });
      } else if (filter === ':user:selected:not(building)') {
        targets = targetEntities.filter((entity) => {
          if (!entity.isEntityControlledByUser()) return false;
          if (!entity.isSelected()) return false;
          if (entity.hasNoUserControl()) return false;
          if (entity.getDataObject().isBuilding()) return false;
          return true;
        });
      } else if (playerRegExp.test(filter)) {
        const playerId = parseInt(filter.match(playerRegExp)[1], 10);
        targets = targetEntities.filter((entity) => {
          if (entity.getDataObject().getTeam() !== playerId) return false;
          return true;
        });
      } else {
        targets = targetEntities.filter(entity => entity.getGUID() === filter);
        return targets[0];
      }
    } else if (typeof filter === 'object') {
      targets = filter;
    } else {
      targets = targetEntities;
    }

    return [].concat.call(targets);
  };
}

function EntityManager() {
  if (!phaserGame) {
    throw new Error('Invoke setGame first to pass the Phaser Game entity!');
  }

  this.entityGroup = Graphics.getInstance().getGroup(GROUP_ENTITIES);
  this.entityBuildingGroup = Graphics.getInstance().getGroup(GROUP_ENTITIES_BUILDINGS);
  this.effectGroup = Graphics.getInstance().getGroup(GROUP_EFFECTS);

  this.updateEntityDistancesOptimised = Util.interval(
    this.updateEntityDistances,
    100,
    this,
  );
}

EntityManager.prototype = {
  /**
   * Adds an entity object to the private collection
   * @param {object} config configuration object
   */
  add(config) {
    if (!config) {
      throw new Error('Invalid configuration object passed as a parameter!');
    }

    if (Object.keys(ns.entities).indexOf(config.id) === -1) {
      throw new Error('The requrested entity is not registered!');
    }

    let dataSource;

    const team = config.team || 1;

    // instanciating a Phaser.Game.Sprite objet for the entity
    const sprite = phaserGame.add.sprite(0, 0, config.id);

    // fetching the DataObject instance from the preloaded JSON file
    if (window.editor && localStorage && localStorage.getItem(config.id)) {
      dataSource = JSON.parse(localStorage.getItem(config.id));
    } else {
      dataSource = phaserGame.cache.getJSON(config.id);
    }

    const dataObject = new DataObject(dataSource);

    // passing the team Id from the config param object
    dataObject.setTeam(team);

    // adding the freshly created entity to the main array
    const entity = new Entity({
      entityManager: this,
      sprite,
      dataObject,
      ...config,
    });

    // sets the coordinates if not ommitted
    if (config.x || config.y) {
      sprite.x = config.x || 0;
      sprite.y = config.y || 0;
    }

    // sets the heading
    if (config.headToCoords) {
      entity.headToCoords(config.headToCoords);
    }

    // Adds the InConstruction Activity straight on init
    if (config.inConstruction) {
      entity.inConstruction();
    }

    entities.push(entity);

    this.notifyListenersThatEntityCountHasChanged();
  },

  /**
   * Removes entity from the private collection
   * @param {object} entity Entity instance
   */
  remove(entity) {
    for (let i = entities.length - 1; i >= 0; i -= 1) {
      if (entity === entities[i]) {
        entities.splice(i, 1);
      }
    }
    if (entity.getNumberOfDockedEntities() > 0) {
      entity.getDockedEntities().forEach((dockedEntity) => {
        this.remove(dockedEntity);
      });
    }
    entity.remove();
    // eslint-disable-next-line no-param-reassign
    entity = null;
    // when an entity is removed we've got to refresh the quad tree
    this.updateEntityDistances();
    this.notifyListenersThatEntityCountHasChanged();
  },

  /**
   * Alters entity attributes and executes update functions according to
   * the elapsed time
   * @param {boolean} authoritative determines whether the player is authorised
   * to issue changes that might alter the gameplay
   * @return {void}
   */
  update(authoritative) {
    this.updateLogic(authoritative);
  },

  /**
   * Updates all entity related game logic
   * @param {boolean} authoritative determines whether the player is authorised
   * to issue changes that might alter the gameplay
   * @return {void}
   */
  updateLogic(authoritative) {
    this.updateEntityDistancesOptimised();
    this.updateEntities(authoritative);
  },

  /**
   * destroys all the existing entities
   * @return {void}
   */
  reset() {
    while (entities.length) {
      const entity = entities.pop();
      entity.delete();
    }
  },

  /**
   * Unselect all entities expect the passed if it is not omitted
   * It can directly employ the private collection of entities since
   * it triggers only client related action
   * @param {object} [entity] [Entity instance that will be excluded from the selection]
   * @return {void}
   */
  unselectAll(excludedEntity) {
    entities.forEach((entity) => {
      if (excludedEntity !== entity && entity.isSelected()) {
        entity.unselect();
      }
    });
  },

  /**
   * Exposes EventAPI to all the active entities
   * @type {object}
   * @see EventAPI
   */
  entities: createSelector(entities),

  /**
   * Initialises a QuadTree to filter candidates for InRange typed functions
   * @param  {object} map Map instance
   * @return {void}
   */
  createQuadTree(map) {
    if (!map) throw new Error('Invalid Map instance has been passed!');

    this.quadTree = new QuadTree({
      x: 0,
      y: 0,
      width: map.getScreenWidth(),
      height: map.getScreenHeight(),
    });
  },

  /**
   * Updates the closest sibling of all the entities. With this information
   * we can easily and efficiently check whether there is an entity in range.
   * @return {void}
   */
  updateEntityDistances() {
    this.updateQuadTree();
    for (let i = entities.length - 1; i >= 0; i -= 1) {
      this.setClosestEntities(entities[i]);
    }
  },

  /**
   * Updates QuadTree according to the current state of the entity array
   * @return {void}
   */
  updateQuadTree() {
    this.quadTree.clear();
    for (let i = entities.length - 1; i >= 0; i -= 1) {
      this.quadTree.insert(entities[i].getSprite());
    }
  },

  /**
   * Emits a local event as the user needs to update all the relevant
   * components that shows the entity count
   */
  notifyListenersThatEntityCountHasChanged() {
    const emitter = EventEmitter.getInstance();
    emitter.local.dispatch('entity/number/change');
    // to alter resource display
    emitter.local.dispatch('user/resource/alter');
    // to alter control panel (to potentially disable production buttons)
    emitter.local.dispatch('gui/controlpage/update');
  },

  /**
   * Sets the closest entities to the given entity
   * @param {object} entity Entity instance
   * @return {void}
   */
  setClosestEntities(entity) {
    if (!entity) throw new Error('Invalid Entity instance is passed!');

    const closests = this.getEntitiesInApproximity(entity);
    let closestAttackableEntity = null;
    let closestEnemyInRange = null;
    const closestAllies = [];

    for (let i = closests.length - 1; i >= 0; i -= 1) {
      const { candidate, inRange, inVision } = closests[i];

      if (!candidate.isHibernated()) {
        if (entity.isEnemy(candidate)) {
          // check if the encountered enemy entity can be targeted
          if (candidate.isTargetableByEntity(entity)) {
            // closest enemy in range
            if (!closestEnemyInRange && inRange) {
              closestEnemyInRange = candidate;
            }
            // closest attackable enemy (for scanning)
            if (!closestAttackableEntity && (inVision || inRange)) {
              closestAttackableEntity = candidate;
            }
          }
        } else if (entity.getPlayer() === candidate.getPlayer()) {
          // we collect the non-hostile entities
          closestAllies.push(candidate);
        }
      }
    }

    entity.setClosestAttackableHostileEntity(closestAttackableEntity);
    entity.setClosestHostileEntityInRange(closestEnemyInRange);
    entity.setClosestAllyEntitiesInRange(closestAllies);
  },

  /**
   * Links the given entity to a new EnergyShield instance
   * @param {object} entity Instance of Eneity
   */
  addEnergyShield(entity) {
    const energyShield = new EnergyShield(phaserGame);
    energyShield.appendTo(entity);
    return energyShield;
  },

  /**
   * Links the given entity to a new JetEngine instance
   * @param {object} entity Instance of Eneity
   */
  addJetEngine(entity) {
    const jetEngine = new JetEngine(phaserGame);
    jetEngine.appendTo(entity);
    return jetEngine;
  },

  /**
   * Returns an array of candidates that are in range to the given entity
   * @param {object} entity [description]
   * @return {object} array of {inVision, inRange, candidate, distance}
   */
  getEntitiesInApproximity(entity) {
    const maxRange = entity.getWeaponManager().getMaxRange();
    const visionRange = entity.getDataObject().getVisionRange() * 1.25;
    const maxDistance = Math.max(maxRange, visionRange);
    const sprite = entity.getSprite();
    const candidates = this.quadTree.retrieve(sprite);
    return candidates
      .map(candidate => ({
        distance: Util.distanceBetweenSprites(sprite, candidate),
        candidate,
      }))
      .filter((data) => {
        if (data.candidate === sprite) return false;
        if (data.candidate._parent.isHibernated()) return false;
        return data.distance <= maxDistance;
      })
      .sort((a, b) => a.distance < b.distance)
      .map(data => ({
        inVision: data.distance <= visionRange,
        inRange: data.distance <= maxRange,
        candidate: data.candidate._parent,
        distance: data.distance,
      }));
  },

  /**
   * Updates each entities
   * @param {boolean} authoritative determines wether the player is authorised
   * to generate effects that migh alter the gameplay
   * @return {void}
   */
  updateEntities(authoritative) {
    for (let i = entities.length - 1; i >= 0; i -= 1) {
      entities[i].update(authoritative);
    }
  },

  /**
   * returns the subsection of the attributes of the given entities
   * @param  {array} targetEntities - Array of the given entities
   * @return {object} consolidated object of attributes
   */
  getMergedAbilities(targetEntities) {
    const subsection = ability => val =>
      ability
        .getAbilityManager()
        .getAbilities()
        .indexOf(val) !== -1;

    let abilities;
    let next;

    if (!targetEntities || !targetEntities.length) {
      return [];
    }

    const clones = targetEntities.slice(0);
    abilities = clones
      .shift()
      .getAbilityManager()
      .getAbilities();

    // eslint-disable-next-line no-cond-assign
    while ((next = clones.shift())) {
      abilities = abilities.filter(subsection(next));
    }

    return abilities.slice(0);
  },

  /**
   * returns the Phaser.Game object for inconvinience
   * @return {object} Phaser.Game instance
   */
  getGame() {
    return phaserGame;
  },

  /**
   * Creates a selector function with the given entities.
   * This selector function can be used to filter down entities through a specified API.
   * @param {object} targetEntities - array of entity instances
   * @return {function}
   */
  getSelector(targetEntities) {
    return createSelector(targetEntities);
  },

  /**
   * Returns the first entity that is hovered by the UserPointer
   * @return {object} Entity instance
   */
  getHoveredEntity() {
    // checks whether the user hovers an entity
    const candidates = this.entities(':not(hibernated)');
    for (let i = candidates.length - 1; i >= 0; i -= 1) {
      if (candidates[i].isHover()) {
        return candidates[i];
      }
    }
    return null;
  },

  /**
   * Returns collection of key-value pairs of the required resources of
   * the given entity
   * @param {string} id
   * @return {object}
   */
  getRequiredResources(id) {
    const targetDO = phaserGame.cache.getJSON(id);
    const {
      titanium, silicium, uranium, energy,
    } = targetDO;
    return {
      titanium,
      silicium,
      uranium,
      energy,
    };
  },
};

export default {
  /**
   * sets the global Phaser.Game instance
   * @param {void}
   */
  setGame(game) {
    phaserGame = game;
  },

  /**
   * returns singleton instance of the manager object
   * @param {boolean} forceNewInstance
   * @return {object} Singleton instance of EntityManager
   */
  getInstance(forceNewInstance) {
    if (!phaserGame) {
      throw new Error('Invoke setGame first to pass the Phaser Game entity!');
    }
    if (!singleton || forceNewInstance) {
      singleton = new EntityManager();
      singleton.reset();
    }
    return singleton;
  },
};


text:
namespace Saiga::Vulkan::Memory
{
}  // namespace Saiga::Vulkan::Memory

redpajama_set_name: RedPajamaGithub


text:
package org.teavm.tooling.sources;

import java.util.Set;
import org.teavm.model.BasicBlockReader;
import org.teavm.model.ProgramReader;
import org.teavm.model.TextLocation;
import org.teavm.model.instructions.AbstractInstructionReader;

class ProgramSourceAggregator extends AbstractInstructionReader {
    private Set<String> sourceFiles;

    public ProgramSourceAggregator(Set<String> sourceFiles) {
        this.sourceFiles = sourceFiles;
    }

    public void addLocationsOfProgram(ProgramReader program) {
        for (int i = 0; i < program.basicBlockCount(); ++i) {
            BasicBlockReader block = program.basicBlockAt(i);
            block.readAllInstructions(this);
        }
    }

    @Override
    public void location(TextLocation location) {
        if (location != null && location.getFileName() != null && !location.getFileName().isEmpty()) {
            sourceFiles.add(location.getFileName());
        }
    }
}


text:
__title__ = 'skurt-djangorestframework-jwt'
__version__ = '1.7.6'
__author__ = 'José Padilla'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014-2015 Blimp LLC'

# Version synonym
VERSION = __version__


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace VkApi.Wrapper.Objects
{
    public class BaseUserId
    {
        ///<summary>
        /// User ID
        ///</summary>
        [JsonProperty("user_id")]
        public int UserId { get; set; }
    }
}


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

package api

import (
	"errors"
	"net/http"
	"time"

	"github.com/minio/minio/pkg/auth"
)

type contentTypeHandler struct {
	handler http.Handler
}

type timeHandler struct {
	handler http.Handler
}

type validateAuthHandler struct {
	handler http.Handler
}

type resourceHandler struct {
	handler http.Handler
}

const (
	iso8601Format = "20060102T150405Z"
)

func parseDate(req *http.Request) (time.Time, error) {
	amzDate := req.Header.Get(http.CanonicalHeaderKey("x-amz-date"))
	switch {
	case amzDate != "":
		if _, err := time.Parse(time.RFC1123, amzDate); err == nil {
			return time.Parse(time.RFC1123, amzDate)
		}
		if _, err := time.Parse(time.RFC1123Z, amzDate); err == nil {
			return time.Parse(time.RFC1123Z, amzDate)
		}
		if _, err := time.Parse(iso8601Format, amzDate); err == nil {
			return time.Parse(iso8601Format, amzDate)
		}
	}
	date := req.Header.Get("Date")
	switch {
	case date != "":
		if _, err := time.Parse(time.RFC1123, date); err == nil {
			return time.Parse(time.RFC1123, date)
		}
		if _, err := time.Parse(time.RFC1123Z, date); err == nil {
			return time.Parse(time.RFC1123Z, date)
		}
		if _, err := time.Parse(iso8601Format, amzDate); err == nil {
			return time.Parse(iso8601Format, amzDate)
		}
	}
	return time.Time{}, errors.New("invalid request")
}

// ValidContentTypeHandler -
func ValidContentTypeHandler(h http.Handler) http.Handler {
	return contentTypeHandler{h}
}

func (h contentTypeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	acceptsContentType := getContentType(r)
	if acceptsContentType == unknownContentType {
		writeErrorResponse(w, r, NotAcceptable, acceptsContentType, r.URL.Path)
		return
	}
	h.handler.ServeHTTP(w, r)
}

// TimeValidityHandler -
func TimeValidityHandler(h http.Handler) http.Handler {
	return timeHandler{h}
}

func (h timeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	acceptsContentType := getContentType(r)
	// Verify if date headers are set, if not reject the request
	if r.Header.Get("Authorization") != "" {
		if r.Header.Get(http.CanonicalHeaderKey("x-amz-date")) == "" && r.Header.Get("Date") == "" {
			// there is no way to knowing if this is a valid request, could be a attack reject such clients
			writeErrorResponse(w, r, RequestTimeTooSkewed, acceptsContentType, r.URL.Path)
			return
		}
		date, err := parseDate(r)
		if err != nil {
			// there is no way to knowing if this is a valid request, could be a attack reject such clients
			writeErrorResponse(w, r, RequestTimeTooSkewed, acceptsContentType, r.URL.Path)
			return
		}
		duration := time.Since(date)
		minutes := time.Duration(5) * time.Minute
		if duration.Minutes() > minutes.Minutes() {
			writeErrorResponse(w, r, RequestTimeTooSkewed, acceptsContentType, r.URL.Path)
			return
		}
	}
	h.handler.ServeHTTP(w, r)
}

// ValidateAuthHeaderHandler -
// validate auth header handler is wrapper handler used for API request validation with authorization header.
// Current authorization layer supports S3's standard HMAC based signature request.
func ValidateAuthHeaderHandler(h http.Handler) http.Handler {
	return validateAuthHandler{h}
}

// validate auth header handler ServeHTTP() wrapper
func (h validateAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	acceptsContentType := getContentType(r)
	accessKeyID, err := StripAccessKeyID(r.Header.Get("Authorization"))
	switch err.(type) {
	case nil:
		// load auth config
		authConfig, err := auth.LoadConfig()
		if err != nil {
			writeErrorResponse(w, r, InternalError, acceptsContentType, r.URL.Path)
			return
		}
		// Access key not found
		if _, ok := authConfig.Users[accessKeyID]; !ok {
			writeErrorResponse(w, r, InvalidAccessKeyID, acceptsContentType, r.URL.Path)
			return
		}
		h.handler.ServeHTTP(w, r)
	default:
		// control reaches here, we should just send the request up the stack - internally
		// individual calls will validate themselves against un-authenticated requests
		h.handler.ServeHTTP(w, r)
	}
}

// IgnoreResourcesHandler -
// Ignore resources handler is wrapper handler used for API request resource validation
// Since we do not support all the S3 queries, it is necessary for us to throw back a
// valid error message indicating such a feature is not implemented.
func IgnoreResourcesHandler(h http.Handler) http.Handler {
	return resourceHandler{h}
}

// Resource handler ServeHTTP() wrapper
func (h resourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	acceptsContentType := getContentType(r)
	if ignoreNotImplementedObjectResources(r) || ignoreNotImplementedBucketResources(r) {
		writeErrorResponse(w, r, NotImplemented, acceptsContentType, r.URL.Path)
		return
	}
	h.handler.ServeHTTP(w, r)
}

//// helpers

// Checks requests for not implemented Bucket resources
func ignoreNotImplementedBucketResources(req *http.Request) bool {
	q := req.URL.Query()
	for name := range q {
		if notimplementedBucketResourceNames[name] {
			return true
		}
	}
	return false
}

// Checks requests for not implemented Object resources
func ignoreNotImplementedObjectResources(req *http.Request) bool {
	q := req.URL.Query()
	for name := range q {
		if notimplementedObjectResourceNames[name] {
			return true
		}
	}
	return false
}


text:
import { getLogger } from './logger';
import { Signale } from 'signale';

describe('options/logger module has a', () => {
  describe('getLogger function that', () => {
    it('should get the correct logger', () => {
      // tslint:disable:no-console
      const verboseLogger = getLogger({ isVerbose: true });
      expect(verboseLogger).toBeInstanceOf(Signale);

      const silentLogger = getLogger({ isVerbose: false });
      expect(silentLogger).toBeInstanceOf(Signale);
      expect(silentLogger).toBeDefined();
      // tslint:enable:no-console
    });
  });
});


text:
#ifndef BITCOINADDRESSVALIDATOR_H
#define BITCOINADDRESSVALIDATOR_H

#include <QValidator>

/** Base48 entry widget validator.
   Corrects near-miss characters and refuses characters that are no part of base48.
 */

class BitcoinAddressEntryValidator : public QValidator
{
    Q_OBJECT

public:
    explicit BitcoinAddressEntryValidator(QObject *parent);

    State validate(QString &input, int &pos) const;
};

/** Bitcoin address widget validator, checks for a valid bitcoin address.
 */
class BitcoinAddressCheckValidator : public QValidator
{
    Q_OBJECT

public:
    explicit BitcoinAddressCheckValidator(QObject *parent);

    State validate(QString &input, int &pos) const;
};

#endif // BITCOINADDRESSVALIDATOR_H


text:
namespace blink {

class DOMWindowDeviceMotion {
 public:
  DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(devicemotion, kDevicemotion)
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_DEVICE_ORIENTATION_DOM_WINDOW_DEVICE_MOTION_H_


text:
require 'mongo/operation/map_reduce/command'
require 'mongo/operation/map_reduce/op_msg'
require 'mongo/operation/map_reduce/result'

module Mongo
  module Operation

    # A MongoDB mapreduce operation.
    #
    # @api private
    #
    # @since 2.5.0
    class MapReduce
      include Specifiable
      include OpMsgOrCommand
    end
  end
end


text:
package com.atlassian.plugin.web;

import com.atlassian.plugin.PluginManager;
import com.atlassian.plugin.PluginAccessor;
import com.atlassian.plugin.web.descriptors.*;

import java.util.*;

import com.atlassian.plugin.web.model.WebPanel;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Stores and manages flexible web interface sections available in the system.
 */
public class DefaultWebInterfaceManager implements WebInterfaceManager
{
    private PluginAccessor pluginAccessor;
    private WebFragmentHelper webFragmentHelper;
    private Map<String, List<WebSectionModuleDescriptor>> sections;
    private Map<String, List<WebItemModuleDescriptor>> items;
    private Map<String, List<WebPanelModuleDescriptor>> panels;
    private static final Logger log = LoggerFactory.getLogger(DefaultWebInterfaceManager.class);

    public static final WeightedDescriptorComparator WEIGHTED_DESCRIPTOR_COMPARATOR = new WeightedDescriptorComparator();

    public DefaultWebInterfaceManager()
    {
        refresh();
    }

    public DefaultWebInterfaceManager(PluginAccessor pluginAccessor, WebFragmentHelper webFragmentHelper)
    {
        this.pluginAccessor = pluginAccessor;
        this.webFragmentHelper = webFragmentHelper;
        refresh();
    }

    public boolean hasSectionsForLocation(String location)
    {
        return !getSections(location).isEmpty();
    }

    public List<WebSectionModuleDescriptor> getSections(String location)
    {
        if (location == null)
        {
            return Collections.emptyList();
        }

        List<WebSectionModuleDescriptor> result = sections.get(location);

        if (result == null)
        {
            result = new ArrayList<WebSectionModuleDescriptor>(); // use a tree map so we get nice weight sorting
            List<WebSectionModuleDescriptor> descriptors = pluginAccessor.getEnabledModuleDescriptorsByClass(WebSectionModuleDescriptor.class);
            for (WebSectionModuleDescriptor descriptor : descriptors) {
                if (location.equalsIgnoreCase(descriptor.getLocation()))
                    result.add(descriptor);
            }

            Collections.sort(result, WEIGHTED_DESCRIPTOR_COMPARATOR);
            sections.put(location, result);
        }

        return result;
    }

    public List<WebSectionModuleDescriptor> getDisplayableSections(String location, Map<String,Object> context)
    {
        return filterFragmentsByCondition(getSections(location), context);
    }

    public List<WebItemModuleDescriptor> getItems(String section)
    {
        if (section == null)
        {
            return Collections.emptyList();
        }

        List<WebItemModuleDescriptor> result = items.get(section);

        if (result == null)
        {
            result = new ArrayList<WebItemModuleDescriptor>(); // use a tree map so we get nice weight sorting
            List<WebItemModuleDescriptor> descriptors = pluginAccessor.getEnabledModuleDescriptorsByClass(WebItemModuleDescriptor.class);
            for (WebItemModuleDescriptor descriptor : descriptors) {
                if (section.equalsIgnoreCase(descriptor.getSection()))
                    result.add(descriptor);
            }

            Collections.sort(result, WEIGHTED_DESCRIPTOR_COMPARATOR);
            items.put(section, result);
        }

        return result;
    }

    public List<WebItemModuleDescriptor> getDisplayableItems(String section, Map<String,Object> context)
    {
        return filterFragmentsByCondition(getItems(section), context);
    }

    public List<WebPanel> getDisplayableWebPanels(String location, Map<String, Object> context)
    {
        return toWebPanels(getDisplayableWebPanelDescriptors(location, context));
    }

    public List<WebPanelModuleDescriptor> getDisplayableWebPanelDescriptors(String location, Map<String, Object> context)
    {
        return filterFragmentsByCondition(getWebPanelDescriptors(location), context);
    }

    public List<WebPanel> getWebPanels(String location)
    {
        return toWebPanels(getWebPanelDescriptors(location));
    }

    private List<WebPanel> toWebPanels(List<WebPanelModuleDescriptor> descriptors)
    {
        return Lists.transform(descriptors, new Function<WebPanelModuleDescriptor, WebPanel>()
        {
            public WebPanel apply(WebPanelModuleDescriptor from)
            {
                return from.getModule();
            }
        });
    }

    public List<WebPanelModuleDescriptor> getWebPanelDescriptors(String location)
    {
        if (location == null)
        {
            return Collections.emptyList();
        }
        else
        {
            List<WebPanelModuleDescriptor> result = panels.get(location);
            if (result == null) {
                result = new ArrayList<WebPanelModuleDescriptor>(); // use a tree map so we get nice weight sorting

                List<WebPanelModuleDescriptor> descriptors = pluginAccessor.getEnabledModuleDescriptorsByClass(WebPanelModuleDescriptor.class);
                for (WebPanelModuleDescriptor descriptor : descriptors)
                {
                    if (location.equalsIgnoreCase(descriptor.getLocation()))
                    {
                        result.add(descriptor);
                    }
                }
                Collections.sort(result, WEIGHTED_DESCRIPTOR_COMPARATOR);
                panels.put(location, result);
            }
            return result;
        }
    }

    private <T extends ConditionalDescriptor> List<T> filterFragmentsByCondition(List<T> relevantItems, Map<String,Object> context)
    {
        if (relevantItems.isEmpty())
        {
            return relevantItems;
        }

        List<T> result = new ArrayList<T>(relevantItems);
        for (Iterator<T> iterator = result.iterator(); iterator.hasNext();)
        {
            ConditionalDescriptor descriptor = iterator.next();
            try
            {
                if (descriptor.getCondition() != null && !descriptor.getCondition().shouldDisplay(context))
                {
                    iterator.remove();
                }
            }
            catch (Throwable t)
            {
                log.error("Could not evaluate condition '" + descriptor.getCondition() + "' for descriptor: " + descriptor, t);
                iterator.remove();
            }
        }

        return result;
    }

    public void refresh()
    {
        sections = Collections.synchronizedMap(new HashMap<String, List<WebSectionModuleDescriptor>>());
        items = Collections.synchronizedMap(new HashMap<String, List<WebItemModuleDescriptor>>());
        panels = Collections.synchronizedMap(new HashMap<String, List<WebPanelModuleDescriptor>>());
    }

    /**
     * @deprecated since 2.2.0, use {@link #setPluginAccessor(PluginAccessor)} instead
     * @param pluginManager
     */
    @Deprecated
    public void setPluginManager(PluginManager pluginManager)
    {
        setPluginAccessor(pluginManager);
    }

    /**
     * @param pluginAccessor The plugin accessor to set
     * @since 2.2.0
     */
    public void setPluginAccessor(PluginAccessor pluginAccessor)
    {
        this.pluginAccessor = pluginAccessor;
    }

    public void setWebFragmentHelper(WebFragmentHelper webFragmentHelper)
    {
        this.webFragmentHelper = webFragmentHelper;
    }

    public WebFragmentHelper getWebFragmentHelper()
    {
        return webFragmentHelper;
    }

}


text:
package hudson.plugins.simpleupdatesite;

import hudson.PluginWrapper;
import hudson.model.Hudson;
import hudson.model.UpdateSite;
import hudson.util.TextFile;

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

/**
 * UpdateSite extension to hack default {@link UpdateSite} behavior
 *
 * @author JunHo Yoon
 */
public class SimpleUpdateSite extends UpdateSite {
	public SimpleUpdateSite(String id) {
		super(id, null);
	}

	public SimpleUpdateSite(String id, String url) {
		super(id, url);
	}

	@Override
	public String getUrl() {
		return getPlugin().getUpdateSiteUrl();
	}

	protected SimpleUpdateSitePlugIn getPlugin() {
		return Hudson.getInstance().getPlugin(SimpleUpdateSitePlugIn.class);
	}

	@Override
	public boolean isLegacyDefault() {
		return false;
	}
	/**
	 * This is the endpoint that receives the update center data file from the
	 * browser.
	 */
	public void doPostBack(StaplerRequest req, StaplerResponse rsp, @QueryParameter String json) throws IOException, GeneralSecurityException {
		if (StringUtils.isEmpty(json) && req != null) {
			json = org.apache.commons.io.IOUtils.toString(req.getInputStream(), "UTF-8");
		}
		if (StringUtils.isNotBlank(json)) {
			getDataFile().write(json);
		}
		if (rsp != null) {
			rsp.setContentType("text/plain");
		}
	}

	/**
	 * This is where we store the update center data. Because getDataFile in
	 * {@link UpdateSite} class is private, the function should be provided in
	 * this class.
	 */
	public TextFile getDataFile() {
		return new TextFile(new File(Hudson.getInstance().getRootDir(), "updates/" + getId() + ".json"));
	}

	public List<Plugin> getInstalled() {
		List<Plugin> installedPlugins = new ArrayList<Plugin>();
		Data data = getData();
		if (data == null) {
			return Collections.emptyList();
		}
		for (Plugin plugin : data.plugins.values()) {
			if (plugin.getInstalled() != null) {
				installedPlugins.add(plugin);
			}
		}
		return installedPlugins;
	}

	/**
	 * Returns the list of plugins that are updates to currently installed ones.
	 *
	 * @return can be empty but never null.
	 */
	@Override
	public List<Plugin> getUpdates() {
		Data data = getData();
		if (data == null) {
			return Collections.emptyList(); // fail to determine
		}

		List<Plugin> updatablePlugins = new ArrayList<Plugin>();
		for (Plugin plugin : data.plugins.values()) {
			PluginWrapper installed = plugin.getInstalled();
			if (installed != null && isNewerPlugin(plugin.version, installed.getVersion())) {
				updatablePlugins.add(plugin);
			}
		}
		return updatablePlugins;
	}

	public boolean isNewerPlugin(String newVersion, String installedVersion) {
		installedVersion = installedVersion.replaceAll("\\(.*\\)", "").trim();
		newVersion = newVersion.replaceAll("\\(.*\\)", "").trim();
		return new VersionNumber(newVersion).compareTo(new VersionNumber(installedVersion)) > 0;
	}
}


text:
#ifndef ANTIC_MAIN_H
#define ANTIC_MAIN_H

#include <Antic/StateManager.h>
#include <Antic/Antic_Graph.h>
#include <Antic/EventSystem.h>

//#include <Antic/Services.h>

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstdio>

#include <Antic/Physics.h>
/*
#include <ctime>
#include <chrono>
#include <thread>
*/
#include <time.h>

/**
 * @brief NameSpace of the Antic_Engine
 */
namespace antic
{
	/**
	 * @brief The core of the game engine.
	 * @details The core of the game engine. Start by instantiating an Engine object.
	 * 			Make sure to initialize the object by running its init() function.
	 * 			Next, either choose to create your own game loop, or run the default game loop
	 * 			with the gameLoop() function.
	 */
	class Engine : public Subject
	{
	public:
		Engine();

		/// Cleans everything up. Also calls close(), so you don't have to worry about it.
		virtual ~Engine();

		/**
		 * @brief Initialization function. Always call this before you start using the engine.
		 * @details Call this before doing anything else with the engine. This function also initializes the window and SDL2.
		 *
		 * @param title This will be the title of the window.
		 * @param width The width of the window.
		 * @param height The height of the window.
		 * @return True if everything went fine, false if not.
		 */
		virtual bool init( std::string title, int width, int height, int fps = -1, b2Vec2 gravity = b2Vec2(0.f, 20.f) );

		/**
		 * @brief Updates the engine.
		 * @details This will update the StateManager.
		 */
		virtual void update();

		/**
		 * @brief Renders to the screen.
		 * @details Calls the StateManager's render function. This also handles swapping and clearing the render buffer.
		 */
		virtual void render();

		/**
		 * @brief This is a simple game loop that is usually just copypasta code.
		 * @details This is a convenience function that will handle the window closing, passing system events, updating, and rendering.
		 */
		virtual void gameLoop();

		/**
		 * @brief Destroyes the engine.
		 * @details You don't need to call this because the destructor will call this. It'll also close SDL2, deleting all loaded textures and such. Only call this if you are going to init() the engine again.
		 */
		void close();

		/**
		 * @brief Set the Game State Manager
		 * @details This is important to call. The engine will run without the StateManager being set, but you typically want this to be set to something or else nothing will be happening. Make sure to add at least one GameState to the StateManager.
		 *
		 * @param r A pointer to the StateManager object that you are passing in. It will be destroyed by the engine.
		 */
		void setStateManager( StateManager* );

		StateManager* getStateManager();

		/**
		 * @brief Set max fps.
		 * @param fps This is the fps to set the max to.
		 */
		void setFPS( int fps );

		/**
		 * You can pass SDL events here.
		 */
		//SDL_Event event;
	private:

		/**
		 * The StateManager that the engine will be updating and rendering.
		 */
		StateManager* sm;

		/**
		 * This is to calculate the delta time.
		 */
		//std::chrono::time_point<std::chrono::system_clock> lastFrame;
		clock_t lastFrame;

		/**
		 * This determines the frames per second. -1 means that there will be no limit.
		 */
		int fps;

		/**
		 * This is to keep track of how long a frame is.
		 */
		double frameTime;
	};
}

#endif


text:
package handler

import (
	"context"
	"errors"
	"sync/atomic"
	"time"

	"cloud.google.com/go/pubsub"
	cepubsub "github.com/cloudevents/sdk-go/protocol/pubsub/v2"
	"github.com/cloudevents/sdk-go/v2/binding"
	"github.com/google/knative-gcp/pkg/broker/handler/processors"
	"github.com/google/knative-gcp/pkg/logging"
	"github.com/google/knative-gcp/pkg/metrics"
	"go.uber.org/zap"
)

// Handler pulls Pubsub messages as events and processes them
// with chain of processors.
type Handler struct {
	// Subscription is the pubsub subscription that messages will be
	// received from.
	Subscription *pubsub.Subscription

	// Processor is the processor to process events.
	Processor processors.Interface

	// Timeout is the timeout for processing each individual event.
	Timeout time.Duration

	// cancel is function to stop pulling messages.
	cancel context.CancelFunc

	// alive is a bool indicator that the handler is still alive.
	alive atomic.Value
}

// NewHandler creates a new Handler.
func NewHandler(
	sub *pubsub.Subscription,
	processor processors.Interface,
	timeout time.Duration,
) *Handler {
	return &Handler{
		Subscription: sub,
		Processor:    processor,
		Timeout:      timeout,
	}
}

// Start starts the handler.
// done func will be called if the pubsub inbound is closed.
func (h *Handler) Start(ctx context.Context, done func(error)) {
	ctx, h.cancel = context.WithCancel(ctx)
	h.alive.Store(true)

	go func() {
		// For any reason if inbound is closed, mark alive as false.
		defer h.alive.Store(false)
		done(h.Subscription.Receive(ctx, h.receive))
	}()
}

// Stop stops the handlers.
func (h *Handler) Stop() {
	h.cancel()
}

// IsAlive indicates whether the handler is alive.
func (h *Handler) IsAlive() bool {
	return h.alive.Load().(bool)
}

// receive converts message to events and invoke processor chain.
func (h *Handler) receive(ctx context.Context, msg *pubsub.Message) {
	ctx = metrics.StartEventProcessing(ctx)
	event, err := binding.ToEvent(ctx, cepubsub.NewMessage(msg))
	if isNonRetryable(err) {
		logEventConversionError(ctx, msg, err, "failed to convert received message to an event, check the msg format")
		// Ack the message so it won't be retried.
		// TODO Should this go to the DLQ once DLQ is implemented?
		msg.Ack()
		return
	}
	if err != nil {
		logEventConversionError(ctx, msg, err, "unknown error when converting the received message to an event")
		msg.Nack()
		return
	}

	if h.Timeout != 0 {
		var cancel context.CancelFunc
		ctx, cancel = context.WithTimeout(ctx, h.Timeout)
		defer cancel()
	}
	if err := h.Processor.Process(ctx, event); err != nil {
		logging.FromContext(ctx).Error("failed to process event", zap.String("eventID", event.ID()), zap.Error(err))
		msg.Nack()
		return
	}

	msg.Ack()
}

func isNonRetryable(err error) bool {
	// The following errors can be returned by ToEvent and are not retryable.
	// TODO Should binding.ToEvent consolidate them and return the generic ErrCannotConvertToEvent?
	return errors.Is(err, binding.ErrCannotConvertToEvent) || errors.Is(err, binding.ErrNotStructured) || errors.Is(err, binding.ErrUnknownEncoding) || errors.Is(err, binding.ErrNotBinary)
}

// Log the full message in debug level and a truncated version as an error in case the message is too big (can be as big as 10MB),
func logEventConversionError(ctx context.Context, pm *pubsub.Message, err error, msg string) {
	maxLen := 2000
	truncated := pm
	if len(pm.Data) > maxLen {
		copy := *pm
		copy.Data = copy.Data[:maxLen]
		truncated = &copy
	}
	logging.FromContext(ctx).Debug(msg, zap.Any("message", pm), zap.Error(err))
	logging.FromContext(ctx).Error(msg, zap.Any("message-truncated", truncated), zap.Error(err))
}


text:
var ErrorHandler = require('./error').errorHandler
  , Alumnos = require('./models./main:coayolo');

module.exports = exports = function(app, db) {

    // Middleware que busca a un usuario que este conectado
    //app.use(sessionHandler.isLoggedInMiddleware);

    // The main page of the blog, filtered by tag
    app.get('/', display);

    // Error handling middleware
    app.use(ErrorHandler);
}


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

    <Spinner
        android:id="@+id/reorder_spinner"
        style="@android:style/Widget.Holo.Spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_margin="15dp"
        android:background="@drawable/section_divider" />

    <RadioGroup
        android:id="@+id/reorder_radiogroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingLeft="15dp" >

        <RadioButton
            android:id="@+id/reorder_asc_rbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ASC"
            android:layout_marginRight="15dp"
            android:textSize="16dp" />

        <RadioButton
            android:id="@+id/reorder_desc_rbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="DESC"
            android:textSize="16dp" />
    </RadioGroup>

    <Space
        android:layout_width="match_parent"
        android:layout_height="35dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="64dp">

        <Button
            android:id="@+id/reorder_cancel_button"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="Cancel"/>
        <Space
            android:layout_width="3dp"
            android:layout_height="match_parent"/>
        <Button
            android:id="@+id/reorder_ok_button"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:enabled="false"
            android:text="OK"/>

    </LinearLayout>

</LinearLayout>


text:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace EnemyFortress.Utilities
{
    public static class Input
    {
        private static KeyboardState KS, oldKS;
        private static MouseState MS, oldMS;
        private static Point mousePoint;
        private static Vector2 mousePosition;
        private static bool isEnabled = true;

        public static void Update()
        {
            if (!isEnabled)
                return;

            oldKS = KS;
            oldMS = MS;

            mousePoint.X = Mouse.GetState().X;
            mousePoint.Y = Mouse.GetState().Y;

            mousePosition.X = Mouse.GetState().X;
            mousePosition.Y = Mouse.GetState().Y;

            MS = Mouse.GetState();
            KS = Keyboard.GetState();
        }

        public static bool LeftButtonClicked()
        {
            return MS.LeftButton == ButtonState.Pressed && oldMS.LeftButton == ButtonState.Released;
        }

        public static bool RightButtonClicked()
        {
            return MS.RightButton == ButtonState.Pressed && oldMS.RightButton == ButtonState.Released;
        }

        public static bool ClickedKey(Keys key)
        {
            return KS.IsKeyDown(key) && oldKS.IsKeyUp(key);
        }

        public static bool HoldingKey(Keys key)
        {
            return KS.IsKeyDown(key);
        }

        public static Point GetMousePoint()
        {
            return mousePoint;
        }

        public static Vector2 GetMousePosition()
        {
            return mousePosition;
        }

        public static bool HoldingLeftButton()
        {
            return MS.LeftButton == ButtonState.Pressed;
        }

        public static bool HoldingRightButton()
        {
            return MS.RightButton == ButtonState.Pressed;
        }

        public static void Enable()
        {
            isEnabled = true;
        }

        public static void Disable()
        {
            isEnabled = false;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>example.group</groupId>
  <artifactId>example-bundle</artifactId>
  <versioning>
    <release>3.2.0</release>
    <versions>
      <version>0.1.0-SNAPSHOT</version>
      <version>3.2.0</version>
    </versions>
    <lastUpdated>20150720165840</lastUpdated>
  </versioning>
</metadata>


text:
<?xml version="1.0" encoding="UTF-8"?>
<ReportFolder xmlns="http://soap.sforce.com/2006/04/metadata">
  <accessType>Shared</accessType>
  <name>foo</name>
  <publicFolderAccess>ReadOnly</publicFolderAccess>
</ReportFolder>


text:
package com.qiscus.sdk.chat.core.data.local;

import com.qiscus.sdk.chat.core.data.model.QiscusRoomMember;

public interface QiscusRoomMemberStore {

    void add(QiscusRoomMember qiscusRoomMember);

    boolean isContains(QiscusRoomMember qiscusRoomMember);

    void update(QiscusRoomMember qiscusRoomMember);

    void addOrUpdate(QiscusRoomMember qiscusRoomMember);

    QiscusRoomMember getMember(String email);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Buellia canescens var. dionysiopolitana Cretz.

### Remarks
null


text:
const int COL_URL = 0;
const int COL_DBID = 1;
const int COL_LOT = 2;
const int COL_YEAR = 3;
const int COL_PRICE = 4;
const int COL_BR = 5;
const int COL_BA = 6;
const int COL_SQFT = 7;
const int COL_ZESTIMATE = 8;
const int COL_SCHOOLS = 9;
const int COL_HOA = 10;
const int COL_ADDRESS = 11;
const int COL_CITY = 12;
const int COL_COUNTY = 13;
const int COL_ZIP = 14;
const int COL_STATE = 15;
const int COL_GEO = 16;
const int COL_DISTANCE = 17;
// Insert new entries here
const int COL_START_USER = 18;

#endif // COLUMNIDS_H


text:
@implementation NSURL (SecureReader)

//http://stackoverflow.com/questions/8756683/best-way-to-parse-url-string-to-get-values-for-keys
- (NSString *)scr_wordpressPostID
{
    NSArray *urlComponents = [self.absoluteString componentsSeparatedByString:@"&"];

    for (NSString *keyValuePair in urlComponents)
    {
        NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
        NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
        NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];

        if([key isEqualToString:@"p"]   ) {
            return value;
        }
    }
    return nil;
}

@end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title><?php echo $title; ?></title>
	<?php echo Asset::css('bootstrap.css'); ?>

	<?php echo Asset::js(array(
		'http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js',
		'bootstrap.js'
	)); ?>

	<?php if ($current_user): ?>

	            My Site

	                <li class="<?php echo Uri::segment(2) == '' ? 'active' : '' ?>">
						<?php echo Html::anchor('admin', 'Dashboard') ?>

					<?php
						$files = new GlobIterator(APPPATH.'classes/controller/admin/*.php');
						foreach($files as $file)
						{
							$section_segment = $file->getBasename('.php');
							$section_title = Inflector::humanize($section_segment);
							?>
							<li class="<?php echo Uri::segment(2) == $section_segment ? 'active' : '' ?>">
								<?php echo Html::anchor('admin/'.$section_segment, $section_title) ?>

							<?php
						}
					?>

	              <?php echo $current_user->username ?>

<?php echo Html::anchor('admin/logout', 'Logout') ?>

	<?php endif; ?>

<?php echo $title; ?>

<?php if (Session::get_flash('success')): ?>

					<button class="close" data-dismiss="alert">×</button>

<?php echo implode('

', (array) Session::get_flash('success')); ?>

<?php endif; ?>
<?php if (Session::get_flash('error')): ?>

					<button class="close" data-dismiss="alert">×</button>

<?php echo implode('

', (array) Session::get_flash('error')); ?>

<?php endif; ?>

<?php echo $content; ?>

Page rendered in {exec_time}s using {mem_usage}mb of memory.

				FuelPHP is released under the MIT license.

				Version: <?php echo e(Fuel::VERSION); ?>


text:
const char* NullToEmpty(const char *Str);
const wchar* NullToEmpty(const wchar *Str);
void IntToExt(const char *Src,char *Dest,size_t DestSize);

enum ACTW_ENCODING { ACTW_DEFAULT, ACTW_OEM, ACTW_UTF8};
void ArcCharToWide(const char *Src,wchar *Dest,size_t DestSize,ACTW_ENCODING Encoding);

int stricomp(const char *s1,const char *s2);
int strnicomp(const char *s1,const char *s2,size_t n);
wchar* RemoveEOL(wchar *Str);
wchar* RemoveLF(wchar *Str);
unsigned char loctolower(unsigned char ch);
unsigned char loctoupper(unsigned char ch);

char* strncpyz(char *dest, const char *src, size_t maxlen);
wchar* wcsncpyz(wchar *dest, const wchar *src, size_t maxlen);
char* strncatz(char* dest, const char* src, size_t maxlen);
wchar* wcsncatz(wchar* dest, const wchar* src, size_t maxlen);

unsigned char etoupper(unsigned char ch);
wchar etoupperw(wchar ch);

bool IsDigit(int ch);
bool IsSpace(int ch);
bool IsAlpha(int ch);

void BinToHex(const byte *Bin,size_t BinSize,char *Hex,wchar *HexW,size_t HexSize);

#ifndef SFX_MODULE
uint GetDigits(uint Number);
#endif

bool LowAscii(const char *Str);
bool LowAscii(const wchar *Str);

int wcsicompc(const wchar *s1,const wchar *s2);
int wcsnicompc(const wchar *s1,const wchar *s2,size_t n);

void itoa(int64 n,char *Str,size_t MaxSize);
void itoa(int64 n,wchar *Str,size_t MaxSize);
const wchar* GetWide(const char *Src);
const wchar* GetCmdParam(const wchar *CmdLine,wchar *Param,size_t MaxSize);
#ifndef SILENT
void PrintfPrepareFmt(const wchar *Org,wchar *Cvt,size_t MaxSize);
#endif

#endif


text:
<?php namespace JimRoh\Comment\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Config;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use JimRoh\Comment\JimrohComment;

/**
 * RESTful API for user comments.
 *
 * @author JRohacik
 */
class CommentController extends BaseController
{
	// Traits
	use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

	/**
	 * Show user comments
	 * @todo break up into methods
	 *
	 * Request $request
	 *
	 * @return Response
	 */
	public function index(Request $request)
	{
		$foreignKeyField = config('jimrohcomment.foreign_key_field');
		$userIdField = config('jimrohcomment.user_id_field');

		// Init Params
		$parameters['order_by'] = 'created_at';
		$parameters['order_type'] = 'asc';
		$parameters[$foreignKeyField] = 0;
		$parameters[$userIdField] = 0;
		$parameters['pagination'] = 0;

		// Get input values if present in query string
		// Foreign Key Value
		if ($request->has($foreignKeyField)) {
			$parameters[$foreignKeyField] = $request->get($foreignKeyField);

			// User ID
			if ($request->has($userIdField)) {
				$parameters[$userIdField] = $request->get($userIdField);
			}

			// Order By
			if ($request->has('ob')) {
				$parameters['order_by'] = $request->get('ob');
			}

			// Order Type
			if ($request->has('ot')) {
				$parameters['order_type'] = $request->get('ot');
			}

			// Pagination
			if ($request->has('pn')) {
				$parameters['pagination'] = $request->get('pn');
			}

			// Build Query
			$query =
				JimrohComment::orderBy(
					$parameters['order_by'],
					$parameters['order_type']
				);

			if ($parameters[$foreignKeyField]) {
				$query
					->where(
						$foreignKeyField,
						$parameters[$foreignKeyField]
					);
			}

			if ($parameters[$userIdField]) {
				$query->where($userIdField, $parameters[$userIdField]);
			}

			// Moderated comments
			if (config('jimrohcomment.moderated')) {
				$query->where('moderated', 1);
			}

			// To paginate or not to paginate
			if ($parameters['pagination']) {
				$comments =
					$query->paginate($parameters['pagination']);
			}
			else {
				$comments =
					$query->get();
			}

			return
				response()->json(['comments' => $comments]);
		}

		return
			response()->json(['Comment API' => date('Y-m-d H:i:s')]);
	}

	/**
	 * Create user comment
	 * @todo add validation
	 *
	 * Request $request
	 *
	 * @return Response
	 */
	public function createComment(Request $request)
	{
		if ($request->isMethod('post') && ! $request->get('spam_control')) {
			// No mass assignment
			$comment = new JimrohComment;

			$foreignKeyField = config('jimrohcomment.foreign_key_field');
			$userIdField = config('jimrohcomment.user_id_field');

			$comment->{$foreignKeyField} = $request->get($foreignKeyField);
			$comment->{$userIdField} = Auth::user() ? Auth::user()->id : 0;
			$comment->email = $request->get('email');
			$comment->comment = $request->get('comment');

			// If moderation is being used, set to 0 so read (listing)
			// does not include newly entered comments.
			if (config('jimrohcomment.moderated')) {
				$comment->moderated = 0;
			}
			else {
				$comment->moderated = 1;
			}

			$result = $comment->save();

			if ($result) {
				return
					response()->json(['error' => 0, 'message' => config('jimrohcomment.success_message')]);
			}
		}

		return
			response()->json(['error' => 1, 'message' => config('jimrohcomment.error_message')]);
	}
}


text:
title: I Won EVE
date: 2019-05-29 22:38:08
author: Nyx Sygnal
tags:
- eve
---
***

<iframe width="560" height="315" src="https://www.youtube.com/embed/hR-CePbkuLQ" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

So long and thanks for all the fish...


text:
var World = {
	init: function initFn() {
		this.createOverlays();
	},

	createOverlays: function createOverlaysFn() {
		/*
			First an AR.ClientTracker needs to be created in order to start the recognition engine. It is initialized with a URL specific to the target collection. Optional parameters are passed as object in the last argument. In this case a callback function for the onLoaded trigger is set. Once the tracker is fully loaded the function worldLoaded() is called.

			Important: If you replace the tracker file with your own, make sure to change the target name accordingly.
			Use a specific target name to respond only to a certain target or use a wildcard to respond to any or a certain group of targets.
		*/
		this.tracker = new AR.ClientTracker("assets/magazine.wtc", {
			onLoaded: this.worldLoaded,
			physicalTargetImageHeights: {
				pageOne:	286
			}
		});

		/*
			The next step is to create the augmentation. In this example an image resource is created and passed to the AR.ImageDrawable. A drawable is a visual component that can be connected to an IR target (AR.Trackable2DObject) or a geolocated object (AR.GeoObject). The AR.ImageDrawable is initialized by the image and its size. Optional parameters allow for position it relative to the recognized target.
		*/

		/* Create overlay for page one */
		var imgOne = new AR.ImageResource("assets/imageOne.png");
		var overlayOne = new AR.ImageDrawable(imgOne, 1, {
			offsetX: -0.15,
			offsetY: 0
		});

		/*
			The last line combines everything by creating an AR.Trackable2DObject with the previously created tracker, the name of the image target and the drawable that should augment the recognized image.
			Please note that in this case the target name is a wildcard. Wildcards can be used to respond to any target defined in the target collection. If you want to respond to a certain target only for a particular AR.Trackable2DObject simply provide the target name as specified in the target collection.
		*/
		var pageOne = new AR.Trackable2DObject(this.tracker, "*", {
			drawables: {
				cam: overlayOne
			},
			distanceToTarget: {
				changedThreshold: 1,
				onDistanceChanged: function(distance) {
					document.getElementById('distanceDisplay').innerHTML = "Distance from target: " + distance / 10 + " cm";
					overlayOne.rotation = distance;
				}
			},
			onExitFieldOfVision: function() {
				document.getElementById('distanceDisplay').innerHTML = "Distance from target: unknown";
			}
		});
	},

	worldLoaded: function worldLoadedFn() {
		var cssDivLeft = " style='display: table-cell;vertical-align: middle; text-align: right; width: 50%; padding-right: 15px;'";
		var cssDivRight = " style='display: table-cell;vertical-align: middle; text-align: left;'";
		document.getElementById('loadingMessage').innerHTML =
			"
Scan Target #1 (surfer), then move closer to the target
" +
			"

";

		// Remove Scan target message after 10 sec.
		setTimeout(function() {
			var e = document.getElementById('loadingMessage');
			e.parentElement.removeChild(e);
		}, 10000);
	}
};

World.init();


text:
'''
Created on May 16, 2017

@author: savvas@purdue.edu
'''

from collections import OrderedDict
import itertools
import operator
import os

from arithmetic_evaluator import eval_expr

# the operators to consider
OPERATORS = ['+', '-', '*', '/', '**']
OPERATOR_PRECEDENCE = {'**':3, '*':4, '/':4, '+':5, '-':5}

# added terms
UNARY_OPERATORS = []
# UNARY_OPERATORS = ['sqrt', 'factorial']

# the digit to use to represent number
DIGIT = 1

# max number of instances of the DIGIT to use
MAX_DIGITS = 10

# Ignore results outside the following limits
RECORD_FROM = 0
RECORD_TO = 1000000

def operandCombinations(digits):
    """
    Returns a list of lists with all allowed combinations of the used DIGITS.

    e.g. for digits = [1, 2, 3] return
    [
        [1, 2, 3], [1, 2, -3], [1, -2, 3], [1, -2, -3], [1, 23], [1, -23],
        [-1, 2, 3], [-1, 2, -3], [-1, -2, 3], [-1, -2, -3], [-1, 23], [-1, -23],
        [12, 3], [12, -3], [-12, 3], [-12, -3],
        [123], [-123]
    ]
    """
    # if there are no more digits to use, return an empty list
    if(len(digits) == 0):
        return [[]]

    # if there is only 1 digit left to use, return both the positive and negative value of the
    # digits as two lists.
    if(len(digits) == 1):
        return [[digits[0]], [-digits[0]]]

    result = []

    # construct all possible lengths of consecutive digit sequences
    # e.g for digits ['1', '2', '3'] construct '1', '12', '123'
    for sequenceLength in range(len(digits)):

        digit = digits[0]
        for index in range(sequenceLength):
            # append next digit
            digit = int(str(digit) + str(digits[index + 1]))

        # recursively construct all combinations for smaller lists
        sublist = operandCombinations(digits[sequenceLength + 1:])
        result += [[digit] + s for s in sublist] + [[-digit] + s for s in sublist]

    return result

def operatorCombinations(operatorList, length):
    """
    Returns a list of lists with all combinations of operands of the given length.

    e.g. for operatorList = ['+', '-', '*'] and length = 3 return
    [
        ['+', '+', '+'], ['+', '+', '-'], ['+', '+', '*'],
        ['+', '-', '+'], ['+', '-', '-'], ['+', '-', '*'],
        ['+', '*', '+'], ['+', '*', '-'], ['+', '*', '*'],
        ['-', '+', '+'], ['-', '+', '-'], ['-', '+', '*'],
        ['-', '-', '+'], ['-', '-', '-'], ['-', '-', '*'],
        ['-', '*', '+'], ['-', '*', '-'], ['-', '*', '*'],
        ['*', '+', '+'], ['*', '+', '-'], ['*', '+', '*'],
        ['*', '-', '+'], ['*', '-', '-'], ['*', '-', '*'],
        ['*', '*', '+'], ['*', '*', '-'], ['*', '*', '*']
    ]
    """
    l = []
    for subset in itertools.product(operatorList, repeat=length):
        l += [list(subset)]

    return l

def unaryCombinations(token):
    l = []
    for uop in UNARY_OPERATORS:
        # construct the subexpression
        s = uop + "(" + token + ")"

        # confirm subexpression is valid, e.g. factorial(-5) will fail
        succeeded = True
        try:
            eval_expr(s)
        except ValueError:
            succeeded = False

        if succeeded:
            l.append(s)

    return l

def highestPrecedence(operators):
    precedence = -1
    for op in operators:
        if OPERATOR_PRECEDENCE[op] > precedence:
            precedence = OPERATOR_PRECEDENCE[op]
    return precedence

def expressionCombinations2(operandList, operatorList, opBefore=''):
    # number of operators must be exactly one less than operands, since all operations are binary
    if len(operandList) != len(operatorList) + 1:
        raise ValueError("Incorrect length of operator list")

    # Base 1: if no operators, return the remaining operand plus unary operations on that operand
    if len(operatorList) == 0:
        first_subexpression = str(operandList[0])
        l = [first_subexpression] + unaryCombinations(first_subexpression)
        return l, [-1 * len(l)]

    # Base 2: if only 1 operator remains, construct and return the resulting 2 operand first_subexpression
    if(len(operatorList) == 1):
        first_subexpression = str(operandList[0]) + operatorList[0] + str(operandList[1])

        # add it to the list of subexpressions to return
        l = []
        l.append(first_subexpression)

        # add unary operations
        l = l + unaryCombinations(first_subexpression)

        return l, [OPERATOR_PRECEDENCE[operatorList[0]] * len(l)]

    # general case: construct expressions in two parts both recursively constructed
    expressions = []
    highest_precedence_list = []
    for sequenceLength in range(len(operatorList)):

        # recursively construct list of subexpressions that come after the first sub expression
        operands_first = operandList[:sequenceLength + 1]
        operators_first = operatorList[:sequenceLength]
        # highest_precedence_first = highestPrecedence(operators_first)
        first_subexpression_list, highest_precedence_first = expressionCombinations2(operands_first, operators_first)
        connecting_op = operatorList[sequenceLength]
        operands_second = operandList[sequenceLength + 1:]
        operators_second = operatorList[sequenceLength + 1:]
        # highest_precedence_second = highestPrecedence(operators_second)
        second_subexpression_list, highest_precedence_second = expressionCombinations2(operands_second, operators_second, connecting_op)

        # combine the two parts
        for se1, he1 in zip(first_subexpression_list, highest_precedence_first):
            for se2, he2 in zip(second_subexpression_list, highest_precedence_second):

                l1 = [se1]
                h1_list = [he1]
                if opBefore != '' and OPERATOR_PRECEDENCE[opBefore] < he1:
                    l1.append('(' + se1 + ')')
                    h1_list.append(-1)
                elif OPERATOR_PRECEDENCE[connecting_op] < he1:
                    l1.append('(' + se1 + ')')
                    h1_list.append(-1)
                elif opBefore == '-' and  he1 == 5:
                    l1.append('(' + se1 + ')')
                    h1_list.append(-1)

                l2 = [se2]
                h2_list = [he2]
                if OPERATOR_PRECEDENCE[connecting_op] < he2:
                    l2.append('(' + se2 + ')')
                    h2_list.append(-1)
                elif connecting_op == '-' and  he2 == 5:
                    l2.append('(' + se2 + ')')
                    h2_list.append(-1)

                for s1, h1 in zip(l1, h1_list):
                    for s2, h2 in zip(l2, h2_list):
                        e = s1 + connecting_op + s2
                        h = max(h1, h2, OPERATOR_PRECEDENCE[connecting_op])
                        if e not in expressions:
                            expressions.append(e)
                            highest_precedence_list.append(h)

    return expressions, highest_precedence_list

"""
Returns a list of expressions with all combinations of parentheses applied to the given operand and
operator lists.

e.g. for operands [2, 3, 4, 5, 6] and operators ['*', '-', '*', '+'] return

['
    2*3-4*5+6', '2*3-4*(5+6)', '2*3-(4*5+6)', '2*3-(4*(5+6))',
    '2*(3-4)*5+6', '2*(3-4)*(5+6)', '2*(3-4*5+6)', '2*(3-4*(5+6))',
    '2*(3-4*5)+6', '(2*3-4)*5+6', '(2*3-4)*(5+6)'
]

"""

def expressionCombinations(operandList, operatorList, opBefore=''):

    # number of operators must be exactly one less than operands
    if len(operandList) != len(operatorList) + 1:
        raise ValueError("Incorrect length of operator list")

    # if no operators, return the remaining operand
    if len(operatorList) == 0:
        x = [str(operandList[0])]

        for uop in UNARY_OPERATORS:
            # construct the subexpression
            s = uop + "(" + str(operandList[0]) + ")"

            # confirm subexpression is valid, e.g. factorial(-5) will fail
            succeeded = True
            try:
                eval_expr(s)
            except ValueError:
                succeeded = False

            if succeeded:
                x.append(s)

        return x

    # if only 1 operator remains, construct and return the expression
    if(len(operatorList) == 1):
        result = []
        result.append(str(operandList[0]) + operatorList[0] + str(operandList[1]))

        for uop in UNARY_OPERATORS:
            sq = uop + "(" + str(operandList[0]) + operatorList[0] + str(operandList[1]) + ")"
            succeeded = True
            try:
                eval_expr(sq)
            except ValueError:
                succeeded = False

            if succeeded:
                result.append(sq)

        if opBefore != '' and OPERATOR_PRECEDENCE[operatorList[0]] > OPERATOR_PRECEDENCE[opBefore]:
            result.append("(" + str(operandList[0]) + operatorList[0] + str(operandList[1]) + ")")
        return result

    result = []

    # construct all possible lengths of expressions
    for sequenceLength in range(len(operatorList)):

        largestPrecedence = -1

        subexpression = str(operandList[0])
        op = operatorList[0]
        for index in range(sequenceLength):
            subexpression += operatorList[index] + str(operandList[index + 1])
            op = operatorList[index + 1]

            if OPERATOR_PRECEDENCE[operatorList[index]] > largestPrecedence:
                largestPrecedence = OPERATOR_PRECEDENCE[operatorList[index]]

        sublist = expressionCombinations(operandList[sequenceLength + 1:], operatorList[sequenceLength + 1:], op)

        result += [subexpression + op + s for s in sublist]

        for uop in UNARY_OPERATORS:
            sq = uop + "(" + subexpression + ")"
            succeeded = True
            try:
                eval_expr(sq)
            except ValueError:
                succeeded = False
            if succeeded:
                result += [sq + op + s for s in sublist]

        if (OPERATOR_PRECEDENCE[op] < largestPrecedence or
          (opBefore in OPERATOR_PRECEDENCE and OPERATOR_PRECEDENCE[opBefore] < largestPrecedence)):
            result += ["(" + subexpression + ")" + op + s for s in sublist]

            if opBefore != '':
                result += ["(" + subexpression + op + s + ")" for s in sublist]

                for uop in UNARY_OPERATORS:
                    sq = uop + "(" + subexpression + op + s + ")"
                    succeeded = True
                    try:
                        eval_expr(sq)
                    except ValueError:
                        succeeded = False
                    if succeeded:
                        result += [sq + op + s for s in sublist]

        if opBefore == '-' and ('-' in subexpression + op + s or '+' in subexpression + op + s):
            result += ["(" + subexpression + op + s + ")" for s in sublist]

            for uop in UNARY_OPERATORS:
                sq = uop + "(" + subexpression + op + s + ")"
                succeeded = True
                try:
                    eval_expr(sq)
                except ValueError:
                    succeeded = False
                if succeeded:
                    result += [sq + op + s for s in sublist]

    return list(OrderedDict.fromkeys(result))
    # return result

RESULT = {}
COUNT = 0
NEXT_IN_SERIES = RECORD_FROM

def evalExpressions(expressionList):
    """
    Evaluate expressions
    """
    global RESULT
    global COUNT
    global NEXT_IN_SERIES

    # remove obsolete expressions
    expressionList = filter(lambda a: "--" not in a, expressionList)
    # expressionList = filter(lambda a: "-(-" not in a, expressionList)
    expressionList = filter(lambda a: "+-" not in a, expressionList)
    # expressionList = filter(lambda a: "+(-" not in a, expressionList)

    for expression in expressionList:

        COUNT += 1
        # if COUNT % 100000 == 0:
        #    print "Evaluated " + str(COUNT) + " expressions"

        # print expression
        try:
            result = float(eval_expr(expression))
        except Exception:
            continue

        # print "BEFORE= " + expression + " = " + str(result)

        if isinstance(result, float):
            if not result.is_integer():
                continue

        x = int(result)
        result = x

        if result < RECORD_FROM:
            continue

        if result > RECORD_TO:
            continue

        if result < NEXT_IN_SERIES:
            continue

        if result == NEXT_IN_SERIES:
            NEXT_IN_SERIES += 1

        if result not in RESULT:
            RESULT[result] = expression

        # print "AFTER= " + expression + " = " + str(result)

    # return result

def execute():
    global RESULT
    global NEXT_IN_SERIES

    for number_of_digits in range(MAX_DIGITS):
        digits = [DIGIT] * (number_of_digits + 1)
        operandComb = operandCombinations(digits)

        print (digits)
        print(len(operandComb))
        for operandListIndex in range(len(operandComb)):
            operandList = operandComb[operandListIndex]
            operatorComb = operatorCombinations(OPERATORS, len(operandList) - 1)

            if len(operatorComb) == 0:
                expressionList = expressionCombinations2(operandList, [])[0]
                evalExpressions(expressionList)
            else:
                for operatorListIndex in range(len(operatorComb)):
                    operatorList = operatorComb[operatorListIndex]
                    expressionList = expressionCombinations2(operandList, operatorList)[0]
                    evalExpressions(expressionList)

            print ("Completed: " + str(operandListIndex) + " = " + str(operandList))

            if (operandListIndex != 0 and operandListIndex % 10 == 0) or operandListIndex == len(operandComb) - 1:

                for i in range(10):
                    try:
                        with open(str(DIGIT) + "_INDEX" + str(operandListIndex - 10 + i) + ".txt", "r") as expressionCombinations:
                            for line in expressionCombinations:
                                r = line.split()
                                if int(r[0]) not in RESULT:
                                    RESULT[int(r[0])] = r[1]

                        # remove previous file
                        try:
                            os.remove(str(DIGIT) + "_INDEX" + str(operandListIndex - 10 + i) + ".txt")
                            print ("deleting " + str(DIGIT) + "_INDEX" + str(operandListIndex - 10 + i) + ".txt")
                        except OSError:
                            pass

                    except Exception:
                            pass

            if operandListIndex == len(operandComb) - 1:
                sorted_x = sorted(RESULT.items(), key=operator.itemgetter(0))
                next_in = RECORD_FROM
                with open(str(DIGIT) + "_FINAL" + str(number_of_digits + 1) + ".txt", "w") as expressionCombinations:
                    for item in sorted_x:
                        expressionCombinations.write("%s\t%s\n" % (item[0], item[1]))
                        if item[0] == next_in:
                            next_in += 1

                try:
                    with open(str(DIGIT) + "_CUMMULATIVE.txt", "r") as expressionCombinations:
                        for line in expressionCombinations:
                            r = line.split()
                            RESULT[int(r[0])] = r[1]
                except Exception:
                        pass

                sorted_x = sorted(RESULT.items(), key=operator.itemgetter(0))
                next_in = RECORD_FROM
                with open(str(DIGIT) + "_CUMMULATIVE.txt", "w") as expressionCombinations:
                    for item in sorted_x:
                        expressionCombinations.write("%s\t%s\n" % (item[0], item[1]))
                        if item[0] == next_in:
                            next_in += 1

            else:
                sorted_x = sorted(RESULT.items(), key=operator.itemgetter(0))
                next_in = RECORD_FROM
                with open(str(DIGIT) + "_INDEX" + str(operandListIndex) + ".txt", "w") as expressionCombinations:
                    for item in sorted_x:
                        expressionCombinations.write("%s\t%s\n" % (item[0], item[1]))
                        if item[0] == next_in:
                            next_in += 1

            if next_in > NEXT_IN_SERIES:
                NEXT_IN_SERIES = next_in

            # re-init results
            RESULT = {}

if __name__ == '__main__':
    execute()


text:
function C = largest_component (A)
%LARGEST_COMPONENT finds the largest connected component in an image.
% C = largest_component (A) returns an image C whose entries are equal to 1
% if A(i,j) is in the largest component of A, or zero otherwise.  In case of
% a tie, the largest component with the largest label A(i,j) is returned.
% If still tied, the component the smallest index i is returned (where i is the
% linear index of A(i) for all entries in the component).
%
% Example:
%
%   A = [ 1 2 2 3
%         1 1 2 3
%         0 0 1 2
%         0 1 3 3 ]
%   C = largest_component (A)
%
%   returns C = [
%         0 1 1 0
%         0 0 1 0
%         0 0 0 0
%         0 0 0 0 ]
%
% See also FIND_COMPONENTS, FIND_COMPONENTS_EXAMPLE, DMPERM

% Copyright 2008, Tim Davis, University of Florida

% return the new binary image with just the largest component
C = zeros (size (A), class (A)) ;
C (find_components (A)) = 1 ;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleBackupService.Contracts
{
    public interface IBackupService
    {
    }
}


text:
import requests
import requests_cache

from templates.button import *

def process(input, entities):
    output = {}
    try:
        anime = entities['anime'][0]['value']

        with requests_cache.enabled('anime_cache', backend='sqlite', expire_after=86400):
            r = requests.get('https://kitsu.io/api/edge/anime', params={
                'filter[text]': anime,
                'page[limit]': 1
            })
            data = r.json()

        top_anime = data['data'][0]['attributes']

        template = TextTemplate()
        template.set_text('Title: ' + top_anime['canonicalTitle'] + '\nSynopsis: ' + top_anime['synopsis'])
        template.set_post_text(
            '\nAverage Rating: {0}%\nPopularity Rank: {1}\nRating Rank: {2}\nEpisode Count: {3}'.format(
                top_anime['averageRating'], str(top_anime['popularityRank']), str(top_anime['ratingRank']),
                str(top_anime['episodeCount'])))
        text = template.get_text()

        template = ButtonTemplate(text)
        template.add_web_url('Kitsu URL', 'https://kitsu.io/anime/' + top_anime['slug'])
        template.add_web_url('YouTube URL', 'https://www.youtube.com/watch?v=' + top_anime['youtubeVideoId'])

        output['input'] = input
        output['output'] = template.get_message()
        output['success'] = True
    except:
        error_message = 'I couldn\'t find any anime matching your query.'
        error_message += '\nPlease ask me something else, like:'
        error_message += '\n  - Death Note anime'
        error_message += '\n  - Dragon ball super anime status'
        error_message += '\n  - What is the anime rating of One Punch Man?'
        output['error_msg'] = TextTemplate(error_message).get_message()
        output['success'] = False
    return output