text:
import {inject, customElement, bindable} from 'aurelia-framework';
import {EventAggregator} from 'aurelia-event-aggregator';
import {BindingEngine} from 'aurelia-binding';
import d3 from 'd3';
import GraphModel from './graph-model';
import {GraphLibD3} from './graphlib-d3';
import {GraphFinder} from './graph-finder';
import {GraphModifier} from './graph-modifier';
import {ActionManager} from './action-manager';
import {GraphPresentationService} from './graph-presentation-service';
import {GraphPresentationModel} from '../models/graph-presentation-model';

@customElement('graph')
@inject(Element, EventAggregator, GraphLibD3, GraphModel, GraphFinder, GraphModifier, ActionManager, BindingEngine,
  GraphPresentationService, GraphPresentationModel)
export class Graph {
  @bindable data;
  @bindable graphInteractionModel;

  constructor(element, pubSub, graphLibD3, graphModel, graphFinder, graphModifier, actionManager, bindingEngine,
      graphPresentationService, graphPresentationModel) {
    this.element = element;
    this.pubSub = pubSub;
    this.graphLibD3 = graphLibD3;
    this.graphModel = graphModel;
    this.graphFinder = graphFinder;
    this.graphModifier = graphModifier;
    this.actionManager = actionManager;
    this.bindingEngine = bindingEngine;
    this.graphPresentationService = graphPresentationService;
    this.graphPresentationModel = graphPresentationModel;

    this.windowSizeAdapter();

    this.displayNodes = [];
    this.displayEdges = [];

    this.pubSub.subscribe('search.node', nodeId => {
      this.addNodeAction([nodeId], true);
    });
  }

  /**
   * Update graph dimensions. Introduce the concept of using a service to update
   * the model (but lots of other places in app where viewModes update models directly)
   */
  windowSizeAdapter() {
    // TODO Also need to respond to window resize so that svg can resize.
    this.graphPresentationService.updateDimensions(
      window.innerWidth - 100,
      window.innerHeight - 112
    );
  }

  /**
   * A new global graph (i.e. project analysis) is available.
   * Create an empty display graph and initialize it with some
   * sample data from the global graph.
   */
  dataChanged(newVal) {
    let unusedTypes;

    if (newVal) {
      unusedTypes = this.graphFinder.findUnusedTypes(this.graphModel.globalGraphModel);
      this.graphModel.initRadii();
      this.displayGraph = this.graphModel.emptyGraph();
      this.addNodeAction([unusedTypes[0]], true);
    }
  }

  /**
   * Perform the add action, and register undo and redo handlers.
   */
  addNodeAction(nodeIds, withNeighbours) {
    this.addAndDisplay(nodeIds, withNeighbours);
    this.actionManager.addAction(this,
      this.removeAndDisplay, [nodeIds, withNeighbours],
      this.addAndDisplay, [nodeIds, withNeighbours]
    );
  }

  addAndDisplay(nodeIds, withNeighbours) {
    this.addToDisplayGraphModel(nodeIds, withNeighbours);
    this.updateForceLayout();
  }

  removeAndDisplay(nodeIds, withNeighbours) {
    this.removeFromDisplayGraphModel(nodeIds, withNeighbours);
    this.updateForceLayout();
  }

  /**
   * Modify the graph display model to include the given node id's.
   * If withNeihbours is true, then also include each node's neighbours.
   */
  addToDisplayGraphModel(nodeIds, withNeighbours) {
    nodeIds.forEach( nodeId => {
      if (withNeighbours) {
        this.graphModifier.addNodeEnv(this.displayGraph, nodeId, 1, this.svgText);
      } else {
        this.graphModifier.addNodeOnly(this.displayGraph, nodeId, this.svgText);
      }
    });
  }

  /**
   * Modify the graph display model to remove the given node id's.
   * If withNeihbours is true, then also remove each node's neighbours.
   */
  removeFromDisplayGraphModel(nodeIds, withNeighbours) {
    nodeIds.forEach( nodeId => {
      if (withNeighbours) {
        this.graphModifier.removeNodeEnv(this.displayGraph, nodeId, 1, this.svgText);
      } else {
        this.graphModifier.removeNodeOnly(this.displayGraph, nodeId, this.svgText);
      }
    });
  }

  /**
   * Use D3 force layout to calculate node positions.
   * A high negative charge value avoids node overlap.
   */
  updateForceLayout() {
    this.d3Data = this.graphLibD3.mapToD3(this.displayGraph);
    let currentNode;
    let numNodes = this.d3Data.nodes.length;

    let force = d3.layout.force()
       .nodes(this.d3Data.nodes)
       .links(this.d3Data.links)
       .size([this.graphPresentationModel.width, this.graphPresentationModel.height])
       .gravity(0.4)
       .linkDistance(200)
       .charge(-4000)
       .on('tick', this.tick.bind(this));

    this.computeLayout(force, numNodes);
    this.updateDisplayData(this.d3Data);
  }

  /**
   * On each tick of D3's force layout calculation, adjust node positions by applying
   * collision detection and bounding box constraints. Both of these algorithms
   * need to know the node's radius. A heuristic is to estimate radius = 45.
   * A complete solution would know each node's actual radius, but this is very
   * difficult from timing perspective because its not known until after its
   * in the DOM, and calculated by NodeCustomElement in micro task queue.
   */
  tick() {
    const heuristicRadius = 45;
    this.applyCollisionDetection(heuristicRadius);
    this.applyBoundingBox(heuristicRadius);
  }

  /**
   * Collision detection algorithm from
   * https://bl.ocks.org/mbostock/3231298
   */
  applyCollisionDetection(heuristicRadius) {
    let q = d3.geom.quadtree(this.d3Data.nodes),
      i = 0,
      n = this.d3Data.nodes.length;

    while (++i < n) q.visit(this.collide(this.d3Data.nodes[i], heuristicRadius));
  }

  collide(node, r) {
    let nx1 = node.x - r,
      nx2 = node.x + r,
      ny1 = node.y - r,
      ny2 = node.y + r;
    return function(quad, x1, y1, x2, y2) {
      if (quad.point && (quad.point !== node)) {
        let x = node.x - quad.point.x,
          y = node.y - quad.point.y,
          l = Math.sqrt(x * x + y * y),
          r = node.radius + quad.point.radius;
        if (l < r) {
          l = (l - r) / l * 0.5;
          node.x -= x *= l;
          node.y -= y *= l;
          quad.point.x += x;
          quad.point.y += y;
        }
      }
      return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
    };
  }

  /**
  * Make nodes fit within bounding box represented by this.graphPresentationModel.
  * http://mbostock.github.io/d3/talk/20110921/bounding.html
  */
  applyBoundingBox(r) {
    this.d3Data.nodes.forEach( node => {
      let curX = node.x;
      node.x = Math.max(r, Math.min(this.graphPresentationModel.width - r, curX));
      let curY = node.y;
      node.y = Math.max(r, Math.min(this.graphPresentationModel.height - r, node.y));
    });
  }

  /**
   * Technique to minimize D3 chaotic bouncing in force layout.
   * http://stackoverflow.com/questions/13463053/calm-down-initial-tick-of-a-force-layout
   */
  computeLayout(force, numIterations) {
    let safety = 0;

    force.start();

    while(force.alpha() > 0.05) {
      force.tick();
      if(safety++ > 500) {
        break;
      }
    }

    force.stop();

    if(safety >= 500) {
      console.warn('Unable to stabilize force layout.');
    }
  }

  /**
   * Update list of display nodes and edges from d3 data.
   */
  updateDisplayData(d3Data) {
    // add nodes that are in d3Data, but not in display
    d3Data.nodes.forEach( node => {
      if (!this.graphLibD3.containsNode(this.displayNodes, node)) {
        this.displayNodes.push(node);
      }
    });

    // add links that are in d3Data, but not in display
    d3Data.links.forEach( link => {
      if (!this.graphLibD3.containsEdge(this.displayEdges, link)) {
        this.displayEdges.push(link);
      }
    });

    // remove nodes that are in display, but not in d3Data (iterate in reverse because splice re-indexes the array)
    let numDisplayNodes = this.displayNodes.length;
    for (let i=numDisplayNodes-1; i >= 0; i--) {
      if (!this.graphLibD3.containsNode(d3Data.nodes, this.displayNodes[i])) {
        this.displayNodes.splice(i, 1);
      }
    }

    // remove edges that are in display, but not in d3Data (iterate in reverse because splice re-indexes the array)
    let numDisplayEdges = this.displayEdges.length;
    for (let j=numDisplayEdges-1; j >=0; j--) {
      if (!this.graphLibD3.containsEdge(d3Data.links, this.displayEdges[j])) {
        this.displayEdges.splice(j, 1);
      }
    }

  }

  /**
   * Based on the currently selected nodes, use 'interaction' and 'type'
   * to find nodes from globalGraph that should be added, but only if
   * they're not already in the display graph.
   */
  findNodesToAdd(interaction, type) {
    let selectedNodeIds,
      relationship,
      nodesByEdgeRelationship;

    selectedNodeIds = this.graphFinder.findSelectedNodeIds(this.displayGraph);
    relationship = type === 'of it' ? 'target' : 'source';
    nodesByEdgeRelationship = this.graphFinder.findNodesByEdgeRelationship(
      this.graphModel.globalGraphModel, selectedNodeIds, interaction, relationship
    );

    return this.graphFinder.filterAlreadyInGraph(nodesByEdgeRelationship, this.displayGraph);
  }

  /**
   * Determine nodes that should be added, and add them as an undo-able action.
   */
  addNodesToDisplay(interaction, type) {
    let nodesToAdd = this.findNodesToAdd(interaction, type);

    if (nodesToAdd.length > 0) {
      this.addNodeAction(nodesToAdd);
    } else {
      // TODO notify https://github.com/CANVE/canve-viz/issues/32
      console.warn('No interaction results');
    }
  }

  /**
   * Invoked by Aurelia when 'graphInteractionModel' binding value has changed.
   * In practice this object it set once in the parent view. After that,
   * register property observers to fire when specific properties of the interaction model change,
   * indicating that the graph should respond to the change by adding more nodes.
   */
  graphInteractionModelChanged(newValue) {
    if (newValue) {
      this.graphInteractionModel = newValue;

      this.bindingEngine.propertyObserver(this.graphInteractionModel, 'callsSelectedVal').subscribe((newValue, oldValue) => {
        this.addNodesToDisplay('uses', newValue);
      });

      this.bindingEngine.propertyObserver(this.graphInteractionModel, 'extensionsSelectedVal').subscribe((newValue, oldValue) => {
        this.addNodesToDisplay('extends', newValue);
      });

      this.bindingEngine.propertyObserver(this.graphInteractionModel, 'ownershipSelectedVal').subscribe((newValue, oldValue) => {
        this.addNodesToDisplay('declares member', newValue);
      });

      // TODO dispose in appropriate lifecycle method http://stackoverflow.com/questions/30283569/array-subscription-in-aurelia
    }
  }

}


text:
using System.Collections.Generic;
using System.Linq;
using MatterHackers.Agg.UI;
using MatterHackers.DataConverters3D;
using MatterHackers.DataConverters3D.UndoCommands;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.DesignTools.Operations;

