text:
<?php

namespace Kunstmaan\LeadGenerationBundle\Entity\Popup;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Kunstmaan\AdminBundle\Entity\EntityInterface;
use Kunstmaan\LeadGenerationBundle\Entity\Rule\AbstractRule;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="kuma_popup")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @UniqueEntity(fields={"name"})
 */
abstract class AbstractPopup implements EntityInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="bigint")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string an unique name for each popup
     * @ORM\Column(type="string", name="name", unique=true)
     * @Assert\NotBlank()
     */
    protected $name;

    /**
     * @var string the html element id of the popup
     * @ORM\Column(type="string", name="html_id")
     * @Assert\NotBlank()
     */
    protected $htmlId;

    /**
     * @var ArrayCollection a list of rules that should be applied for this popup
     * @ORM\OneToMany(targetEntity="\Kunstmaan\LeadGenerationBundle\Entity\Rule\AbstractRule", mappedBy="popup", cascade={"persist", "remove"}, orphanRemoval=true)
     */
    protected $rules;

    public function __construct()
    {
        $this->rules = new ArrayCollection();
    }

    /**
     * @param int $id
     *
     * @return AbstractPopup
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     *
     * @return AbstractPopup
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return string
     */
    public function getHtmlId()
    {
        return $this->htmlId;
    }

    /**
     * @param string $htmlId
     *
     * @return AbstractPopup
     */
    public function setHtmlId($htmlId)
    {
        $this->htmlId = $htmlId;

        return $this;
    }

    /**
     * @return ArrayCollection
     */
    public function getRules()
    {
        return $this->rules;
    }

    /**
     * @param ArrayCollection $rules
     *
     * @return AbstractPopup
     */
    public function setRules(ArrayCollection $rules)
    {
        $this->rules = $rules;

        return $this;
    }

    /**
     * @param AbstractRule $rule
     *
     * @return AbstractPopup
     */
    public function addRule(AbstractRule $rule)
    {
        $this->rules->add($rule);

        return $this;
    }

    /**
     * @param AbstractRule $rule
     *
     * @return AbstractPopup
     */
    public function removeRule(AbstractRule $rule)
    {
        $this->rules->removeElement($rule);

        return $this;
    }

    /**
     * @return int
     */
    public function getRuleCount()
    {
        return count($this->rules);
    }

    /**
     * @return string
     */
    public function getFullClassname()
    {
        return get_class($this);
    }

    /**
     * @return string
     */
    public function getClassname()
    {
        return basename(str_replace('\\', '/', get_class($this)));
    }

    /**
     * Get a list of available rules for this popup.
     * When null is returned, all rules are available.
     *
     * @return array|null
     */
    public function getAvailableRules()
    {
        return null;
    }

    /**
     * Should return the controller that should be executed.
     *
     * @return string
     */
    abstract public function getControllerAction();

    /**
     * @return string
     */
    abstract public function getAdminType();
}


text:
package io.wildernesstp.command;

import io.wildernesstp.Main;
import io.wildernesstp.util.WTPConstants;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.Collections;
import java.util.List;

public final class GUICommand extends BaseCommand {

    public GUICommand(Main plugin, String name, String description, String usage, List<String> aliases, String permission, boolean onlyPlayer) {
        super(plugin, name, description, usage, aliases, permission, onlyPlayer);
    }

    @Override
    protected void execute(CommandSender sender, Command cmd, String[] args) {
        final Player player = (Player) sender;

        player.closeInventory();
        player.openInventory(WTPConstants.BIOME_SELECTOR);
    }

    @Override
    protected List<String> suggest(CommandSender sender, Command cmd, String[] args) {
        return Collections.emptyList();
    }
}

redpajama_set_name: RedPajamaGithub


text:
const common = require('../../../common');
const expect = common.expect;
const endpoint = '/api/v1/permissions/unmapped';

common.startTest('should get unmapped permissions in staging', async function () {
    const res = await common.post(endpoint, {environment: 'staging'});
    expect(res).to.have.status(200);
});

common.startTest('should get unmapped permissions in production', async function () {
    const res = await common.post(endpoint, {environment: 'production'});
    expect(res).to.have.status(200);
});

