text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
  <style name="MwmWidget.Editor"/>

  <style name="MwmWidget.Editor.TimePicker">
    <item name="android:headerBackground">@null</item>
    <item name="android:headerTimeTextAppearance" tools:targetApi="lollipop">@style/MwmTextAppearance.Editor.TimePicker</item>
    <item name="android:headerAmPmTextAppearance" tools:targetApi="lollipop">@style/MwmTextAppearance.Editor.Buttons</item>
    <item name="android:timePickerMode" tools:targetApi="lollipop">clock</item>
  </style>

  <style name="MwmWidget.Editor.CardView">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_marginBottom">@dimen/margin_base</item>
    <item name="cardBackgroundColor">?cardBackground</item>
    <item name="android:padding">@dimen/margin_base</item>
    <item name="cardPreventCornerOverlap">false</item>
  </style>

  <style name="MwmWidget.Editor.MetadataBlock">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:minHeight">@dimen/editor_height_field</item>
    <item name="android:layout_marginBottom">@dimen/margin_base</item>
  </style>

  <style name="MwmWidget.Editor.MetadataBlock.Clickable">
    <item name="android:background">?clickableBackground</item>
  </style>

  <style name="MwmWidget.Editor.MetadataIcon">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_centerVertical">true</item>
    <item name="android:layout_margin">@dimen/margin_half</item>
    <item name="android:tint">?iconTint</item>
  </style>

  <style name="MwmWidget.Editor.DayCheckBox">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:checked">true</item>
  </style>

  <style name="MwmWidget.Editor.DayText">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textAppearance">@style/MwmTextAppearance.Body1</item>
  </style>

  <style name="MwmWidget.Editor.DayLayout">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:gravity">center_horizontal</item>
    <item name="android:orientation">vertical</item>
  </style>

  <style name="MwmWidget.Editor.FieldLayout">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:ellipsize">end</item>
    <item name="android:layout_marginLeft">@dimen/editor_margin_left</item>
    <item name="android:layout_marginStart" tools:targetApi="jelly_bean_mr1">@dimen/editor_margin_left</item>
  </style>

  <style name="MwmWidget.Editor.FieldLayout.EditText">
    <item name="android:singleLine">true</item>
    <item name="android:textAppearance">@style/MwmTextAppearance.Body1</item>
    <!-- TODO check night colors -->
    <item name="android:theme">@style/MwmTheme.Editor.EditText</item>
  </style>

  <style name="MwmWidget.Editor.Problem" tools:ignore="NewApi">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">@dimen/height_block_base</item>
    <item name="android:gravity">center_vertical</item>
    <item name="android:paddingEnd">@dimen/margin_base</item>
    <item name="android:paddingRight">@dimen/margin_base</item>
    <item name="android:paddingLeft">@dimen/margin_base</item>
    <item name="android:paddingStart">@dimen/margin_base</item>
    <item name="android:background">?selectableItemBackground</item>
    <item name="android:clickable">true</item>
    <item name="android:textAppearance">@style/MwmTextAppearance.Body1</item>
  </style>
</resources>


text:
package com.shehabic.droppy.animations;

import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;

import com.shehabic.droppy.DroppyMenuPopup;
import com.shehabic.droppy.views.DroppyMenuPopupView;

public class DroppyScaleAnimation implements DroppyAnimation
{
    private static int ANIMATION_DURATION = 200;

    @Override
    public void animateHide(final DroppyMenuPopup popup, final DroppyMenuPopupView popupView, final View anchor, final boolean itemSelected)
    {
        ScaleAnimation scaleAnimation
            = new ScaleAnimation(1f, 0f, 1f, 0f, Animation.RELATIVE_TO_SELF, 0.25f, Animation.RELATIVE_TO_SELF, 1f);
        scaleAnimation.setDuration(ANIMATION_DURATION);
        scaleAnimation.setFillAfter(true);
        scaleAnimation.setAnimationListener(new Animation.AnimationListener()
        {
            @Override public void onAnimationStart(Animation animation) { }
            @Override public void onAnimationRepeat(Animation animation) { }
            @Override
            public void onAnimationEnd(Animation animation)
            {
                popup.hideAnimationCompleted(itemSelected);
            }

        });
        popupView.startAnimation(scaleAnimation);
    }

    @Override
    public void animateShow(final DroppyMenuPopupView popup, final View anchor)
    {
        ScaleAnimation scaleAnimation
            = new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.25f, Animation.RELATIVE_TO_SELF, 1f);
        scaleAnimation.setDuration(ANIMATION_DURATION);
        scaleAnimation.setFillAfter(true);
        popup.startAnimation(scaleAnimation);
    }
}

redpajama_set_name: RedPajamaGithub


text:
module TeX.Parser.HorizontalList
( HorizontalListElem(HBoxChar, HPenalty)
, horizontalList
)
where

import Prelude ( Char, Int, Show, Eq
               , (<$>), (>>), (<*>), ($), (<*), (*>), (++)
               )
import Text.Parsec

import TeX.Category
import TeX.Parser.Expand
import TeX.Parser.Parser
import TeX.Parser.Prim
import TeX.Token
import TeX.Parser.Assignment

data HorizontalListElem
  = HBoxChar Char
  | HPenalty Int
  deriving (Eq, Show)

horizontalListElem :: TeXParser HorizontalListElem
horizontalListElem =
  expand
  (HBoxChar <$> (extractChar <$> (categoryToken Letter)) <|>
   HBoxChar <$> (extractChar <$> (categoryToken Other)) <|>
   HBoxChar <$> (extractChar <$> (categoryToken Space))
   <?> "horizontal list elem")

groupedHorizontalList :: TeXParser [HorizontalListElem]
groupedHorizontalList =
  (expand $ categoryToken BeginGroup) *>
   horizontalList <*
   (expand $ categoryToken EndGroup)

horizontalList :: TeXParser [HorizontalListElem]
horizontalList = do
  option [] $ (assignment >> horizontalList) <|>
              ((:) <$> horizontalListElem <*> horizontalList) <|>
              ((++) <$> groupedHorizontalList <*> horizontalList)


text:
<?php

namespace CreateIt\TestBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CreateItTestBundle extends Bundle
{
}


text:
DELETE FROM tax_lot;
DELETE FROM position;

ALTER TABLE position
ADD COLUMN realized_pl double precision NOT NULL
;

-- END SEGMENT


text:
{% extends "layout.html" %}

{% block page_title %}
Enter the details of the vehicle being checked
{% endblock %}

{% block head %}
{% include "includes/head.html" %}
{% include "includes/scripts.html" %}
{% endblock %}

{% import "templates/button.html" as button %}

{% block content %}

    {% include "includes/phase_banner_beta.html" %}

            {% include "includes/errors/enter-details-error-box.html" %}

Enter the details of the vehicle being checked

            <form class="form">

                    <fieldset>
                        <legend class="visuallyhidden">Enter either a registration number or a V5C registration certificate (logbook) 11 digit reference number</legend>

                                Registration number
                                For example, CU57ABC
                                Provide a valid registration number

                            <input class="form-control form-control-1-4" id="vehReg" name="vehReg" type="text" style="text-transform:uppercase;" maxlength="8" value="">

                                To check vehicle tax rate and the date of the latest V5C enter the 11 digit reference number found on the latest V5C registration certificate (optional)
                                For example, 12345678910
                                The reference number you have provided is less than 11 digits long

                            <input class="form-control form-control-1-4" id="refNum" name="refNum" type="tel" maxlength="11" value="">

                            {% include "includes/help-images/where-to-find-ref.html" %}

                        {{ button.input(id='continue', name='continue', class='button', type='button', value='Continue') }}

                    </fieldset>

            </form>

{% endblock %}


text:
from django.shortcuts import get_object_or_404, render
from django.template import Template, Context
from django.http import HttpResponse

from .models import User, Memory