namespace MatterHackers.MatterControl.DesignTools
{
	public class ComponentObject3D : Object3D, IVisualLeafNode
	{
		private const string imageConverterComponentID = "4D9BD8DB-C544-4294-9C08-4195A409217A";

		public ComponentObject3D()
		{
		}

		public ComponentObject3D(IEnumerable<IObject3D> children)
			: base(children)
		{
		}

		public override bool CanFlatten => Finalized;
		public bool Finalized { get; set; } = true;
		public List<string> SurfacedEditors { get; set; } = new List<string>();
		public string ComponentID { get; set; }

		public override void Flatten(UndoBuffer undoBuffer)
		{
			// we want to end up with just a group of all the visible mesh objects
			using (RebuildLock())
			{
				List<IObject3D> newChildren = new List<IObject3D>();

				// push our matrix into a copy of our visible children
				foreach (var child in this.VisibleMeshes())
				{
					var meshOnlyItem = new Object3D();
					meshOnlyItem.Matrix = child.WorldMatrix(this);
					meshOnlyItem.Color = child.WorldColor(this);
					meshOnlyItem.MaterialIndex = child.WorldMaterialIndex(this);
					meshOnlyItem.OutputType = child.WorldOutputType(this);
					meshOnlyItem.Mesh = child.Mesh;
					meshOnlyItem.Name = "Mesh".Localize();
					newChildren.Add(meshOnlyItem);
				}

				if (newChildren.Count > 1)
				{
					var group = new GroupObject3D();
					group.Name = this.Name;
					group.Children.Modify(list =>
					{
						list.AddRange(newChildren);
					});
					newChildren.Clear();
					newChildren.Add(group);
				}
				else if (newChildren.Count == 1)
				{
					newChildren[0].Name = this.Name;
				}

				// and replace us with the children
				undoBuffer.AddAndDo(new ReplaceCommand(new[] { this }, newChildren));
			}

			Invalidate(InvalidateType.Children);
		}