common.startTest('should get unmapped production permissions when no environment is specified', async function () {
    const res = await common.post(endpoint, {});
    expect(res).to.have.status(200);
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Penetration Testing</title>
    <meta name="viewport" content="width=device-width">
    <meta name="description" content="Locked Networks is a technology services firm that solves problems for business and other entities. We tackle problems in cloud, information security, enterprise, or wherever help is needed.">
    <link rel="canonical" href="https://locked.net/2016/08/12/pentest/">

    <link rel="stylesheet" href="/style.css">

    <link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Locked Networks

                        Services

                        Portfolio

                        About

                        Team

                        Contact

Locked Networks

Technology solutions for business

                Tell Me More

Services

Security and Compliance

We understand the challenge of technology defense having worked with hundreds of customers, vendors, and partners across a variety of industries.

 Because every client environment is different, our team of consultants and engineers are vendor-agnostic and build solutions anticipating our client's outcomes and not specific products.

 A mature technology program empowered by effective security architecture is one with lower risks, efficient operations, threat and vulnerability awareness, decreased fragility, and increased ability to adapt and react. Locked understands the attacker and translates this to creating effective defensive controls for your business, data, and customers.

Technology

We believe in providing technology solutions that are built around your specific business needs and budget.

Our approach is to deliver IT products and systems that are designed to help you get the most for your technology investment using vendor and open-source solutions best suited to the unique needs of your organization.

Our depth and breadth of real-world experience in large-scale environments enables us to assess, scope, and complete projects efficiently. Our architects work closely with your team to determine the solution that best fits your company's needs and constraints.

Leadership

A Virtual CISO can provide you with expert guidance, strategic leadership, and minimize related costs.

 Most businesses and organizations don't need a full-time information security officer, but nearly all of them can benefit from occasional expert advice in making critical decisions.

 Our Virtual CIO advisory service gives you access to a range of expertise to assist you in understanding the issues you encounter and managing your technology.

These services are provided on retainer with a guaranteed access to expertise when you need it so that you can focus on your business.

Portfolio

Application Security

CISO Advisory

Penetration Testing

Security Assessment

Technology Strategy

Security Programs

Internet

Data Programs

Cloud Security Strategy

Where we've been

Beginnings

Locked got their start in acedemic supercomputing, development startups, ISPs, and credit networks of the early 90s. Abandoning most other aspects of their lives to put together and run things that mattered to the lives of others implementing new technology and making it inter-operate with other friendly systems.

  When users and systems haven't been so friendly, they ran security incidents, e-janitoring and re-architecting tech stacks, gathering evidence, and improving conditions so that history is less likely to repeat itself.

Hands-on

in the trenches

Having seen many excellent examples of both sterling technology practices and pronounced avoidable anti-patterns of how not to do things, our staff was recruited by consulting outfits to work on projects involving system administration, network management, software deployment and development, integration activities, and special projects for technology management and security operations.

 It is our passion to create stable, trusted, and well-run technology products, processes, and services for our clients using the resources and manpower available.  We like to solve problems.

Cyber-defense

Quality assurance for complicated systems

Technology security is not a process in itself, but a product of a well run technology practice.  The recurring problems of security in technology has mostly been that design considerations being detached from technology planning and management.

 Making decisions without a good model or in implicit acceptance of risk without analysis are rooted in misalignment of risks and objective.  These are common problems in most organizations, and we've helped our clients adjust their positions to a more measured and intentional approach.

Integrity

Our commitment

To this end, Locked's work has been in establishing data and security programs that meet the goals of their clients and their partners since before the internet was generally available and continues to this day.

Our Team

Ian Gorrie

Principal

Tucker Preston

Network Architect

Contact Us

We're here to help.

                    <form name="sentMessage" id="contactForm" novalidate>

                                    <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                    <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                    <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                                    <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-xl">Send Message</button>

                    </form>

                    Copyright © Locked Networks 2016

Privacy Policy

Terms of Use

Application Security

Adoption of agile security practices to provide assurance to compliance and client environments

Client:

Date:

Service:

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

CISO Advisory

Assisting in the role of a security officer, or in supplementing CISO teams, when a full time role is not required or additional efforts are needed.

Client:

Date:

Service:

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Penetration Testing

An exercise to simulate a technical capable adversary inside of a well defined scope.

Client:

Date:

Service:

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Security Assessment

Independent evaluation of projects, products, and programs.

Client:

Date:

Service:

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Technology Strategy

Leveraging technology to enable business efficiently

Client:

Date:

Service:

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Security Programs

Focusing efforts and budgets on effectively addressing business risks most effectively.

Client:

Date:

Service:

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Internet

Assembling technology to enable clients to use the web, conduct commerce, use data, and communicate.

Client:

Date:

Service:

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Data Programs

Leveraging modern platforms to answer questions of interest in security, analytics, maturity, and risk

Client:

Date:

Service:

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Cloud Security Strategy

Adoption of agile security practices to provide assurance to compliance and client environments.  All the more important to plan effectively when adopting a hybrid approach.

Client:
                                    Cloud vendor

Date:

Service:

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
package org.springframework.boot.env;

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

import org.junit.Test;

import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link YamlPropertySourceLoader}.
 *
 * @author Dave Syer
 * @author Phillip Webb
 * @author Andy Wilkinson
 */
public class YamlPropertySourceLoaderTests {

	private YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

	@Test
	public void load() throws Exception {
		ByteArrayResource resource = new ByteArrayResource(
				"foo:\n  bar: spam".getBytes());
		PropertySource<?> source = this.loader.load("resource", resource, null);
		assertThat(source).isNotNull();
		assertThat(source.getProperty("foo.bar")).isEqualTo("spam");
	}

	@Test
	public void orderedItems() throws Exception {
		StringBuilder yaml = new StringBuilder();
		List<String> expected = new ArrayList<>();
		for (char c = 'a'; c <= 'z'; c++) {
			yaml.append(c + ": value" + c + "\n");
			expected.add(String.valueOf(c));
		}
		ByteArrayResource resource = new ByteArrayResource(yaml.toString().getBytes());
		EnumerablePropertySource<?> source = (EnumerablePropertySource<?>) this.loader
				.load("resource", resource, null);
		assertThat(source).isNotNull();
		assertThat(source.getPropertyNames())
				.isEqualTo(expected.toArray(new String[] {}));
	}

	@Test
	public void mergeItems() throws Exception {
		StringBuilder yaml = new StringBuilder();
		yaml.append("foo:\n  bar: spam\n");
		yaml.append("---\n");
		yaml.append("foo:\n  baz: wham\n");
		ByteArrayResource resource = new ByteArrayResource(yaml.toString().getBytes());
		PropertySource<?> source = this.loader.load("resource", resource, null);
		assertThat(source).isNotNull();
		assertThat(source.getProperty("foo.bar")).isEqualTo("spam");
		assertThat(source.getProperty("foo.baz")).isEqualTo("wham");
	}

	@Test
	public void timestampLikeItemsDoNotBecomeDates() throws Exception {
		ByteArrayResource resource = new ByteArrayResource("foo: 2015-01-28".getBytes());
		PropertySource<?> source = this.loader.load("resource", resource, null);
		assertThat(source).isNotNull();
		assertThat(source.getProperty("foo")).isEqualTo("2015-01-28");
	}

	@Test
	public void loadOriginAware() throws Exception {
		Resource resource = new ClassPathResource("test-yaml.yml", getClass());
		PropertySource<?> source = this.loader.load("resource", resource, null);
		EnumerablePropertySource<?> enumerableSource = (EnumerablePropertySource<?>) source;
		for (String name : enumerableSource.getPropertyNames()) {
			System.out.println(name + " = " + enumerableSource.getProperty(name));
		}
	}

}


text:
define(
  'tinymce.plugins.help.api.Commands',
  [
    'tinymce.plugins.help.ui.Dialog'
  ],
  function (Dialog) {
    var register = function (editor, pluginUrl) {
      editor.addCommand('mceHelp', Dialog.open(editor, pluginUrl));
    };

    return {
      register: register
    };
  }
);


text:
package goryachev.swing.theme;
import goryachev.swing.Theme;
import goryachev.swing.UI;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JComponent;
import javax.swing.JSplitPane;
import javax.swing.LookAndFeel;
import javax.swing.UIDefaults;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicSplitPaneDivider;
import javax.swing.plaf.basic.BasicSplitPaneUI;

// TODO needs to honor component orientation in horizontal split mode!
// http://bugs.sun.com/view_bug.do?bug_id=4265389
public class AgSplitPaneUI
	extends BasicSplitPaneUI
{
	private static int dividerSize = 5;
	protected boolean paintedHack;
	protected boolean keepHiddenHack;
	protected boolean dividerLocationIsSetHack;
	protected boolean ignoreDividerLocationChangeHack;
	protected CSplitPaneLayoutManager layoutManagerHack;

	public AgSplitPaneUI()
	{
	}

	public static void init(UIDefaults d)
	{
		d.put("SplitPaneUI", AgSplitPaneUI.class.getName());
		d.put("SplitPane.continuousLayout", Boolean.TRUE);

//		SplitPane.ancestorInputMap = InputMapUIResource
//		SplitPane.background = ColorUIResource(EEEEEE)
//		SplitPane.border = javax.swing.plaf.basic.BasicBorders$SplitPaneBorder
//		SplitPane.centerOneTouchButtons = false
//		SplitPane.darkShadow = ColorUIResource(7A8A99)
//		SplitPane.dividerFocusColor = ColorUIResource(C8DDF2)
//		SplitPane.dividerSize = 10
//		SplitPane.highlight = ColorUIResource(FFFFFF)
//		SplitPane.oneTouchButtonsOpaque = false
//		SplitPane.shadow = ColorUIResource(B8CFE5)
//		SplitPaneDivider.border = javax.swing.plaf.basic.BasicBorders$SplitPaneDividerBorder
//		SplitPaneDivider.draggingColor = ColorUIResource(404040)
//		SplitPaneUI = "javax.swing.plaf.metal.MetalSplitPaneUI"
	}

	public void installUI(JComponent c)
	{
		super.installUI(c);
		keepHiddenHack = false;
		dividerLocationIsSetHack = false;
	}

	public void uninstallUI(JComponent c)
	{
		if(splitPane.getLayout() == layoutManagerHack)
		{
			splitPane.setLayout(null);
		}

		super.uninstallUI(c);

		dividerLocationIsSetHack = false;
		layoutManagerHack = null;
	}

	public void resetToPreferredSizes(JSplitPane c)
	{
		if(splitPane != null)
		{
			layoutManagerHack.resetToPreferredSizes();
			splitPane.revalidate();
			splitPane.repaint();
		}
	}

	public Dimension getPreferredSize(JComponent jc)
	{
		if(splitPane != null)
		{
			return layoutManagerHack.preferredLayoutSize(splitPane);
		}
		return new Dimension(0, 0);
	}

	public Dimension getMinimumSize(JComponent jc)
	{
		if(splitPane != null)
		{
			return layoutManagerHack.minimumLayoutSize(splitPane);
		}
		return new Dimension(0, 0);
	}

	public Dimension getMaximumSize(JComponent jc)
	{
		if(splitPane != null)
		{
			return layoutManagerHack.maximumLayoutSize(splitPane);
		}
		return new Dimension(0, 0);
	}

	protected void resetLayoutManager()
	{
		if(getOrientation() == JSplitPane.HORIZONTAL_SPLIT)
		{
			layoutManagerHack = new CSplitPaneLayoutManager(this, true);
		}
		else
		{
			layoutManagerHack = new CSplitPaneLayoutManager(this, false);
		}

		splitPane.setLayout(layoutManagerHack);
		layoutManagerHack.updateComponents();

		splitPane.revalidate();
		splitPane.repaint();
	}

	protected void setKeepHiddenHack(boolean on)
	{
		keepHiddenHack = on;
	}

	public boolean getKeepHiddenHack()
	{
		return keepHiddenHack;
	}

	public void setDividerLocation(JSplitPane split, int location)
	{
		if(!ignoreDividerLocationChangeHack)
		{
			dividerLocationIsSetHack = true;
			splitPane.revalidate();
			splitPane.repaint();

			if(keepHiddenHack)
			{
				Insets insets = splitPane.getInsets();
				int orientation = splitPane.getOrientation();
				if((orientation == JSplitPane.VERTICAL_SPLIT && location != insets.top && location != splitPane.getHeight() - divider.getHeight() - insets.top) || (orientation == JSplitPane.HORIZONTAL_SPLIT && location != insets.left && location != splitPane.getWidth() - divider.getWidth() - insets.left))
				{
					setKeepHiddenHack(false);
				}
			}
		}
		else
		{
			ignoreDividerLocationChangeHack = false;
		}
	}

	public static ComponentUI createUI(JComponent x)
	{
		return new AgSplitPaneUI();
	}

	protected void installDefaults()
	{
		super.installDefaults();

		if(UI.isNullOrResource(splitPane.getBorder()))
		{
			splitPane.setBorder(new CSplitPaneBorder());
		}

		LookAndFeel.installProperty(splitPane, "dividerSize", dividerSize);
		divider.setDividerSize(splitPane.getDividerSize());
	}

	public BasicSplitPaneDivider createDefaultDivider()
	{
		return new CSplitPaneDivider(this);
	}

	public JSplitPane getJSplitPane()
	{
		return splitPane;
	}

	public void paint(Graphics g, JComponent jc)
	{
		if(!paintedHack && splitPane.getDividerLocation() < 0)
		{
			ignoreDividerLocationChangeHack = true;
			splitPane.setDividerLocation(getDividerLocation(splitPane));
		}
		paintedHack = true;
	}
}


text:
Gamestate = require 'hump.gamestate'

local init = require 'states.init'
local pause = require 'states.pause'

function love.load()
    Gamestate.registerEvents()
    Gamestate.switch(init)
end

function love.visible(visible)
    if not visible then
        Gamestate.switch(pause)
    end
end


text:
-- phpMyAdmin SQL Dump
-- version 4.4.14
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Oct 28, 2015 at 02:56 AM
-- Server version: 5.6.26
-- PHP Version: 5.6.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `zf2app`
--

-- --------------------------------------------------------

--
-- Table structure for table `menu`
--

CREATE TABLE IF NOT EXISTS `menu` (
  `menu_id` int(11) NOT NULL,
  `menu` varchar(255) NOT NULL,
  `display` enum('Show','Hide') NOT NULL DEFAULT 'Hide',
  `description` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `menu`
--

INSERT INTO `menu` (`menu_id`, `menu`, `display`, `description`) VALUES
(1, 'User', 'Show', ''),
(2, 'Menu', 'Show', ''),
(3, 'Sub Menu', 'Show', '');

-- --------------------------------------------------------

--
-- Table structure for table `role`
--

CREATE TABLE IF NOT EXISTS `role` (
  `role_id` int(11) NOT NULL,
  `role` varchar(255) NOT NULL,
  `description` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

--
-- Dumping data for table `role`
--

INSERT INTO `role` (`role_id`, `role`, `description`) VALUES
(1, 'Super Admin', ''),
(2, 'Admin', ''),
(3, 'Registered User', ''),
(4, 'Guest', ''),
(5, 'Custom Admin', '');

-- --------------------------------------------------------

--
-- Table structure for table `role_permission`
--

CREATE TABLE IF NOT EXISTS `role_permission` (
  `role_permission_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  `sub_menu_id` int(11) NOT NULL,
  `descroptiion` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `role_permission`
--

INSERT INTO `role_permission` (`role_permission_id`, `role_id`, `sub_menu_id`, `descroptiion`) VALUES
(1, 4, 2, ''),
(2, 0, 0, '');

-- --------------------------------------------------------

--
-- Table structure for table `sub_menu`
--

CREATE TABLE IF NOT EXISTS `sub_menu` (
  `sub_menu_id` int(11) NOT NULL,
  `sub_menu` varchar(255) NOT NULL,
  `menu_id` int(11) NOT NULL,
  `route` varchar(255) NOT NULL,
  `display` enum('Show','Hide') NOT NULL DEFAULT 'Hide',
  `descroptiion` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `sub_menu`
--

INSERT INTO `sub_menu` (`sub_menu_id`, `sub_menu`, `menu_id`, `route`, `display`, `descroptiion`) VALUES
(1, 'List User', 1, 'users/list', 'Show', ''),
(2, 'Add User', 1, 'users/add', 'Show', ''),
(3, 'Edit User', 1, 'users/edit', 'Show', ''),
(4, 'Delete User', 1, 'users/delete', 'Show', ''),
(5, 'List Menu', 2, 'menu/list', 'Show', ''),
(6, 'Add Menu', 2, 'menu/add', 'Show', ''),
(7, 'Edit Menu', 2, 'menu/edit', 'Show', ''),
(8, 'Delete Menu', 2, 'menu/delete', 'Show', ''),
(9, 'Sub Menu List', 3, 'subMenu/list', 'Show', ''),
(10, 'Sub Menu Add', 3, 'subMenu/add', 'Show', ''),
(11, 'Sub Menu Edit', 3, 'subMenu/edit', 'Show', ''),
(12, 'Sub Menu Delete', 3, 'subMenu/delete', 'Show', '');

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `user_id` int(11) NOT NULL,
  `username` varchar(15) DEFAULT NULL,
  `password` text NOT NULL,
  `email` varchar(50) DEFAULT NULL,
  `display_name` varchar(50) DEFAULT NULL,
  `status` enum('Active','Inactive') NOT NULL DEFAULT 'Active'
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`user_id`, `username`, `password`, `email`, `display_name`, `status`) VALUES
(1, 'rpaneru', 'f2506e25230f4f5572a4b79727d02454', 'rpaneru1986@gmail.com', 'Rajesh Paneru', 'Active');

-- --------------------------------------------------------

--
-- Table structure for table `user_role`
--

CREATE TABLE IF NOT EXISTS `user_role` (
  `user_role_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `role_id` int(11) NOT NULL,
  `description` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user_role`
--

INSERT INTO `user_role` (`user_role_id`, `user_id`, `role_id`, `description`) VALUES
(1, 1, 1, ''),
(2, 1, 2, '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `menu`
--
ALTER TABLE `menu`
  ADD PRIMARY KEY (`menu_id`);

--
-- Indexes for table `role`
--
ALTER TABLE `role`
  ADD PRIMARY KEY (`role_id`);

--
-- Indexes for table `role_permission`
--
ALTER TABLE `role_permission`
  ADD PRIMARY KEY (`role_permission_id`);

--
-- Indexes for table `sub_menu`
--
ALTER TABLE `sub_menu`
  ADD PRIMARY KEY (`sub_menu_id`);

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`),
  ADD UNIQUE KEY `username` (`username`),
  ADD UNIQUE KEY `email` (`email`);

--
-- Indexes for table `user_role`
--
ALTER TABLE `user_role`
  ADD PRIMARY KEY (`user_role_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `menu`
--
ALTER TABLE `menu`
  MODIFY `menu_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `role`
--
ALTER TABLE `role`
  MODIFY `role_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `role_permission`
--
ALTER TABLE `role_permission`
  MODIFY `role_permission_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `sub_menu`
--
ALTER TABLE `sub_menu`
  MODIFY `sub_menu_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=13;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `user_role`
--
ALTER TABLE `user_role`
  MODIFY `user_role_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
<!DOCTYPE html>

    <meta name="_csrf" content="" th:content="${_csrf.token}"/>

    <meta name="_csrf_header" content="" th:content="${_csrf.headerName}"/>
    <title th:text="${defenseOrder.sortNum + ' _  ' + defenseOrder.studentName + ' ' + defenseOrder.studentNumber}">
        ISY</title>

    <link href="css/sticky-footer.css" rel="stylesheet" th:href="@{/css/custom/sticky-footer.css}"/>

        <form id="example2form">
            <input class="btn btn-default" type='button' value='继续' id="play" disabled="disabled"/>
            <input class="btn btn-default" type='button' value='暂停' id="pause"/>
            <input class="btn btn-default" type='button' value='重新' id="rePlay"/>
        </form>

© Company 2016


text:
var CONSTANT = 1;

// when only varying the non-sensitive parameter, the
// context sensitivity should _not_ be toggled.
function f(a,b){
    TAJS_addContextSensitivity("a");
    return a+b;
}

var f_c1 = f(CONSTANT,2);
TAJS_assert(f_c1, "isMaybeNumUInt", false);
var f_c2 = f(CONSTANT,3);
TAJS_assert(f_c2, "isMaybeNumUInt", true);

// this function proves that it is the variance of the
// second parameter which forces the context sensitivity
function g(a,b){
    TAJS_addContextSensitivity("a");
    return a+b;
}
var g_c1 = g(CONSTANT,CONSTANT);
TAJS_assert(g_c1, "isMaybeNumUInt", false);
var g_c2 = g(CONSTANT + 1,CONSTANT);
TAJS_assert(g_c2, "isMaybeNumUInt", false);


text:
import inspect
import os
import time

from abc import ABCMeta, abstractmethod
from datetime import datetime
from distutils.version import LooseVersion

from ansible.module_utils.cloud import CloudRetry
from ansible.module_utils.common._collections_compat import Mapping

try:
    from enum import Enum  # enum is a ovirtsdk4 requirement
    import ovirtsdk4 as sdk
    import ovirtsdk4.version as sdk_version
    import ovirtsdk4.types as otypes
    HAS_SDK = LooseVersion(sdk_version.VERSION) >= LooseVersion('4.3.0')
except ImportError:
    HAS_SDK = False

BYTES_MAP = {
    'kib': 2**10,
    'mib': 2**20,
    'gib': 2**30,
    'tib': 2**40,
    'pib': 2**50,
}

def check_sdk(module):
    if not HAS_SDK:
        module.fail_json(
            msg='ovirtsdk4 version 4.3.0 or higher is required for this module'
        )

def get_dict_of_struct(struct, connection=None, fetch_nested=False, attributes=None):
    """
    Convert SDK Struct type into dictionary.
    """
    res = {}

    def remove_underscore(val):
        if val.startswith('_'):
            val = val[1:]
            remove_underscore(val)
        return val

    def convert_value(value):
        nested = False

        if isinstance(value, sdk.Struct):
            if not fetch_nested or not value.href:
                return get_dict_of_struct(value)

            # Fetch nested values of struct:
            try:
                value = connection.follow_link(value)
            except sdk.Error:
                value = None
            nested_obj = dict(
                (attr, convert_value(getattr(value, attr)))
                for attr in attributes if getattr(value, attr, None)
            )
            nested_obj['id'] = getattr(value, 'id', None)
            nested_obj['href'] = getattr(value, 'href', None)
            return nested_obj
        elif isinstance(value, Enum) or isinstance(value, datetime):
            return str(value)
        elif isinstance(value, list) or isinstance(value, sdk.List):
            if isinstance(value, sdk.List) and fetch_nested and value.href:
                try:
                    value = connection.follow_link(value)
                    nested = True
                except sdk.Error:
                    value = []

            ret = []
            for i in value:
                if isinstance(i, sdk.Struct):
                    if not nested:
                        ret.append(get_dict_of_struct(i))
                    else:
                        nested_obj = dict(
                            (attr, convert_value(getattr(i, attr)))
                            for attr in attributes if getattr(i, attr, None)
                        )
                        nested_obj['id'] = getattr(i, 'id', None)
                        ret.append(nested_obj)
                elif isinstance(i, Enum):
                    ret.append(str(i))
                else:
                    ret.append(i)
            return ret
        else:
            return value

    if struct is not None:
        for key, value in struct.__dict__.items():
            if value is None:
                continue

            key = remove_underscore(key)
            res[key] = convert_value(value)

    return res

def engine_version(connection):
    """
    Return string representation of oVirt engine version.
    """
    engine_api = connection.system_service().get()
    engine_version = engine_api.product_info.version
    return '%s.%s' % (engine_version.major, engine_version.minor)

def create_connection(auth):
    """
    Create a connection to Python SDK, from task `auth` parameter.
    If user doesnt't have SSO token the `auth` dictionary has following parameters mandatory:
     url, username, password

    If user has SSO token the `auth` dictionary has following parameters mandatory:
     url, token

    The `ca_file` parameter is mandatory in case user want to use secure connection,
    in case user want to use insecure connection, it's mandatory to send insecure=True.

    :param auth: dictionary which contains needed values for connection creation
    :return: Python SDK connection
    """

    url = auth.get('url')
    if url is None and auth.get('hostname') is not None:
        url = 'https://{0}/ovirt-engine/api'.format(auth.get('hostname'))

    return sdk.Connection(
        url=url,
        username=auth.get('username'),
        password=auth.get('password'),
        ca_file=auth.get('ca_file', None),
        insecure=auth.get('insecure', False),
        token=auth.get('token', None),
        kerberos=auth.get('kerberos', None),
        headers=auth.get('headers', None),
    )

def convert_to_bytes(param):
    """
    This method convert units to bytes, which follow IEC standard.

    :param param: value to be converted
    """
    if param is None:
        return None

    # Get rid of whitespaces:
    param = ''.join(param.split())

    # Convert to bytes:
    if len(param) > 3 and param[-3].lower() in ['k', 'm', 'g', 't', 'p']:
        return int(param[:-3]) * BYTES_MAP.get(param[-3:].lower(), 1)
    elif param.isdigit():
        return int(param) * 2**10
    else:
        raise ValueError(
            "Unsupported value(IEC supported): '{value}'".format(value=param)
        )

def follow_link(connection, link):
    """
    This method returns the entity of the element which link points to.

    :param connection: connection to the Python SDK
    :param link: link of the entity
    :return: entity which link points to
    """

    if link:
        return connection.follow_link(link)
    else:
        return None

def get_link_name(connection, link):
    """
    This method returns the name of the element which link points to.

    :param connection: connection to the Python SDK
    :param link: link of the entity
    :return: name of the entity, which link points to
    """

    if link:
        return connection.follow_link(link).name
    else:
        return None

def equal(param1, param2, ignore_case=False):
    """
    Compare two parameters and return if they are equal.
    This parameter doesn't run equal operation if first parameter is None.
    With this approach we don't run equal operation in case user don't
    specify parameter in their task.

    :param param1: user inputted parameter
    :param param2: value of entity parameter
    :return: True if parameters are equal or first parameter is None, otherwise False
    """
    if param1 is not None:
        if ignore_case:
            return param1.lower() == param2.lower()
        return param1 == param2
    return True

def search_by_attributes(service, list_params=None, **kwargs):
    """
    Search for the entity by attributes. Nested entities don't support search
    via REST, so in case using search for nested entity we return all entities
    and filter them by specified attributes.
    """
    list_params = list_params or {}
    # Check if 'list' method support search(look for search parameter):
    if 'search' in inspect.getargspec(service.list)[0]:
        res = service.list(
            search=' and '.join('{0}={1}'.format(k, v) for k, v in kwargs.items()),
            **list_params
        )
    else:
        res = [
            e for e in service.list(**list_params) if len([
                k for k, v in kwargs.items() if getattr(e, k, None) == v
            ]) == len(kwargs)
        ]

    res = res or [None]
    return res[0]

def search_by_name(service, name, **kwargs):
    """
    Search for the entity by its name. Nested entities don't support search
    via REST, so in case using search for nested entity we return all entities
    and filter them by name.

    :param service: service of the entity
    :param name: name of the entity
    :return: Entity object returned by Python SDK
    """
    # Check if 'list' method support search(look for search parameter):
    if 'search' in inspect.getargspec(service.list)[0]:
        res = service.list(
            search="name={name}".format(name=name)
        )
    else:
        res = [e for e in service.list() if e.name == name]

    if kwargs:
        res = [
            e for e in service.list() if len([
                k for k, v in kwargs.items() if getattr(e, k, None) == v
            ]) == len(kwargs)
        ]

    res = res or [None]
    return res[0]

def get_entity(service, get_params=None):
    """
    Ignore SDK Error in case of getting an entity from service.
    """
    entity = None
    try:
        if get_params is not None:
            entity = service.get(**get_params)
        else:
            entity = service.get()
    except sdk.Error:
        # We can get here 404, we should ignore it, in case
        # of removing entity for example.
        pass
    return entity

def get_id_by_name(service, name, raise_error=True, ignore_case=False):
    """
    Search an entity ID by it's name.
    """
    entity = search_by_name(service, name)

    if entity is not None:
        return entity.id

    if raise_error:
        raise Exception("Entity '%s' was not found." % name)

def wait(
    service,
    condition,
    fail_condition=lambda e: False,
    timeout=180,
    wait=True,
    poll_interval=3,
):
    """
    Wait until entity fulfill expected condition.

    :param service: service of the entity
    :param condition: condition to be fulfilled
    :param fail_condition: if this condition is true, raise Exception
    :param timeout: max time to wait in seconds
    :param wait: if True wait for condition, if False don't wait
    :param poll_interval: Number of seconds we should wait until next condition check
    """
    # Wait until the desired state of the entity:
    if wait:
        start = time.time()
        while time.time() < start + timeout:
            # Exit if the condition of entity is valid:
            entity = get_entity(service)
            if condition(entity):
                return
            elif fail_condition(entity):
                raise Exception("Error while waiting on result state of the entity.")

            # Sleep for `poll_interval` seconds if none of the conditions apply:
            time.sleep(float(poll_interval))

        raise Exception("Timeout exceed while waiting on result state of the entity.")

def __get_auth_dict():
    OVIRT_URL = os.environ.get('OVIRT_URL')
    OVIRT_HOSTNAME = os.environ.get('OVIRT_HOSTNAME')
    OVIRT_USERNAME = os.environ.get('OVIRT_USERNAME')
    OVIRT_PASSWORD = os.environ.get('OVIRT_PASSWORD')
    OVIRT_TOKEN = os.environ.get('OVIRT_TOKEN')
    OVIRT_CAFILE = os.environ.get('OVIRT_CAFILE')
    OVIRT_INSECURE = OVIRT_CAFILE is None

    env_vars = None
    if OVIRT_URL is None and OVIRT_HOSTNAME is not None:
        OVIRT_URL = 'https://{0}/ovirt-engine/api'.format(OVIRT_HOSTNAME)
    if OVIRT_URL and ((OVIRT_USERNAME and OVIRT_PASSWORD) or OVIRT_TOKEN):
        env_vars = {
            'url': OVIRT_URL,
            'username': OVIRT_USERNAME,
            'password': OVIRT_PASSWORD,
            'insecure': OVIRT_INSECURE,
            'token': OVIRT_TOKEN,
            'ca_file': OVIRT_CAFILE,
        }
    if env_vars is not None:
        auth = dict(default=env_vars, type='dict')
    else:
        auth = dict(required=True, type='dict')

    return auth

def ovirt_facts_full_argument_spec(**kwargs):
    """
    Extend parameters of facts module with parameters which are common to all
    oVirt facts modules.

    :param kwargs: kwargs to be extended
    :return: extended dictionary with common parameters
    """
    spec = dict(
        auth=__get_auth_dict(),
        fetch_nested=dict(default=False, type='bool'),
        nested_attributes=dict(type='list', default=list()),
    )
    spec.update(kwargs)
    return spec

def ovirt_full_argument_spec(**kwargs):
    """
    Extend parameters of module with parameters which are common to all oVirt modules.

    :param kwargs: kwargs to be extended
    :return: extended dictionary with common parameters
    """
    spec = dict(
        auth=__get_auth_dict(),
        timeout=dict(default=180, type='int'),
        wait=dict(default=True, type='bool'),
        poll_interval=dict(default=3, type='int'),
        fetch_nested=dict(default=False, type='bool'),
        nested_attributes=dict(type='list', default=list()),
    )
    spec.update(kwargs)
    return spec

def check_params(module):
    """
    Most modules must have either `name` or `id` specified.
    """
    if module.params.get('name') is None and module.params.get('id') is None:
        module.fail_json(msg='"name" or "id" is required')

def engine_supported(connection, version):
    return LooseVersion(engine_version(connection)) >= LooseVersion(version)

def check_support(version, connection, module, params):
    """
    Check if parameters used by user are supported by oVirt Python SDK
    and oVirt engine.
    """
    api_version = LooseVersion(engine_version(connection))
    version = LooseVersion(version)
    for param in params:
        if module.params.get(param) is not None:
            return LooseVersion(sdk_version.VERSION) >= version and api_version >= version

    return True

class BaseModule(object):
    """
    This is base class for oVirt modules. oVirt modules should inherit this
    class and override method to customize specific needs of the module.
    The only abstract method of this class is `build_entity`, which must
    to be implemented in child class.
    """
    __metaclass__ = ABCMeta

    def __init__(self, connection, module, service, changed=False):
        self._connection = connection
        self._module = module
        self._service = service
        self._changed = changed
        self._diff = {'after': dict(), 'before': dict()}

    @property
    def changed(self):
        return self._changed

    @changed.setter
    def changed(self, changed):
        if not self._changed:
            self._changed = changed

    @abstractmethod
    def build_entity(self):
        """
        This method should return oVirt Python SDK type, which we want to
        create or update, initialized by values passed by Ansible module.

        For example if we want to create VM, we will return following:
          types.Vm(name=self._module.params['vm_name'])

        :return: Specific instance of sdk.Struct.
        """
        pass

    def param(self, name, default=None):
        """
        Return a module parameter specified by it's name.
        """
        return self._module.params.get(name, default)

    def update_check(self, entity):
        """
        This method handle checks whether the entity values are same as values
        passed to ansible module. By default we don't compare any values.

        :param entity: Entity we want to compare with Ansible module values.
        :return: True if values are same, so we don't need to update the entity.
        """
        return True

    def pre_create(self, entity):
        """
        This method is called right before entity is created.

        :param entity: Entity to be created or updated.
        """
        pass

    def post_create(self, entity):
        """
        This method is called right after entity is created.

        :param entity: Entity which was created.
        """
        pass

    def post_update(self, entity):
        """
        This method is called right after entity is updated.

        :param entity: Entity which was updated.
        """
        pass

    def diff_update(self, after, update):
        for k, v in update.items():
            if isinstance(v, Mapping):
                after[k] = self.diff_update(after.get(k, dict()), v)
            else:
                after[k] = update[k]
        return after

    def create(
        self,
        entity=None,
        result_state=None,
        fail_condition=lambda e: False,
        search_params=None,
        update_params=None,
        _wait=None,
        force_create=False,
        **kwargs
    ):
        """
        Method which is called when state of the entity is 'present'. If user
        don't provide `entity` parameter the entity is searched using
        `search_params` parameter. If entity is found it's updated, whether
        the entity should be updated is checked by `update_check` method.
        The corresponding updated entity is build by `build_entity` method.

        Function executed after entity is created can optionally be specified
        in `post_create` parameter. Function executed after entity is updated
        can optionally be specified in `post_update` parameter.

        :param entity: Entity we want to update, if exists.
        :param result_state: State which should entity has in order to finish task.
        :param fail_condition: Function which checks incorrect state of entity, if it returns `True` Exception is raised.
        :param search_params: Dictionary of parameters to be used for search.
        :param update_params: The params which should be passed to update method.
        :param kwargs: Additional parameters passed when creating entity.
        :return: Dictionary with values returned by Ansible module.
        """
        if entity is None and not force_create:
            entity = self.search_entity(search_params)

        self.pre_create(entity)

        if entity:
            # Entity exists, so update it:
            entity_service = self._service.service(entity.id)
            if not self.update_check(entity):
                new_entity = self.build_entity()
                if not self._module.check_mode:
                    update_params = update_params or {}
                    updated_entity = entity_service.update(
                        new_entity,
                        **update_params
                    )
                    self.post_update(entity)

                # Update diffs only if user specified --diff parameter,
                # so we don't useless overload API:
                if self._module._diff:
                    before = get_dict_of_struct(
                        entity,
                        self._connection,
                        fetch_nested=True,
                        attributes=['name'],
                    )
                    after = before.copy()
                    self.diff_update(after, get_dict_of_struct(new_entity))
                    self._diff['before'] = before
                    self._diff['after'] = after

                self.changed = True
        else:
            # Entity don't exists, so create it:
            if not self._module.check_mode:
                entity = self._service.add(
                    self.build_entity(),
                    **kwargs
                )
                self.post_create(entity)
            self.changed = True

        if not self._module.check_mode:
            # Wait for the entity to be created and to be in the defined state:
            entity_service = self._service.service(entity.id)

            def state_condition(entity):
                return entity

            if result_state:

                def state_condition(entity):
                    return entity and entity.status == result_state

            wait(
                service=entity_service,
                condition=state_condition,
                fail_condition=fail_condition,
                wait=_wait if _wait is not None else self._module.params['wait'],
                timeout=self._module.params['timeout'],
                poll_interval=self._module.params['poll_interval'],
            )

        return {
            'changed': self.changed,
            'id': getattr(entity, 'id', None),
            type(entity).__name__.lower(): get_dict_of_struct(
                struct=entity,
                connection=self._connection,
                fetch_nested=self._module.params.get('fetch_nested'),
                attributes=self._module.params.get('nested_attributes'),
            ),
            'diff': self._diff,
        }

    def pre_remove(self, entity):
        """
        This method is called right before entity is removed.

        :param entity: Entity which we want to remove.
        """
        pass

    def entity_name(self, entity):
        return "{e_type} '{e_name}'".format(
            e_type=type(entity).__name__.lower(),
            e_name=getattr(entity, 'name', None),
        )

    def remove(self, entity=None, search_params=None, **kwargs):
        """
        Method which is called when state of the entity is 'absent'. If user
        don't provide `entity` parameter the entity is searched using
        `search_params` parameter. If entity is found it's removed.

        Function executed before remove is executed can optionally be specified
        in `pre_remove` parameter.

        :param entity: Entity we want to remove.
        :param search_params: Dictionary of parameters to be used for search.
        :param kwargs: Additional parameters passed when removing entity.
        :return: Dictionary with values returned by Ansible module.
        """
        if entity is None:
            entity = self.search_entity(search_params)

        if entity is None:
            return {
                'changed': self.changed,
                'msg': "Entity wasn't found."
            }

        self.pre_remove(entity)

        entity_service = self._service.service(entity.id)
        if not self._module.check_mode:
            entity_service.remove(**kwargs)
            wait(
                service=entity_service,
                condition=lambda entity: not entity,
                wait=self._module.params['wait'],
                timeout=self._module.params['timeout'],
                poll_interval=self._module.params['poll_interval'],
            )
        self.changed = True

        return {
            'changed': self.changed,
            'id': entity.id,
            type(entity).__name__.lower(): get_dict_of_struct(
                struct=entity,
                connection=self._connection,
                fetch_nested=self._module.params.get('fetch_nested'),
                attributes=self._module.params.get('nested_attributes'),
            ),
        }

    def action(
        self,
        action,
        entity=None,
        action_condition=lambda e: e,
        wait_condition=lambda e: e,
        fail_condition=lambda e: False,
        pre_action=lambda e: e,
        post_action=lambda e: None,
        search_params=None,
        **kwargs
    ):
        """
        This method is executed when we want to change the state of some oVirt
        entity. The action to be executed on oVirt service is specified by
        `action` parameter. Whether the action should be executed can be
        specified by passing `action_condition` parameter. State which the
        entity should be in after execution of the action can be specified
        by `wait_condition` parameter.

        Function executed before an action on entity can optionally be specified
        in `pre_action` parameter. Function executed after an action on entity can
        optionally be specified in `post_action` parameter.

        :param action: Action which should be executed by service on entity.
        :param entity: Entity we want to run action on.
        :param action_condition: Function which is executed when checking if action should be executed.
        :param fail_condition: Function which checks incorrect state of entity, if it returns `True` Exception is raised.
        :param wait_condition: Function which is executed when waiting on result state.
        :param pre_action: Function which is executed before running the action.
        :param post_action: Function which is executed after running the action.
        :param search_params: Dictionary of parameters to be used for search.
        :param kwargs: Additional parameters passed to action.
        :return: Dictionary with values returned by Ansible module.
        """
        if entity is None:
            entity = self.search_entity(search_params)

        entity = pre_action(entity)

        if entity is None:
            self._module.fail_json(
                msg="Entity not found, can't run action '{0}'.".format(
                    action
                )
            )

        entity_service = self._service.service(entity.id)
        entity = entity_service.get()
        if action_condition(entity):
            if not self._module.check_mode:
                getattr(entity_service, action)(**kwargs)
            self.changed = True

        post_action(entity)

        wait(
            service=self._service.service(entity.id),
            condition=wait_condition,
            fail_condition=fail_condition,
            wait=self._module.params['wait'],
            timeout=self._module.params['timeout'],
            poll_interval=self._module.params['poll_interval'],
        )
        return {
            'changed': self.changed,
            'id': entity.id,
            type(entity).__name__.lower(): get_dict_of_struct(
                struct=entity,
                connection=self._connection,
                fetch_nested=self._module.params.get('fetch_nested'),
                attributes=self._module.params.get('nested_attributes'),
            ),
            'diff': self._diff,
        }

    def wait_for_import(self, condition=lambda e: True):
        if self._module.params['wait']:
            start = time.time()
            timeout = self._module.params['timeout']
            poll_interval = self._module.params['poll_interval']
            while time.time() < start + timeout:
                entity = self.search_entity()
                if entity and condition(entity):
                    return entity
                time.sleep(poll_interval)

    def search_entity(self, search_params=None, list_params=None):
        """
        Always first try to search by `ID`, if ID isn't specified,
        check if user constructed special search in `search_params`,
        if not search by `name`.
        """
        entity = None

        if 'id' in self._module.params and self._module.params['id'] is not None:
            entity = get_entity(self._service.service(self._module.params['id']), get_params=list_params)
        elif search_params is not None:
            entity = search_by_attributes(self._service, list_params=list_params, **search_params)
        elif self._module.params.get('name') is not None:
            entity = search_by_attributes(self._service, list_params=list_params, name=self._module.params['name'])

        return entity

    def _get_major(self, full_version):
        if full_version is None or full_version == "":
            return None
        if isinstance(full_version, otypes.Version):
            return int(full_version.major)
        return int(full_version.split('.')[0])

    def _get_minor(self, full_version):
        if full_version is None or full_version == "":
            return None
        if isinstance(full_version, otypes.Version):
            return int(full_version.minor)
        return int(full_version.split('.')[1])

def _sdk4_error_maybe():
    """
    Allow for ovirtsdk4 not being installed.
    """
    if HAS_SDK:
        return sdk.Error
    return type(None)

class OvirtRetry(CloudRetry):
    base_class = _sdk4_error_maybe()

    @staticmethod
    def status_code_from_exception(error):
        return error.code

    @staticmethod
    def found(response_code, catch_extra_error_codes=None):
        # This is a list of error codes to retry.
        retry_on = [
            # HTTP status: Conflict
            409,
        ]
        if catch_extra_error_codes:
            retry_on.extend(catch_extra_error_codes)

        return response_code in retry_on


text:
from discord.ext import commands
from .utils.chat_formatting import box
from .utils.dataIO import dataIO
from .utils import checks
from __main__ import user_allowed, send_cmd_help
from copy import deepcopy
import os
import discord
import time
import random

pulse = 0

class Ressurect:
    """Ressurect Something"""

    def __init__(self, bot):
        self.bot = bot

    @commands.command(pass_context=True)
    async def Ressurect(self, ctx, *, ded:str):

        try:
            await self.bot.delete_message(ctx.message)
        except:
            pass

        await self.bot.say("Attempting to ressurect {}".format(ded))
        time.sleep(1)
        await self.bot.say("Shocking... Clear!")
        pulse = (random.randint(1, 2))
        if pulse == 1:
            await self.bot.say("Unsuccessful, trying again")
            time.sleep(1)
            await self.bot.say("Shocking... Clear!")
            pulse = (random.randint(1, 2))
            if pulse == 1:
                await self.bot.say("Unsuccessful, trying again")
                time.sleep(1)
                await self.bot.say("Shocking... Clear!")
                pulse = (random.randint(1, 2))
                if pulse == 1:
                    await self.bot.say("Unsuccessful, I'm sorry but {} has died".format(ded))

                else:
                    time.sleep(1)
                    await self.bot.say("{} has been recovered!".format(ded))

            else:
                time.sleep(1)
                await self.bot.say("{} has been recovered!".format(ded))

        else:
            time.sleep(1)
            await self.bot.say("{} has been recovered!".format(ded))

def setup(bot):
    bot.add_cog(Ressurect(bot))


text:
class CreatePeerCandidateComments < ActiveRecord::Migration
  def change
    create_table :peer_candidate_comments do |t|
      t.references :peer_candidate, index: true, foreign_key: true
      t.references :person, index: true, foreign_key: true
      t.timestamp :timestamp, null: false
      t.text :comments

      t.timestamps null: false
    end
  end
end


text:
package com.dremio.common.config;

import java.util.Set;

import com.dremio.common.expression.FieldReference;
import com.dremio.common.expression.LogicalExpression;
import com.dremio.common.expression.SchemaPath;
import com.dremio.common.logical.FormatPluginConfigBase;
import com.dremio.common.logical.StoragePluginConfigBase;
import com.dremio.common.logical.data.LogicalOperatorBase;
import com.dremio.common.scanner.persistence.ScanResult;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;

public class LogicalPlanPersistence {
  private ObjectMapper mapper;

  public ObjectMapper getMapper() {
    return mapper;
  }

  public LogicalPlanPersistence(SabotConfig conf, ScanResult scanResult) {
    mapper = new ObjectMapper();

    SimpleModule deserModule = new SimpleModule("LogicalExpressionDeserializationModule")
        .addDeserializer(LogicalExpression.class, new LogicalExpression.De())
        .addDeserializer(SchemaPath.class, new SchemaPath.De())
        .addDeserializer(FieldReference.class, new FieldReference.De());

    mapper.registerModule(new AfterburnerModule());
    mapper.registerModule(deserModule);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
    mapper.configure(Feature.ALLOW_COMMENTS, true);
    registerSubtypes(LogicalOperatorBase.getSubTypes(scanResult));
    registerSubtypes(StoragePluginConfigBase.getSubTypes(scanResult));
    registerSubtypes(FormatPluginConfigBase.getSubTypes(scanResult));
  }

  private <T> void registerSubtypes(Set<Class<? extends T>> types) {
    for (Class<? extends T> type : types) {
      mapper.registerSubtypes(type);
    }
  }
}


text:
PARSER::FloatResult PARSER::FNFlt::EvaluateDouble() const
{
    std::string stringValue(m_rContext.GetElement(m_Index));

    return FloatResult(stringValue);
}

PARSER::FloatResult PARSER::FNNegate::EvaluateDouble() const
{
    double value = m_pNode->EvaluateDouble().GetFloatValue();
    return FloatResult(-value);
}

PARSER::FloatResult PARSER::FNAdd::EvaluateDouble() const
{
    double leftValue = m_pLeft->EvaluateDouble().GetFloatValue();
    double rightValue = m_pRight->EvaluateDouble().GetFloatValue();

    if ((std::numeric_limits<double>::max() - leftValue) < rightValue)
    {
        throw EXCEPTIONS::Overflow("Overflow while adding.");
    }

    return FloatResult(leftValue + rightValue);
}

PARSER::FloatResult PARSER::FNSubtract::EvaluateDouble() const
{
    double leftValue = m_pLeft->EvaluateDouble().GetFloatValue();
    double rightValue = m_pRight->EvaluateDouble().GetFloatValue();

    if ((std::numeric_limits<double>::min() + rightValue) > leftValue)
    {
        throw EXCEPTIONS::Overflow("Underflow while substracting.");
    }

    return FloatResult(leftValue - rightValue);
}

PARSER::FloatResult PARSER::FNMultiply::EvaluateDouble() const
{
    double leftValue = m_pLeft->EvaluateDouble().GetFloatValue();
    double rightValue = m_pRight->EvaluateDouble().GetFloatValue();

    if ((std::numeric_limits<double>::max() / leftValue) < rightValue)
    {
        throw EXCEPTIONS::Overflow("Overflow while multiplying.");
    }

    return FloatResult(leftValue * rightValue);
}

PARSER::FloatResult PARSER::FNDivide::EvaluateDouble() const
{
    double leftValue = m_pLeft->EvaluateDouble().GetFloatValue();
    double rightValue = m_pRight->EvaluateDouble().GetFloatValue();

    if (0 == rightValue)
    {
        throw EXCEPTIONS::DivByZero("");
    }

    return FloatResult(leftValue / rightValue);
}


text:
<?php

namespace E2E;

use Facebook\WebDriver\WebDriverBy;

class ArtistsScreenTest extends TestCase
{
    public function testArtistsScreen()
    {
        $this->loginAndGoTo('artists');

        static::assertNotEmpty($this->els('#artistsWrapper .artists article.item'));
        $firstArtist = $this->el('#artistsWrapper .artists article.item:nth-child(1)');
        static::assertNotEmpty($firstArtist->findElement(WebDriverBy::cssSelector('.info .name'))->getText());
        static::assertContains('5 albums • 50 songs', $firstArtist->findElement(WebDriverBy::cssSelector('.meta'))->getText());

        // test the view modes
        $this->click('#artistsWrapper > h1.heading > span.view-modes > a.list');
        static::assertCount(1, $this->els('#artistsWrapper > div.artists.as-list'));
        $this->click('#artistsWrapper > h1.heading > span.view-modes > a.thumbnails');
        static::assertCount(1, $this->els('#artistsWrapper > div.artists.as-thumbnails'));
    }
}


text:
ActiveRecord::Schema.define(version: 20141207230426) do

  create_table "messenger_groups", force: true do |t|
    t.string   "name"
    t.integer  "owner_id"
    t.string   "owner_type"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "messenger_groups", ["name", "owner_id", "owner_type"], name: "index_messenger_groups_on_name_and_owner_id_and_owner_type", unique: true
  add_index "messenger_groups", ["name"], name: "index_messenger_groups_on_name"
  add_index "messenger_groups", ["owner_id", "owner_type"], name: "index_messenger_groups_on_owner_id_and_owner_type"

  create_table "messenger_memberships", force: true do |t|
    t.integer  "group_id"
    t.integer  "member_id"
    t.string   "member_type"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "messenger_memberships", ["group_id"], name: "index_messenger_memberships_on_group_id"
  add_index "messenger_memberships", ["member_id", "member_type"], name: "imm"
  add_index "messenger_memberships", ["member_type"], name: "index_messenger_memberships_on_member_type"

  create_table "messenger_messages", force: true do |t|
    t.text     "body"
    t.text     "encoded_recipients"
    t.string   "subject"
    t.integer  "sender_id"
    t.string   "sender_type"
    t.datetime "sent_at"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "messenger_messages", ["sender_id", "sender_type"], name: "index_messenger_messages_on_sender_id_and_sender_type"

  create_table "messenger_receipts", force: true do |t|
    t.integer  "message_id"
    t.datetime "read_at"
    t.integer  "recipient_id"
    t.string   "recipient_type"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "messenger_receipts", ["message_id", "recipient_id", "recipient_type"], name: "mrr"
  add_index "messenger_receipts", ["message_id"], name: "index_messenger_receipts_on_message_id"
  add_index "messenger_receipts", ["recipient_id", "recipient_type"], name: "index_messenger_receipts_on_recipient_id_and_recipient_type"

  create_table "users", force: true do |t|
    t.string "name"
  end

  add_index "users", ["name"], name: "index_users_on_name", unique: true

end


text:
require 'chef/win32/api'

class Chef
  module ReservedNames::Win32
    module API
      module Process
        extend Chef::ReservedNames::Win32::API

        ###############################################
        # Win32 API Bindings
        ###############################################

        ffi_lib 'kernel32'

        safe_attach_function :GetCurrentProcess, [], :HANDLE
        safe_attach_function :GetProcessHandleCount, [ :HANDLE, :LPDWORD ], :BOOL
        safe_attach_function :GetProcessId, [ :HANDLE ], :DWORD
        safe_attach_function :CloseHandle, [ :HANDLE ], :BOOL

      end
    end
  end
end


text:
li {
    padding: 2px;
}

table.changetypes .edit, .legend .edit { background: #fd8 }
table.changetypes .delete, .legend .delete { background: #f88 }
table.changetypes .add, .legend .add { background: #bfb }
table.changetypes .copy, .legend .copy { background: #88f }
table.changetypes .move, .legend .move { background: #ccc }
table.changetypes .unknown, .legend .unknown { background: #fff }

table.changetypes td {
    padding: 1px 2px;
    margin: 2px 2px 2px 0;
}

/* Legend for diff and file colors */
.legend {
 font-size: 9px;
 line-height: 1em;
 padding: .5em 0;
}
.legend h3 { display: none; }
.legend dt {
 background: #fff;
 border: 1px solid #999;
 float: left;
 margin: .1em .5em .1em 0;
 overflow: hidden;
 width: .8em; height: .8em;
}
.legend dl {
 display: inline;
 padding: 0;
 margin: 0;
 margin-right: .5em;
}
.legend dd {
 display: inline;
 float: left;
 padding: 0;
 margin: 0;
 margin-right: 2em;
}

/* tables */
table.tablesorter thead tr th, table.tablesorter tfoot tr th {
    border-bottom: 1px solid lightgray;
    font-size: 8pt;
    padding: 2px;
}
table.tablesorter thead tr .header {
    background-repeat: no-repeat;
    background-position: center right;
    cursor: pointer;
}
table.tablesorter thead tr .headerSortUp {
    background-image: url(asc.gif);
}
table.tablesorter thead tr .headerSortDown {
    background-image: url(desc.gif);
}

table.tablesorter thead tr .headerSortDown, table.tablesorter thead tr .headerSortUp {
    font-weight: bold;
}


text:
<?php

namespace TelegramBot\Constants;

class TelegramLimits
{
    /**
     * Download file limit in Byte. (20 MB)
     * For the moment, bots can download files of up to 20MB in size.
     */
    public const DOWNLOAD = 20971520;

    /**
     * Upload file limit in Byte. (50 MB)
     */
    public const UPLOAD = 52428800;

    /**
     * Caption max characters length
     */
    public const CAPTION_LENGTH = 1024;

    /**
     * Text max characters length
     */
    public const TEXT_LENGTH = 4096;

    /**
     * Minimum period in seconds for which the location will be updated (1 minute)
     */
    public const MIN_LIVE_PERIOD = 60;

    /**
     * Maximum period in seconds for which the location will be updated (24 hours)
     */
    public const MAX_LIVE_PERIOD = 86400;

    /**
     * Maximum poll question length
     */
    public const POLL_QUESTION_LENGTH = 300;
}


text:
This cookbook provides support for installing the BrightBox builds of Ruby.

For more documentation on these builds, please see [the official brightbox documentation](http://blog.brightbox.co.uk/posts/next-generation-ruby-packages-for-ubuntu).

**Please Note:** If you're upgrading from an older version, the default action is to upgrade packages. To change this, you need to override `node['brightbox-ruby']['default_action']`.

# Requirements

## Platform:

* Ubuntu

## Cookbooks:

* apt

# Attributes

* `node['brightbox-ruby']['default_action']` - Default action for Ruby install. Available options: `:upgrade`, `:install`. Defaults to `:upgrade`.
* `node['brightbox-ruby']['version']` - The version of Ruby to install. Defaults to `2.1`.
* `node['brightbox-ruby']['install_dev_package']` - Install the dev package, which provides headers for gem native extensions. Available options: `true`, `false`. Defaults to `true`.
* `node['brightbox-ruby']['gems']` - Gems to be installed by default. Defaults to `["bundler", "rake", "rubygems-bundler"]`.

# Recipes

* brightbox-ruby::default - Adds the brightbox repository, installs the Ruby package, sets it as the default then installs a sane server gemrc and adds bundler, rake and rubygems-bundler gems to bootstrap your environment.

## Contributing

We encourage all community contributions. Keeping this in mind, please follow these general guidelines when contributing:

* Fork the project
* Create a topic branch for what you're working on (git checkout -b awesome_feature)
* Commit away, push that up (git push your\_remote awesome\_feature)
* Create a new GitHub Issue with the commit, asking for review. Alternatively, send a pull request with details of what you added.
* Once it's accepted, if you want access to the core repository feel free to ask! Otherwise, you can continue to hack away in your own fork.

Other than that, our guidelines very closely match the GemCutter guidelines [here](http://wiki.github.com/qrush/gemcutter/contribution-guidelines).

(Thanks to [GemCutter](http://wiki.github.com/qrush/gemcutter/) for the contribution guide)

# License and Maintainer

Maintainer:: Filter Squad (<darcy@filtersquad.com>)

License:: Apache 2.0


text:
<?php

/**
 * Latte macro.
 *
 * @author     David Grudl
 * @package Nette\Latte
 */
interface IMacro
{

	/**
	 * Initializes before template parsing.
	 * @return void
	 */
	function initialize();

	/**
	 * Finishes template parsing.
	 * @return array(prolog, epilog)
	 */
	function finalize();

	/**
	 * New node is found. Returns FALSE to reject or code.
	 * @return bool|string
	 */
	function nodeOpened(NMacroNode $node);

	/**
	 * Node is closed. Returns code.
	 * @return string
	 */
	function nodeClosed(NMacroNode $node);

}


text:
from pallets_sphinx_themes import get_version
from pallets_sphinx_themes import ProjectLink

# Project --------------------------------------------------------------

project = "Jinja"
copyright = "2007 Pallets"
author = "Pallets"
release, version = get_version("Jinja2")

# General --------------------------------------------------------------

master_doc = "index"
extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.intersphinx",
    "pallets_sphinx_themes",
    "sphinxcontrib.log_cabinet",
    "sphinx_issues",
]
intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}
issues_github_path = "pallets/jinja"

# HTML -----------------------------------------------------------------

html_theme = "jinja"
html_theme_options = {"index_sidebar_logo": False}
html_context = {
    "project_links": [
        ProjectLink("Donate to Pallets", "https://palletsprojects.com/donate"),
        ProjectLink("Jinja Website", "https://palletsprojects.com/p/jinja/"),
        ProjectLink("PyPI releases", "https://pypi.org/project/Jinja2/"),
        ProjectLink("Source Code", "https://github.com/pallets/jinja/"),
        ProjectLink("Issue Tracker", "https://github.com/pallets/jinja/issues/"),
    ]
}
html_sidebars = {
    "index": ["project.html", "localtoc.html", "searchbox.html"],
    "**": ["localtoc.html", "relations.html", "searchbox.html"],
}
singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}
html_static_path = ["_static"]
html_favicon = "_static/jinja-logo-sidebar.png"
html_logo = "_static/jinja-logo-sidebar.png"
html_title = f"Jinja Documentation ({version})"
html_show_sourcelink = False

# LaTeX ----------------------------------------------------------------

latex_documents = [(master_doc, f"Jinja-{version}.tex", html_title, author, "manual")]


text:
<?php
class ModelCheckoutExtension extends Model {
	function getExtensions($type) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "extension WHERE `type` = '" . $this->db->escape($type) . "'");

		return $query->rows;
	}

	function getExtensionsByPosition($type, $position) {
		$module_data = array();

		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "extension WHERE `type` = '" . $this->db->escape($type) . "'");

		foreach ($query->rows as $result) {
			if ($this->config->get($result['key'] . '_status') && ($this->config->get($result['key'] . '_position') == $position)) {
				$module_data[] = array(
					'code'       => $result['key'],
					'sort_order' => $this->config->get($result['key'] . '_sort_order')
				);
			}
		}

		$sort_order = array();

		foreach ($module_data as $key => $value) {
      		$sort_order[$key] = $value['sort_order'];
    	}

    	array_multisort($sort_order, SORT_ASC, $module_data);

    	return $module_data;
	}
}
?>


text:
<component name="libraryTable">
  <library name="Maven: net.sourceforge.htmlunit:htmlunit-core-js:2.7">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/net/sourceforge/htmlunit/htmlunit-core-js/2.7/htmlunit-core-js-2.7.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/net/sourceforge/htmlunit/htmlunit-core-js/2.7/htmlunit-core-js-2.7-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/net/sourceforge/htmlunit/htmlunit-core-js/2.7/htmlunit-core-js-2.7-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
namespace Abp.RealTime
{
    public static class OnlineClientExtensions
    {
        public static UserIdentifier ToUserIdentifier(this IOnlineClient onlineClient)
        {
            return onlineClient.UserId.HasValue
                ? new UserIdentifier(onlineClient.TenantId, onlineClient.UserId.Value)
                : null;
        }
    }
}


text:
package com.dl7.mvp.injector.components;

import com.dl7.mvp.injector.PerFragment;
import com.dl7.mvp.injector.modules.VideoCompleteModule;
import com.dl7.mvp.module.manage.download.complete.VideoCompleteFragment;

import dagger.Component;

/**
 * Created by long on 2016/12/16.
 * video 缓存完成 Component
 */
@PerFragment
@Component(dependencies = ApplicationComponent.class, modules = VideoCompleteModule.class)
public interface VideoCompleteComponent {
    void inject(VideoCompleteFragment fragment);
}


text:
package org.apache.commons.bcel6.generic;

import org.apache.commons.bcel6.classfile.ConstantCP;
import org.apache.commons.bcel6.classfile.ConstantNameAndType;
import org.apache.commons.bcel6.classfile.ConstantPool;
import org.apache.commons.bcel6.classfile.ConstantUtf8;

/**
 * Super class for InvokeInstruction and FieldInstruction, since they have
 * some methods in common!
 *
 * @version $Id$
 */
public abstract class FieldOrMethod extends CPInstruction implements LoadClass {

    /**
     * Empty constructor needed for the Class.newInstance() statement in
     * Instruction.readInstruction(). Not to be used otherwise.
     */
    FieldOrMethod() {
    }

    /**
     * @param index to constant pool
     */
    protected FieldOrMethod(short opcode, int index) {
        super(opcode, index);
    }

    /** @return signature of referenced method/field.
     */
    public String getSignature( ConstantPoolGen cpg ) {
        ConstantPool cp = cpg.getConstantPool();
        ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
        ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex());
        return ((ConstantUtf8) cp.getConstant(cnat.getSignatureIndex())).getBytes();
    }

    /** @return name of referenced method/field.
     */
    public String getName( ConstantPoolGen cpg ) {
        ConstantPool cp = cpg.getConstantPool();
        ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
        ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex());
        return ((ConstantUtf8) cp.getConstant(cnat.getNameIndex())).getBytes();
    }

    /**
     * @return name of the referenced class/interface
     * @deprecated If the instruction references an array class,
     *    this method will return "java.lang.Object".
     *    For code generated by Java 1.5, this answer is
     *    sometimes wrong (e.g., if the "clone()" method is
     *    called on an array).  A better idea is to use
     *    the {@link #getReferenceType()} method, which correctly distinguishes
     *    between class types and array types.
     *
     */
    @Deprecated
    public String getClassName( ConstantPoolGen cpg ) {
        ConstantPool cp = cpg.getConstantPool();
        ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
        String className = cp.getConstantString(cmr.getClassIndex(),
                org.apache.commons.bcel6.Constants.CONSTANT_Class);
        if (className.startsWith("[")) {
            // Turn array classes into java.lang.Object.
            return "java.lang.Object";
        }
        return className.replace('/', '.');
    }

    /**
     * Return the reference type representing the class, interface,
     * or array class referenced by the instruction.
     * @param cpg the ConstantPoolGen used to create the instruction
     * @return an ObjectType (if the referenced class type is a class
     *   or interface), or an ArrayType (if the referenced class
     *   type is an array class)
     */
    public ReferenceType getReferenceType( ConstantPoolGen cpg ) {
        ConstantPool cp = cpg.getConstantPool();
        ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex());
        String className = cp.getConstantString(cmr.getClassIndex(),
                org.apache.commons.bcel6.Constants.CONSTANT_Class);
        if (className.startsWith("[")) {
            return (ArrayType) Type.getType(className);
        }
        className = className.replace('/', '.');
        return ObjectType.getInstance(className);
    }

    /** @return type of the referenced class/interface
     */
    @Override
    public ObjectType getLoadClassType( ConstantPoolGen cpg ) {
        return (ObjectType)getReferenceType(cpg);
    }
}


text:
{{_("Awarded to:")}}

        {{ award.user }}
        {% if request.user == award.user %}
            {{ _("(That's you!)") }}
        {% endif %}

    {% if award.nomination %}

{{_('Nominated by:')}}

{{ award.nomination.creator }}

{{_('Approved by:')}}

        {% if award.badge.nominations_autoapproved %}

{{_('(auto-approved)')}}

        {% elif award.nomination.approver %}

{{ award.nomination.approver }}

        {% endif %}
    {% else %}

{{_("Awarded by:")}}

{{ award.creator }}

    {% endif %}

{{_("Awarded at:")}}

{{ award.created }}

    {% if award.description %}

{{_("Explanation:")}}

{{ award.description | bleach_markup }}

    {% endif %}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>colour.models.dataset.dci_p3 Module — Colour 0.3.1 documentation</title>

    <link rel="stylesheet" href="_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootswatch-3.1.0/colour/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="_static/styles.css" type="text/css" />

    <link rel="top" title="Colour 0.3.1 documentation" href="index.html" />
    <link rel="up" title="colour.models.dataset Package" href="colour.models.dataset.html" />
    <link rel="next" title="colour.models.dataset.don_rgb_4 Module" href="colour.models.dataset.don_rgb_4.html" />
    <link rel="prev" title="colour.models.dataset.color_match_rgb Module" href="colour.models.dataset.color_match_rgb.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          Colour 0.3

colour-science.org

                   Documentation

                           API Reference

                           IPython Notebooks

                           Features

                           Contributing

    « colour.models.da...

    colour.models.da... »

<form class="navbar-form navbar-right" action="search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

colour.models.dataset.dci_p3 Module¶

DCI-P3 Colourspace¶

Defines the DCI-P3 colourspace:

<tt class="xref py py-attr docutils literal">DCI_P3_COLOURSPACE</tt>.

See also

RGB Colourspaces IPython Notebook

References

<colgroup><col class="label" /><col /></colgroup>

[1]	Understanding the HP DreamColor LP2480zx DCI-P3 Emulation Color Space
(Last accessed 24 February 2014)

<tt class="descclassname">colour.models.dataset.dci_p3.</tt><tt class="descname">DCI_P3_PRIMARIES</tt> = array([[ 0.68 ,  0.32 ],        [ 0.265,  0.69 ],        [ 0.15 ,  0.06 ]])¶

DCI-P3 colourspace primaries.

DCI_P3_PRIMARIES : ndarray, (3, 2)

<tt class="descclassname">colour.models.dataset.dci_p3.</tt><tt class="descname">DCI_P3_WHITEPOINT</tt> = (0.314, 0.351)¶

DCI-P3 colourspace whitepoint.

DCI_P3_WHITEPOINT : tuple

<tt class="descclassname">colour.models.dataset.dci_p3.</tt><tt class="descname">DCI_P3_TO_XYZ_MATRIX</tt> = array([[ 0.44516982,  0.27713441,  0.17228267],        [ 0.20949168,  0.72159525,  0.06891307],        [ 0.        ,  0.04706056,  0.90735539]])¶

DCI-P3 colourspace to CIE XYZ colourspace matrix.

DCI_P3_TO_XYZ_MATRIX : array_like, (3, 3)

<tt class="descclassname">colour.models.dataset.dci_p3.</tt><tt class="descname">XYZ_TO_DCI_P3_MATRIX</tt> = array([[ 2.72539401, -1.01800301, -0.44016319],        [-0.79516803,  1.68973207,  0.02264719],        [ 0.04124189, -0.08763902,  1.10092938]])¶

CIE XYZ colourspace to DCI-P3 colourspace matrix.

XYZ_TO_DCI_P3_MATRIX : array_like, (3, 3)

<tt class="descclassname">colour.models.dataset.dci_p3.</tt><tt class="descname">DCI_P3_TRANSFER_FUNCTION</tt><big>(</big>x<big>)</big>¶

Transfer function from linear to DCI-P3 colourspace.

DCI_P3_TRANSFER_FUNCTION : object

<tt class="descclassname">colour.models.dataset.dci_p3.</tt><tt class="descname">DCI_P3_INVERSE_TRANSFER_FUNCTION</tt><big>(</big>x<big>)</big>¶

Inverse transfer function from DCI-P3 colourspace to linear.

DCI_P3_INVERSE_TRANSFER_FUNCTION : object

<tt class="descclassname">colour.models.dataset.dci_p3.</tt><tt class="descname">DCI_P3_COLOURSPACE</tt> = <colour.models.rgb_colourspace.RGB_Colourspace object at 0x102e1dad0>¶

DCI-P3 colourspace.

DCI_P3_COLOURSPACE : RGB_Colourspace

      Back to top

        © Copyright 2013 - 2014, Colour Developers.

      Created using Sphinx 1.2.2.


text:
module MustdownHelper
  def markdown(content, markdown_extensions={}, renderer_options={})
    mark_exts = SelectraMustdown.markdown_extensions.merge(markdown_extensions)
    rend_opts = SelectraMustdown.renderer_options.merge(renderer_options)

    rndr  = SelectraMustdown.renderer.new(rend_opts)
    mdown = Redcarpet::Markdown.new(rndr, mark_exts)

    mdown.render(content).html_safe
  end

  def mustache(template, resource)
    Mustache.render(template, resource)
  end

  def mustdown(template, resource, *markdown_args)
    markdown mustache(template, resource), *markdown_args
  end
end


text:
class Test {
  public static void main(String[] args) {
    double x = <flown1>0;
    System.out.println(<caret>x);
  }
}


text:
namespace NETMF.OpenSource.XBee.Api
{

    /// <summary>
    ///  TODO: Update comments
    ///
    /// </summary>
    /// <remarks>
    ///
    /// </remarks>
    public class XBeeTimeoutException : XBeeException
    {
    }
}


text:
package net.kaczmarzyk.spring.data.jpa.domain;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import net.kaczmarzyk.spring.data.jpa.utils.QueryContext;

/**
 * Filters with {@code path like %pattern%} where-clause and ignores pattern case
 *
 * @author Michal Jankowski, Hazecod
 *
 */
public class LikeIgnoreCase<T> extends Like<T> {

	private static final long serialVersionUID = 1L;

	public LikeIgnoreCase(QueryContext queryCtx, String path, String... args) {
        super(queryCtx, path, args);
    }

    @Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
        return builder.like(builder.upper(this.<String> path(root)), pattern.toUpperCase());
    }

}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.freebasicacc.services;

import com.sun.pdfview.PDFFile;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 *
 * @author benzyaa
 */
public class PDFPrintService {
    public void printFile(String filePath) throws Exception{
        File f = new File(filePath);
        FileInputStream fis = new FileInputStream(f);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page
        PDFPrintPage pages = new PDFPrintPage(pdfFile);
        // Create Print Job
        PrinterJob pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
        pjob.setJobName(f.getName());
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);
        // Send print job to default printer
        //if(pjob.){
            pjob.print();
        //};//.print();
    }
}


text:
'use strict';

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _localizers = require('./localizers');

var _localizers2 = _interopRequireDefault(_localizers);

var _filter = require('./filter');

var _filter2 = _interopRequireDefault(_filter);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var filterTypes = Object.keys(_filter2.default).filter(function (i) {
  return i !== 'filter';
});

function getInteractionPropType(key) {
  var types = [_react.PropTypes.bool, _react.PropTypes.oneOf([key])],
      propType = _react.PropTypes.oneOfType(types);

  propType.acceptsArray = _react.PropTypes.oneOfType(types.concat(_react.PropTypes.array));

  return propType;
}

module.exports = {

  elementType: createChainableTypeChecker(function (props, propName, componentName) {

    if (typeof props[propName] !== 'function') {
      if (_react2.default.isValidElement(props[propName])) return new Error('Invalid prop `' + propName + '` specified in  `' + componentName + '`.' + ' Expected an Element `type`, not an actual Element');

      if (typeof props[propName] !== 'string') return new Error('Invalid prop `' + propName + '` specified in  `' + componentName + '`.' + ' Expected an Element `type` such as a tag name or return value of React.createClass(...)');
    }
    return null;
  }),

  numberFormat: createChainableTypeChecker(function () {
    var _localizers$number;

    return (_localizers$number = _localizers2.default.number).propType.apply(_localizers$number, arguments);
  }),

  dateFormat: createChainableTypeChecker(function () {
    var _localizers$date;

    return (_localizers$date = _localizers2.default.date).propType.apply(_localizers$date, arguments);
  }),

  disabled: getInteractionPropType('disabled'),
  readOnly: getInteractionPropType('readOnly'),

  accessor: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.func]),

  message: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.node, _react2.default.PropTypes.string]),

  filter: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.func, _react2.default.PropTypes.bool, _react2.default.PropTypes.oneOf(filterTypes)])
};