def profiletest(request, user_id):
	u = User.objects.get(pk=user_id)
	output = ("
You're looking at user %s.
" % user_id)

	output = output + "
" + u.first_name + " " + u.last_name

	return HttpResponse(output)

def userlist(request):
	lastest_user_list = User.objects.order_by('pk')[:5]
	output = ', '.join([u.first_name for u in lastest_user_list])
	return HttpResponse(output)

def signup(request):
	return render(request, 'signup.html', {})

def settings(request):
	return render(request, 'settings.html', {})

def post(request, memory_id):
	memory = get_object_or_404(Memory, pk=memory_id)
	author = get_object_or_404(User, pk=memory.author)
	return render(request, 'post.html', {'memory': memory, 'author': author})

def passwordreset(request):
	return render(request, 'password-reset.html', {})

def login(request):
	return render(request, 'login.html', {})

def friends(request):
	return render(request, 'friends.html', {})


text:
package project

import (
	"context"
	"fmt"
	"net/http"
	"net/url"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/lxc/lxd/lxd/db"
	"github.com/lxc/lxd/lxd/db/cluster"
	deviceconfig "github.com/lxc/lxd/lxd/device/config"
	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/rbac"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/idmap"
	"github.com/lxc/lxd/shared/units"
	"github.com/lxc/lxd/shared/validate"
)

// AllowInstanceCreation returns an error if any project-specific limit or
// restriction is violated when creating a new instance.
func AllowInstanceCreation(tx *db.ClusterTx, projectName string, req api.InstancesPost) error {
	info, err := fetchProject(tx, projectName, true)
	if err != nil {
		return err
	}

	if info == nil {
		return nil
	}

	var instanceType instancetype.Type
	switch req.Type {
	case api.InstanceTypeContainer:
		instanceType = instancetype.Container
	case api.InstanceTypeVM:
		instanceType = instancetype.VM
	default:
		return fmt.Errorf("Unexpected instance type %q", req.Type)
	}

	if req.Profiles == nil {
		req.Profiles = []string{"default"}
	}

	err = checkInstanceCountLimit(info, instanceType)
	if err != nil {
		return err
	}

	err = checkTotalInstanceCountLimit(info)
	if err != nil {
		return err
	}

	// Add the instance being created.
	info.Instances = append(info.Instances, api.Instance{
		Name:        req.Name,
		Project:     projectName,
		InstancePut: req.InstancePut,
	})

	// Special case restriction checks on volatile.* keys.
	strip := false

	if shared.StringInSlice(req.Source.Type, []string{"copy", "migration"}) {
		// Allow stripping volatile keys if dealing with a copy or migration.
		strip = true
	}

	err = checkRestrictionsOnVolatileConfig(
		info.Project, instanceType, req.Name, req.Config, map[string]string{}, strip)
	if err != nil {
		return err
	}

	err = checkRestrictionsAndAggregateLimits(tx, info)
	if err != nil {
		return err
	}

	return nil
}

// Check that we have not exceeded the maximum total allotted number of instances for both containers and vms.
func checkTotalInstanceCountLimit(info *projectInfo) error {
	count, limit, err := getTotalInstanceCountLimit(info)
	if err != nil {
		return err
	}

	if limit >= 0 && count >= limit {
		return fmt.Errorf("Reached maximum number of instances in project %q", info.Project.Name)
	}

	return nil
}

func getTotalInstanceCountLimit(info *projectInfo) (int, int, error) {
	overallValue, ok := info.Project.Config["limits.instances"]
	if ok {
		limit, err := strconv.Atoi(overallValue)
		if err != nil {
			return -1, -1, err
		}

		return len(info.Instances), limit, nil
	}

	return len(info.Instances), -1, nil
}

// Check that we have not reached the maximum number of instances for this type.
func checkInstanceCountLimit(info *projectInfo, instanceType instancetype.Type) error {
	count, limit, err := getInstanceCountLimit(info, instanceType)
	if err != nil {
		return err
	}

	if limit >= 0 && count >= limit {
		return fmt.Errorf("Reached maximum number of instances of type %q in project %q", instanceType, info.Project.Name)
	}

	return nil
}

func getInstanceCountLimit(info *projectInfo, instanceType instancetype.Type) (int, int, error) {
	var key string
	switch instanceType {
	case instancetype.Container:
		key = "limits.containers"
	case instancetype.VM:
		key = "limits.virtual-machines"
	default:
		return -1, -1, fmt.Errorf("Unexpected instance type %q", instanceType)
	}

	instanceCount := 0
	for _, inst := range info.Instances {
		if inst.Type == instanceType.String() {
			instanceCount++
		}
	}

	value, ok := info.Project.Config[key]
	if ok {
		limit, err := strconv.Atoi(value)
		if err != nil || limit < 0 {
			return -1, -1, fmt.Errorf("Unexpected %q value: %q", key, value)
		}

		return instanceCount, limit, nil
	}

	return instanceCount, -1, nil
}

// Check restrictions on setting volatile.* keys.
func checkRestrictionsOnVolatileConfig(project api.Project, instanceType instancetype.Type, instanceName string, config, currentConfig map[string]string, strip bool) error {
	if project.Config["restrict"] == "false" {
		return nil
	}

	var restrictedLowLevel string
	switch instanceType {
	case instancetype.Container:
		restrictedLowLevel = "restricted.containers.lowlevel"
	case instancetype.VM:
		restrictedLowLevel = "restricted.virtual-machines.lowlevel"
	}

	if project.Config[restrictedLowLevel] == "allow" {
		return nil
	}

	// Checker for safe volatile keys.
	isSafeKey := func(key string) bool {
		if shared.StringInSlice(key, []string{"volatile.apply_template", "volatile.base_image", "volatile.last_state.power"}) {
			return true
		}

		if strings.HasPrefix(key, shared.ConfigVolatilePrefix) {
			if strings.HasSuffix(key, ".apply_quota") {
				return true
			}

			if strings.HasSuffix(key, ".hwaddr") {
				return true
			}
		}

		return false
	}

	for key, value := range config {
		if !strings.HasPrefix(key, shared.ConfigVolatilePrefix) {
			continue
		}

		// Allow given safe volatile keys to be set
		if isSafeKey(key) {
			continue
		}

		if strip {
			delete(config, key)
			continue
		}

		currentValue, ok := currentConfig[key]
		if !ok {
			return fmt.Errorf(
				"Setting %q on %s %q in project %q is forbidden",
				key, instanceType, instanceName, project.Name)
		}

		if currentValue != value {
			return fmt.Errorf(
				"Changing %q on %s %q in project %q is forbidden",
				key, instanceType, instanceName, project.Name)
		}
	}

	return nil
}

// AllowVolumeCreation returns an error if any project-specific limit or
// restriction is violated when creating a new custom volume in a project.
func AllowVolumeCreation(tx *db.ClusterTx, projectName string, req api.StorageVolumesPost) error {
	info, err := fetchProject(tx, projectName, true)
	if err != nil {
		return err
	}

	if info == nil {
		return nil
	}

	// If "limits.disk" is not set, there's nothing to do.
	if info.Project.Config["limits.disk"] == "" {
		return nil
	}

	// Add the volume being created.
	info.Volumes = append(info.Volumes, db.StorageVolumeArgs{
		Name:   req.Name,
		Config: req.Config,
	})

	err = checkRestrictionsAndAggregateLimits(tx, info)
	if err != nil {
		return err
	}

	return nil
}

// GetImageSpaceBudget returns how much disk space is left in the given project
// for writing images.
//
// If no limit is in place, return -1.
func GetImageSpaceBudget(tx *db.ClusterTx, projectName string) (int64, error) {
	info, err := fetchProject(tx, projectName, true)
	if err != nil {
		return -1, err
	}

	if info == nil {
		return -1, nil
	}

	// If "features.images" is not enabled, the budget is unlimited.
	if shared.IsFalse(info.Project.Config["features.images"]) {
		return -1, nil
	}

	// If "limits.disk" is not set, the budget is unlimited.
	if info.Project.Config["limits.disk"] == "" {
		return -1, nil
	}

	parser := aggregateLimitConfigValueParsers["limits.disk"]
	quota, err := parser(info.Project.Config["limits.disk"])
	if err != nil {
		return -1, err
	}

	instances, err := expandInstancesConfigAndDevices(info.Instances, info.Profiles)
	if err != nil {
		return -1, err
	}

	info.Instances = instances

	totals, err := getTotalsAcrossProjectEntities(info, []string{"limits.disk"}, false)
	if err != nil {
		return -1, err
	}

	if totals["limits.disk"] < quota {
		return quota - totals["limits.disk"], nil
	}

	return 0, nil
}

// Check that we would not violate the project limits or restrictions if we
// were to commit the given instances and profiles.
func checkRestrictionsAndAggregateLimits(tx *db.ClusterTx, info *projectInfo) error {
	// List of config keys for which we need to check aggregate values
	// across all project instances.
	aggregateKeys := []string{}
	isRestricted := false
	for key, value := range info.Project.Config {
		if shared.StringInSlice(key, allAggregateLimits) {
			aggregateKeys = append(aggregateKeys, key)
			continue
		}

		if key == "restricted" && shared.IsTrue(value) {
			isRestricted = true
			continue
		}
	}

	if len(aggregateKeys) == 0 && !isRestricted {
		return nil
	}

	instances, err := expandInstancesConfigAndDevices(info.Instances, info.Profiles)
	if err != nil {
		return err
	}

	info.Instances = instances

	err = checkAggregateLimits(info, aggregateKeys)
	if err != nil {
		return err
	}

	if isRestricted {
		err = checkRestrictions(info.Project, info.Instances, info.Profiles)
		if err != nil {
			return err
		}
	}

	return nil
}

func getAggregateLimits(info *projectInfo, aggregateKeys []string) (map[string]api.ProjectStateResource, error) {
	result := map[string]api.ProjectStateResource{}

	if len(aggregateKeys) == 0 {
		return result, nil
	}

	totals, err := getTotalsAcrossProjectEntities(info, aggregateKeys, true)
	if err != nil {
		return nil, err
	}

	for _, key := range aggregateKeys {
		max := int64(-1)
		limit := info.Project.Config[key]
		if limit != "" {
			parser := aggregateLimitConfigValueParsers[key]
			max, err = parser(info.Project.Config[key])
			if err != nil {
				return nil, err
			}
		}

		resource := api.ProjectStateResource{
			Usage: totals[key],
			Limit: max,
		}

		result[key] = resource
	}

	return result, nil
}

func checkAggregateLimits(info *projectInfo, aggregateKeys []string) error {
	if len(aggregateKeys) == 0 {
		return nil
	}

	totals, err := getTotalsAcrossProjectEntities(info, aggregateKeys, false)
	if err != nil {
		return err
	}

	for _, key := range aggregateKeys {
		parser := aggregateLimitConfigValueParsers[key]
		max, err := parser(info.Project.Config[key])
		if err != nil {
			return err
		}

		if totals[key] > max {
			return fmt.Errorf(
				"Reached maximum aggregate value %s for %q in project %s",
				info.Project.Config[key], key, info.Project.Name)
		}
	}
	return nil
}

// parseHostIDMapRange parse the supplied list of host ID map ranges into a idmap.IdmapEntry slice.
func parseHostIDMapRange(isUID bool, isGID bool, listValue string) ([]idmap.IdmapEntry, error) {
	var idmaps []idmap.IdmapEntry

	for _, listItem := range shared.SplitNTrimSpace(listValue, ",", -1, true) {
		rangeStart, rangeSize, err := validate.ParseUint32Range(listItem)
		if err != nil {
			return nil, err
		}

		idmaps = append(idmaps, idmap.IdmapEntry{
			Hostid:   int64(rangeStart),
			Maprange: int64(rangeSize),
			Isuid:    isUID,
			Isgid:    isGID,
			Nsid:     -1, // We don't have this as we are just parsing host IDs.
		})
	}

	return idmaps, nil
}

// Check that the project's restrictions are not violated across the given
// instances and profiles.
func checkRestrictions(project api.Project, instances []api.Instance, profiles []api.Profile) error {
	containerConfigChecks := map[string]func(value string) error{}
	devicesChecks := map[string]func(value map[string]string) error{}

	allowContainerLowLevel := false
	allowVMLowLevel := false
	var allowedIDMapHostUIDs, allowedIDMapHostGIDs []idmap.IdmapEntry

	for key, defaultValue := range allRestrictions {
		// Check if this particular restriction is defined explicitly
		// in the project config. If not, use the default value.
		restrictionValue, ok := project.Config[key]
		if !ok {
			restrictionValue = defaultValue
		}

		switch key {
		case "restricted.containers.interception":
			for _, key := range allowableIntercept {
				containerConfigChecks[key] = func(instanceValue string) error {
					disabled := shared.IsFalseOrEmpty(instanceValue)

					if restrictionValue != "allow" && !disabled {
						return fmt.Errorf("Container syscall interception is forbidden")
					}

					return nil
				}
			}
		case "restricted.containers.nesting":
			containerConfigChecks["security.nesting"] = func(instanceValue string) error {
				if restrictionValue == "block" && shared.IsTrue(instanceValue) {
					return fmt.Errorf("Container nesting is forbidden")
				}

				return nil
			}

		case "restricted.containers.lowlevel":
			if restrictionValue == "allow" {
				allowContainerLowLevel = true
			}

		case "restricted.containers.privilege":
			containerConfigChecks["security.privileged"] = func(instanceValue string) error {
				if restrictionValue != "allow" && shared.IsTrue(instanceValue) {
					return fmt.Errorf("Privileged containers are forbidden")
				}

				return nil
			}

			containerConfigChecks["security.idmap.isolated"] = func(instanceValue string) error {
				if restrictionValue == "isolated" && shared.IsFalseOrEmpty(instanceValue) {
					return fmt.Errorf("Non-isolated containers are forbidden")
				}

				return nil
			}

		case "restricted.virtual-machines.lowlevel":
			if restrictionValue == "allow" {
				allowVMLowLevel = true
			}

		case "restricted.devices.unix-char":
			devicesChecks["unix-char"] = func(device map[string]string) error {
				if restrictionValue != "allow" {
					return fmt.Errorf("Unix character devices are forbidden")
				}

				return nil
			}

		case "restricted.devices.unix-block":
			devicesChecks["unix-block"] = func(device map[string]string) error {
				if restrictionValue != "allow" {
					return fmt.Errorf("Unix block devices are forbidden")
				}

				return nil
			}

		case "restricted.devices.unix-hotplug":
			devicesChecks["unix-hotplug"] = func(device map[string]string) error {
				if restrictionValue != "allow" {
					return fmt.Errorf("Unix hotplug devices are forbidden")
				}

				return nil
			}

		case "restricted.devices.infiniband":
			devicesChecks["infiniband"] = func(device map[string]string) error {
				if restrictionValue != "allow" {
					return fmt.Errorf("Infiniband devices are forbidden")
				}

				return nil
			}

		case "restricted.devices.gpu":
			devicesChecks["gpu"] = func(device map[string]string) error {
				if restrictionValue != "allow" {
					return fmt.Errorf("GPU devices are forbidden")
				}

				return nil
			}

		case "restricted.devices.usb":
			devicesChecks["usb"] = func(device map[string]string) error {
				if restrictionValue != "allow" {
					return fmt.Errorf("USB devices are forbidden")
				}

				return nil
			}

		case "restricted.devices.pci":
			devicesChecks["pci"] = func(device map[string]string) error {
				if restrictionValue != "allow" {
					return fmt.Errorf("PCI devices are forbidden")
				}

				return nil
			}

		case "restricted.devices.proxy":
			devicesChecks["proxy"] = func(device map[string]string) error {
				if restrictionValue != "allow" {
					return fmt.Errorf("Proxy devices are forbidden")
				}

				return nil
			}

		case "restricted.devices.nic":
			devicesChecks["nic"] = func(device map[string]string) error {
				switch restrictionValue {
				case "block":
					return fmt.Errorf("Network devices are forbidden")
				case "managed":
					if device["network"] == "" {
						return fmt.Errorf("Only managed network devices are allowed")
					}
				}
				return nil
			}

		case "restricted.devices.disk":
			devicesChecks["disk"] = func(device map[string]string) error {
				// The root device is always allowed.
				if device["path"] == "/" && device["pool"] != "" {
					return nil
				}

				// Always allow the cloud-init config drive.
				if device["path"] == "" && device["source"] == "cloud-init:config" {
					return nil
				}

				switch restrictionValue {
				case "block":
					return fmt.Errorf("Disk devices are forbidden")
				case "managed":
					if device["pool"] == "" {
						return fmt.Errorf("Attaching disks not backed by a pool is forbidden")
					}

				case "allow":
					var allowed bool
					allowed, _ = CheckRestrictedDevicesDiskPaths(project.Config, device["source"])
					if !allowed {
						return fmt.Errorf("Disk source path %q not allowed", device["source"])
					}
				}

				return nil
			}

		case "restricted.idmap.uid":
			var err error
			allowedIDMapHostUIDs, err = parseHostIDMapRange(true, false, restrictionValue)
			if err != nil {
				return fmt.Errorf("Failed parsing %q: %w", "restricted.idmap.uid", err)
			}

		case "restricted.idmap.gid":
			var err error
			allowedIDMapHostGIDs, err = parseHostIDMapRange(false, true, restrictionValue)
			if err != nil {
				return fmt.Errorf("Failed parsing %q: %w", "restricted.idmap.uid", err)
			}
		}
	}

	// Common config check logic between instances and profiles.
	entityConfigChecker := func(instType instancetype.Type, entityName string, config map[string]string) error {
		entityTypeLabel := instType.String()
		if instType == instancetype.Any {
			entityTypeLabel = "profile"
		}

		isContainerOrProfile := instType == instancetype.Container || instType == instancetype.Any
		isVMOrProfile := instType == instancetype.VM || instType == instancetype.Any

		// Check if unrestricted low-level options are available. For profiles we require that low-level
		// features for both containers and VMs are enabled as we don't know which instance the profile
		// will be used on.
		allowUnrestrictedLowLevel := (instType == instancetype.Any && allowContainerLowLevel && allowVMLowLevel) ||
			(instType == instancetype.Container && allowContainerLowLevel) ||
			(instType == instancetype.VM && allowVMLowLevel)

		for key, value := range config {
			if !allowUnrestrictedLowLevel {
				if key == "raw.idmap" {
					// If the low-level raw.idmap is used check whether the raw.idmap host IDs
					// are allowed based on the project's allowed ID map Host UIDs and GIDs.
					idmaps, err := idmap.ParseRawIdmap(value)
					if err != nil {
						return err
					}

					for idmapIndex, idmap := range idmaps {
						if !idmap.HostIDsCoveredBy(allowedIDMapHostUIDs, allowedIDMapHostGIDs) {
							return fmt.Errorf(`Use of low-level "raw.idmap" element %d on %s %q of project %q is forbidden`, idmapIndex, entityTypeLabel, entityName, project.Name)
						}
					}
				} else if (isContainerOrProfile && isContainerLowLevelOptionForbidden(key)) || (isVMOrProfile && isVMLowLevelOptionForbidden(key)) {
					// Otherwise check if the key is a forbidden low-level one.
					return fmt.Errorf("Use of low-level config %q on %s %q of project %q is forbidden", key, entityTypeLabel, entityName, project.Name)
				}
			}

			var checker func(value string) error
			if isContainerOrProfile {
				checker = containerConfigChecks[key]
			}

			if checker == nil {
				continue
			}

			err := checker(value)
			if err != nil {
				return fmt.Errorf("Invalid value %q for config %q on %s %q of project %q: %w", value, key, instType, entityName, project.Name, err)
			}
		}

		return nil
	}

	// Common devices check logic between instances and profiles.
	entityDevicesChecker := func(instType instancetype.Type, entityName string, devices map[string]map[string]string) error {
		entityTypeLabel := instType.String()
		if instType == instancetype.Any {
			entityTypeLabel = "profile"
		}

		for name, device := range devices {
			check, ok := devicesChecks[device["type"]]
			if !ok {
				continue
			}

			err := check(device)
			if err != nil {
				return fmt.Errorf("Invalid device %q on %s %q of project %q: %w", name, entityTypeLabel, entityName, project.Name, err)
			}
		}
		return nil
	}

	for _, instance := range instances {
		instType, err := instancetype.New(instance.Type)
		if err != nil {
			return err
		}

		err = entityConfigChecker(instType, instance.Name, instance.Config)
		if err != nil {
			return err
		}

		err = entityDevicesChecker(instType, instance.Name, instance.Devices)
		if err != nil {
			return err
		}
	}

	for _, profile := range profiles {
		err := entityConfigChecker(instancetype.Any, profile.Name, profile.Config)
		if err != nil {
			return err
		}

		err = entityDevicesChecker(instancetype.Any, profile.Name, profile.Devices)
		if err != nil {
			return err
		}
	}

	return nil
}

// CheckRestrictedDevicesDiskPaths checks whether the disk's source path is within the allowed paths specified in
// the project's restricted.devices.disk.paths config setting.
// If no allowed paths are specified in project, then it allows all paths, and returns true and empty string.
// If allowed paths are specified, and one matches, returns true and the matching allowed parent source path.
// Otherwise if sourcePath not allowed returns false and empty string.
func CheckRestrictedDevicesDiskPaths(projectConfig map[string]string, sourcePath string) (bool, string) {
	if projectConfig["restricted.devices.disk.paths"] == "" {
		return true, ""
	}

	// Clean, then add trailing slash, to ensure we are prefix matching on whole path.
	sourcePath = fmt.Sprintf("%s/", filepath.Clean(shared.HostPath(sourcePath)))
	for _, parentSourcePath := range strings.SplitN(projectConfig["restricted.devices.disk.paths"], ",", -1) {
		// Clean, then add trailing slash, to ensure we are prefix matching on whole path.
		parentSourcePathTrailing := fmt.Sprintf("%s/", filepath.Clean(shared.HostPath(parentSourcePath)))
		if strings.HasPrefix(sourcePath, parentSourcePathTrailing) {
			return true, parentSourcePath
		}
	}

	return false, ""
}

var allAggregateLimits = []string{
	"limits.cpu",
	"limits.disk",
	"limits.memory",
	"limits.processes",
}

// allRestrictions lists all available 'restrict.*' config keys along with their default setting.
var allRestrictions = map[string]string{
	"restricted.backups":                   "block",
	"restricted.cluster.groups":            "",
	"restricted.cluster.target":            "block",
	"restricted.containers.nesting":        "block",
	"restricted.containers.interception":   "block",
	"restricted.containers.lowlevel":       "block",
	"restricted.containers.privilege":      "unprivileged",
	"restricted.virtual-machines.lowlevel": "block",
	"restricted.devices.unix-char":         "block",
	"restricted.devices.unix-block":        "block",
	"restricted.devices.unix-hotplug":      "block",
	"restricted.devices.infiniband":        "block",
	"restricted.devices.gpu":               "block",
	"restricted.devices.usb":               "block",
	"restricted.devices.pci":               "block",
	"restricted.devices.proxy":             "block",
	"restricted.devices.nic":               "managed",
	"restricted.devices.disk":              "managed",
	"restricted.devices.disk.paths":        "",
	"restricted.idmap.uid":                 "",
	"restricted.idmap.gid":                 "",
	"restricted.snapshots":                 "block",
}

// allowableIntercept lists all syscall interception keys which may be allowed.
var allowableIntercept = []string{
	"security.syscalls.intercept.bpf",
	"security.syscalls.intercept.bpf.devices",
	"security.syscalls.intercept.mknod",
	"security.syscalls.intercept.mount",
	"security.syscalls.intercept.mount.fuse",
	"security.syscalls.intercept.setxattr",
	"security.syscalls.intercept.sysinfo",
}

// Return true if a low-level container option is forbidden.
func isContainerLowLevelOptionForbidden(key string) bool {
	if strings.HasPrefix(key, "security.syscalls.intercept") && !shared.StringInSlice(key, allowableIntercept) {
		return true
	}

	if shared.StringInSlice(key, []string{
		"boot.host_shutdown_timeout",
		"linux.kernel_modules",
		"raw.apparmor",
		"raw.idmap",
		"raw.lxc",
		"raw.seccomp",
		"security.devlxd.images",
		"security.idmap.base",
		"security.idmap.size",
	}) {
		return true
	}

	return false
}

// Return true if a low-level VM option is forbidden.
func isVMLowLevelOptionForbidden(key string) bool {
	return shared.StringInSlice(key, []string{
		"boot.host_shutdown_timeout",
		"limits.memory.hugepages",
		"raw.idmap",
		"raw.qemu",
	})
}

// AllowInstanceUpdate returns an error if any project-specific limit or
// restriction is violated when updating an existing instance.
func AllowInstanceUpdate(tx *db.ClusterTx, projectName, instanceName string, req api.InstancePut, currentConfig map[string]string) error {
	var updatedInstance *api.Instance
	info, err := fetchProject(tx, projectName, true)
	if err != nil {
		return err
	}

	if info == nil {
		return nil
	}

	// Change the instance being updated.
	for i, instance := range info.Instances {
		if instance.Name != instanceName {
			continue
		}

		info.Instances[i].Profiles = req.Profiles
		info.Instances[i].Config = req.Config
		info.Instances[i].Devices = req.Devices
		updatedInstance = &info.Instances[i]
	}

	instType, err := instancetype.New(updatedInstance.Type)
	if err != nil {
		return err
	}

	// Special case restriction checks on volatile.* keys, since we want to
	// detect if they were changed or added.
	err = checkRestrictionsOnVolatileConfig(
		info.Project, instType, updatedInstance.Name, req.Config, currentConfig, false)
	if err != nil {
		return err
	}

	err = checkRestrictionsAndAggregateLimits(tx, info)
	if err != nil {
		return err
	}

	return nil
}

// AllowVolumeUpdate returns an error if any project-specific limit or
// restriction is violated when updating an existing custom volume.
func AllowVolumeUpdate(tx *db.ClusterTx, projectName, volumeName string, req api.StorageVolumePut, currentConfig map[string]string) error {
	info, err := fetchProject(tx, projectName, true)
	if err != nil {
		return err
	}

	if info == nil {
		return nil
	}

	// If "limits.disk" is not set, there's nothing to do.
	if info.Project.Config["limits.disk"] == "" {
		return nil
	}

	// Change the volume being updated.
	for i, volume := range info.Volumes {
		if volume.Name != volumeName {
			continue
		}

		info.Volumes[i].Config = req.Config
	}

	err = checkRestrictionsAndAggregateLimits(tx, info)
	if err != nil {
		return err
	}

	return nil
}

// AllowProfileUpdate checks that project limits and restrictions are not
// violated when changing a profile.
func AllowProfileUpdate(tx *db.ClusterTx, projectName, profileName string, req api.ProfilePut) error {
	info, err := fetchProject(tx, projectName, true)
	if err != nil {
		return err
	}

	if info == nil {
		return nil
	}

	// Change the profile being updated.
	for i, profile := range info.Profiles {
		if profile.Name != profileName {
			continue
		}

		info.Profiles[i].Config = req.Config
		info.Profiles[i].Devices = req.Devices
	}

	err = checkRestrictionsAndAggregateLimits(tx, info)
	if err != nil {
		return err
	}

	return nil
}

// AllowProjectUpdate checks the new config to be set on a project is valid.
func AllowProjectUpdate(tx *db.ClusterTx, projectName string, config map[string]string, changed []string) error {
	info, err := fetchProject(tx, projectName, false)
	if err != nil {
		return err
	}

	info.Instances, err = expandInstancesConfigAndDevices(info.Instances, info.Profiles)
	if err != nil {
		return err
	}

	// List of keys that need to check aggregate values across all project
	// instances.
	aggregateKeys := []string{}

	for _, key := range changed {
		if strings.HasPrefix(key, "restricted.") {
			project := api.Project{
				Name: projectName,
				ProjectPut: api.ProjectPut{
					Config: config,
				},
			}

			err := checkRestrictions(project, info.Instances, info.Profiles)
			if err != nil {
				return fmt.Errorf("Conflict detected when changing %q in project %q: %w", key, projectName, err)
			}

			continue
		}

		switch key {
		case "limits.instances":
			err := validateTotalInstanceCountLimit(info.Instances, config[key], projectName)
			if err != nil {
				return fmt.Errorf("Can't change limits.instances in project %q: %w", projectName, err)
			}

		case "limits.containers":
			fallthrough
		case "limits.virtual-machines":
			err := validateInstanceCountLimit(info.Instances, key, config[key], projectName)
			if err != nil {
				return fmt.Errorf("Can't change %q in project %q: %w", key, projectName, err)
			}

		case "limits.processes":
			fallthrough
		case "limits.cpu":
			fallthrough
		case "limits.memory":
			fallthrough
		case "limits.disk":
			aggregateKeys = append(aggregateKeys, key)
		}
	}

	if len(aggregateKeys) > 0 {
		totals, err := getTotalsAcrossProjectEntities(info, aggregateKeys, false)
		if err != nil {
			return err
		}

		for _, key := range aggregateKeys {
			err := validateAggregateLimit(totals, key, config[key])
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// Check that limits.instances, i.e. the total limit of containers/virtual machines allocated
// to the user is equal to or above the current count.
func validateTotalInstanceCountLimit(instances []api.Instance, value, project string) error {
	if value == "" {
		return nil
	}

	limit, err := strconv.Atoi(value)
	if err != nil {
		return err
	}

	count := len(instances)

	if limit < count {
		return fmt.Errorf("'limits.instances' is too low: there currently are %d total instances in project %s", count, project)
	}

	return nil
}

// Check that limits.containers or limits.virtual-machines is equal or above
// the current count.
func validateInstanceCountLimit(instances []api.Instance, key, value, project string) error {
	if value == "" {
		return nil
	}

	instanceType := countConfigInstanceType[key]
	limit, err := strconv.Atoi(value)
	if err != nil {
		return err
	}

	dbType, err := instancetype.New(string(instanceType))
	if err != nil {
		return err
	}

	count := 0
	for _, instance := range instances {
		if instance.Type == dbType.String() {
			count++
		}
	}

	if limit < count {
		return fmt.Errorf(
			"'%s' is too low: there currently are %d instances of type %s in project %s",
			key, count, instanceType, project)
	}

	return nil
}

var countConfigInstanceType = map[string]api.InstanceType{
	"limits.containers":       api.InstanceTypeContainer,
	"limits.virtual-machines": api.InstanceTypeVM,
}

// Validates an aggregate limit, checking that the new value is not below the
// current total amount.
func validateAggregateLimit(totals map[string]int64, key, value string) error {
	if value == "" {
		return nil
	}

	parser := aggregateLimitConfigValueParsers[key]
	limit, err := parser(value)
	if err != nil {
		return fmt.Errorf("Invalid value '%s' for limit %s: %w", value, key, err)
	}

	total := totals[key]
	if limit < total {
		printer := aggregateLimitConfigValuePrinters[key]
		return fmt.Errorf("'%s' is too low: current total is %s", key, printer(total))
	}

	return nil
}

// Return true if the project has some limits or restrictions set.
func projectHasLimitsOrRestrictions(project api.Project) bool {
	for k, v := range project.Config {
		if strings.HasPrefix(k, "limits.") {
			return true
		}

		if k == "restricted" && shared.IsTrue(v) {
			return true
		}
	}

	return false
}

// Hold information associated with the project, such as profiles and
// instances.
type projectInfo struct {
	Project   api.Project
	Profiles  []api.Profile
	Instances []api.Instance
	Volumes   []db.StorageVolumeArgs
}

// Fetch the given project from the database along with its profiles, instances
// and possibly custom volumes.
//
// If the skipIfNoLimits flag is true, then profiles, instances and volumes
// won't be loaded if the profile has no limits set on it, and nil will be
// returned.
func fetchProject(tx *db.ClusterTx, projectName string, skipIfNoLimits bool) (*projectInfo, error) {
	ctx := context.Background()
	dbProject, err := cluster.GetProject(ctx, tx.Tx(), projectName)
	if err != nil {
		return nil, fmt.Errorf("Fetch project database object: %w", err)
	}

	project, err := dbProject.ToAPI(ctx, tx.Tx())
	if err != nil {
		return nil, err
	}

	if skipIfNoLimits && !projectHasLimitsOrRestrictions(*project) {
		return nil, nil
	}

	profilesFilter := cluster.ProfileFilter{}

	// If the project has the profiles feature enabled, we use its own
	// profiles to expand the instances configs, otherwise we use the
	// profiles from the default project.
	defaultProject := Default
	if projectName == Default || shared.IsTrue(project.Config["features.profiles"]) {
		profilesFilter.Project = &projectName
	} else {
		profilesFilter.Project = &defaultProject
	}

	dbProfiles, err := cluster.GetProfiles(ctx, tx.Tx(), profilesFilter)
	if err != nil {
		return nil, fmt.Errorf("Fetch profiles from database: %w", err)
	}

	profiles := make([]api.Profile, 0, len(dbProfiles))
	for _, profile := range dbProfiles {
		apiProfile, err := profile.ToAPI(ctx, tx.Tx())
		if err != nil {
			return nil, err
		}

		profiles = append(profiles, *apiProfile)
	}

	dbInstances, err := cluster.GetInstances(ctx, tx.Tx(), cluster.InstanceFilter{Project: &projectName})
	if err != nil {
		return nil, fmt.Errorf("Fetch project instances from database: %w", err)
	}

	instances := make([]api.Instance, 0, len(dbInstances))
	for _, instance := range dbInstances {
		apiInstance, err := instance.ToAPI(ctx, tx.Tx())
		if err != nil {
			return nil, fmt.Errorf("Failed to get API data for instance %q in project %q: %w", instance.Name, instance.Project, err)
		}

		instances = append(instances, *apiInstance)
	}

	volumes, err := tx.GetCustomVolumesInProject(projectName)
	if err != nil {
		return nil, fmt.Errorf("Fetch project custom volumes from database: %w", err)
	}

	info := &projectInfo{
		Project:   *project,
		Profiles:  profiles,
		Instances: instances,
		Volumes:   volumes,
	}

	return info, nil
}

// Expand the configuration and devices of the given instances, taking the give
// project profiles into account.
func expandInstancesConfigAndDevices(instances []api.Instance, profiles []api.Profile) ([]api.Instance, error) {
	expandedInstances := make([]api.Instance, len(instances))

	// Index of all profiles by name.
	profilesByName := map[string]api.Profile{}
	for _, profile := range profiles {
		profilesByName[profile.Name] = profile
	}

	for i, instance := range instances {
		apiProfiles := make([]api.Profile, len(instance.Profiles))

		for j, name := range instance.Profiles {
			profile := profilesByName[name]
			apiProfiles[j] = profile
		}

		expandedInstances[i] = instance
		expandedInstances[i].Config = db.ExpandInstanceConfig(instance.Config, apiProfiles)
		expandedInstances[i].Devices = db.ExpandInstanceDevices(deviceconfig.NewDevices(instance.Devices), apiProfiles).CloneNative()
	}

	return expandedInstances, nil
}

// Sum of the effective values for the given limits across all project
// enties (instances and custom volumes).
func getTotalsAcrossProjectEntities(info *projectInfo, keys []string, skipUnset bool) (map[string]int64, error) {
	totals := map[string]int64{}

	for _, key := range keys {
		totals[key] = 0
		if key == "limits.disk" {
			for _, volume := range info.Volumes {
				value, ok := volume.Config["size"]
				if !ok {
					if skipUnset {
						continue
					}

					return nil, fmt.Errorf(
						"Custom volume %s in project %s has no 'size' config set",
						volume.Name, info.Project.Name)
				}

				limit, err := units.ParseByteSizeString(value)
				if err != nil {
					return nil, fmt.Errorf(
						"Parse 'size' for custom volume %s in project %s: %w",
						volume.Name, info.Project.Name, err)
				}

				totals[key] += limit
			}
		}
	}

	for _, instance := range info.Instances {
		limits, err := getInstanceLimits(instance, keys, skipUnset)
		if err != nil {
			return nil, err
		}

		for _, key := range keys {
			totals[key] += limits[key]
		}
	}

	return totals, nil
}

// Return the effective instance-level values for the limits with the given keys.
func getInstanceLimits(instance api.Instance, keys []string, skipUnset bool) (map[string]int64, error) {
	var err error
	limits := map[string]int64{}

	for _, key := range keys {
		var limit int64
		parser := aggregateLimitConfigValueParsers[key]

		if key == "limits.disk" {
			_, device, err := shared.GetRootDiskDevice(instance.Devices)
			if err != nil {
				return nil, fmt.Errorf("Failed getting root disk device for instance %q in project %q: %w", instance.Name, instance.Project, err)
			}

			value, ok := device["size"]
			if !ok || value == "" {
				if skipUnset {
					continue
				}

				return nil, fmt.Errorf(`Instance %q in project %q has no "size" config set on the root device either directly or via a profile`, instance.Name, instance.Project)
			}

			limit, err = parser(value)
			if err != nil {
				if skipUnset {
					continue
				}

				return nil, fmt.Errorf("Failed parsing %q for instance %q in project %q", key, instance.Name, instance.Project)
			}

			// Add size.state accounting for VM root disks.
			if instance.Type == instancetype.VM.String() {
				sizeStateValue, ok := device["size.state"]
				if !ok {
					sizeStateValue = deviceconfig.DefaultVMBlockFilesystemSize
				}

				sizeStateLimit, err := parser(sizeStateValue)
				if err != nil {
					if skipUnset {
						continue
					}

					return nil, fmt.Errorf("Failed parsing %q for instance %q in project %q", "size.state", instance.Name, instance.Project)
				}

				limit += sizeStateLimit
			}
		} else {
			value, ok := instance.Config[key]
			if !ok || value == "" {
				if skipUnset {
					continue
				}

				return nil, fmt.Errorf("Instance %q in project %s has no %q config, either directly or via a profile", instance.Name, instance.Project, key)
			}

			limit, err = parser(value)
			if err != nil {
				if skipUnset {
					continue
				}

				return nil, fmt.Errorf("Failed parsing %q for instance %q in project %q", key, instance.Name, instance.Project)
			}
		}

		limits[key] = limit
	}

	return limits, nil
}

var aggregateLimitConfigValueParsers = map[string]func(string) (int64, error){
	"limits.memory": func(value string) (int64, error) {
		if strings.HasSuffix(value, "%") {
			return -1, fmt.Errorf("Value can't be a percentage")
		}

		return units.ParseByteSizeString(value)
	},
	"limits.processes": func(value string) (int64, error) {
		limit, err := strconv.Atoi(value)
		if err != nil {
			return -1, err
		}

		return int64(limit), nil
	},
	"limits.cpu": func(value string) (int64, error) {
		if strings.Contains(value, ",") || strings.Contains(value, "-") {
			return -1, fmt.Errorf("CPUs can't be pinned if project limits are used")
		}

		limit, err := strconv.Atoi(value)
		if err != nil {
			return -1, err
		}

		return int64(limit), nil
	},
	"limits.disk": func(value string) (int64, error) {
		return units.ParseByteSizeString(value)
	},
}

var aggregateLimitConfigValuePrinters = map[string]func(int64) string{
	"limits.memory": func(limit int64) string {
		return units.GetByteSizeStringIEC(limit, 1)
	},
	"limits.processes": func(limit int64) string {
		return fmt.Sprintf("%d", limit)
	},
	"limits.cpu": func(limit int64) string {
		return fmt.Sprintf("%d", limit)
	},
	"limits.disk": func(limit int64) string {
		return units.GetByteSizeStringIEC(limit, 1)
	},
}

// FilterUsedBy filters a UsedBy list based on project access.
func FilterUsedBy(r *http.Request, entries []string) []string {
	// Shortcut for admins and non-RBAC environments.
	if rbac.UserIsAdmin(r) {
		return entries
	}

	// Filter the entries.
	usedBy := []string{}
	for _, entry := range entries {
		projectName := Default

		// Try to parse the query part of the URL.
		u, err := url.Parse(entry)
		if err != nil {
			// Skip URLs we can't parse.
			continue
		}

		// Check if project= is specified in the URL.
		val := u.Query().Get("project")
		if val != "" {
			projectName = val
		}

		if !rbac.UserHasPermission(r, projectName, "view") {
			continue
		}

		usedBy = append(usedBy, entry)
	}

	return usedBy
}

// Return true if particular restriction in project is violated.
func projectHasRestriction(project *api.Project, restrictionKey string, blockValue string) bool {
	if shared.IsFalseOrEmpty(project.Config["restricted"]) {
		return false
	}

	restrictionValue, ok := project.Config[restrictionKey]
	if !ok {
		restrictionValue = allRestrictions[restrictionKey]
	}

	if restrictionValue == blockValue {
		return true
	}

	return false
}

// CheckClusterTargetRestriction check if user is allowed to use cluster member targeting.
func CheckClusterTargetRestriction(tx *db.ClusterTx, r *http.Request, project *api.Project, targetFlag string) error {
	// Allow server administrators to move instances around even when restricted (node evacuation, ...)
	if rbac.UserIsAdmin(r) {
		return nil
	}

	if projectHasRestriction(project, "restricted.cluster.target", "block") && targetFlag != "" {
		return fmt.Errorf("This project doesn't allow cluster member targeting")
	}

	return nil
}

// AllowBackupCreation returns an error if any project-specific restriction is violated
// when creating a new backup in a project.
func AllowBackupCreation(tx *db.ClusterTx, projectName string) error {
	ctx := context.Background()
	dbProject, err := cluster.GetProject(ctx, tx.Tx(), projectName)
	if err != nil {
		return err
	}

	project, err := dbProject.ToAPI(ctx, tx.Tx())
	if err != nil {
		return err
	}

	if projectHasRestriction(project, "restricted.backups", "block") {
		return fmt.Errorf("Project %s doesn't allow for backup creation", projectName)
	}

	return nil
}

// AllowSnapshotCreation returns an error if any project-specific restriction is violated
// when creating a new snapshot in a project.
func AllowSnapshotCreation(tx *db.ClusterTx, dbProject *cluster.Project) error {
	project, err := dbProject.ToAPI(context.Background(), tx.Tx())
	if err != nil {
		return err
	}

	if projectHasRestriction(project, "restricted.snapshots", "block") {
		return fmt.Errorf("Project %s doesn't allow for snapshot creation", project.Name)
	}

	return nil
}


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package fh.ooe.mc.mobilesportsapp;

public final class Manifest {
    public static final class permission {
        public static final String C2D_MESSAGE="fh.ooe.mc.mobilesportsapp.permission.C2D_MESSAGE";
    }
}


text:
/**
 * This file is part of the CernVM File System.
 *
 * Mac OS X specific system/library calls.
 */

#ifndef CVMFS_PLATFORM_OSX_H_
#define CVMFS_PLATFORM_OSX_H_

#include <alloca.h>
#include <dirent.h>
#include <fcntl.h>
#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \
    __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
#include <os/lock.h>  // NOLINT
#else
#include <libkern/OSAtomic.h>
#endif  //  defined(__MAC_OS_X_VERSION_MIN_REQUIRED) &&
        //  __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
#include <mach-o/dyld.h>
#include <mach/mach.h>  // NOLINT
#include <mach/mach_time.h>
#include <signal.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/ucred.h>
#include <sys/xattr.h>

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <string>
#include <vector>

#include "smalloc.h"

#ifdef CVMFS_NAMESPACE_GUARD
namespace CVMFS_NAMESPACE_GUARD {
#endif

/**
 * UNIX domain sockets:
 * MSG_NOSIGNAL prevents send() from sending SIGPIPE
 * and EPIPE is return instead, where supported.
 * MSG_NOSIGNAL is Linux specific, SO_NOSIGPIPE is the Mac OS X equivalent.
 */
#define MSG_NOSIGNAL SO_NOSIGPIPE

/**
 * HOST_NAME_MAX does on exist on OS X
 */
#define HOST_NAME_MAX _POSIX_HOST_NAME_MAX

#define platform_sighandler_t sig_t

inline std::vector<std::string> platform_mountlist() {
  std::vector<std::string> result;
  struct statfs *mntbufp;
  int num_elems = getmntinfo(&mntbufp, MNT_NOWAIT);  // modifies static memory
  for (int i = 0; i < num_elems; ++i) {
    result.push_back(mntbufp[i].f_mntonname);
  }
  return result;
}

inline bool platform_umount(const char *mountpoint, const bool lazy) {
  const int flags = lazy ? MNT_FORCE : 0;
  int retval = unmount(mountpoint, flags);
  return retval == 0;
}

/**
 * Spinlocks on OS X are not in pthread but in OS X specific APIs.
 */
#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && \
    __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200
typedef os_unfair_lock platform_spinlock;

inline int platform_spinlock_init(platform_spinlock *lock, int /*pshared*/) {
  *lock = OS_UNFAIR_LOCK_INIT;
  return 0;
}

inline int platform_spinlock_destroy(platform_spinlock * /*lock*/) { return 0; }

inline int platform_spinlock_trylock(platform_spinlock *lock) {
  return os_unfair_lock_trylock(lock) ? 0 : -1;
}

inline void platform_spinlock_unlock(platform_spinlock *lock) {
  os_unfair_lock_unlock(lock);
}

#else
typedef OSSpinLock platform_spinlock;

inline int platform_spinlock_init(platform_spinlock *lock, int /*pshared*/) {
  *lock = 0;
  return 0;
}

inline int platform_spinlock_destroy(platform_spinlock * /*lock*/) { return 0; }

inline int platform_spinlock_trylock(platform_spinlock *lock) {
  return OSSpinLockTry(lock) ? 0 : -1;
}

inline void platform_spinlock_unlock(platform_spinlock *lock) {
  OSSpinLockUnlock(lock);
}

#endif

/**
 * pthread_self() is not necessarily an unsigned long.
 */
inline thread_port_t platform_gettid() { return mach_thread_self(); }

inline int platform_sigwait(const int signum) {
  sigset_t sigset;
  int retval = sigemptyset(&sigset);
  assert(retval == 0);
  retval = sigaddset(&sigset, signum);
  assert(retval == 0);
  int result;
  retval = sigwait(&sigset, &result);
  assert(retval == 0);
  return result;
}

/**
 * See platform_linux.h
 */
inline bool platform_allow_ptrace(const pid_t pid) {
  // No-op on Mac OS X
  return true;
}

/**
 * File system functions, Mac OS X has 64bit functions by default.
 */
typedef struct dirent platform_dirent64;

inline platform_dirent64 *platform_readdir(DIR *dirp) { return readdir(dirp); }

typedef struct stat platform_stat64;

inline int platform_stat(const char *path, platform_stat64 *buf) {
  return stat(path, buf);
}

inline int platform_lstat(const char *path, platform_stat64 *buf) {
  return lstat(path, buf);
}

inline int platform_fstat(int filedes, platform_stat64 *buf) {
  return fstat(filedes, buf);
}

inline bool platform_getxattr(const std::string &path, const std::string &name,
                              std::string *value) {
  int size = 0;
  void *buffer = NULL;
  int retval;
  retval = getxattr(path.c_str(), name.c_str(), buffer, size, 0, 0);
  if (retval >= 1) {
    size = retval;
    buffer = smalloc(size);
    retval = getxattr(path.c_str(), name.c_str(), buffer, size, 0, 0);
  }
  if ((retval < 0) || (retval > size)) {
    free(buffer);
    return false;
  }
  if (retval > 0) {
    value->assign(static_cast<const char *>(buffer), size);
    free(buffer);
  } else {
    value->assign("");
  }
  return true;
}

inline bool platform_setxattr(const std::string &path, const std::string &name,
                              const std::string &value) {
  int retval =
      setxattr(path.c_str(), name.c_str(), value.c_str(), value.size(), 0, 0);
  return retval == 0;
}

inline ssize_t platform_lgetxattr(const char *path, const char *name,
                                  void *value, size_t size) {
  return getxattr(path, name, value, size, 0 /* position */, XATTR_NOFOLLOW);
}

inline ssize_t platform_llistxattr(const char *path, char *list, size_t size) {
  return listxattr(path, list, size, XATTR_NOFOLLOW);
}

inline void platform_disable_kcache(int filedes) {
  fcntl(filedes, F_RDAHEAD, 0);
  fcntl(filedes, F_NOCACHE, 1);
}

inline void platform_invalidate_kcache(const int fd, const off_t offset,
                                       const size_t length) {
  // NOOP
  // TODO(rmeusel): implement
}

inline int platform_readahead(int filedes) {
  // TODO(jblomer): is there a readahead equivalent?
  return 0;
}

inline bool read_line(FILE *f, std::string *line) {
  char *buffer_line = NULL;
  size_t buffer_size = 0;
  const int res = getline(&buffer_line, &buffer_size, f);
  if (res < 0) {
    free(buffer_line);
    return false;
  }

  line->clear();
  line->assign(buffer_line);
  free(buffer_line);
  return true;
}

inline uint64_t platform_monotonic_time() {
  uint64_t val_abs = mach_absolute_time();
  // Doing the conversion every time is slow but thread-safe
  mach_timebase_info_data_t info;
  mach_timebase_info(&info);
  uint64_t val_ns = val_abs * (info.numer / info.denom);
  return val_ns * 1e-9;
}

/**
 * strdupa does not exist on OSX
 */
#define strdupa(s)                    \
  strcpy(/* NOLINT(runtime/printf) */ \
         reinterpret_cast<char *>(alloca(strlen((s)) + 1)), (s))

inline std::string platform_libname(const std::string &base_name) {
  return "lib" + base_name + ".dylib";
}

inline const char *platform_getexepath() {
  static const char *path = _dyld_get_image_name(0);
  return path;
}

/**
 * sysconf() is broken on OSX
 */
inline uint64_t platform_memsize() {
  int mib[] = {CTL_HW, HW_MEMSIZE};
  int64_t ramsize;
  int rc;
  size_t len;

  len = sizeof(ramsize);
  rc = sysctl(mib, 2, &ramsize, &len, NULL, 0);
  assert(rc == 0);
  return ramsize;
}

#ifdef CVMFS_NAMESPACE_GUARD
}  // namespace CVMFS_NAMESPACE_GUARD
#endif

#endif  // CVMFS_PLATFORM_OSX_H_


text:
import sys
import pickle
import gzip
import json
import collections

# those file loader/dumper are python2/3 compatibles.

def pickle_dump(data, file_path, gz=False):
    open_fct = open
    if gz:
        open_fct = gzip.open
        file_path += ".gz"

    with open_fct(file_path, "wb") as f:
        pickle.dump(data, f)

def pickle_loader(file_path, gz=False):
    open_fct = open
    if gz:
        open_fct = gzip.open

    with open_fct(file_path, "rb") as f:
        if sys.version_info > (3, 0):  # Workaround to load pickle data python2 -> python3
            u = pickle._Unpickler(f)
            u.encoding = 'latin1'
            return u.load()
        else:
            return pickle.load(f)

def flatten(x):
    if isinstance(x, collections.Iterable):
        return [a for i in x for a in flatten(i)]
    else:
        return [x]

def dump_json(file_path, json_string):
    with open(file_path, "wb") as f:
        results_json = json.dumps(json_string)
        f.write(results_json.encode('utf8', 'replace'))


text:
(function () {
    'use strict';

    angular
        .module('doleticApp')
        .controller('hrUserDetailsTabController', hrUserDetailsTabController);

    hrUserDetailsTabController.$inject = ['$scope', '$state', 'UserService', 'KernelService', 'ConfirmModalService', 'ModalService', 'MessageBoxService'];

    function hrUserDetailsTabController($scope, $state, UserService, KernelService, ConfirmModalService, ModalService, MessageBoxService) {
        $scope.userService = UserService;
        $scope.kernelService = KernelService;

        $scope.loadUser = function (cache) {
            UserService.getUserDetails($state.params.id, cache).success(function (data) {

            }).error(function (data) {
                MessageBoxService.showError(
                    "Echec du chargement",
                    "L'utilisateur n'a pas pu être chargé. Il est possible qu'un autre utilisateur vienne de le supprimer."
                );
            });
        };

        $scope.showUserForm = function () {
            ModalService.showModal({
                templateUrl: "app/components/hr/membersTab/user-form/user-form.template.html",
                controller: "hrUserFormController",
                inputs: {
                    editMode: true,
                    user: UserService.selectedUser
                }
            }).then(function (modal) {
                modal.element.modal('show');
            }).catch(function (error) {
                // error contains a detailed error message.
                console.log(error);
            });
        };

        $scope.disableUser = function () {
            var name = UserService.selectedUser.fullName;
            var service = UserService.selectedUser.mainPosition.old ? 'disableOldUser' : 'disableCurrentUser';
            ConfirmModalService.showConfirmModal(
                "Confirmer la désactivation",
                "Voulez-vous vraiment désactiver l'utilisateur " + name + " ?",
                "delete user",
                function () {
                    UserService[service](angular.copy(UserService.selectedUser)).success(function (data) {
                        MessageBoxService.showSuccess(
                            "Désactivation réussie !",
                            "L'utilisateur " + name + " a été désactivé."
                        );
                    }).error(function (data) {
                        MessageBoxService.showError(
                            "Echec de la désactivation...",
                            "L'utilisateur " + name + " n'a pas pu être désactivé."
                        );
                    });
                }
            )
        };

        $scope.enableUser = function () {
            var name = UserService.selectedUser.fullName;
            ConfirmModalService.showConfirmModal(
                "Confirmer la réactivation",
                "Voulez-vous vraiment réactiver l'utilisateur " + name + " ?",
                "reply",
                function () {
                    UserService.enableUser(angular.copy(UserService.selectedUser)).success(function (data) {
                        MessageBoxService.showSuccess(
                            "Réactivé réussie !",
                            "L'utilisateur " + name + " a été réactivé."
                        );
                    }).error(function (data) {
                        MessageBoxService.showError(
                            "Echec de la réactivation...",
                            "L'utilisateur " + name + " n'a pas pu être réactivé."
                        );
                    });
                }
            )
        };
    }
})();


text:
import React, {Component, PropTypes} from 'react';

class Message extends Component {
    constructor(props) {
        super(props);
    }
    checkMessageType() {
        const {userName, message} = this.props;
        if (message.type !== 'system') {
            return (

{message.creator.name}

{message.message}

            );
        }
        return (

{message.message}

        );
    }
    render() {
        return this.checkMessageType();
    }
}
export default Message;


text:
package io.dongyue.at15.tree.indexer.mapreduce.pre;

import io.dongyue.at15.tree.indexer.mapreduce.Config;

/**
 * Created by at15 on 16-1-1.
 * <p/>
 * pre sort map reduce path configs
 *
 * @TODO Add separator config
 */
public class PreSortConfig implements Config {
    private String input;
    private String output;
    private Integer keyColumn = 0;

    public String[] toArray() {
        String[] args = {input, output, String.valueOf(keyColumn)};
        return args;
    }

    public void fromArray(String[] args) {
        setInput(args[0]);
        setOutput(args[1]);
        setKeyColumn(args[2]);
    }

    public void fromBasePath(String base){
        setInput(base + "/src");
        setOutput(base + "/pre-sort/out");
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public String getOutput() {
        return output;
    }

    public void setOutput(String output) {
        this.output = output;
    }

    public Integer getKeyColumn() {
        return keyColumn;
    }

    public String getKeyColumnAsString() {
        return String.valueOf(keyColumn);
    }

    public void setKeyColumn(String keyColumn) {
        setKeyColumn(Integer.valueOf(keyColumn));
    }

    public void setKeyColumn(Integer keyColumn) {
        this.keyColumn = keyColumn;
    }
}


text:
Kazan creates rails project and setups predefined gems and tools.

![img](http://res.cloudinary.com/dtoqqxqjv/image/upload/c_scale,w_300/v1489144588/github/imageedit_4_6229938689_bt8x5c.png)

## Installation

Install gem:

    $ gem install kazan

## Usage

By default this rails application generator uses PostgreSQL as db and RSpec as test framework. Also it installs and setups a lot usefull gems, and you don't need waste time then you stat new project.

Just run:

    $ kazan projectname

This generator maps all flags to rails native generator, for example you can create api application:

    $ kazan projectname --api

See all gems that will be installed to project in [Gemfile](https://github.com/khusnetdinov/kazan/blob/master/templates/Gemfile.erb) for web application or for api [Gemfile.api](https://github.com/khusnetdinov/kazan/blob/master/templates/Gemfile.api.erb).

## Gems

It includes applications gems:

  - [Dotenv](https://github.com/bkeepers/dotenv) Shim to load environment variables from .env into ENV in development.
  - [I18n](https://github.com/svenfuchs/rails-i18n) is central point to collect locale data for use in Ruby on Rails.
  - [MetaTags](https://github.com/kpumuk/meta-tags) a gem to make your Rails application SEO-friendly. Gem is not generated if --api is selected.
  - [PostgreSQL](https://www.postgresql.org/) database with [PG](https://rubygems.org/gems/pg/versions/0.18.4) adapter is used by defaul.
  - [Puma](http://puma.io/) is a simple, fast, threaded, and highly concurrent HTTP 1.1 server for Ruby/Rack applications.
  - [Rack Timeout](https://github.com/heroku/rack-timeout) aborts requests that are taking too long; an exception is raised.
  - [Rails 5.2.0](http://rubyonrails.org/)
  - [Rails Config](https://github.com/railsconfig/config) helps you easily manage environment specific settings in an easy and usable manner.
  - [Rollbar](https://rollbar.com/) error monitoring fits right into your continuous delivery and deployment workflows to provide confidence in every code release.
  - [Simple From](https://github.com/plataformatec/simple_form) [API EXCLUDED] aims to be as flexible as possible while helping you with powerful components to create your forms.

It includes assets gems [API EXCLUDED]:

  - [Normalize Css](https://necolas.github.io/normalize.css/) makes browsers render all elements more consistently and in line with modern standards. It precisely targets only the styles that need normalizing.
  - [Sass](http://sass-lang.com/) is the most mature, stable, and powerful professional grade CSS extension language in the world.

It includes development gems:

  - [Annotate](https://github.com/ctran/annotate_models) adds a comment summarizing the current schema.
  - [Awesome Print](https://github.com/awesome-print/awesome_print) prints pretty Ruby objects in full color exposing their internal structure with proper indentation.
  - [Better Errors](https://github.com/charliesome/better_errors) [API EXCLUDED] replaces the standard Rails error page with a much better and more useful error page.
  - [Brakeman](https://github.com/presidentbeef/brakeman) is an open source static analysis tool which checks Ruby on Rails applications for security vulnerabilities.
  - [ByeBug](https://github.com/deivid-rodriguez/byebug) is a simple to use, feature rich debugger for Ruby 2.
  - [Bundler Audit](https://github.com/rubysec/bundler-audit) is patch-level verification for bundler.
  - [Bullet](https://github.com/flyerhzm/bullet) is designed to help you increase your application's performance by reducing the number of queries it makes.
  - [Foreman](https://github.com/ddollar/foreman) procfile-based applications.
  - [Letter Opener](https://github.com/ryanb/letter_opener) previews email in the default browser instead of sending it.
  - [Listen](https://github.com/guard/listen) listens to file modifications and notifies you about the changes.
  - [Pry](https://github.com/rweng/pry-rails) for interactively exploring objects.
  - [Rack Mini Profiler](https://github.com/MiniProfiler/rack-mini-profiler) [API EXCLUDED] displays speed badge for every html page.
  - [Reek](https://github.com/troessner/reek) - code smell detector for Ruby.
  - [RuboCop](https://github.com/bbatsov/rubocop) is a Ruby static code analyzer. Out of the box it will enforce many of the guidelines outlined in the community [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide).
  - [scss-lint](https://github.com/brigade/scss-lint) is a tool to help keep your [SCSS](http://sass-lang.com/) files clean and readable by running it against a collection of configurable linter rules.
  - [Spring](https://github.com/rails/spring) speeds up development by keeping your application running in the background.
  - [Web Console](https://github.com/rails/web-console) [API EXCLUDED] is a debugging tool for your Ruby on Rails applications.

It includes tests gems:
 - [Capybara](https://github.com/jnicklas/capybara) [API EXCLUDED] helps you test web applications by simulating how a real user would interact with your app.
 - [Database Cleaner](https://github.com/DatabaseCleaner/database_cleaner) is a set of strategies for cleaning your database in Ruby.
 - [Factory Bot](https://github.com/thoughtbot/factory_bot) is a fixtures replacement with a straightforward definition syntax.
 - [Faker](https://github.com/stympy/faker) a port of Perl's Data::Faker library that generates fake data.
 - [Formulaic](https://github.com/thoughtbot/formulaic) [API EXCLUDED] the tedium of formulaic form filling with Capybara.
 - [I18n-Tasks](https://github.com/glebm/i18n-tasks) [API EXCLUDED] Gem that helps manage locales and test if are there problems.
 - [I18n-Yaml-Sorter](https://github.com/redealumni/i18n_yaml_sorter) [API EXCLUDED] Sort all locales by keys.
 - [Launchy](https://github.com/copiousfreetime/launchy) [API EXCLUDED] helper class for launching cross-platform applications in a fire and forget manner.
 - [Rspec](https://github.com/rspec/rspec-rails) is a testing framework for Rails.
 - [Simplecov](https://github.com/colszowka/simplecov) is a code coverage analysis tool for Ruby.
 - [Shoulda Matchers](https://github.com/thoughtbot/shoulda-matchers) provides RSpec- and Minitest-compatible one-liners that test common Rails functionality.
 - [Timecop](https://github.com/travisjeffery/timecop) providing "time travel" and "time freezing" capabilities, making it dead simple to test time-dependent code.
 - [Web Mock](https://github.com/bblimke/webmock) for stubbing and setting expectations on HTTP requests in Ruby.

## Bonuses

  - t() and l() in specs without prefixing with I18n.
  - Low database connection pool limit.
  - Rails' flashes set up and in application layout.
  - [Rack::Deflater](https://robots.thoughtbot.com/content-compression-with-rack-deflater) to compress responses with Gzip.
  - [Safe binstubs](https://github.com/thoughtbot/suspenders/pull/282).
  - Ready Seo controller with methods for generating files - robots.txt,
    sitemap.xml.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
<?php
/**
 * Created by PhpStorm.
 * User: Abu Andabekov
 * Date: 15/04/2015
 * Time: 12:25
 */

namespace Pidzhak\Model\admin;

use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Expression;
use Zend\Db\Sql\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;

class UserTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function fetchPage($rowCount, $offset, $orderby, $searchPhrase){

        $sql = new Sql($this->tableGateway->adapter);
        $select = $sql->select();
        $select->from($this->tableGateway->table)
            ->join('rolestable', 'userstable.access_type_id = rolestable.id');

        $select->columns(array('*', new Expression('userstable.id as user_id')));

        if ($rowCount < 0)
            $select->offset(0);
        else
            $select->limit($rowCount)->offset($offset);
        $select->order($orderby);

        /*if($searchPhrase)
            $select->where->like('firstname', '%'.strtolower($searchPhrase).'%')->OR->like('lastname', '%'.strtolower($searchPhrase).'%');*/

        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();

        $resultSet = new ResultSet();
        $resultSet->initialize($result);

        return $resultSet;
    }

    public function getCount(){
        $resultSet = $this->tableGateway->select();
        return $resultSet->count();
    }

    public function getUser($id) {
        $id  = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function saveUser(User $user)
    {
        $data = array(
            'username' => $user->username,
            'password' => md5($user->password),
            'name' => $user->name,
            'surname' => $user->surname,
            'access_type_id' => $user->access_type_id,
            'email' => $user->email,
            'phone' => $user->phone,
        );

        $id = (int) $user->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getUser($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('User_id does not exist');
            }
        }
    }

    public function deleteUser($id)
    {
        $this->tableGateway->delete(array('id' => (int) $id));
    }
}


text:
'use strict';
exports.__esModule = true;

const extname = require('path').extname;

const log = require('debug')('eslint-plugin-import:utils:ignore');

// one-shot memoized
let cachedSet; let lastSettings;
function validExtensions(context) {
  if (cachedSet && context.settings === lastSettings) {
    return cachedSet;
  }

  lastSettings = context.settings;
  cachedSet = makeValidExtensionSet(context.settings);
  return cachedSet;
}

function makeValidExtensionSet(settings) {
  // start with explicit JS-parsed extensions
  const exts = new Set(settings['import/extensions'] || [ '.js' ]);

  // all alternate parser extensions are also valid
  if ('import/parsers' in settings) {
    for (const parser in settings['import/parsers']) {
      const parserSettings = settings['import/parsers'][parser];
      if (!Array.isArray(parserSettings)) {
        throw new TypeError('"settings" for ' + parser + ' must be an array');
      }
      parserSettings.forEach(ext => exts.add(ext));
    }
  }

  return exts;
}
exports.getFileExtensions = makeValidExtensionSet;

exports.default = function ignore(path, context) {
  // check extension whitelist first (cheap)
  if (!hasValidExtension(path, context)) return true;

  if (!('import/ignore' in context.settings)) return false;
  const ignoreStrings = context.settings['import/ignore'];

  for (let i = 0; i < ignoreStrings.length; i++) {
    const regex = new RegExp(ignoreStrings[i]);
    if (regex.test(path)) {
      log(`ignoring ${path}, matched pattern /${ignoreStrings[i]}/`);
      return true;
    }
  }

  return false;
};

function hasValidExtension(path, context) {
  return validExtensions(context).has(extname(path));
}
exports.hasValidExtension = hasValidExtension;


text:
/**
 * sse
 *
 * 專門處理 Server Sent-Event 的函式。
 */

jA.sse = function(obj)
{
    var sse = new EventSource(obj.url)

    /** Message */
    if(typeof obj.message == 'object')
        for(var i in obj.message)
            sse.addEventListener(i, obj.message[i], false)
    else if(typeof obj.message !== 'undefined')
        sse.onmessage = obj.message

    /** Error */
    if(typeof obj.error !== 'undefined')
        sse.onerror = obj.error

    /** Open */
    if(typeof obj.open !== 'undefined')
        sse.addEventListener('open', obj.open, false)
}


text:
package org.sparkcommerce.common.util;

import org.hibernate.Session;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.dialect.PostgreSQL81Dialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * @author Joel Dasari
 */
@Repository("blDialectHelper")
public class DialectHelper {

    @PersistenceContext(unitName="blPU")
    protected EntityManager em;

    protected Dialect cachedDialect = null;

    public synchronized Dialect getHibernateDialect() {
        if (cachedDialect == null) {
            SessionFactoryImplementor factory = (SessionFactoryImplementor) em.unwrap(Session.class).getSessionFactory();
            cachedDialect = factory.getDialect();
        }
        return cachedDialect;
    }

    public boolean isOracle() {
        //Since should handle other Oracle dialects as well, since they derive from Oracle8iDialect
        return getHibernateDialect() instanceof Oracle8iDialect;
    }

    public boolean isPostgreSql() {
        //Since should handle other Postgres dialects as well, since they derive from PostgreSQL81Dialect
        return getHibernateDialect() instanceof PostgreSQL81Dialect;
    }

    public boolean isSqlServer() {
        return getHibernateDialect() instanceof SQLServerDialect;
    }

    public boolean isMySql() {
        return getHibernateDialect() instanceof MySQLDialect;
    }

    public void clear() {
        cachedDialect = null;
    }
}


text:
#if DEV12_OR_LATER

using System.Collections.Generic;
using System.Linq;
using Microsoft.PythonTools.Django.Project;
using Microsoft.PythonTools.Django.TemplateParsing;
using Microsoft.PythonTools.Intellisense;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;

#if DEV14_OR_LATER
using Microsoft.Html.Editor.Document;
using Microsoft.Web.Core.Text;
#else
using Microsoft.Html.Editor;
using Microsoft.Web.Core;
#endif

namespace Microsoft.PythonTools.Django.Intellisense {
    internal class DjangoCompletionSource : DjangoCompletionSourceBase {
        public DjangoCompletionSource(IGlyphService glyphService, DjangoAnalyzer analyzer, ITextBuffer textBuffer)
            : base(glyphService, analyzer, textBuffer) {
        }

        public override void AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets) {
            var doc = HtmlEditorDocument.FromTextBuffer(_buffer);
            if (doc == null) {
                return;
            }
            doc.HtmlEditorTree.EnsureTreeReady();

            var primarySnapshot = doc.PrimaryView.TextSnapshot;
            var nullableTriggerPoint = session.GetTriggerPoint(primarySnapshot);
            if (!nullableTriggerPoint.HasValue) {
                return;
            }
            var triggerPoint = nullableTriggerPoint.Value;

            var artifacts = doc.HtmlEditorTree.ArtifactCollection;
            var index = artifacts.GetItemContaining(triggerPoint.Position);
            if (index < 0) {
                return;
            }

            var artifact = artifacts[index] as TemplateArtifact;
            if (artifact == null) {
                return;
            }

            var artifactText = doc.HtmlEditorTree.ParseTree.Text.GetText(artifact.InnerRange);
            artifact.Parse(artifactText);

            ITrackingSpan applicableSpan;
            var completionSet = GetCompletionSet(session.GetOptions(_analyzer._serviceProvider), _analyzer, artifact.TokenKind, artifactText, artifact.InnerRange.Start, triggerPoint, out applicableSpan);
            completionSets.Add(completionSet);
        }

        protected override IEnumerable<DjangoBlock> GetBlocks(IEnumerable<CompletionInfo> results, SnapshotPoint triggerPoint) {
            var doc = HtmlEditorDocument.FromTextBuffer(_buffer);
            if (doc == null) {
                yield break;
            }

            var artifacts = doc.HtmlEditorTree.ArtifactCollection.ItemsInRange(new TextRange(0, triggerPoint.Position));
            foreach (var artifact in artifacts.OfType<TemplateBlockArtifact>().Reverse()) {
                var artifactText = doc.HtmlEditorTree.ParseTree.Text.GetText(artifact.InnerRange);
                artifact.Parse(artifactText);
                if (artifact.Block != null) {
                    yield return artifact.Block;
                }
            }
        }
    }
}

#endif


text:
"""
Code originally from: http://www.aminus.org/blogs/index.php/2009/01/09/assertnodiff
"""

import difflib
from pprint import pformat

class DiffTestCaseMixin(object):

    def get_diff_msg(self, first, second,
                     fromfile='First', tofile='Second'):
        """Return a unified diff between first and second."""
        # Force inputs to iterables for diffing.
        # use pformat instead of str or repr to output dicts and such
        # in a stable order for comparison.
        if isinstance(first, (tuple, list)):
            first = [pformat(d) for d in first]
        elif isinstance(first, dict):
            first = ["%s:%s" % (pformat(key), pformat(val)) for key,val in first.iteritems()]
        else:
            first = [pformat(first)]

        if isinstance(second, (tuple, list)):
            second = [pformat(d) for d in second]
        elif isinstance(second, dict):
            second = ["%s:%s" % (pformat(key), pformat(val)) for key,val in second.iteritems()]
        else:
            second = [pformat(second)]

        diff = difflib.unified_diff(
            first, second, fromfile=fromfile, tofile=tofile)
        # Add line endings.
        return '\n' + ''.join([d + '\n' for d in diff])

    def failIfDiff(self, first, second, fromfile='First', tofile='Second'):
        """If not first == second, fail with a unified diff."""
        if not first == second:
            msg = self.get_diff_msg(first, second, fromfile, tofile)
            raise self.failureException, msg


text:
/* Set Box Sizing to border-box on every elements*/

*,
*::after,
*::before {
  box-sizing: border-box;
}


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
    <dimen name="size30">30dp</dimen>
    <dimen name="textViewSize">12sp</dimen>
</resources>


text:
namespace bp = boost::python;

struct Scale2DCommand_wrapper : osgManipulator::Scale2DCommand, bp::wrapper< osgManipulator::Scale2DCommand > {

    Scale2DCommand_wrapper( )
    : osgManipulator::Scale2DCommand( )
      , bp::wrapper< osgManipulator::Scale2DCommand >(){
        // null constructor

    }

    virtual void accept( ::osgManipulator::Constraint const & constraint ) {
        namespace bpl = boost::python;
        if( bpl::override func_accept = this->get_override( "accept" ) ){
            bpl::object py_result = bpl::call<bpl::object>( func_accept.ptr(), constraint );
        }
        else{
            osgManipulator::Scale2DCommand::accept( boost::ref(constraint) );
        }
    }

    static void default_accept_289ad61f697b095e2efb0253d5ca6ee7( ::osgManipulator::Scale2DCommand & inst, ::osgManipulator::Constraint & constraint ){
        if( dynamic_cast< Scale2DCommand_wrapper * >( boost::addressof( inst ) ) ){
            inst.::osgManipulator::Scale2DCommand::accept(constraint);
        }
        else{
            inst.accept(constraint);
        }
    }

    virtual void accept( ::osgManipulator::DraggerCallback & callback ) {
        if( bp::override func_accept = this->get_override( "accept" ) )
            func_accept( boost::ref(callback) );
        else{
            this->osgManipulator::Scale2DCommand::accept( boost::ref(callback) );
        }
    }

    void default_accept( ::osgManipulator::DraggerCallback & callback ) {
        osgManipulator::Scale2DCommand::accept( boost::ref(callback) );
    }

    virtual ::osgManipulator::MotionCommand * createCommandInverse(  ) {
        if( bp::override func_createCommandInverse = this->get_override( "createCommandInverse" ) )
            return func_createCommandInverse(  );
        else{
            return this->osgManipulator::Scale2DCommand::createCommandInverse(  );
        }
    }

    ::osgManipulator::MotionCommand * default_createCommandInverse(  ) {
        return osgManipulator::Scale2DCommand::createCommandInverse( );
    }

    virtual ::osg::Matrix getMotionMatrix(  ) const  {
        if( bp::override func_getMotionMatrix = this->get_override( "getMotionMatrix" ) )
            return func_getMotionMatrix(  );
        else{
            return this->osgManipulator::Scale2DCommand::getMotionMatrix(  );
        }
    }

    ::osg::Matrix default_getMotionMatrix(  ) const  {
        return osgManipulator::Scale2DCommand::getMotionMatrix( );
    }

    virtual void setThreadSafeRefUnref( bool threadSafe ) {
        if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
            func_setThreadSafeRefUnref( threadSafe );
        else{
            this->osg::Referenced::setThreadSafeRefUnref( threadSafe );
        }
    }

    void default_setThreadSafeRefUnref( bool threadSafe ) {
        osg::Referenced::setThreadSafeRefUnref( threadSafe );
    }

};

void register_Scale2DCommand_class(){

    bp::class_< Scale2DCommand_wrapper, bp::bases< osgManipulator::MotionCommand >, osg::ref_ptr< Scale2DCommand_wrapper >, boost::noncopyable >( "Scale2DCommand", "\n Command for 2D scaling.\n", bp::no_init )
        .def( bp::init< >("\n Command for 2D scaling.\n") )
        .def(
            "accept"
            , (void (*)( ::osgManipulator::Scale2DCommand &,::osgManipulator::Constraint & ))( &Scale2DCommand_wrapper::default_accept_289ad61f697b095e2efb0253d5ca6ee7 )
            , ( bp::arg("inst"), bp::arg("constraint") ) )
        .def(
            "accept"
            , (void ( ::osgManipulator::Scale2DCommand::* )( ::osgManipulator::DraggerCallback & ))(&::osgManipulator::Scale2DCommand::accept)
            , (void ( Scale2DCommand_wrapper::* )( ::osgManipulator::DraggerCallback & ))(&Scale2DCommand_wrapper::default_accept)
            , ( bp::arg("callback") ) )
        .def(
            "createCommandInverse"
            , (::osgManipulator::MotionCommand * ( ::osgManipulator::Scale2DCommand::* )(  ))(&::osgManipulator::Scale2DCommand::createCommandInverse)
            , (::osgManipulator::MotionCommand * ( Scale2DCommand_wrapper::* )(  ))(&Scale2DCommand_wrapper::default_createCommandInverse)
            , bp::return_internal_reference< >() )
        .def(
            "getMinScale"
            , (::osg::Vec2d const & ( ::osgManipulator::Scale2DCommand::* )(  )const)( &::osgManipulator::Scale2DCommand::getMinScale )
            , bp::return_internal_reference< >() )
        .def(
            "getMotionMatrix"
            , (::osg::Matrix ( ::osgManipulator::Scale2DCommand::* )(  )const)(&::osgManipulator::Scale2DCommand::getMotionMatrix)
            , (::osg::Matrix ( Scale2DCommand_wrapper::* )(  )const)(&Scale2DCommand_wrapper::default_getMotionMatrix) )
        .def(
            "getReferencePoint"
            , (::osg::Vec2d const & ( ::osgManipulator::Scale2DCommand::* )(  )const)( &::osgManipulator::Scale2DCommand::getReferencePoint )
            , bp::return_internal_reference< >() )
        .def(
            "getScale"
            , (::osg::Vec2d const & ( ::osgManipulator::Scale2DCommand::* )(  )const)( &::osgManipulator::Scale2DCommand::getScale )
            , bp::return_internal_reference< >() )
        .def(
            "getScaleCenter"
            , (::osg::Vec2d const & ( ::osgManipulator::Scale2DCommand::* )(  )const)( &::osgManipulator::Scale2DCommand::getScaleCenter )
            , bp::return_internal_reference< >() )
        .def(
            "setMinScale"
            , (void ( ::osgManipulator::Scale2DCommand::* )( ::osg::Vec2d const & ))( &::osgManipulator::Scale2DCommand::setMinScale )
            , ( bp::arg("min") ) )
        .def(
            "setReferencePoint"
            , (void ( ::osgManipulator::Scale2DCommand::* )( ::osg::Vec2d const & ))( &::osgManipulator::Scale2DCommand::setReferencePoint )
            , ( bp::arg("rp") )
            , " ReferencePoint is used only for snapping." )
        .def(
            "setScale"
            , (void ( ::osgManipulator::Scale2DCommand::* )( ::osg::Vec2d const & ))( &::osgManipulator::Scale2DCommand::setScale )
            , ( bp::arg("s") ) )
        .def(
            "setScaleCenter"
            , (void ( ::osgManipulator::Scale2DCommand::* )( ::osg::Vec2d const & ))( &::osgManipulator::Scale2DCommand::setScaleCenter )
            , ( bp::arg("center") ) );

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using TreeEdit.Spg.Builder;
using TreeElement;
using TreeElement.Spg.Node;
using TreeElement.Spg.Walker;

namespace TreeEdit.Spg.Script
{
    public class EditScriptGenerator<T>
    {
        /// <summary>
        /// Create an edit script
        /// </summary>
        /// <param name="t1">Source tree</param>
        /// <param name="t2">Target tree</param>
        /// <param name="M">Mapping between source and target tree nodes</param>
        public List<EditOperation<T>> EditScript(TreeNode<T> t1, TreeNode<T> t2, Dictionary<TreeNode<T>, TreeNode<T>> M)
        {
            var editScript = new List<EditOperation<T>>();
            var bfs = BFSWalker<T>.BreadFirstSearch(t2);

            foreach (var x in bfs)
            {
                //Combines the update, insert, align, and move phases
                var y = x.Parent;
                var z = M.ToList().Find(o => o.Value.Equals(y)).Key;
                var w = M.ToList().Find(o => o.Value.Equals(x)).Key;

                if (w == null)
                {
                    int k = FindPos(x, M);
                    var xnode = new TreeNode<T>(x.Value, x.Label);
                    var insert = new Insert<T>(xnode, z, k);
                    z.AddChild(xnode, k - 1);
                    M.Add(xnode, x);

                    editScript.Add(insert);
                }
                else //x has a partner in M
                {
                    var v = w.Parent;
                    if (!w.Children.Any() && !x.Children.Any() && !w.ToString().Equals(x.ToString()))
                    {
                        var update = new Update<T>(w, x, z, y);
                        int index = v.Children.TakeWhile(item => !item.Equals(w)).Count();
                        v.RemoveNode(index);
                        var xnode = new TreeNode<T>(x.Value, x.Label);
                        v.AddChild(xnode, index);
                        M.Add(xnode, x);
                        M.Remove(w);
                        w = xnode;
                        editScript.Add(update);
                    }

                    if (z != null && M.ToList().Find(o => o.Value.Equals(y) && o.Key.Equals(v)).Key == null)
                    {
                        int k = FindPos(x, M);
                        var znode = ConverterHelper.MakeACopy(z);
                        var wnode = ConverterHelper.MakeACopy(w);
                        var move = new Move<T>(wnode, znode, k);
                        move.PreviousParent = w.Parent;
                        z.AddChild(w, k - 1);
                        int index = v.Children.TakeWhile(item => !item.Equals(w)).Count();
                        v.RemoveNode(index);
                        editScript.Add(move);
                    }
                }
                //AlignChildren(x, w);
            }

            var traversal = new TreeTraversal<T>();
            var nodes = traversal.PostOrderTraversal(t1); //the delete phase

            for (int i = 0;  i < nodes.Count; i++)
            {
                var w = nodes[i];
                if (!M.ContainsKey(w))
                {
                    var delete = new Delete<T>(w);
                    var v = delete.Parent;
                    int index = v.Children.TakeWhile(item => !item.Equals(w)).Count();
                    delete.K = index;
                    v.RemoveNode(index);
                    editScript.Add(delete);
                }
            }

            foreach (var s in editScript)
            {
                if (s is Move<T>) continue;
                var t1copy = ConverterHelper.MakeACopy(s.T1Node);
                t1copy.Children = new List<TreeNode<T>>();
                var parentcopy = ConverterHelper.MakeACopy(s.Parent);
                parentcopy.Children = new List<TreeNode<T>>();

                s.T1Node = t1copy;
                s.Parent = parentcopy;
            }

            for (int i = 0; i < editScript.Count; i++)
            {
                var v = editScript[i];
                if (v is Insert<T>)
                {
                    var xnode = new TreeNode<T>(v.T1Node.Value, v.T1Node.Label);
                    var znode = new TreeNode<T>(v.Parent.Value, v.Parent.Label);

                    var insert = new Insert<T>(xnode, znode, v.K);
                    editScript[i] = insert;
                }
            }

            var removes = new List<Tuple<EditOperation<T>, List<EditOperation<T>>>>();
            foreach (var v in editScript)
            {
                if (v is Move<T>)
                {
                    var move = (Move<T>)v;
                    var t1copy = ConverterHelper.MakeACopy(v.T1Node);
                    var parentcopy = ConverterHelper.MakeACopy(v.Parent);
                    var previousParentCopy = ConverterHelper.MakeACopy(move.PreviousParent);
                    EditOperation<T> insert = new Insert<T>(t1copy, parentcopy, v.K);
                    var delete = new Delete<T>(ConverterHelper.MakeACopy(t1copy));
                    delete.Parent = previousParentCopy;
                    var list = new List<EditOperation<T>>();
                    list.Add(delete);
                    list.Add(insert);
                    removes.Add(Tuple.Create(v, list));
                }
            }
            foreach (var v in removes)
            {
                var index = editScript.FindIndex(o => o.Equals(v.Item1));
                editScript.InsertRange(index, v.Item2);
                editScript.Remove(v.Item1);
            }
            return editScript;
        }

        /// <summary>
        /// Find the index in which the edit operations will be executed.
        /// </summary>
        /// <param name="x">Node in t2</param>
        /// <param name="M">Mapping</param>
        /// <returns>Index to be updated</returns>
        private int FindPos(TreeNode<T> x, Dictionary<TreeNode<T>, TreeNode<T>> M)
        {
            TreeNode<T> y = x.Parent; TreeNode<T> w = M.ToList().Find(o => o.Value.Equals(x)).Key;

            TreeNode<T> firstChild = y.Children.ElementAt(0);

            if (firstChild.Equals(x)) return 1;

            TreeNode<T> v = null;
            foreach (TreeNode<T> c in y.Children)
            {
                if (c.Equals(x))
                {
                    break;
                }

                v = c;
            }
            TreeNode<T> u = M.ToList().Find(o => o.Value.Equals(v)).Key;
            int count = 1;
            foreach (TreeNode<T> c in u.Parent.Children)
            {
                if (c.Equals(u)) return count + 1;

                count++;
            }
            return -1;
        }
    }
}


text:
@interface SPExportController (SharedPrivateAPI)
- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo;
- (void)_hideExportProgress;
@end