		public override void Remove(UndoBuffer undoBuffer)
		{
			// Custom remove for ImageConverter
			if (this.ComponentID == imageConverterComponentID)
			{
				var parent = this.Parent;

				using (RebuildLock())
				{
					if (this.Descendants<ImageObject3D>().FirstOrDefault() is ImageObject3D imageObject3D)
					{
						imageObject3D.Matrix = this.Matrix;

						if (undoBuffer != null)
						{
							undoBuffer.AddAndDo(new ReplaceCommand(new[] { this }, new[] { imageObject3D }));
						}
						else
						{
							parent.Children.Modify(list =>
							{
								list.Remove(this);
								list.Add(imageObject3D);
							});
						}
					}
				}

				parent.Invalidate(new InvalidateArgs(this, InvalidateType.Children));
			}
			else
			{
				base.Remove(undoBuffer);
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sep;

/**
 *
 * @author J.JNAVARRETE
 */
public class Usuarios {

    public String id;
    public String nombre;
    public String dependencia;
    public String email;
    public String telefono;
    public String tipoUsuario;
    public String curp;
    public String usuario;

    public Usuarios(String id, String nombre, String dependencia, String email, String telefono, String tipoUsuario, String curp, String usuario) {
        this.id=id;
        this.nombre = nombre;
        this.dependencia = dependencia;
        this.email = email;
        this.telefono = telefono;
        this.tipoUsuario = tipoUsuario;
        this.curp = curp;
        this.usuario = usuario;
    }

}


text:
import pytest

from limits import limits
from limits.util import granularity_from_string, parse, parse_many

class TestRatelimitParser:
    def test_singles(self):
        for rl_string in ["1 per second", "1/SECOND", "1 / Second"]:
            assert parse(rl_string) == limits.RateLimitItemPerSecond(1)

        for rl_string in ["1 per minute", "1/MINUTE", "1/Minute"]:
            assert parse(rl_string) == limits.RateLimitItemPerMinute(1)

        for rl_string in ["1 per hour", "1/HOUR", "1/Hour"]:
            assert parse(rl_string) == limits.RateLimitItemPerHour(1)

        for rl_string in ["1 per day", "1/DAY", "1 / Day"]:
            assert parse(rl_string) == limits.RateLimitItemPerDay(1)

        for rl_string in ["1 per month", "1/MONTH", "1 / Month"]:
            assert parse(rl_string) == limits.RateLimitItemPerMonth(1)

        for rl_string in ["1 per year", "1/Year", "1 / year"]:
            assert parse(rl_string) == limits.RateLimitItemPerYear(1)

    def test_multiples(self):
        assert parse("1 per 3 hour").get_expiry() == 3 * 60 * 60
        assert parse("1 per 2 hours").get_expiry() == 2 * 60 * 60
        assert parse("1/2 day").get_expiry() == 2 * 24 * 60 * 60

    def test_parse_many(self):
        parsed = parse_many("1 per 3 hour; 1 per second")
        assert len(parsed) == 2
        assert parsed[0].get_expiry() == 3 * 60 * 60
        assert parsed[1].get_expiry() == 1

    def test_parse_many_csv(self):
        parsed = parse_many("1 per 3 hour, 1 per second")
        assert len(parsed) == 2
        assert parsed[0].get_expiry() == 3 * 60 * 60
        assert parsed[1].get_expiry() == 1

    @pytest.mark.parametrize("value", [None, "1 per millenium", "meow"])
    def test_invalid_string_parse(self, value):
        with pytest.raises(ValueError):
            parse(value)

    @pytest.mark.parametrize("value", ["millenium", "meow"])
    def test_invalid_string_granularity(self, value):
        with pytest.raises(ValueError):
            granularity_from_string(value)

    @pytest.mark.parametrize(
        "value",
        ["1 per yearl; 2 per decade"],
    )
    def test_invalid_string_parse_many(self, value):
        with pytest.raises(ValueError):
            parse_many(value)


text:
<?php
namespace Aspose\Imaging\ManagingRasterFormats;

use com\aspose\imaging\Image as Image;
use com\aspose\imaging\Rectangle as Rectangle;
class CropImages{

    public static function run($dataDir=null){

        # Cropping by Shifts
        CropImages::crop_by_shifts($dataDir);

        # Cropping by Rectangle
        CropImages::crop_by_rectangle($dataDir);
    }

    public static function crop_by_shifts($dataDir=null){

    # Load an existing image (of type bmp) in an instance of Image class
    $image=new Image();
    $image = $image->load($dataDir."test.jpg");

    # Before cropping, the image should be cached for better performance
    if (!$image->isCached()) {
    $image->cacheData();
    }

    # Define shift values for all four sides
    $left_shift = 10;
    $right_shift = 10;
    $top_shift = 10;
    $bottom_shift = 10;

    # Based on the shift values, apply the cropping on image
    # Crop method will shift the image bounds toward the center of image
    $image->crop($left_shift, $right_shift, $top_shift, $bottom_shift);

    # Save the image to disk
    $image->save($dataDir . "CropByShifts.jpg");

    # Display Status.
    print "Cropped image by shifts successfully!".PHP_EOL;
    }

    public static function crop_by_rectangle($dataDir=null){

    # Load an existing image (of type bmp) in an instance of Image class
    $image=new Image();
    $image = $image->load($dataDir . "test.jpg");

    # Before cropping, the image should be cached for better performance
    if (!$image->isCached()) {
    $image->cacheData();
    }

    # Create an instance of Rectangle class with desired size
    $rectangle = new Rectangle(10, 10, 100, 100);

    # Perform the crop operation on object of Rectangle class
    $image->crop($rectangle);

    # Save the image to disk
    $image->save($dataDir . "crop_by_rectangle.jpg");

    # Display Status.
    print "Cropped image by rectangle successfully!".PHP_EOL;

    }

}
?>


text: <ng-outlet flex layout="column"></ng-outlet>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>F - 索引</title>
<meta name="date" content="2017-07-08">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

概览

程序包

类

树

已过时

索引

帮助

上一个字母

下一个字母

框架

无框架

所有类

A B C D E F G H I L M N O P R S T U V W X

F

find(int, int, int, int, int[][]) - 类 中的静态方法org.ogcs.utilities.astar.AStarAlgorithm

A* search algorithm

find(int, int, int, int, int[][], boolean) - 类 中的静态方法org.ogcs.utilities.astar.AStarAlgorithm

A* search algorithm

fireEvent(Object, Object) - 接口 中的方法org.ogcs.event.EventListener

Fire event

format(String, Object...) - 类 中的静态方法org.ogcs.utilities.StringUtil

Returns a formatted string using the specified format string and arguments.

formatDate(long) - 类 中的静态方法org.ogcs.utilities.DateUtil

格式转换(日期)

formatTime(long) - 类 中的静态方法org.ogcs.utilities.DateUtil

格式转换(日期 + 时间)

formatTime(long, String) - 类 中的静态方法org.ogcs.utilities.DateUtil

格式转换()

A B C D E F G H I L M N O P R S T U V W X

跳过导航链接

概览

程序包

类

树

已过时

索引

帮助

上一个字母

下一个字母

框架

无框架

所有类


text:
//********************************************************************
//*
//* Warning: This file was generated by ecore4CPP Generator
//*
//********************************************************************

#ifndef UML_EXPANSIONREGION_HPP
#define UML_EXPANSIONREGION_HPP

#include <memory>
#include <string>
// forward declarations
template<class T> class Bag;

//*********************************
// generated Includes
#include <map> // used for Persistence
#include <vector> // used for Persistence
namespace persistence
{
	namespace interfaces
	{
		class XLoadHandler; // used for Persistence
		class XSaveHandler; // used for Persistence
	}
}

namespace uml
{
	class umlFactory;
}

//Forward Declaration for used types
namespace uml
{
	class Activity;
	class ActivityEdge;
	class ActivityPartition;
	class Classifier;
	class Comment;
	class Constraint;
	class Dependency;
	class ElementImport;
	class ExceptionHandler;
	class ExpansionNode;
	class InputPin;
	class InterruptibleActivityRegion;
	class OutputPin;
	class PackageImport;
	class PackageableElement;
	class StringExpression;
	class Variable;
}

// namespace macro header include
#include "uml/uml.hpp"

// base class includes
#include "uml/StructuredActivityNode.hpp"

// enum includes
#include "uml/ExpansionKind.hpp"
#include "uml/VisibilityKind.hpp"

//*********************************
namespace uml
{
	/*!
	An ExpansionRegion is a StructuredActivityNode that executes its content multiple times corresponding to elements of input collection(s).

From package UML::Actions.

	*/

	class UML_API ExpansionRegion: virtual public StructuredActivityNode
	{
		public:
 			ExpansionRegion(const ExpansionRegion &) {}

		protected:
			ExpansionRegion(){}

		public:
			virtual std::shared_ptr<ecore::EObject> copy() const = 0;

			//destructor
			virtual ~ExpansionRegion() {}

			//*********************************
			// Operations
			//*********************************

			//*********************************
			// Attribute Getters & Setters
			//*********************************
			/*!
			The mode in which the ExpansionRegion executes its contents. If parallel, executions are concurrent. If iterative, executions are sequential. If stream, a stream of values flows into a single execution.

From package UML::Actions.

			*/

			virtual uml::ExpansionKind getMode() const = 0;
			/*!
			The mode in which the ExpansionRegion executes its contents. If parallel, executions are concurrent. If iterative, executions are sequential. If stream, a stream of values flows into a single execution.

From package UML::Actions.

			*/

			virtual void setMode (uml::ExpansionKind _mode)= 0;

			//*********************************
			// Reference Getters & Setters
			//*********************************
			/*!
			The ExpansionNodes that hold the input collections for the ExpansionRegion.

From package UML::Actions.

			*/

			virtual std::shared_ptr<Bag<uml::ExpansionNode>> getInputElement() const = 0;
			/*!
			The ExpansionNodes that form the output collections of the ExpansionRegion.

From package UML::Actions.

			*/

			virtual std::shared_ptr<Bag<uml::ExpansionNode>> getOutputElement() const = 0;

			//*********************************
			// Union Reference Getters
			//*********************************
			/*!
			ActivityEdges immediately contained in the ActivityGroup.

From package UML::Activities.

			*/

			virtual std::shared_ptr<Union<uml::ActivityEdge>> getContainedEdge() const = 0;
			/*!
			ActivityNodes immediately contained in the ActivityGroup.

From package UML::Activities.

			*/

			virtual std::shared_ptr<Union<uml::ActivityNode>> getContainedNode() const = 0;
			/*!
			ActivityGroups containing the ActivityNode.

From package UML::Activities.

			*/

			virtual std::shared_ptr<Union<uml::ActivityGroup>> getInGroup() const = 0;
			/*!
			The ordered set of InputPins representing the inputs to the Action.

From package UML::Actions.

			*/

			virtual std::shared_ptr<SubsetUnion<uml::InputPin, uml::Element>> getInput() const = 0;
			/*!
			A collection of NamedElements identifiable within the Namespace, either by being owned or by being introduced by importing or inheritance.

From package UML::CommonStructure.

			*/

			virtual std::shared_ptr<Union<uml::NamedElement>> getMember() const = 0;
			/*!
			The ordered set of OutputPins representing outputs from the Action.

From package UML::Actions.

			*/

			virtual std::shared_ptr<SubsetUnion<uml::OutputPin, uml::Element>> getOutput() const = 0;
			/*!
			The Elements owned by this Element.

From package UML::CommonStructure.

			*/

			virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const = 0;
			/*!
			A collection of NamedElements owned by the Namespace.

From package UML::CommonStructure.

			*/

			virtual std::shared_ptr<SubsetUnion<uml::NamedElement, uml::Element, uml::NamedElement>> getOwnedMember() const = 0;
			/*!
			The Element that owns this Element.

From package UML::CommonStructure.

			*/

			virtual std::weak_ptr<uml::Element> getOwner() const = 0;
			/*!
			The RedefinableElement that is being redefined by this element.

From package UML::Classification.

			*/

			virtual std::shared_ptr<Union<uml::RedefinableElement>> getRedefinedElement() const = 0;

			//*********************************
			// Container Getter
			//*********************************
			virtual std::shared_ptr<ecore::EObject> eContainer() const = 0;

			//*********************************
			// Persistence Functions
			//*********************************
			virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) = 0;
			virtual void resolveReferences(const int featureID, std::vector<std::shared_ptr<ecore::EObject> > references) = 0;
			virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const = 0;

		protected:
			//*********************************
			// Attribute Members
			//*********************************
			/*!
			The mode in which the ExpansionRegion executes its contents. If parallel, executions are concurrent. If iterative, executions are sequential. If stream, a stream of values flows into a single execution.

From package UML::Actions.

			*/

			uml::ExpansionKind m_mode= uml::ExpansionKind::ITERATIVE;

			//*********************************
			// Reference Members
			//*********************************
			/*!
			The ExpansionNodes that hold the input collections for the ExpansionRegion.

From package UML::Actions.

			*/

			mutable std::shared_ptr<Bag<uml::ExpansionNode>> m_inputElement;
			/*!
			The ExpansionNodes that form the output collections of the ExpansionRegion.

From package UML::Actions.

			*/

			mutable std::shared_ptr<Bag<uml::ExpansionNode>> m_outputElement;
	};
}
#endif /* end of include guard: UML_EXPANSIONREGION_HPP */


text:
from pydblite import Base
from scrapy.xlib.pydispatch import dispatcher
from scrapy import signals
import codecs
import datetime

class DBPipeline(object):
    def __init__(self):

        #Creating log file
        filename = "session_log.txt"
        self.log_target = codecs.open(filename, 'a+', encoding='utf-8')
        self.log_target.truncate()
        self.log_target.write("***New session started at: "+ str(datetime.datetime.strftime(datetime.datetime.now(), ' %Y-%m-%d %H:%M:%S ')) + " ***" +"\n")

        #Creating database for items
        self.db = Base('QuestionThreadExtracted.pdl')
        self.db.create('uid', 'type', 'author', 'title', 'text', 'date_time',
                       'tags', 'views', 'answers', 'resolve', 'upvotes', 'url', mode="open")

        #Some data for the log file
        self.number_of_questions = 0
        self.number_of_answers = 0
        self.last_id=0
        dispatcher.connect(self.spider_closed, signals.spider_closed)

    def process_item(self, item, spider):

        self.db.insert(uid=item['uid'],
                       type=item['type'],
                       author=item['author'],
                       title=item['title'],
                       text=item['text'],
                       date_time=item['date_time'],
                       tags=item['tags'],
                       views=item['views'],
                       answers=item['answers'],
                       resolve=item['resolve'],
                       upvotes=item['upvotes'],
                       url=item['url']
                       )
        #Count questions and answers
        if "question" in item['type']:
            self.number_of_questions+=1
            if self.last_id<item['uid']:
                self.last_id=item['uid']
        else:
            self.number_of_answers+=1

        self.db.commit()
        return item

    def spider_closed(self, spider):
        self.log_target.write("Questions founded: "+ str(self.number_of_questions) + "\n")
        self.log_target.write("Answers founded: "+ str(self.number_of_answers) + "\n")
        self.log_target.write("Last UID: "+str(self.last_id) + "\n" + "\n")

        self.log_target.write("***Session End at: "+ str(datetime.datetime.strftime(datetime.datetime.now(), ' %Y-%m-%d %H:%M:%S ')) + " ***" +"\n")

        self.log_target.close()


text:
"""Functional tests for modules/course_explorer/course_explorer.py."""

__author__ = 'rahulsingal@google.com (Rahul Singal)'

import actions
from actions import assert_contains
from actions import assert_does_not_contain
from actions import assert_equals
from controllers import sites
from models import config
from models import courses
from models import models
from models import transforms
from models.models import PersonalProfile
from modules.course_explorer import course_explorer
from modules.course_explorer import student

class BaseExplorerTest(actions.TestBase):
    """Base class for testing explorer pages."""

    def setUp(self):
        super(BaseExplorerTest, self).setUp()
        config.Registry.test_overrides[
            models.CAN_SHARE_STUDENT_PROFILE.name] = True
        config.Registry.test_overrides[
            course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True

    def tearDown(self):
        config.Registry.test_overrides = {}
        super(BaseExplorerTest, self).tearDown()

class CourseExplorerTest(BaseExplorerTest):
    """Tests course_explorer module."""

    def test_single_uncompleted_course(self):
        """Tests for a single available course."""
        # This call should redirect to explorer page.
        response = self.get('/')
        assert_contains('/explorer', response.location)

        name = 'Test student courses page'
        email = 'Student'

        actions.login(email)

        # Test the explorer page.
        response = self.get('/explorer')
        assert_equals(response.status_int, 200)
        assert_contains('Register', response.body)

        # Navbar should not contain profile tab.
        assert_does_not_contain(
            'Profile', response.body)

        # Test 'my courses' page when a student is not enrolled in any course.
        response = self.get('/explorer/courses')
        assert_equals(response.status_int, 200)
        assert_contains('You are not currently enrolled in any course',
                        response.body)

        # Test 'my courses' page when a student is enrolled in all courses.
        actions.register(self, name)
        response = self.get('/explorer/courses')
        assert_equals(response.status_int, 200)
        assert_contains('Go to course', response.body)
        assert_does_not_contain('You are not currently enrolled in any course',
                                response.body)

        # After the student registers for a course,
        # profile tab should be visible in navbar.
        assert_contains(
            'Profile', response.body)

        # Test profile page.
        response = self.get('/explorer/profile')
        assert_contains('%s	' % email, response.body)
        assert_contains('%s	' % name, response.body)
        assert_contains('Progress', response.body)
        assert_does_not_contain('View score', response.body)

    def test_single_completed_course(self):
        """Tests when a single completed course is present."""
        name = 'Test Assessments'

        # Register.
        user = actions.login('test_assessments@google.com')
        actions.register(self, name)

        response = self.get('/explorer')
        # Before a course is not completed,
        # explorer page should not show 'view score' button.
        assert_does_not_contain('View score', response.body)

        # Assign a grade to the course enrolled to mark it complete.
        profile = PersonalProfile.get_by_key_name(user.user_id())
        info = {'final_grade': 'A'}
        course_info_dict = {'': info}
        profile.course_info = transforms.dumps(course_info_dict)
        profile.put()

        # Check if 'View score' text is visible on profile page.
        response = self.get('/explorer/profile')
        assert_contains('View score', response.body)

        # Check if 'Go to course' button is not visible on explorer page.
        response = self.get('/explorer')
        assert_does_not_contain('Go to course', response.body)

        # Check if 'View score' button is visible on explorer page.
        response = self.get('/explorer')
        assert_contains('View score', response.body)

    def test_multiple_course(self):
        """Tests when multiple courses are available."""
        sites.setup_courses('course:/test::ns_test, course:/:/')
        name = 'Test completed course'
        email = 'Student'

        # Make the course available.
        get_environ_old = sites.ApplicationContext.get_environ

        def get_environ_new(self):
            environ = get_environ_old(self)
            environ['course']['now_available'] = True
            return environ

        sites.ApplicationContext.get_environ = get_environ_new

        actions.login(email)
        actions.register(self, name)
        response = self.get('/explorer/courses')
        # Assert if 'View course list' text is shown on my course page.
        assert_contains('View course list', response.body)

        # Clean up app_context.
        sites.ApplicationContext.get_environ = get_environ_old
        sites.reset_courses()

    def test_can_register_true(self):
        courses.Course.ENVIRON_TEST_OVERRIDES = {
            'reg_form': {'can_register': True}}

        dom = self.parse_html_string(self.get('/explorer').body)
        item = dom.find('.//li[@class="gcb-explorer-list-item"]')
        self.assertEquals(
            'Power Searching with Google',
            item.find('.//a[@class="gcb-explorer-course-title"]').text)
        # Registration button present
        self.assertIsNotNone(item.find('.//a[@href="/register"]'))

    def test_can_register_false(self):
        courses.Course.ENVIRON_TEST_OVERRIDES = {
            'reg_form': {'can_register': False}}

        dom = self.parse_html_string(self.get('/explorer').body)
        item = dom.find('.//li[@class="gcb-explorer-list-item"]')
        self.assertEquals(
            'Power Searching with Google',
            item.find('.//a[@class="gcb-explorer-course-title"]').text)
        # No registration button present
        self.assertIsNone(item.find('.//a[@href="/register"]'))

class CourseExplorerDisabledTest(actions.TestBase):
    """Tests when course explorer is disabled."""

    def get_auto_deploy(self):
        return False

    def test_anonymous_access(self):
        """Tests for disabled course explorer page."""

        # disable the explorer
        config.Registry.test_overrides[
            course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = False
        self.assertFalse(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value)

        # check root URL's properly redirect to login
        response = self.get('/')
        assert_equals(response.status_int, 302)
        assert_contains(
            'http://localhost/admin/welcome', response.location)

        response = self.get('/assets/img/your_logo_here.png')
        assert_equals(response.status_int, 302)
        assert_contains('accounts/Login', response.location)

        # check explorer pages are not accessible
        not_accessibles = [
            '/explorer',
            '/explorer/courses',
            '/explorer/profile',
            '/explorer/assets/img/your_logo_here.png']
        for not_accessible in not_accessibles:
            response = self.get(not_accessible, expect_errors=True)
            assert_equals(response.status_int, 404)

        # enable course explorer
        config.Registry.test_overrides[
            course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True
        self.assertTrue(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value)

        # check explorer pages are accessible
        accessibles = [
            '/explorer',
            '/explorer/courses',
            '/explorer/assets/img/your_logo_here.png']
        for accessible in accessibles:
            response = self.get(accessible, expect_errors=True)
            assert_equals(response.status_int, 200)

        # check student pages are not accessible
        response = self.get('/explorer/profile')
        assert_equals(response.status_int, 302)
        self.assertEqual('http://localhost/explorer', response.location)

    def test_student_access(self):
        # enable course explorer
        config.Registry.test_overrides[
            course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True
        self.assertTrue(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value)

        # check not being logged in
        response = self.get('/explorer')
        assert_contains('Explore Courses', response.body)
        assert_does_not_contain('My Courses', response.body)
        assert_does_not_contain('Site admin', response.body)

        # login and check logged in student perspective
        config.Registry.test_overrides[
            sites.GCB_COURSES_CONFIG.name] = 'course:/:/'

        email = 'student'
        actions.login(email)
        response = self.get('/explorer')
        assert_contains('Explore Courses', response.body)
        assert_contains('My Courses', response.body)
        assert_does_not_contain('Site admin', response.body)

    def test_admin_access(self):
        # enable course explorer
        config.Registry.test_overrides[
            course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.name] = True
        self.assertTrue(course_explorer.GCB_ENABLE_COURSE_EXPLORER_PAGE.value)

        # check the admin site link
        actions.login('admin@test.foo', is_admin=True)
        response = self.get('/explorer')
        assert_contains('Site admin', response.body)

class GlobalProfileTest(BaseExplorerTest):
    """Tests course_explorer module."""

    def test_change_of_name(self):
        """Tests for a single available course."""
        # This call should redirect to explorer page.
        response = self.get('/')
        assert_contains('/explorer', response.location)

        name = 'Test global profile page'
        email = 'student_global_profile@example.com'

        actions.login(email)

        # Test the explorer page.
        response = self.get('/explorer')
        assert_equals(response.status_int, 200)
        assert_contains('Register', response.body)

        # Test 'my courses' page when a student is enrolled in all courses.
        actions.register(self, name)
        # Test profile page.
        response = self.get('/explorer/profile')
        assert_contains('%s	' % email, response.body)
        assert_contains('%s	' % name, response.body)

        # Change the name now
        new_name = 'New global name'
        response.form.set('name', new_name)
        response = self.submit(response.form)
        assert_equals(response.status_int, 302)
        response = self.get('/explorer/profile')
        assert_contains('%s	' % email, response.body)
        assert_contains('%s	' % new_name, response.body)

        # Change name with bad xsrf token.
        response = self.get('/explorer/profile')
        assert_equals(response.status_int, 200)
        new_name = 'New Bad global name'
        response.form.set('name', new_name)
        response.form.set('xsrf_token', 'asdfsdf')
        response = response.form.submit(expect_errors=True)
        assert_equals(response.status_int, 403)

        # Change name with empty name shold fail.
        response = self.get('/explorer/profile')
        assert_equals(response.status_int, 200)
        new_name = ''
        response.form.set('name', new_name)
        response = response.form.submit(expect_errors=True)
        assert_equals(response.status_int, 400)

        # Change name with overlong name should fail for str.
        response = self.get('/explorer/profile')
        assert_equals(response.status_int, 200)
        new_name = 'a' * (student._STRING_PROPERTY_MAX_BYTES + 1)
        response.form.set('name', new_name)
        response = response.form.submit(expect_errors=True)
        assert_equals(response.status_int, 400)

        # Change name with overlong name should fail for unicode.
        response = self.get('/explorer/profile')
        assert_equals(response.status_int, 200)
        # \u03a3 == Sigma. len == 1 for unicode; 2 for utf-8 encoded str.
        new_name = u'\u03a3' + ('a' * (student._STRING_PROPERTY_MAX_BYTES - 1))
        response.form.set('name', new_name)
        response = response.form.submit(expect_errors=True)
        assert_equals(response.status_int, 400)


text:
package com.interface21.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Workflow interface that allows for customized handler execution chains.
 * Applications can register any number of existing or custom interceptors
 * for certain groups of handlers, to add common preprocessing behavior
 * without needing to modify each handler implementation.
 *
 *
A HandlerInterceptor gets called before the appropriate HandlerAdapter
 * triggers the execution of the handler itself. This mechanism can be used
 * for a large field of preprocessing aspects, e.g. for authorization checks,
 * or common handler behavior like locale or theme changes. Its main purpose
 * is to allow for factoring out repetitive handler code.
 *
 *
Typically an interceptor chain is defined per HandlerMapping bean,
 * sharing its granularity. To be able to apply a certain interceptor chain
 * to a group of handlers, one needs to map the desired handlers via one
 * HandlerMapping bean. The interceptors themselves are defined as beans
 * in the application context, referenced by the mapping bean definition
 * via its "interceptors" property (in XML: a <list> of <ref>).
 *
 *
HandlerInterceptor is basically similar to a Servlet 2.3 Filter, but in
 * contrast to the latter it just allows custom pre-processing with the option
 * of prohibiting the execution of the handler itself, and custom post-processing.
 * Filters are more powerful, for example they allow for exchanging the request
 * and response objects that are handed down the chain. Note that a filter
 * gets configured in web.xml, a HandlerInterceptor in the application context.
 *
 *
As a basic guideline, fine-grained handler-related preprocessing tasks are
 * candidates for HandlerInterceptor implementations, especially factored-out
 * common handler code and authorization checks. On the other hand, a Filter
 * is well-suited for request content and view content handling, like multipart
 * forms and GZIP compression. This typically shows when one needs to map the
 * filter to certain content types (e.g. images), or to all requests.
 *
 * @author Juergen Hoeller
 * @since 20.06.2003
 * @see HandlerExecutionChain#getInterceptors
 * @see com.interface21.web.servlet.handler.AbstractHandlerMapping#setInterceptors
 * @see com.interface21.web.servlet.support.UserRoleAuthorizationInterceptor
 * @see com.interface21.web.servlet.i18n.LocaleChangeInterceptor
 * @see com.interface21.web.servlet.theme.ThemeChangeInterceptor
 * @see javax.servlet.Filter
 */
public interface HandlerInterceptor {

	/**
	 * Intercept the execution of a handler. Called after HandlerMapping determined
	 * an appropriate handler object, but before HandlerAdapter invokes the handler.
	 *
	 *
DispatcherServlet processes a handler in an execution chain, consisting
	 * of any number of interceptors, with the handler itself at the end.
	 * With this method, each interceptor can decide to abort the execution chain,
	 * typically sending a HTTP error or writing a custom response.
	 *
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param handler chosen handler to execute, for type and/or instance evaluation
	 * @return if the execution chain should proceed with the next interceptor resp.
	 * the handler itself, else DispatcherServlet assumes that this interceptor has
	 * already dealed with the response
	 * @throws ServletException if there is an internal error
	 * @throws IOException in case of an I/O error when writing the response
	 */
	boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
	    throws ServletException, IOException;

	/**
	 * Intercept the execution of a handler. Called after HandlerAdapter actually
	 * invoked the handler.
	 *
	 *
DispatcherServlet processes a handler in an execution chain, consisting
	 * of any number of interceptors, with the handler itself at the end.
	 * With this method, each interceptor can post-process an execution,
	 * getting applied in inverse order of the execution chain.
	 *
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param handler chosen handler to execute, for type and/or instance evaluation
	 * @throws ServletException if there is an internal error
	 * @throws IOException in case of an I/O error when writing the response
	 */
	void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
	    throws ServletException, IOException;

}


text:
.visible { visibility: inherit !important; }
.top { vertical-align: top !important; }
.middle { vertical-align: middle !important; }
.bottom { vertical-align: bottom !important; }
.nowrap { white-space: nowrap !important; }
.italic { font-style: italic !important; }
.bold { font-weight: bold !important; }
.underline { text-decoration: underline !important; }
.line-through { text-decoration: line-through !important; }
.normal { font-weight: normal !important; font-style: normal !important; }
.gap { margin: 1em 0 !important; padding: 1em 0 !important; }
.sub { color: #777; font-size: 0.9em;}
.cursor-pointer { cursor: pointer !important;}
.cursor-help { cursor: help !important;}
.cursor-wait { cursor: wait !important;}
.cursor-crosshair { cursor: crosshair !important;}
.cursor-text { cursor: text !important;}
.cursor-default { cursor: default !important;}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_buy_from_taobao"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zhanghao.skinexpert.Activity.CommonWebviewActivity">

    <RelativeLayout
        android:id="@+id/rv_detail_comonweb_top"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center_vertical">

        <ImageView
            android:id="@+id/img_detail_commonweb_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:clickable="true"
            android:onClick="onClick"
            android:src="@mipmap/ic_return_back"/>

        <TextView
            android:id="@+id/tv_commonweb_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_gravity="center"
            android:text=""
            android:textSize="20sp"/>
    </RelativeLayout>

    <WebView
        android:id="@+id/web_commonweb"
        android:layout_below="@id/rv_detail_comonweb_top"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>

    <RelativeLayout
        android:visibility="gone"
        android:id="@+id/rv_all_elements"
        android:layout_below="@id/rv_detail_comonweb_top"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:id="@+id/ll_all_elements_table_head"
            android:layout_width="match_parent"
            android:orientation="horizontal"
            android:layout_height="50dp">
            <TextView
                android:layout_width="0dp"
                android:layout_weight="4"
                android:text="成分名称"
                android:textColor="@color/black"
                android:layout_marginLeft="10dp"
                android:textSize="15sp"
                android:gravity="center_vertical"
                android:layout_height="match_parent"/>
            <TextView
                android:layout_width="0dp"
                android:layout_weight="1.8"
                android:text="功效成分"
                android:textColor="@color/black"
                android:layout_marginLeft="10dp"
                android:textSize="15sp"
                android:gravity="center"
                android:layout_height="match_parent"/>

            <TextView
                android:layout_width="0dp"
                android:layout_weight="2"
                android:text="风险提示"
                android:textColor="@color/black"
                android:layout_marginLeft="10dp"
                android:textSize="15sp"
                android:gravity="center"
                android:layout_height="match_parent"/>

            <TextView
                android:layout_width="0dp"
                android:layout_weight="2.2"
                android:text="主要作用"
                android:textColor="@color/black"
                android:layout_marginLeft="10dp"
                android:textSize="15sp"
                android:gravity="center"
                android:layout_height="match_parent"/>
        </LinearLayout>
        <ListView
            android:id="@+id/lv_show_all_elements"
            android:layout_below="@+id/ll_all_elements_table_head"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></ListView>
    </RelativeLayout>
</RelativeLayout>


text:
package be.gest.dao;

import org.springframework.stereotype.Repository;

import be.gest.model.MaterielLocation;

@Repository("materielLocationDAO")
public class MaterielLocationDAOImpl extends AbstractDaoImpl<MaterielLocation> implements MaterielLocationDAO {

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE404_Improper_Resource_Shutdown__w32CreateFile_fclose_81.h
Label Definition File: CWE404_Improper_Resource_Shutdown__w32CreateFile.label.xml
Template File: source-sinks-81.tmpl.h
*/
/*
 * @description
 * CWE: 404 Improper Resource Shutdown or Release
 * BadSource:  Open a file using CreateFile()
 * Sinks: fclose
 *    GoodSink: Close the file using CloseHandle()
 *    BadSink : Close the file using fclose()
 * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
 *
 * */

#include "std_testcase.h"

#include <windows.h>

namespace CWE404_Improper_Resource_Shutdown__w32CreateFile_fclose_81
{

class CWE404_Improper_Resource_Shutdown__w32CreateFile_fclose_81_base
{
public:
    /* pure virtual function */
    virtual void action(HANDLE data) const = 0;
};

#ifndef OMITBAD

class CWE404_Improper_Resource_Shutdown__w32CreateFile_fclose_81_bad : public CWE404_Improper_Resource_Shutdown__w32CreateFile_fclose_81_base
{
public:
    void action(HANDLE data) const;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE404_Improper_Resource_Shutdown__w32CreateFile_fclose_81_goodB2G : public CWE404_Improper_Resource_Shutdown__w32CreateFile_fclose_81_base
{
public:
    void action(HANDLE data) const;
};

#endif /* OMITGOOD */

}


text:
<?php declare(strict_types=1);

namespace Kuria\Cache\Driver\Filesystem\Entry\Exception;

use Kuria\Cache\Driver\Exception\DriverException;

class FileHandleException extends DriverException
{
}


text:
package net.dontdrinkandroot.example.angularrestspringsecurity.transfer;

public class TokenTransfer
{

	private final String token;

	public TokenTransfer(String token)
	{
		this.token = token;
	}

	public String getToken()
	{
		return this.token;
	}

}


text:
var TwitterAdapter = function(_options) {
	this.init(_options);
	return this;
};

// Init with application only authorization (bearer)
TwitterAdapter.prototype.init = function(_options) {
	this.service = _options && _options.service || 'twitter';
	var Codebird = require("vendor/codebird");
	this.cb = new Codebird();
	this.cb.setConsumerKey(Ti.App.Properties.getString('twitter.consumerkey'), Ti.App.Properties.getString('twitter.consumersecret'));
	this.accessToken = null;
	this.accessTokenSecret = null;
	var bearerToken = Ti.App.Properties.getString('TwitterBearerToken', null);
	var self = this;
	if (bearerToken == null) {
		console.log('Info: bearertoken missing => fetching one');
		this.fetch('oauth2_token', {}, function(reply) {
			var bearer_token = reply.access_token;
			console.log('Info: bearertoken =' + bearer_token);
			self.cb.setBearerToken(bearer_token);
			Ti.App.Properties.setString('TwitterBearerToken', bearer_token);
		});
	} else {
		console.log('Info: bearertoken always in system');
		this.cb.setBearerToken(bearerToken);
	}
};

// Helpers:
TwitterAdapter.prototype.loadAccessToken = function() {
	if (!Ti.App.Properties.hasProperty(this.service) || !Ti.App.Properties.getString(this.service)) {
		console.log('Info: missing accesstoken in local storage');
		return;
	}
	var config = undefined;
	try {
		config = JSON.parse(Ti.App.Properties.getString(this.service));
	} catch(ex) {
		console.log('Info: accesstoken invalice => removing it');
		Ti.App.Properties.removeProperty(this.service);
		return;
	}
	if (config.accessToken) {
		this.accessToken = config.accessToken;
	}
	if (config.accessTokenSecret) {
		this.accessTokenSecret = config.accessTokenSecret;
	}
};

TwitterAdapter.prototype.saveAccessToken = function() {
	Ti.App.Properties.setString(this.service, JSON.stringify({
		accessToken : this.accessToken,
		accessTokenSecret : this.accessTokenSecret
	}));
	Ti.API.info('Info: Saving access token: done.');
};

TwitterAdapter.prototype.clearAccessToken = function() {
	Ti.App.Properties.setString(this.service, JSON.stringify({
		accessToken : null,
		accessTokenSecret : null
	}));
	this.accessToken = null;
	this.accessTokenSecret = null;
};
// End of Helpers

// send a tweet (only if accesstoken is present)
TwitterAdapter.prototype.addTweet = function(_args) {
	if (!_args.tweet.match(/#ergobaby/i))
		_args.tweet += '#ErgoBaby';
	this.cb.__call("statuses_update", {
		"status" : _args.tweet
	}, function(reply) {
		if (reply.httpstatus == 200) {
			Ti.Android && Ti.UI.createNotification({
				message : "Tweet erfolgreich publiziert.",
				duration : Ti.UI.NOTIFICATION_DURATION_LONG
			}).show();
			_args.ontweeted && _args.ontweeted(true);
		} else {
			_args.ontweeted && _args.ontweeted(false);
		}
	});
};

TwitterAdapter.prototype.authorize = function(_callback) {
	console.log('Info: starting with tweeting, test on tokens:');
	//this.clearAccessToken();
	this.loadAccessToken();
	if (this.accessTokenSecret != null && this.accessToken != null) {
		this.cb.setToken(this.accessToken, this.accessTokenSecret);
		_callback && _callback({
			success : true
		});
	} else {
		Ti.Android && Ti.UI.createNotification({
			message : "Starte Login bei Twitter.",
			duration : Ti.UI.NOTIFICATION_DURATION_LONG
		}).show();
		var self = this;
		this.cb.__call("oauth_requestToken", {
			oauth_callback : "oob"
		}, function(reply) {
			console.log('Info: got request token: ' + JSON.stringify(reply));
			self.cb.setToken(reply.oauth_token, reply.oauth_token_secret);
			self.cb.__call("oauth_authorize", {}, function(auth_url) {
				var win = Ti.UI.createWindow({
					fullscreen : true,
					enableZoomControls : false,
					disableBounce : true,
					modal : true,navBarHidden:true,
					hideLoadIndicator : true,
					transform : Ti.UI.create2DMatrix({
						scale : 0.95
					})
				});
				win.open();
				var webView = Ti.UI.createWebView({
					url : auth_url,
					width : Ti.UI.FILL,
					height : Ti.UI.FILL
				});
				win.add(webView);
				var destroyAuthorizeUI = function() {
					Ti.API.info('destroyAuthorizeUI');
					try {
						webView.removeEventListener('load', authorizeUICallback);
						win.remove(webView);
						webView = null;
						win.close();
					} catch(ex) {
						Ti.API.info('Cannot destroy the authorize UI. Ignoring.');
					}
				};
				var authorizeUICallback = function(e) {
					var val = webView.evalJS('window.document.querySelector(\'kbd[aria-labelledby="code-desc"] > code\').innerHTML');
					if (val) {
						destroyAuthorizeUI();
						self.cb.__call("oauth_accessToken", {
							oauth_verifier : val
						}, function(reply) {
							self.cb.setToken(reply.oauth_token, reply.oauth_token_secret);
							Ti.API.info(reply);

							self.accessToken = reply.oauth_token;
							self.accessTokenSecret = reply.oauth_token_secret;
							self.saveAccessToken();
							_callback && _callback({
								success : true
							});

						});
					}
				};
				webView.addEventListener('load', authorizeUICallback);
			});
		});
	}
};

//  anonymous fetching of twitter:
TwitterAdapter.prototype.fetch = function(_action, _needle, _callback) {
	this.cb.__call(_action, {
		q : Ti.Network.encodeURIComponent(_needle)
	}, function(reply) {
		if (reply.httpstatus == 200)
			_callback && _callback(reply);
	}, true);
};

module.exports = TwitterAdapter;


text:
import { StopSignFilled24 } from "../../";

export = StopSignFilled24;


text:
                <form class="form-signin form-horizontal" id="search_alumno_form" method="POST" action="<?php echo base_url(); ?>admin/inscribir/busca_alumno.jsp">

                        Nombre del alumno

                            <input name="cta" class="form-control" id="cta_input" />

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

                </form>

                Nombre
                Apellido Paterno
                Apellido Materno
                Fecha de nacimiento
                Acciones


text:
 <?=$lang['add-success-message']?>

<?=$lang['add-success-message-redirect']?>

0


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding model 'DailyStatus'
        db.create_table('status_dailystatus', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('daily_visitors', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)),
            ('date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
        ))
        db.send_create_signal('status', ['DailyStatus'])

    def backwards(self, orm):

        # Deleting model 'DailyStatus'
        db.delete_table('status_dailystatus')

    models = {
        'status.dailystatus': {
            'Meta': {'object_name': 'DailyStatus'},
            'daily_visitors': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        }
    }

    complete_apps = ['status']


text:
package course.labs.locationlab;

import android.app.ListActivity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class PlaceViewActivity extends ListActivity implements LocationListener {
    private static final long FIVE_MINS = 5 * 60 * 1000;
    private static final String TAG = "Lab-Location";

    // Set to false if you don't have network access
    public static boolean sHasNetwork = false;

    private Location mLastLocationReading;
    private PlaceViewAdapter mAdapter;
    private LocationManager mLocationManager;
    private boolean mMockLocationOn = false;

    // default minimum time between new readings
    private long mMinTime = 5000;

    // default minimum distance between old and new readings.
    private float mMinDistance = 1000.0f;

    // A fake location provider used for testing
    private MockLocationProvider mMockLocationProvider;
    private View footerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set up the app's user interface. This class is a ListActivity,
        // so it has its own ListView. ListView's adapter should be a PlaceViewAdapter

        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        ListView placesListView = getListView();

        footerView = getLayoutInflater().inflate(R.layout.footer_view, null);
        getListView().addFooterView(footerView);
        footerView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Log.i(TAG, "Entered footerView.OnClickListener.onClick()");
                if (mLastLocationReading == null) {
                    Toast.makeText(getApplicationContext(), "No location found!", Toast.LENGTH_LONG).show();
                    footerView.setClickable(false);
                    return;
                } else {
                    if (mAdapter.intersects(mLastLocationReading)) {
                        Toast.makeText(getApplicationContext(), "You already have this location badge", Toast.LENGTH_LONG).show();
                        return;
                    } else {
                        sHasNetwork = true;
                        new PlaceDownloaderTask(PlaceViewActivity.this, sHasNetwork).execute(mLastLocationReading);

                    }
                }
            }
        });

        placesListView.addFooterView(footerView);
        mAdapter = new PlaceViewAdapter(getApplicationContext());
        setListAdapter(mAdapter);

    }

    @Override
    protected void onResume() {
        super.onResume();
        startMockLocationManager();
        if (null == mLastLocationReading
                || mLastLocationReading.getAccuracy() > mMinDistance
                || mLastLocationReading.getTime() < System.currentTimeMillis()
                - mMinTime) {
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, mMinTime, mMinDistance, this);
            footerView.setClickable(true);
            return;
        }

    }

    @Override
    protected void onPause() {
        mLocationManager.removeUpdates(this);

        shutdownMockLocationManager();
        super.onPause();
    }

    // Callback method used by PlaceDownloaderTask
    public void addNewPlace(PlaceRecord place) {
        Log.i(TAG, "Entered addNewPlace()");
        if (mLastLocationReading != null && mAdapter.intersects(mLastLocationReading)) {
            Toast.makeText(getApplicationContext(), "You already have this location badge", Toast.LENGTH_LONG).show();
            return;
        }
        if (place == null) {
            Toast.makeText(getApplicationContext(), "PlaceBadge could not be acquired", Toast.LENGTH_LONG).show();
            return;
        }
        if (place.getCountryName() == "") {
            Toast.makeText(getApplicationContext(), "There is no country at this location", Toast.LENGTH_LONG).show();
            return;
        }
        mAdapter.add(place);
    }

    // LocationListener methods
    @Override
    public void onLocationChanged(Location currentLocation) {
        footerView.setClickable(true);
        if (mLastLocationReading == null) {
            mLastLocationReading = currentLocation;
            return;
        }

        if (currentLocation.getTime() < mLastLocationReading.getTime())
            return;

        mLastLocationReading = currentLocation;
    }

    @Override
    public void onProviderDisabled(String provider) {
        // not implemented
    }

    @Override
    public void onProviderEnabled(String provider) {
        // not implemented
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // not implemented
    }

    // Returns age of location in milliseconds
    private long ageInMilliseconds(Location location) {
        return System.currentTimeMillis() - location.getTime();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.delete_badges:
                mAdapter.removeAllViews();
                return true;
            case R.id.place_one:
                footerView.setClickable(true);
                mMockLocationProvider.pushLocation(37.422, -122.084);
                return true;
            case R.id.place_no_country:
                mMockLocationProvider.pushLocation(0, 0);
                return true;
            case R.id.place_two:
                footerView.setClickable(true);
                mMockLocationProvider.pushLocation(38.996667, -76.9275);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void shutdownMockLocationManager() {
        if (mMockLocationOn) {
            mMockLocationProvider.shutdown();
        }
    }

    private void startMockLocationManager() {
        if (!mMockLocationOn) {
            mMockLocationProvider = new MockLocationProvider(
                    LocationManager.NETWORK_PROVIDER, this);
        }
    }
}


text:
function main() {

  const atomic_def = atomics(graph).map(atomic_process).join('\n\n')
  const compound_def = compounds(graph).map((node) => compound_process(node, graph)).join('\n\n')
  const main_name = compounds(graph).filter((n) => n.componentId === 'main')[0]

  return `#include <future>
#include <cstdlib>
#include <iostream>
#include <string>

typedef int Number;

struct String {
  String(std::string v) : value(v) {}
  std::string value;
};

struct IO {
  void print_string(const String &str) {
    std::cout << str.value;
  }
};

${ atomic_def }

${ compound_def }

int main(int argc, char *argv[])
{
  // Workaround: Need to create promise to get a future which is needed for the call to P_main.
  // In future sequential calls should directly take the value!
  std::promise<IO> out_from_here_IO;
  std::shared_future<IO> in_to_P_main_IO = out_from_here_IO.get_future().share();
  out_from_here_IO.set_value(IO());

  std::promise<IO> out_from_P_main_value;
  std::shared_future<IO> in_to_here_value = out_from_P_main_value.get_future().share();

  ${ func_name(main_name) }(in_to_P_main_IO, std::move(out_from_P_main_value));
  in_to_here_value.wait();

  return 0;
}`
}

function port_name(port) {
  return `${port.port}`
}


text:
@echo off

set PROJDIR=%~dp0

for /f "usebackq tokens=*" %%i in (`"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere" -latest -products * -requires Microsoft.Component.MSBuild -property installationPath`) do (
  set InstallDir=%%i
)

if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" (
	call "%InstallDir%\Common7\Tools\VsDevCmd.bat"
	pushd %PROJDIR%
	"%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" /m:%NUMBER_OF_PROCESSORS% /nr:false /nologo /verbosity:minimal %*
	popd
)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_attrappendchild6</title>
<link href="activity-home.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css">

Test http://www.w3.org/2001/DOM-Test-Suite/level1/core/hc_attrappendchild6

Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C(r) Software License in the
hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


text: REST API in Go with MongoDB as the data store.


text:
/* tslint:disable */
/* eslint-disable */

import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type FairsIndex_featuredFairs = ReadonlyArray<{
    readonly items: ReadonlyArray<{
        readonly internalID?: string | null;
        readonly title?: string | null;
        readonly image?: {
            readonly cropped: {
                readonly width: number;
                readonly height: number;
                readonly src: string;
                readonly srcSet: string;
            } | null;
        } | null;
    } | null> | null;
    readonly " $refType": "FairsIndex_featuredFairs";
}>;
export type FairsIndex_featuredFairs$data = FairsIndex_featuredFairs;
export type FairsIndex_featuredFairs$key = ReadonlyArray<{
    readonly " $data"?: FairsIndex_featuredFairs$data;
    readonly " $fragmentRefs": FragmentRefs<"FairsIndex_featuredFairs">;
}>;

const node: ReaderFragment = {
  "argumentDefinitions": [],
  "kind": "Fragment",
  "metadata": {
    "plural": true
  },
  "name": "FairsIndex_featuredFairs",
  "selections": [
    {
      "alias": null,
      "args": null,
      "concreteType": null,
      "kind": "LinkedField",
      "name": "items",
      "plural": true,
      "selections": [
        {
          "kind": "InlineFragment",
          "selections": [
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "internalID",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "kind": "ScalarField",
              "name": "title",
              "storageKey": null
            },
            {
              "alias": null,
              "args": null,
              "concreteType": "Image",
              "kind": "LinkedField",
              "name": "image",
              "plural": false,
              "selections": [
                {
                  "alias": null,
                  "args": [
                    {
                      "kind": "Literal",
                      "name": "height",
                      "value": 410
                    },
                    {
                      "kind": "Literal",
                      "name": "width",
                      "value": 547
                    }
                  ],
                  "concreteType": "CroppedImageUrl",
                  "kind": "LinkedField",
                  "name": "cropped",
                  "plural": false,
                  "selections": [
                    {
                      "alias": null,
                      "args": null,
                      "kind": "ScalarField",
                      "name": "width",
                      "storageKey": null
                    },
                    {
                      "alias": null,
                      "args": null,
                      "kind": "ScalarField",
                      "name": "height",
                      "storageKey": null
                    },
                    {
                      "alias": null,
                      "args": null,
                      "kind": "ScalarField",
                      "name": "src",
                      "storageKey": null
                    },
                    {
                      "alias": null,
                      "args": null,
                      "kind": "ScalarField",
                      "name": "srcSet",
                      "storageKey": null
                    }
                  ],
                  "storageKey": "cropped(height:410,width:547)"
                }
              ],
              "storageKey": null
            }
          ],
          "type": "FeaturedLink"
        }
      ],
      "storageKey": null
    }
  ],
  "type": "OrderedSet"
};
(node as any).hash = 'cc81fb4953a72c4ccea5b747da589837';
export default node;


text:
START_ATF_NAMESPACE
    #pragma pack(push, 8)
    struct tagLVFINDINFOA
    {
        unsigned int flags;
        const char *psz;
        __int64 lParam;
        tagPOINT pt;
        unsigned int vkDirection;
    };
    #pragma pack(pop)
END_ATF_NAMESPACE


text:
  Minimal CSS Framework

Alerts provide feedback messages for user actions.

Examples


text:
set -o errexit  # the script ends if a command fails
set -o pipefail # the script ends if a command fails in a pipe
set -o nounset  # the script ends if it uses an undeclared variable

# script que añade, busca y opera con movimientos bancarios.

# variables globales
BANCO_SCRIPT=./banco

# función de ayuda
function help() {
cat << DESCRIPCION_AYUDA
SYNOPIS
    $0 [OPCIÓN] [PARÁMETROS]

DESCRIPCIÓN
    Añade, busca, lista y opera con movimientos bancarios.

OPCIONES
    -h --help                           Muestra una ayuda.
    -a --add    FECHA CONCEPTO CANTIDAD Añade un movimiento bancario.
    -s --search PATRÓN                  Busca un movimiento bancario.
    -l --list                           Lista los movimientos bancarios ordenados por fecha.
    -t --total                          Calcula el saldo total de la cuenta.

CÓDIGOS DE RETORNO
    0 Si no hay ningún error.
    1 Si la opción introducida no es válida.
    2 Si un argumento númerico no es un número.
    3 Si el número de parámetros es erróneo.
    4 Si un argumento de tipo fecha no es una fecha.
    5 Si hay un error de entrada/salida en el fichero de datos.
    6 Si no introducen ningún parámetro.
DESCRIPCION_AYUDA
}

# función para añadir un movimiento bancario
function add() {
    echo "AÑADIR UN MOVIMIENTO BANCARIO"
    $BANCO_SCRIPT --add "$@"
    echo "-----------------------------"
}

# función para búscar un movimiento bancario
function search() {
    echo "BUSCAR MOVIMIENTO BANCARIO ($*)"
    $BANCO_SCRIPT --search "$@"
    echo "-----------------------------"
}

# función para listar movimientos bancarios ordenados por mes y día
function list() {
    echo "LISTAR ORDENADO POR FECHA"
    $BANCO_SCRIPT --list
    echo "-----------------------------"
}

# función para mostrar el saldo total de la cuenta
function total() {
    echo "SALDO TOTAL DE LA CUENTA"
    $BANCO_SCRIPT --total
    echo "-----------------------------"
}

# función opción invalida
function opcion_invalida() {
    echo "Opción '$1' inválida."
    exit 6
}

# si número de parámetros menor o igual que 0
if [ $# -le 0 ]; then
    echo "Hay que introducir al menos un parámetro."
    help
    exit 6
fi

case $1 in
    -h|--help)                  help;;
    -a|--add)    shift;     add "$@";;
    -s|--search) shift;  search "$@";;
    -l|--list)                  list;;
    -t|--total)                total;;
    *) exitWithError $LINENO "Opción '$1' inválida." 1