function createChainableTypeChecker(validate) {

  function checkType(isRequired, props, propName, componentName) {
    componentName = componentName || '<<anonymous>>';

    for (var _len = arguments.length, args = Array(_len > 4 ? _len - 4 : 0), _key = 4; _key < _len; _key++) {
      args[_key - 4] = arguments[_key];
    }

    if (props[propName] == null) {
      if (isRequired) {
        return new Error('Required prop `' + propName + '` was not specified in  `' + componentName + '`.');
      }
    } else return validate.apply(undefined, [props, propName, componentName].concat(args));
  }

  var chainedCheckType = checkType.bind(null, false);
  chainedCheckType.isRequired = checkType.bind(null, true);

  return chainedCheckType;
}


text:
<?php

namespace Google\Service\SecurityCommandCenter;

class GoogleCloudSecuritycenterV1BigQueryExport extends \Google\Model
{
  /**
   * @var string
   */
  public $createTime;
  /**
   * @var string
   */
  public $dataset;
  /**
   * @var string
   */
  public $description;
  /**
   * @var string
   */
  public $filter;
  /**
   * @var string
   */
  public $mostRecentEditor;
  /**
   * @var string
   */
  public $name;
  /**
   * @var string
   */
  public $principal;
  /**
   * @var string
   */
  public $updateTime;