esac


text:
@interface PodsDummy_swiftRemoteLogger : NSObject
@end
@implementation PodsDummy_swiftRemoteLogger
@end


text:
package commands

import (
	"context"
	"fmt"
	"reflect"
	"strings"

	"github.com/ghodss/yaml"
	"github.com/golang/protobuf/jsonpb"
	"github.com/golang/protobuf/proto"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"

	"go.ligato.io/vpp-agent/v3/cmd/agentctl/api/types"
	agentcli "go.ligato.io/vpp-agent/v3/cmd/agentctl/cli"
)

func NewGenerateCommand(cli agentcli.Cli) *cobra.Command {
	var (
		opts GenerateOptions
	)
	cmd := &cobra.Command{
		Use:     "generate MODEL",
		Aliases: []string{"gen"},
		Short:   "Generate config samples",
		Args:    cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			opts.Model = args[0]
			return runGenerate(cli, opts)
		},
	}
	flags := cmd.Flags()
	flags.StringVarP(&opts.Format, "format", "f", "json",
		"Output formats: json, yaml")
	flags.BoolVar(&opts.OneLine, "oneline", false,
		"Print output as single line (only json format)")
	return cmd
}

type GenerateOptions struct {
	Model   string
	Format  string
	OneLine bool
}

func runGenerate(cli agentcli.Cli, opts GenerateOptions) error {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	allModels, err := cli.Client().ModelList(ctx, types.ModelListOptions{
		Class: "config",
	})
	if err != nil {
		return err
	}

	modelList := filterModelsByRefs(allModels, []string{opts.Model})

	if len(modelList) == 0 {
		return fmt.Errorf("no model found for: %s", opts.Model)
	}

	logrus.Debugf("models: %+v", modelList)
	model := modelList[0]

	valueType := proto.MessageType(model.ProtoName)
	if valueType == nil {
		return fmt.Errorf("unknown proto message defined for: %s", model.ProtoName)
	}
	modelInstance := reflect.New(valueType.Elem()).Interface().(proto.Message)

	var out string

	switch strings.ToLower(opts.Format) {
	case "j", "json":
		m := jsonpb.Marshaler{
			EnumsAsInts:  false,
			EmitDefaults: true,
			Indent:       "  ",
			OrigName:     true,
			AnyResolver:  nil,
		}
		if opts.OneLine {
			m.Indent = ""
		}
		out, err = m.MarshalToString(modelInstance)
		if err != nil {
			return fmt.Errorf("encoding to json failed: %v", err)
		}
	case "y", "yaml":
		m := jsonpb.Marshaler{
			EnumsAsInts:  false,
			EmitDefaults: true,
			Indent:       "  ",
			OrigName:     true,
			AnyResolver:  nil,
		}
		out, err = m.MarshalToString(modelInstance)
		if err != nil {
			return fmt.Errorf("encoding to json failed: %v", err)
		}
		b, err := yaml.JSONToYAML([]byte(out))
		if err != nil {
			return fmt.Errorf("encoding to yaml failed: %v", err)
		}
		out = string(b)
	case "p", "proto":
		m := proto.TextMarshaler{
			Compact:   false,
			ExpandAny: false,
		}
		out = m.Text(modelInstance)
	default:
		return fmt.Errorf("unknown format: %s", opts.Format)
	}

	fmt.Fprintf(cli.Out(), "%s\n", out)
	return nil
}


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

namespace _15.DebuggingSubstring
{
    class DebuggingSubstring
    {
        static void Main(string[] args)
        {
            string text = Console.ReadLine();
            int jump = int.Parse(Console.ReadLine());

            char letterP = 'p';
            bool hasMatch = false;

            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] == letterP)
                {
                    text = text.ToString();
                    hasMatch = true;
                    int endIndex = jump + i;

                    if (endIndex > text.Length - 1)
                    {
                        endIndex = text.Length - 1;
                    }
                    string matchedString = text.Substring(i, endIndex - i + 1);
                    Console.WriteLine(matchedString);
                    i += jump;
                }
            }

            if (!hasMatch)
            {
                Console.WriteLine("no");
            }
        }
    }
}


text:
namespace swift {

/// A file containing Swift source code.
///
/// This is a .swift or .sil file (or a virtual file, such as the contents of
/// the REPL). Since it contains raw source, it must be parsed and name-bound
/// before being used for anything; a full type-check is also necessary for
/// IR generation.
class SourceFile final : public FileUnit {
public:
  class Impl;
  struct SourceFileSyntaxInfo;

  /// The implicit module import that the SourceFile should get.
  enum class ImplicitModuleImportKind {
    None,
    Builtin,
    Stdlib
  };

  /// Possible attributes for imports in source files.
  enum class ImportFlags {
    /// The imported module is exposed to anyone who imports the parent module.
    Exported = 0x1,