  /**
   * @param string
   */
  public function setCreateTime($createTime)
  {
    $this->createTime = $createTime;
  }
  /**
   * @return string
   */
  public function getCreateTime()
  {
    return $this->createTime;
  }
  /**
   * @param string
   */
  public function setDataset($dataset)
  {
    $this->dataset = $dataset;
  }
  /**
   * @return string
   */
  public function getDataset()
  {
    return $this->dataset;
  }
  /**
   * @param string
   */
  public function setDescription($description)
  {
    $this->description = $description;
  }
  /**
   * @return string
   */
  public function getDescription()
  {
    return $this->description;
  }
  /**
   * @param string
   */
  public function setFilter($filter)
  {
    $this->filter = $filter;
  }
  /**
   * @return string
   */
  public function getFilter()
  {
    return $this->filter;
  }
  /**
   * @param string
   */
  public function setMostRecentEditor($mostRecentEditor)
  {
    $this->mostRecentEditor = $mostRecentEditor;
  }
  /**
   * @return string
   */
  public function getMostRecentEditor()
  {
    return $this->mostRecentEditor;
  }
  /**
   * @param string
   */
  public function setName($name)
  {
    $this->name = $name;
  }
  /**
   * @return string
   */
  public function getName()
  {
    return $this->name;
  }
  /**
   * @param string
   */
  public function setPrincipal($principal)
  {
    $this->principal = $principal;
  }
  /**
   * @return string
   */
  public function getPrincipal()
  {
    return $this->principal;
  }
  /**
   * @param string
   */
  public function setUpdateTime($updateTime)
  {
    $this->updateTime = $updateTime;
  }
  /**
   * @return string
   */
  public function getUpdateTime()
  {
    return $this->updateTime;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudSecuritycenterV1BigQueryExport::class, 'Google_Service_SecurityCommandCenter_GoogleCloudSecuritycenterV1BigQueryExport');


text:
from __future__ import unicode_literals

import django.contrib.postgres.fields.hstore
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('product', '0021_add_hstore_extension'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='product',
            name='attributes',
        ),
        migrations.AddField(
            model_name='product',
            name='attributes',
            field=django.contrib.postgres.fields.hstore.HStoreField(default={},
                                                                    verbose_name='attributes'),
        ),
        migrations.AlterField(
            model_name='product',
            name='product_class',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='products', to='product.ProductClass'),
        ),
    ]