    /// This source file has access to testable declarations in the imported
    /// module.
    Testable = 0x2,

    /// This source file has access to private declarations in the imported
    /// module.
    PrivateImport = 0x4,

    /// The imported module is an implementation detail of this file and should
    /// not be required to be present if the main module is ever imported
    /// elsewhere.
    ///
    /// Mutually exclusive with Exported.
    ImplementationOnly = 0x8
  };

  /// \see ImportFlags
  using ImportOptions = OptionSet<ImportFlags>;

  struct ImportedModuleDesc {
    ModuleDecl::ImportedModule module;
    ImportOptions importOptions;
    StringRef filename;

    ImportedModuleDesc(ModuleDecl::ImportedModule module, ImportOptions options,
                       StringRef filename = {})
        : module(module), importOptions(options), filename(filename) {
      assert(!(importOptions.contains(ImportFlags::Exported) &&
               importOptions.contains(ImportFlags::ImplementationOnly)));
    }
  };

private:
  std::unique_ptr<SourceLookupCache> Cache;
  SourceLookupCache &getCache() const;

  /// This is the list of modules that are imported by this module.
  ///
  /// This is filled in by the Name Binding phase.
  ArrayRef<ImportedModuleDesc> Imports;

  /// A unique identifier representing this file; used to mark private decls
  /// within the file to keep them from conflicting with other files in the
  /// same module.
  mutable Identifier PrivateDiscriminator;

  /// The root TypeRefinementContext for this SourceFile.
  ///
  /// This is set during type checking.
  TypeRefinementContext *TRC = nullptr;

  /// If non-null, used to track name lookups that happen within this file.
  Optional<ReferencedNameTracker> ReferencedNames;

  /// The class in this file marked \@NS/UIApplicationMain.
  ClassDecl *MainClass = nullptr;

  /// The source location of the main class.
  SourceLoc MainClassDiagLoc;

  /// A hash of all interface-contributing tokens that have been lexed for
  /// this source file so far.
  /// We only collect interface hash for primary input files.
  llvm::Optional<llvm::MD5> InterfaceHash;

  /// The ID for the memory buffer containing this file's source.
  ///
  /// May be -1, to indicate no association with a buffer.
  int BufferID;

  /// Does this source file have any implementation-only imports?
  /// If not, we can fast-path module checks.
  bool HasImplementationOnlyImports = false;

  /// The scope map that describes this source file.
  std::unique_ptr<ASTScope> Scope;

  /// The set of validated opaque return type decls in the source file.
  llvm::SmallVector<OpaqueTypeDecl *, 4> OpaqueReturnTypes;
  llvm::StringMap<OpaqueTypeDecl *> ValidatedOpaqueReturnTypes;
  /// The set of parsed decls with opaque return types that have not yet
  /// been validated.
  llvm::SetVector<ValueDecl *> UnvalidatedDeclsWithOpaqueReturnTypes;

  /// The list of top-level declarations in the source file.
  std::vector<Decl *> Decls;

  friend ASTContext;
  friend Impl;

public:
  /// Appends the given declaration to the end of the top-level decls list.
  void addTopLevelDecl(Decl *d) {
    Decls.push_back(d);
  }

  /// Prepends a declaration to the top-level decls list.
  ///
  /// FIXME: This entrypoint exists to support LLDB. Calls to this function are
  /// always a mistake, and additional uses should not be added.
  ///
  /// See rdar://58355191
  void prependTopLevelDecl(Decl *d) {
    Decls.insert(Decls.begin(), d);
  }

  /// Retrieves an immutable view of the list of top-level decls in this file.
  ArrayRef<Decl *> getTopLevelDecls() const {
    return Decls;
  }

  /// Truncates the list of top-level decls so it contains \c count elements.
  void truncateTopLevelDecls(unsigned count) {
    assert(count <= Decls.size() && "Can only truncate top-level decls!");
    Decls.resize(count);
  }

  /// A cache of syntax nodes that can be reused when creating the syntax tree
  /// for this file.
  swift::SyntaxParsingCache *SyntaxParsingCache = nullptr;

  /// The list of local type declarations in the source file.
  llvm::SetVector<TypeDecl *> LocalTypeDecls;

  /// A set of special declaration attributes which require the
  /// Foundation module to be imported to work. If the foundation
  /// module is still not imported by the time type checking is
  /// complete, we diagnose.
  llvm::SetVector<const DeclAttribute *> AttrsRequiringFoundation;

  /// A set of synthesized declarations that need to be type checked.
  llvm::SmallVector<Decl *, 8> SynthesizedDecls;

  /// We might perform type checking on the same source file more than once,
  /// if its the main file or a REPL instance, so keep track of the last
  /// checked synthesized declaration to avoid duplicating work.
  unsigned LastCheckedSynthesizedDecl = 0;

  /// A mapping from Objective-C selectors to the methods that have
  /// those selectors.
  llvm::DenseMap<ObjCSelector, llvm::TinyPtrVector<AbstractFunctionDecl *>>
    ObjCMethods;

  /// List of Objective-C methods, which is used for checking unintended
  /// Objective-C overrides.
  std::vector<AbstractFunctionDecl *> ObjCMethodList;

  /// An unsatisfied, optional @objc requirement in a protocol conformance.
  using ObjCUnsatisfiedOptReq = std::pair<DeclContext *, AbstractFunctionDecl *>;

  /// List of optional @objc protocol requirements that have gone
  /// unsatisfied, which might conflict with other Objective-C methods.
  std::vector<ObjCUnsatisfiedOptReq> ObjCUnsatisfiedOptReqs;

  using ObjCMethodConflict = std::tuple<ClassDecl *, ObjCSelector, bool>;

  /// List of Objective-C member conflicts we have found during type checking.
  std::vector<ObjCMethodConflict> ObjCMethodConflicts;

  template <typename T>
  using OperatorMap = llvm::DenseMap<Identifier,llvm::PointerIntPair<T,1,bool>>;

  OperatorMap<InfixOperatorDecl*> InfixOperators;
  OperatorMap<PostfixOperatorDecl*> PostfixOperators;
  OperatorMap<PrefixOperatorDecl*> PrefixOperators;
  OperatorMap<PrecedenceGroupDecl*> PrecedenceGroups;

  /// Describes what kind of file this is, which can affect some type checking
  /// and other behavior.
  const SourceFileKind Kind;

  enum ASTStage_t {
    /// Parsing is underway.
    Parsing,
    /// Parsing has completed.
    Parsed,
    /// Name binding has completed.
    NameBound,
    /// Type checking has completed.
    TypeChecked
  };

  /// Defines what phases of parsing and semantic analysis are complete for a
  /// source file.
  ///
  /// Only files that have been fully processed (i.e. type-checked) will be
  /// forwarded on to IRGen.
  ASTStage_t ASTStage = Parsing;

  SourceFile(ModuleDecl &M, SourceFileKind K, Optional<unsigned> bufferID,
             ImplicitModuleImportKind ModImpKind, bool KeepParsedTokens = false,
             bool KeepSyntaxTree = false);

  ~SourceFile();