text:
<?php

namespace Users;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Authentication\Storage;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;

class Module {

    public function onBootstrap(MvcEvent $e) {
        $eventManager = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getConfig() {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig() {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getServiceConfig() {
        return array(
            'factories' => array(
                'Application\Model\MyAuthStorage' => function($sm) {
                    return new \Users\Service\MyAuthStorage();
                },
                'AuthService' => function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'employees', 'userid', 'password');

                    $authService = new AuthenticationService();
                    $authService->setAdapter($dbTableAuthAdapter);
                    $authService->setStorage($sm->get('Application\Model\MyAuthStorage'));

                    return $authService;
                },
            )
        );
    }

}


text:
class CompaniesController < ApplicationController

	def index
		@companies = Company.first(20)
	end

	def start_search
	end

	def search
		@companies = SearchCompanies.new(params[:search_term]).search_companies
		render :'companies/index'
	end

	def show
		@company = Company.find_by(id: params[:id])
		yahoo_client = YahooFinance::Client.new
		raw_data = yahoo_client.historical_quotes(@company.symbol, { start_date: Time::now-(24*60*60*30), end_date: Time::now })
		@average_price = raw_data.map do |day|
											[day.low.to_f,
											 day.high.to_f,
											 day.open.to_f,
											 day.close.to_f].reduce(:+)/4.0
		end
	end

end


text:
package middleware

import (
	"net/http"

	"github.com/golang/glog"
)

func Recovery(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				glog.Errorf("panic: %+v", err)
				http.Error(w, http.StatusText(500), 500)
			}
		}()

		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}