  void addImports(ArrayRef<ImportedModuleDesc> IM);

  enum ImportQueryKind {
    /// Return the results for testable or private imports.
    TestableAndPrivate,
    /// Return the results only for testable imports.
    TestableOnly,
    /// Return the results only for private imports.
    PrivateOnly
  };

  bool
  hasTestableOrPrivateImport(AccessLevel accessLevel, const ValueDecl *ofDecl,
                             ImportQueryKind kind = TestableAndPrivate) const;

  bool hasImplementationOnlyImports() const {
    return HasImplementationOnlyImports;
  }

  bool isImportedImplementationOnly(const ModuleDecl *module) const;

  /// This is a hack for 'main' file parsing and the integrated REPL.
  ///
  /// FIXME: Refactor main file parsing to not pump the parser incrementally.
  /// FIXME: Remove the integrated REPL.
  void clearLookupCache();

  void cacheVisibleDecls(SmallVectorImpl<ValueDecl *> &&globals) const;
  const SmallVectorImpl<ValueDecl *> &getCachedVisibleDecls() const;

  virtual void lookupValue(DeclName name, NLKind lookupKind,
                           SmallVectorImpl<ValueDecl*> &result) const override;

  virtual void lookupVisibleDecls(ModuleDecl::AccessPathTy accessPath,
                                  VisibleDeclConsumer &consumer,
                                  NLKind lookupKind) const override;

  virtual void lookupClassMembers(ModuleDecl::AccessPathTy accessPath,
                                  VisibleDeclConsumer &consumer) const override;
  virtual void
  lookupClassMember(ModuleDecl::AccessPathTy accessPath, DeclName name,
                    SmallVectorImpl<ValueDecl*> &results) const override;

  void lookupObjCMethods(
         ObjCSelector selector,
         SmallVectorImpl<AbstractFunctionDecl *> &results) const override;

  virtual void getTopLevelDecls(SmallVectorImpl<Decl*> &results) const override;

  virtual void
  getPrecedenceGroups(SmallVectorImpl<PrecedenceGroupDecl*> &results) const override;

  virtual TypeDecl *lookupLocalType(llvm::StringRef MangledName) const override;

  virtual void
  getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &results) const override;
  virtual void
  getOpaqueReturnTypeDecls(SmallVectorImpl<OpaqueTypeDecl*> &results) const override;

  virtual void
  getImportedModules(SmallVectorImpl<ModuleDecl::ImportedModule> &imports,
                     ModuleDecl::ImportFilter filter) const override;

  virtual void
  collectLinkLibraries(ModuleDecl::LinkLibraryCallback callback) const override;

  Identifier getDiscriminatorForPrivateValue(const ValueDecl *D) const override;
  Identifier getPrivateDiscriminator() const { return PrivateDiscriminator; }
  Optional<BasicDeclLocs> getBasicLocsForDecl(const Decl *D) const override;

  virtual bool walk(ASTWalker &walker) override;

  /// @{

  /// Look up the given operator in this file.
  ///
  /// The file must be name-bound already. If the operator is not found, or if
  /// there is an ambiguity, returns null.
  ///
  /// \param isCascading If true, the lookup of this operator may affect
  /// downstream files.
  InfixOperatorDecl *lookupInfixOperator(Identifier name, bool isCascading,
                                         SourceLoc diagLoc = {});
  PrefixOperatorDecl *lookupPrefixOperator(Identifier name, bool isCascading,
                                           SourceLoc diagLoc = {});
  PostfixOperatorDecl *lookupPostfixOperator(Identifier name, bool isCascading,
                                             SourceLoc diagLoc = {});
  PrecedenceGroupDecl *lookupPrecedenceGroup(Identifier name, bool isCascading,
                                             SourceLoc diagLoc = {});
  /// @}

  ReferencedNameTracker *getReferencedNameTracker() {
    return ReferencedNames ? ReferencedNames.getPointer() : nullptr;
  }
  const ReferencedNameTracker *getReferencedNameTracker() const {
    return ReferencedNames ? ReferencedNames.getPointer() : nullptr;
  }

  void createReferencedNameTracker();

  /// The buffer ID for the file that was imported, or None if there
  /// is no associated buffer.
  Optional<unsigned> getBufferID() const {
    if (BufferID == -1)
      return None;
    return BufferID;
  }

  /// If this buffer corresponds to a file on disk, returns the path.
  /// Otherwise, return an empty string.
  StringRef getFilename() const;

  /// Retrieve the scope that describes this source file.
  ASTScope &getScope();

  SWIFT_DEBUG_DUMP;
  void dump(raw_ostream &os) const;

  /// Pretty-print the contents of this source file.
  ///
  /// \param Printer The AST printer used for printing the contents.
  /// \param PO Options controlling the printing process.
  void print(ASTPrinter &Printer, const PrintOptions &PO);
  void print(raw_ostream &OS, const PrintOptions &PO);

  static bool classof(const FileUnit *file) {
    return file->getKind() == FileUnitKind::Source;
  }
  static bool classof(const DeclContext *DC) {
    return isa<FileUnit>(DC) && classof(cast<FileUnit>(DC));
  }

  /// True if this is a "script mode" source file that admits top-level code.
  bool isScriptMode() const {
    switch (Kind) {
    case SourceFileKind::Main:
    case SourceFileKind::REPL:
      return true;

    case SourceFileKind::Library:
    case SourceFileKind::Interface:
    case SourceFileKind::SIL:
      return false;
    }
    llvm_unreachable("bad SourceFileKind");
  }

  ClassDecl *getMainClass() const override {
    return MainClass;
  }
  SourceLoc getMainClassDiagLoc() const {
    assert(hasMainClass());
    return MainClassDiagLoc;
  }

  /// Register a "main" class for the module, complaining if there is more than
  /// one.
  ///
  /// Should only be called during type-checking.
  bool registerMainClass(ClassDecl *mainClass, SourceLoc diagLoc);

  /// True if this source file has an application entry point.
  ///
  /// This is true if the source file either is in script mode or contains
  /// a designated main class.
  bool hasEntryPoint() const override {
    return isScriptMode() || hasMainClass();
  }

  /// Get the root refinement context for the file. The root context may be
  /// null if the context hierarchy has not been built yet. Use
  /// TypeChecker::getOrBuildTypeRefinementContext() to get a built
  /// root of the hierarchy.
  TypeRefinementContext *getTypeRefinementContext();

  /// Set the root refinement context for the file.
  void setTypeRefinementContext(TypeRefinementContext *TRC);

  void enableInterfaceHash() {
    assert(!hasInterfaceHash());
    InterfaceHash.emplace();
  }

  bool hasInterfaceHash() const {
    return InterfaceHash.hasValue();
  }

  void recordInterfaceToken(StringRef token) {
    assert(!token.empty());
    InterfaceHash->update(token);
    // Add null byte to separate tokens.
    uint8_t a[1] = {0};
    InterfaceHash->update(a);
  }

  void getInterfaceHash(llvm::SmallString<32> &str) const {
    // Copy to preserve idempotence.
    llvm::MD5 md5 = *InterfaceHash;
    llvm::MD5::MD5Result result;
    md5.final(result);
    llvm::MD5::stringifyResult(result, str);
  }

  void dumpInterfaceHash(llvm::raw_ostream &out) {
    llvm::SmallString<32> str;
    getInterfaceHash(str);
    out << str << '\n';
  }

  std::vector<Token> &getTokenVector();

  ArrayRef<Token> getAllTokens() const;

  bool shouldCollectToken() const;

  bool shouldBuildSyntaxTree() const;

  bool canBeParsedInFull() const;

  bool isSuitableForASTScopes() const { return canBeParsedInFull(); }

  syntax::SourceFileSyntax getSyntaxRoot() const;
  void setSyntaxRoot(syntax::SourceFileSyntax &&Root);
  bool hasSyntaxRoot() const;

  OpaqueTypeDecl *lookupOpaqueResultType(StringRef MangledName) override;

  /// Do not call when inside an inactive clause (\c
  /// InInactiveClauseEnvironment)) because it will later on result in a lookup
  /// to something that won't be in the ASTScope tree.
  void addUnvalidatedDeclWithOpaqueResultType(ValueDecl *vd) {
    UnvalidatedDeclsWithOpaqueReturnTypes.insert(vd);
  }

  ArrayRef<OpaqueTypeDecl *> getOpaqueReturnTypeDecls();

private:

  /// If not None, the underlying vector should contain tokens of this source file.
  Optional<std::vector<Token>> AllCorrectedTokens;

  std::unique_ptr<SourceFileSyntaxInfo> SyntaxInfo;
};

inline SourceFile &
ModuleDecl::getMainSourceFile(SourceFileKind expectedKind) const {
  assert(!Files.empty() && "No files added yet");
  assert(cast<SourceFile>(Files.front())->Kind == expectedKind);
  return *cast<SourceFile>(Files.front());
}

inline FileUnit *ModuleDecl::EntryPointInfoTy::getEntryPointFile() const {
  return storage.getPointer();
}
inline void ModuleDecl::EntryPointInfoTy::setEntryPointFile(FileUnit *file) {
  assert(!storage.getPointer());
  storage.setPointer(file);
}

inline bool ModuleDecl::EntryPointInfoTy::hasEntryPoint() const {
  return storage.getPointer();
}

inline bool ModuleDecl::EntryPointInfoTy::markDiagnosedMultipleMainClasses() {
  bool res = storage.getInt().contains(Flags::DiagnosedMultipleMainClasses);
  storage.setInt(storage.getInt() | Flags::DiagnosedMultipleMainClasses);
  return !res;
}

inline bool ModuleDecl::EntryPointInfoTy::markDiagnosedMainClassWithScript() {
  bool res = storage.getInt().contains(Flags::DiagnosedMainClassWithScript);
  storage.setInt(storage.getInt() | Flags::DiagnosedMainClassWithScript);
  return !res;
}

inline void simple_display(llvm::raw_ostream &out, const SourceFile *SF) {
  assert(SF && "Cannot display null source file!");

  out << "source_file " << '\"' << SF->getFilename() << '\"';
}
} // end namespace swift

#endif


text:
"""Storage time range objects."""

class TimeRange(object):
  """Date and time range.

  The timestamp are integers containing the number of microseconds
  since January 1, 1970, 00:00:00 UTC.

  Attributes:
    duration (int): duration of the range in microseconds.
    end_timestamp (int): timestamp that marks the end of the range.
    start_timestamp (int): timestamp that marks the start of the range.
  """

  def __init__(self, start_timestamp, end_timestamp):
    """Initializes a date and time range.

    The timestamp are integers containing the number of microseconds
    since January 1, 1970, 00:00:00 UTC.

    Args:
      start_timestamp (int): timestamp that marks the start of the range.
      end_timestamp (int): timestamp that marks the end of the range.

    Raises:
      ValueError: If the time range is badly formed.
    """
    if start_timestamp is None or end_timestamp is None:
      raise ValueError(
          'Time range must have either a start and an end timestamp.')

    if start_timestamp > end_timestamp:
      raise ValueError(
          'Invalid start must be earlier than end timestamp.')

    super(TimeRange, self).__init__()
    self.duration = end_timestamp - start_timestamp
    self.end_timestamp = end_timestamp
    self.start_timestamp = start_timestamp