text:
<?php

use Symfony\Component\Translation\MessageCatalogue;

$catalogue = new MessageCatalogue('en', array (
  'validators' =>
  array (
    'This value should be false.' => 'This value should be false.',
    'This value should be true.' => 'This value should be true.',
    'This value should be of type {{ type }}.' => 'This value should be of type {{ type }}.',
    'This value should be blank.' => 'This value should be blank.',
    'The value you selected is not a valid choice.' => 'The value you selected is not a valid choice.',
    'You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.' => 'You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.',
    'You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.' => 'You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.',
    'One or more of the given values is invalid.' => 'One or more of the given values is invalid.',
    'This field was not expected.' => 'This field was not expected.',
    'This field is missing.' => 'This field is missing.',
    'This value is not a valid date.' => 'This value is not a valid date.',
    'This value is not a valid datetime.' => 'This value is not a valid datetime.',
    'This value is not a valid email address.' => 'This value is not a valid email address.',
    'The file could not be found.' => 'The file could not be found.',
    'The file is not readable.' => 'The file is not readable.',
    'The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.' => 'The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.',
    'The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.' => 'The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.',
    'This value should be {{ limit }} or less.' => 'This value should be {{ limit }} or less.',
    'This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less.' => 'This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less.',
    'This value should be {{ limit }} or more.' => 'This value should be {{ limit }} or more.',
    'This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more.' => 'This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more.',
    'This value should not be blank.' => 'This value should not be blank.',
    'This value should not be null.' => 'This value should not be null.',
    'This value should be null.' => 'This value should be null.',
    'This value is not valid.' => 'This value is not valid.',
    'This value is not a valid time.' => 'This value is not a valid time.',
    'This value is not a valid URL.' => 'This value is not a valid URL.',
    'The two values should be equal.' => 'The two values should be equal.',
    'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.' => 'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.',
    'The file is too large.' => 'The file is too large.',
    'The file could not be uploaded.' => 'The file could not be uploaded.',
    'This value should be a valid number.' => 'This value should be a valid number.',
    'This file is not a valid image.' => 'This file is not a valid image.',
    'This is not a valid IP address.' => 'This is not a valid IP address.',
    'This value is not a valid language.' => 'This value is not a valid language.',
    'This value is not a valid locale.' => 'This value is not a valid locale.',
    'This value is not a valid country.' => 'This value is not a valid country.',
    'This value is already used.' => 'This value is already used.',
    'The size of the image could not be detected.' => 'The size of the image could not be detected.',
    'The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.' => 'The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.',
    'The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.' => 'The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.',
    'The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.' => 'The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.',
    'The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.' => 'The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.',
    'This value should be the user\'s current password.' => 'This value should be the user\'s current password.',
    'This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters.' => 'This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters.',
    'The file was only partially uploaded.' => 'The file was only partially uploaded.',
    'No file was uploaded.' => 'No file was uploaded.',
    'No temporary folder was configured in php.ini.' => 'No temporary folder was configured in php.ini, or the configured folder does not exist.',
    'Cannot write temporary file to disk.' => 'Cannot write temporary file to disk.',
    'A PHP extension caused the upload to fail.' => 'A PHP extension caused the upload to fail.',
    'This collection should contain {{ limit }} element or more.|This collection should contain {{ limit }} elements or more.' => 'This collection should contain {{ limit }} element or more.|This collection should contain {{ limit }} elements or more.',
    'This collection should contain {{ limit }} element or less.|This collection should contain {{ limit }} elements or less.' => 'This collection should contain {{ limit }} element or less.|This collection should contain {{ limit }} elements or less.',
    'This collection should contain exactly {{ limit }} element.|This collection should contain exactly {{ limit }} elements.' => 'This collection should contain exactly {{ limit }} element.|This collection should contain exactly {{ limit }} elements.',
    'Invalid card number.' => 'Invalid card number.',
    'Unsupported card type or invalid card number.' => 'Unsupported card type or invalid card number.',
    'This is not a valid International Bank Account Number (IBAN).' => 'This is not a valid International Bank Account Number (IBAN).',
    'This value is not a valid ISBN-10.' => 'This value is not a valid ISBN-10.',
    'This value is not a valid ISBN-13.' => 'This value is not a valid ISBN-13.',
    'This value is neither a valid ISBN-10 nor a valid ISBN-13.' => 'This value is neither a valid ISBN-10 nor a valid ISBN-13.',
    'This value is not a valid ISSN.' => 'This value is not a valid ISSN.',
    'This value is not a valid currency.' => 'This value is not a valid currency.',
    'This value should be equal to {{ compared_value }}.' => 'This value should be equal to {{ compared_value }}.',
    'This value should be greater than {{ compared_value }}.' => 'This value should be greater than {{ compared_value }}.',
    'This value should be greater than or equal to {{ compared_value }}.' => 'This value should be greater than or equal to {{ compared_value }}.',
    'This value should be identical to {{ compared_value_type }} {{ compared_value }}.' => 'This value should be identical to {{ compared_value_type }} {{ compared_value }}.',
    'This value should be less than {{ compared_value }}.' => 'This value should be less than {{ compared_value }}.',
    'This value should be less than or equal to {{ compared_value }}.' => 'This value should be less than or equal to {{ compared_value }}.',
    'This value should not be equal to {{ compared_value }}.' => 'This value should not be equal to {{ compared_value }}.',
    'This value should not be identical to {{ compared_value_type }} {{ compared_value }}.' => 'This value should not be identical to {{ compared_value_type }} {{ compared_value }}.',
    'The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.' => 'The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.',
    'The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.' => 'The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.',
    'The image is square ({{ width }}x{{ height }}px). Square images are not allowed.' => 'The image is square ({{ width }}x{{ height }}px). Square images are not allowed.',
    'The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed.' => 'The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed.',
    'The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed.' => 'The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed.',
    'An empty file is not allowed.' => 'An empty file is not allowed.',
    'The host could not be resolved.' => 'The host could not be resolved.',
    'This value does not match the expected {{ charset }} charset.' => 'This value does not match the expected {{ charset }} charset.',
    'This is not a valid Business Identifier Code (BIC).' => 'This is not a valid Business Identifier Code (BIC).',
    'This form should not contain extra fields.' => 'This form should not contain extra fields.',
    'The uploaded file was too large. Please try to upload a smaller file.' => 'The uploaded file was too large. Please try to upload a smaller file.',
    'The CSRF token is invalid. Please try to resubmit the form.' => 'The CSRF token is invalid. Please try to resubmit the form.',
  ),
  'security' =>
  array (
    'An authentication exception occurred.' => 'An authentication exception occurred.',
    'Authentication credentials could not be found.' => 'Authentication credentials could not be found.',
    'Authentication request could not be processed due to a system problem.' => 'Authentication request could not be processed due to a system problem.',
    'Invalid credentials.' => 'Invalid credentials.',
    'Cookie has already been used by someone else.' => 'Cookie has already been used by someone else.',
    'Not privileged to request the resource.' => 'Not privileged to request the resource.',
    'Invalid CSRF token.' => 'Invalid CSRF token.',
    'Digest nonce has expired.' => 'Digest nonce has expired.',
    'No authentication provider found to support the authentication token.' => 'No authentication provider found to support the authentication token.',
    'No session available, it either timed out or cookies are not enabled.' => 'No session available, it either timed out or cookies are not enabled.',
    'No token could be found.' => 'No token could be found.',
    'Username could not be found.' => 'Username could not be found.',
    'Account has expired.' => 'Account has expired.',
    'Credentials have expired.' => 'Credentials have expired.',
    'Account is disabled.' => 'Account is disabled.',
    'Account is locked.' => 'Account is locked.',
  ),
  'KnpPaginatorBundle' =>
  array (
    'label_previous' => 'Previous',
    'label_next' => 'Next',
  ),
  'messages' =>
  array (
    'name' => 'Name',
    'first.name' => 'First Name',
    'user.list' => 'User List',
    'create.account' => 'Create an Account',
    'last.name' => 'Last Name',
    'username' => 'Username',
    'actions' => 'Actions',
    'add.page' => 'Add a Page',
    'page.list' => 'Page List',
    'create.page' => 'Create a Page',
    'url' => 'URL',
    'add.user' => 'Add a User',
    'logout' => 'Logout',
    'users' => 'Users',
    'content' => 'Content',
    'admin.home' => 'Admin Home',
    'home' => 'Home',
    'Toggle navigation' => 'Toggle navigation',
    'admin.panel' => 'Admin Panel',
    'overview' => 'Overview',
    'content.manager' => 'Content Manager',
    'reports' => 'Reports',
    'analytics' => 'Analytics',
    'export' => 'Export',
    'dashboard' => 'Dashboard',
    'users.Overview' => 'Users Overview',
    'create.user' => 'Create a User',
    'users.manager' => 'Users Manager',
    'search' => 'Search',
    'password' => 'Password',
    'email' => 'Email',
    'user' => 'User',
    'admin' => 'Administrator',
    'super.admin' => 'Super Administrator',
    'english' => 'English',
    'francais' => 'Français',
    'update.user' => 'Update User',
    'language' => 'Language',
    'navigation' => 'Navigation',
    'edit.user' => 'Edit User',
    'content.pages' => 'Content Pages',
    'blog.posts' => 'Blog Posts',
    'user.manage' => 'Manage Users',
    'role.manage' => 'Manage Roles',
    'role.list' => 'Role List',
    'create.role' => 'Create a role',
    'edit.role' => 'Edit Role',
    'update.role' => 'Update Role',
    'general' => 'General',
    'general.settings' => 'Site Settings',
    'click.here' => 'Click Here',
    'clear.cache' => 'Clear Cache',
    'userful.links' => 'Useful Link',
    'powered.by' => 'Powered By',
    'widgets' => 'Widgets',
    'widget.name' => 'Calling name for Widget:',
    'widget.list' => 'Widget List',
    'widget.add' => 'Create a Widget',
    'widget.id' => 'Widget Identifier',
    'published.date' => 'Date published:',
    'comment' => 'Comment',
    'save' => 'Save',
    'edit' => 'Edit',
    'remove' => 'Remove',
    'author' => 'Author',
    'last.edit.time' => 'Last edit time',
    'navigation.list' => 'Navigation list',
    'add.nav' => 'Create Navigation Link',
    'page.description' => 'Here is a list of all your content pages for the site  the link is automaticly made from the name of the page by adding \'-\' between words.',
    'gallery' => 'Gallery',
    'gallery.settings' => 'Gallery Settings',
    'add.image' => 'Add Image',
    'portfolio.projects' => 'Portfolio Projects',
    'project.list' => 'Project List',
    'project.create' => 'Create new project',
    'project.settings' => 'Portfolio Settings',
    'news' => 'News',
    'news.list' => 'News Articles List',
    'create.article' => 'Create a Article',
    'news.overview' => 'News Overview',
    'news.manager' => 'News Manager',
    'news.articles' => 'News Articles',
    'posts.list' => 'Blog Posts List',
    'create.post' => 'Create a Post',
    'sitename' => 'Site Name',
    'logo' => 'Logo',
    'default.locale' => 'Default locale',
    'timezone' => 'Timezone',
    'time.format' => 'Time Format (PHP Date() function)',
  ),
));

return $catalogue;


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using MOE.Common.Business.SiteSecurity;
using MOE.Common.Models;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using SPM.Filters;

namespace SPM.Controllers
{

    [Authorize(Roles = "Admin")]
    public class SPMUsersController : Controller
    {
        // GET: SPMUsers
        public ActionResult Index()
        {
            List<Models.UserViewModel> users = new List<Models.UserViewModel>();
            using (var context = new MOE.Common.Models.SPM())
            {
                var userStore = new UserStore<SPMUser>(context);
                var userManager = new UserManager<SPMUser>(userStore);
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);
                foreach (SPMUser user in userStore.Users.OrderBy(u=> u.Email).ToList())
                {
                    Models.UserViewModel userViewModel = new Models.UserViewModel();
                    userViewModel.User = user;
                    foreach(IdentityUserRole role in user.Roles)
                    {
                        userViewModel.Roles.Add(roleManager.Roles.Where(r => r.Id == role.RoleId).First().Name);
                    }
                    users.Add(userViewModel);
                }
            }
            return View(users);
        }

        //// GET: SPMUsers/Details/5
        //public ActionResult Details(string id)
        //{
        //    if (id == null)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    SPMUser sPMUser = db.SPMUsers.Find(id);
        //    if (sPMUser == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(sPMUser);
        //}

        // GET: SPMUsers/Edit/5
        public ActionResult Edit(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Models.UserViewModel user = new Models.UserViewModel();

            using (var context = new MOE.Common.Models.SPM())
            {
                List<string> roles;
                var userStore = new UserStore<SPMUser>(context);
                var userManager = new UserManager<SPMUser>(userStore);
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);
                user.User = userManager.Users.Where(u => u.Id == id).FirstOrDefault();
                foreach (IdentityUserRole role in user.User.Roles)
                {
                    user.Roles.Add(roleManager.Roles.Where(r => r.Id == role.RoleId).First().Name);
                }
                roles = (from r in roleManager.Roles select r.Name).ToList();
                ViewBag.Roles = new SelectList(roles.OrderBy(r=>r));
            }
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: SPMUsers/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Models.UserViewModel sPMUser)
        {
            if (ModelState.IsValid)
            {
                SPMUser user;
                using (var context = new MOE.Common.Models.SPM())
                {
                    try
                    {
                        var userStore = new UserStore<SPMUser>(context);
                        var userManager = new UserManager<SPMUser>(userStore);
                        user = userManager.Users.Where(u => u.Id == sPMUser.User.Id).FirstOrDefault();
                        user.ReceiveAlerts = sPMUser.User.ReceiveAlerts;
                        user.Email = sPMUser.User.Email;
                        user.UserName = sPMUser.User.Email;
                        context.SaveChanges();
                    }
                    catch(Exception ex)
                    {
                        return Content("<h1>" + ex.Message + "</h1>");
                    }
                }
                return RedirectToAction("Index");
            }
            return View(sPMUser);
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateJsonAntiForgeryToken]
        public ActionResult RemoveRoleFromUser(string roleName, string userName)
        {
            using (var context = new MOE.Common.Models.SPM())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);
                var userStore = new UserStore<SPMUser>(context);
                var userManager = new UserManager<SPMUser>(userStore);
                var user = userManager.FindByName(userName);
                if (user == null)
                {
                    return Content("User not found");
                }
                var role = roleManager.FindByName(roleName);
                if (role == null)
                {
                    return Content("Role not found");
                }
                if (!userManager.IsInRole(user.Id, role.Name))
                {
                    return Content("This user does not have this role assigned");
                }
                userManager.RemoveFromRole(user.Id, role.Name);
                context.SaveChanges();
                return Content("Role Removed");
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        [ValidateJsonAntiForgeryToken]
        public ActionResult AddRoleToUser(string roleName, string userName)
        {
            using (var context = new MOE.Common.Models.SPM())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var roleManager = new RoleManager<IdentityRole>(roleStore);
                var userStore = new UserStore<SPMUser>(context);
                var userManager = new UserManager<SPMUser>(userStore);
                var user = userManager.FindByName(userName);
                if (user == null)
                {
                    return Content("User not found");
                }
                var role = roleManager.FindByName(roleName);
                if (role == null)
                {
                    return Content("Role not found");
                }
                if (userManager.IsInRole(user.Id, role.Name))
                {
                    return Content("This user already has this role assigned");
                }
                userManager.AddToRole(user.Id, role.Name);
                context.SaveChanges();
                return Content("Role Added");
            }
        }

        // GET: SPMUsers/Delete/5
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            SPMUser user;
            using (var context = new MOE.Common.Models.SPM())
            {
                var userStore = new UserStore<SPMUser>(context);
                var userManager = new UserManager<SPMUser>(userStore);
                user = userManager.Users.Where(u => u.Id == id).FirstOrDefault();
            }
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // POST: SPMUsers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            SPMUser user;
            using (var context = new MOE.Common.Models.SPM())
            {
                var userStore = new UserStore<SPMUser>(context);
                var userManager = new UserManager<SPMUser>(userStore);
                user = userManager.Users.Where(u => u.Id == id).FirstOrDefault();
                userManager.Delete(user);
            }
            return RedirectToAction("Index");
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace _0140_1
{
    public class Solution
    {
        public IList<string> WordBreak(string s, IList<string> wordDict)
        {

            var f = new Dictionary<string, List<string>>();
            var wordSet = new HashSet<string>(wordDict);
            f[String.Empty] = new List<string>{String.Empty};

            return DP(s, wordSet, f);
        }

        private List<string> DP(string s, HashSet<string> wordSet, Dictionary<string, List<string>> f)
        {
            if (f.ContainsKey(s))
            {
                return f[s];
            }

            f[s] = new List<string>();

            // left part length is i
            for (var i = 0; i < s.Length; ++i)
            {
                var right = s.Substring(i, s.Length - i);
                if (wordSet.Contains(right))
                {
                    var left = s.Substring(0, i);
                    // need to clone result here, otherwise it will change f[left]
                    var leftResult = new List<string>(DP(left, wordSet, f));
                    if (leftResult.Count > 0)
                    {
                        for (var j = 0; j < leftResult.Count; ++j)
                        {
                            if (leftResult[j] != String.Empty)
                            {
                                leftResult[j] += " ";
                            }
                            leftResult[j] += right;
                        }
                        f[s].AddRange(leftResult);
                    }
                }
            }

            return f[s];
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            new Solution().WordBreak("catsanddog", new List<string>() { "cat", "cats", "and", "sand", "dog" });
            Console.WriteLine("Hello World!");
        }
    }
}


text:
package cli

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"

	"github.com/ory/hydra/internal/httpclient/client/admin"
	"github.com/ory/hydra/internal/httpclient/models"
	"github.com/ory/hydra/x"
	"github.com/ory/x/cmdx"
	"github.com/ory/x/flagx"
	"github.com/ory/x/pointerx"
)

type ClientHandler struct{}

func newClientHandler() *ClientHandler {
	return &ClientHandler{}
}

func (h *ClientHandler) ImportClients(cmd *cobra.Command, args []string) {
	cmdx.MinArgs(cmd, args, 1)
	m := configureClient(cmd)

	ek, encryptSecret, err := newEncryptionKey(cmd, nil)
	cmdx.Must(err, "Failed to load encryption key: %s", err)

	for _, path := range args {
		reader, err := os.Open(path)
		cmdx.Must(err, "Could not open file %s: %s", path, err)

		var c models.OAuth2Client
		err = json.NewDecoder(reader).Decode(&c)
		cmdx.Must(err, "Could not parse JSON from file %s: %s", path, err)

		response, err := m.Admin.CreateOAuth2Client(admin.NewCreateOAuth2ClientParams().WithBody(&c))
		cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
		result := response.Payload

		if c.ClientSecret == "" {
			if encryptSecret {
				enc, err := ek.Encrypt([]byte(result.ClientSecret))
				if err == nil {
					fmt.Printf("Imported OAuth 2.0 Client %s from: %s\n", result.ClientID, path)
					fmt.Printf("OAuth 2.0 Encrypted Client Secret: %s\n\n", enc.Base64Encode())
					continue
				}

				fmt.Printf("Imported OAuth 2.0 Client %s:%s from: %s\n", result.ClientID, result.ClientSecret, path)
				cmdx.Must(err, "Failed to encrypt client secret: %s", err)
			}

			fmt.Printf("Imported OAuth 2.0 Client %s:%s from: %s\n", result.ClientID, result.ClientSecret, path)
		} else {
			fmt.Printf("Imported OAuth 2.0 Client %s from: %s\n", result.ClientID, path)
		}
	}
}

func (h *ClientHandler) CreateClient(cmd *cobra.Command, args []string) {
	var err error
	m := configureClient(cmd)
	secret := flagx.MustGetString(cmd, "secret")

	var echoSecret bool
	if secret == "" {
		var secretb []byte
		secretb, err = x.GenerateSecret(26)
		cmdx.Must(err, "Could not generate OAuth 2.0 Client Secret: %s", err)
		secret = string(secretb)

		echoSecret = true
	} else {
		fmt.Println("You should not provide secrets using command line flags, the secret might leak to bash history and similar systems")
	}

	ek, encryptSecret, err := newEncryptionKey(cmd, nil)
	cmdx.Must(err, "Failed to load encryption key: %s", err)

	cc := models.OAuth2Client{
		ClientID:                          flagx.MustGetString(cmd, "id"),
		ClientSecret:                      secret,
		ResponseTypes:                     flagx.MustGetStringSlice(cmd, "response-types"),
		Scope:                             strings.Join(flagx.MustGetStringSlice(cmd, "scope"), " "),
		GrantTypes:                        flagx.MustGetStringSlice(cmd, "grant-types"),
		RedirectUris:                      flagx.MustGetStringSlice(cmd, "callbacks"),
		ClientName:                        flagx.MustGetString(cmd, "name"),
		TokenEndpointAuthMethod:           flagx.MustGetString(cmd, "token-endpoint-auth-method"),
		JwksURI:                           flagx.MustGetString(cmd, "jwks-uri"),
		TosURI:                            flagx.MustGetString(cmd, "tos-uri"),
		PolicyURI:                         flagx.MustGetString(cmd, "policy-uri"),
		LogoURI:                           flagx.MustGetString(cmd, "logo-uri"),
		ClientURI:                         flagx.MustGetString(cmd, "client-uri"),
		AllowedCorsOrigins:                flagx.MustGetStringSlice(cmd, "allowed-cors-origins"),
		SubjectType:                       flagx.MustGetString(cmd, "subject-type"),
		Audience:                          flagx.MustGetStringSlice(cmd, "audience"),
		PostLogoutRedirectUris:            flagx.MustGetStringSlice(cmd, "post-logout-callbacks"),
		BackchannelLogoutSessionRequired:  flagx.MustGetBool(cmd, "backchannel-logout-session-required"),
		BackchannelLogoutURI:              flagx.MustGetString(cmd, "backchannel-logout-callback"),
		FrontchannelLogoutSessionRequired: flagx.MustGetBool(cmd, "frontchannel-logout-session-required"),
		FrontchannelLogoutURI:             flagx.MustGetString(cmd, "frontchannel-logout-callback"),
	}

	response, err := m.Admin.CreateOAuth2Client(admin.NewCreateOAuth2ClientParams().WithBody(&cc))
	cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
	result := response.Payload

	fmt.Printf("OAuth 2.0 Client ID: %s\n", result.ClientID)
	if result.ClientSecret == "" {
		fmt.Println("This OAuth 2.0 Client has no secret")
	} else {
		if echoSecret {
			if encryptSecret {
				enc, err := ek.Encrypt([]byte(result.ClientSecret))
				if err == nil {
					fmt.Printf("OAuth 2.0 Encrypted Client Secret: %s\n", enc.Base64Encode())
					return
				}

				// executes this at last to print raw client secret
				// because if executes immediately, nobody knows client secret
				defer cmdx.Must(err, "Failed to encrypt client secret: %s", err)
			}

			fmt.Printf("OAuth 2.0 Client Secret: %s\n", result.ClientSecret)
		}
	}
}

func (h *ClientHandler) UpdateClient(cmd *cobra.Command, args []string) {
	cmdx.ExactArgs(cmd, args, 1)
	m := configureClient(cmd)
	newSecret := flagx.MustGetString(cmd, "secret")

	var echoSecret bool
	if newSecret != "" {
		echoSecret = true
		fmt.Println("You should not provide secrets using command line flags, the secret might leak to bash history and similar systems")
	}

	ek, encryptSecret, err := newEncryptionKey(cmd, nil)
	cmdx.Must(err, "Failed to load encryption key: %s", err)

	id := args[0]
	cc := models.OAuth2Client{
		ClientID:                          id,
		ClientSecret:                      newSecret,
		ResponseTypes:                     flagx.MustGetStringSlice(cmd, "response-types"),
		Scope:                             strings.Join(flagx.MustGetStringSlice(cmd, "scope"), " "),
		GrantTypes:                        flagx.MustGetStringSlice(cmd, "grant-types"),
		RedirectUris:                      flagx.MustGetStringSlice(cmd, "callbacks"),
		ClientName:                        flagx.MustGetString(cmd, "name"),
		TokenEndpointAuthMethod:           flagx.MustGetString(cmd, "token-endpoint-auth-method"),
		JwksURI:                           flagx.MustGetString(cmd, "jwks-uri"),
		TosURI:                            flagx.MustGetString(cmd, "tos-uri"),
		PolicyURI:                         flagx.MustGetString(cmd, "policy-uri"),
		LogoURI:                           flagx.MustGetString(cmd, "logo-uri"),
		ClientURI:                         flagx.MustGetString(cmd, "client-uri"),
		AllowedCorsOrigins:                flagx.MustGetStringSlice(cmd, "allowed-cors-origins"),
		SubjectType:                       flagx.MustGetString(cmd, "subject-type"),
		Audience:                          flagx.MustGetStringSlice(cmd, "audience"),
		PostLogoutRedirectUris:            flagx.MustGetStringSlice(cmd, "post-logout-callbacks"),
		BackchannelLogoutSessionRequired:  flagx.MustGetBool(cmd, "backchannel-logout-session-required"),
		BackchannelLogoutURI:              flagx.MustGetString(cmd, "backchannel-logout-callback"),
		FrontchannelLogoutSessionRequired: flagx.MustGetBool(cmd, "frontchannel-logout-session-required"),
		FrontchannelLogoutURI:             flagx.MustGetString(cmd, "frontchannel-logout-callback"),
	}

	response, err := m.Admin.UpdateOAuth2Client(admin.NewUpdateOAuth2ClientParams().WithID(id).WithBody(&cc))
	cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
	result := response.Payload
	fmt.Printf("%s OAuth 2.0 Client updated\n", result.ClientID)

	if echoSecret {
		if encryptSecret {
			enc, err := ek.Encrypt([]byte(result.ClientSecret))
			if err == nil {
				fmt.Printf("OAuth 2.0 Encrypted Client Secret: %s\n", enc.Base64Encode())
				return
			}

			// executes this at last to print raw client secret
			// because if executes immediately, nobody knows client secret
			defer cmdx.Must(err, "Failed to encrypt client secret: %s", err)
		}
		fmt.Printf("Updated OAuth 2.0 Client Secret: %s\n", result.ClientSecret)
	}
}

func (h *ClientHandler) DeleteClient(cmd *cobra.Command, args []string) {
	cmdx.MinArgs(cmd, args, 1)
	m := configureClient(cmd)

	for _, c := range args {
		_, err := m.Admin.DeleteOAuth2Client(admin.NewDeleteOAuth2ClientParams().WithID(c))
		cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
	}

	fmt.Println("OAuth 2.0 Client(s) deleted")
}

func (h *ClientHandler) GetClient(cmd *cobra.Command, args []string) {

	m := configureClient(cmd)
	if len(args) == 0 {
		fmt.Print(cmd.UsageString())
		return
	}

	response, err := m.Admin.GetOAuth2Client(admin.NewGetOAuth2ClientParams().WithID(args[0]))
	cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
	cl := response.Payload
	fmt.Println(cmdx.FormatResponse(cl))
}

func (h *ClientHandler) ListClients(cmd *cobra.Command, args []string) {
	m := configureClient(cmd)

	limit := flagx.MustGetInt(cmd, "limit")
	page := flagx.MustGetInt(cmd, "page")
	offset := (limit * page) - limit

	response, err := m.Admin.ListOAuth2Clients(admin.NewListOAuth2ClientsParams().WithLimit(pointerx.Int64(int64(limit))).WithOffset(pointerx.Int64(int64(offset))))
	cmdx.Must(err, "The request failed with the following error message:\n%s", formatSwaggerError(err))
	cls := response.Payload

	table := newTable()
	table.SetHeader([]string{
		"Client ID",
		"Name",
		"Response Types",
		"Scope",
		"Redirect Uris",
		"Grant Types",
		"Token Endpoint Auth Method",
	})

	data := make([][]string, len(cls))
	for i, cl := range cls {
		data[i] = []string{
			cl.ClientID,
			cl.ClientName,
			strings.Join(cl.ResponseTypes, ","),
			cl.Scope,
			strings.Join(cl.RedirectUris, "\n"),
			strings.Join(cl.GrantTypes, ","),
			cl.TokenEndpointAuthMethod,
		}
	}

	table.AppendBulk(data)
	table.Render()
}


text:
package uk.gov.homeoffice.rtp.proxy

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import akka.actor.{ActorLogging, Props}
import akka.event.LoggingReceive
import akka.io.IO
import akka.pattern.ask
import spray.can.Http
import spray.http.{HttpRequest, HttpResponse}
import spray.routing.{HttpServiceActor, RequestContext}
import uk.gov.homeoffice.json.Json

object ProxyActor {
  def props(proxiedConnectorSetup: Http.HostConnectorSetup) = Props(new ProxyActor(proxiedConnectorSetup))
}

class ProxyActor(proxiedConnectorSetup: Http.HostConnectorSetup) extends HttpServiceActor with ProxyRoute with Json with ActorLogging {
  def receive: Receive = LoggingReceive {
    runRoute(route)
  }

  def proxy(ctx: RequestContext): Future[HttpResponse] = {
    log(ctx.request)

    IO(Http)(context.system) ask proxiedConnectorSetup flatMap {
      case Http.HostConnectorInfo(proxiedConnector, _) =>
        proxiedConnector.ask(ctx.request).mapTo[HttpResponse] map { response =>
          log(response)
          response
        }
    }
  }

  private def log(request: HttpRequest): Unit = {
    val protocol = request.protocol
    val uri = request.uri
    val method = request.method
    val headers = request.headers.map(_.toString()).mkString(", ")
    val entity = request.entity.asString

    super.log.info(s"Proxying $protocol request to $uri, method = $method, headers = $headers, entity = $entity")
  }

  private def log(response: HttpResponse): Unit = {
    val protocol = response.protocol
    val status = response.status
    val headers = response.headers.map(_.toString()).mkString(", ")
    val entity = response.entity.asString

    super.log.info(s"Proxied $protocol response of status $status, headers = $headers, entity = $entity")
  }
}


text:
<?php

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SetPlayerName extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('gameName')
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'App\Entity\Player'
        ));
    }

    /**
     * @return string
     */
    public function getBlockPrefix()
    {
        return '_tournamentbundle_player';
    }
}


text:
package org.mockito.internal.stubbing;

import org.mockito.stubbing.Answer;
import org.mockito.stubbing.OngoingStubbing;

public class ConsecutiveStubbing<T> extends BaseStubbing<T> {

    private final InvocationContainerImpl invocationContainer;

    ConsecutiveStubbing(InvocationContainerImpl invocationContainer) {
        super(invocationContainer.invokedMock());
        this.invocationContainer = invocationContainer;
    }

    public OngoingStubbing<T> thenAnswer(Answer<?> answer) {
        invocationContainer.addConsecutiveAnswer(answer);
        return this;
    }
}


text:
#include <boost/assign/list_of.hpp>

#include <cfg/cfg_init.h>
#include <cfg/cfg_interface.h>
#include <oper/operdb_init.h>
#include <controller/controller_init.h>
#include <pkt/pkt_init.h>
#include <services/services_init.h>
#include <ksync/ksync_init.h>
#include <cmn/agent_cmn.h>
#include <base/task.h>
#include <io/event_manager.h>
#include <base/util.h>
#include <ifmap_agent_parser.h>
#include <ifmap_agent_table.h>
#include <oper/vn.h>
#include <oper/vm.h>
#include <oper/interface_common.h>

#include <io/test/event_manager_test.h>
#include "testing/gunit.h"
#include "test_cmn_util.h"
#include "vr_types.h"

#include <async/TAsioAsync.h>
#include <protocol/TBinaryProtocol.h>
#include <gen-cpp/InstanceService.h>

#include <async/TFuture.h>
#include <io/event_manager.h>
#include <db/db.h>
#include <cmn/agent_cmn.h>
#include <cfg/cfg_interface.h>
#include <cfg/cfg_types.h>
#include <base/test/task_test_util.h>

using namespace std;
using namespace boost::assign;
using namespace apache::thrift;
using boost::shared_ptr;

extern void InstanceInfoServiceServerInit(Agent *agent);

void RouterIdDepInit(Agent *agent) {
}

//namespace {
class NovaInfoServerTest : public ::testing::Test {
protected:
};

DB *db;

int8_t port_id []     = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int8_t instance_id [] = {0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int8_t vn_id []       = {0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
string mac("00:00:00:00:00:");
string ip_address("10.10.10.");
string tap_name("tap");
string display_name("vm");
string host_name("vm");
string host("vm");

bool connection_complete = false;
bool port_resp_done  = false;

boost::shared_ptr<InstanceServiceAsyncClient> client_service;

void AddPortCallback(tuuid port_id, std::string tap_name, bool ret)
{
    std::cout << "Device " << tap_name << ", Return value " << ret << std::endl;
}

void AddPortErrback(const InstanceService_AddPort_result& result)
{
    std::cout << "Exception caught " << __FUNCTION__ << std::endl;
}

void DeletePortCallback(tuuid port_id, bool ret)
{
    std::cout << "DeletePort " << ret << std::endl;
}

void DeletePortErrback(const InstanceService_DeletePort_result& result)
{
    std::cout << "Exception caught " << __FUNCTION__ << std::endl;
}

void ConnectCallback(bool ret)
{
    std::cout << "Connect, " << "Return value " << ret << std::endl;
}

void KeepAliveCallback(bool ret)
{
    std::cout << "Keepalive, " << "Return value " << ret << std::endl;
}

static inline const std::string integerToHexString(const int8_t &num)
{
    std::stringstream ss;
    ss << std::hex << (uint16_t)num;
    return ss.str();
}

void CreatePort(Port &port, int8_t portid, int8_t instanceid, int8_t vnid) {
    std::string id_hex_str = integerToString(portid);
    port.tap_name = (tap_name + id_hex_str);
    port.ip_address = (ip_address + integerToString(portid));
    port.mac_address = (mac + id_hex_str);
    port.__set_display_name(display_name + integerToString(instanceid));
    port.__set_hostname(host_name + integerToHexString(instanceid));
    port.__set_host(host + integerToHexString(instanceid));

    tuuid port_tuuid;
    int8_t t_port_id[sizeof(port_id)];
    memcpy(t_port_id, port_id, sizeof(t_port_id));
    t_port_id[15] = portid;
    port_tuuid.insert(port_tuuid.begin(), t_port_id,
                      t_port_id + (sizeof(t_port_id)/sizeof(int8_t)));
    port.port_id = port_tuuid;

    tuuid instance_tuuid;
    int8_t t_instance_id[sizeof(instance_id)];
    memcpy(t_instance_id, instance_id, sizeof(t_instance_id));
    t_instance_id[15] = instanceid;
    instance_tuuid.insert(instance_tuuid.begin(), t_instance_id,
                          t_instance_id + (sizeof(t_instance_id)/sizeof(int8_t)));
    port.instance_id = instance_tuuid;

    tuuid vn_tuuid;
    int8_t t_vn_id[sizeof(vn_id)];
    memcpy(t_vn_id, vn_id, sizeof(t_vn_id));
    t_vn_id[15] = vnid;
    vn_tuuid.insert(vn_tuuid.begin(), t_vn_id,
                    t_vn_id + (sizeof(t_vn_id)/sizeof(int8_t)));
    port.vn_id = vn_tuuid;
}

void DelVmPort(boost::shared_ptr<InstanceServiceAsyncClient> inst_client, int8_t portid) {
    tuuid port_tuuid;
    int8_t t_port_id[sizeof(port_id)];
    memcpy(t_port_id, port_id, sizeof(t_port_id));
    t_port_id[15] = portid;
    port_tuuid.insert(port_tuuid.begin(), t_port_id,
                      t_port_id + (sizeof(t_port_id)/sizeof(int8_t)));
    inst_client->DeletePort(port_tuuid).setCallback(
        boost::bind(&DeletePortCallback, port_tuuid, _1)).setErrback(DeletePortErrback);
}

void AddVmPort(boost::shared_ptr<InstanceServiceAsyncClient> inst_client, int8_t portid,
               int8_t instanceid, int8_t vnid) {
    std::vector<Port> pl;
    Port port;
    CreatePort(port, portid, instanceid, vnid);
    pl.push_back(port);
    inst_client->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
}

void ConnectToServer(boost::shared_ptr<InstanceServiceAsyncClient> inst_client) {
    inst_client->Connect().setCallback(
        boost::bind(&ConnectCallback, _1));
}

void SendKeepAlive(boost::shared_ptr<InstanceServiceAsyncClient> inst_client) {
    inst_client->KeepAliveCheck().setCallback(
        boost::bind(&KeepAliveCallback, _1));
}

void connected(boost::shared_ptr<InstanceServiceAsyncClient> inst_client) {
    std::cout << "connected!!!" << std::endl;
    client_service = inst_client;
    connection_complete = true;
}

static void PortReqResponse(Sandesh *sandesh, string &resp_str) {
    PortResp *resp = dynamic_cast<PortResp *>(sandesh);
    std::string s_resp_str = resp->get_resp();
    EXPECT_EQ(resp_str, s_resp_str);
    port_resp_done = true;
}

TEST_F(NovaInfoServerTest, IntrospecPortAdd) {
    AddPortReq *req = new AddPortReq();
    req->set_port_uuid(std::string("00000000-0000-0000-0000-000000000001"));
    req->set_instance_uuid(std::string("00000000-0000-0000-0000-000000000001"));
    req->set_tap_name(std::string("tap1"));
    req->set_ip_address(std::string("1.1.1.1"));
    req->set_vn_uuid(std::string("00000000-0000-0000-0000-000000000001"));
    req->set_mac_address(std::string("00:00:00:00:00:1"));
    req->set_vm_name(std::string("vm1"));
    req->set_vlan_id(100);
    req->set_vm_project_uuid("00000000-0000-0000-0000-000000000001");
    port_resp_done = false;
    Sandesh::set_response_callback(boost::bind(PortReqResponse, _1, std::string("Success")));
    req->HandleRequest();
    client->WaitForIdle();
    EXPECT_EQ(1, Agent::GetInstance()->GetIntfCfgTable()->Size());
    req->Release();
}

TEST_F(NovaInfoServerTest, IntrospecPortDelete) {
    DeletePortReq *req = new DeletePortReq();
    req->set_port_uuid(std::string("00000000-0000-0000-0000-000000000001"));
    port_resp_done = false;
    Sandesh::set_response_callback(boost::bind(PortReqResponse, _1, std::string("Success")));
    req->HandleRequest();
    client->WaitForIdle();
    EXPECT_EQ(0, Agent::GetInstance()->GetIntfCfgTable()->Size());
    req->Release();
}

EventManager *client_evm;
ServerThread *client_thread;

class NovaInfoClientServerTest : public ::testing::Test {
protected:
};

TEST_F(NovaInfoClientServerTest, ConnectionStart) {
    client_evm = new EventManager();
    client_thread = new ServerThread(client_evm);
    boost::shared_ptr<protocol::TProtocolFactory>
            protocolFactory(new protocol::TBinaryProtocolFactory());
    boost::shared_ptr<async::TAsioClient> nova_client (
        new async::TAsioClient(
            *(client_evm->io_service()),
            protocolFactory,
            protocolFactory));
    client_thread->Start();
    nova_client->connect("localhost", 9090, connected);
    TASK_UTIL_EXPECT_EQ(true, connection_complete);
}

TEST_F(NovaInfoClientServerTest, ConnectTest) {
    ConnectToServer(client_service);
}

TEST_F(NovaInfoClientServerTest, KeepAliveTest) {
    SendKeepAlive(client_service);
}

TEST_F(NovaInfoClientServerTest, PortAdd) {
    // Add and delete port check the status of the cfg intf db
    AddVmPort(client_service, 1, 1, 1);
    CfgIntTable *cfgtable = Agent::GetInstance()->GetIntfCfgTable();
    CfgIntKey key(MakeUuid(1));
    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->GetIntfCfgTable()->Size());
    CfgIntEntry *cfg_entry;
    TASK_UTIL_EXPECT_NE((CfgIntEntry *)NULL,
                        (cfg_entry =
                         static_cast<CfgIntEntry *>(Agent::GetInstance()->GetIntfCfgTable()->Find(&key))));
    EXPECT_EQ(cfg_entry->GetVersion(), 1);
}

TEST_F(NovaInfoClientServerTest, PortDelete) {
    CfgIntTable *cfgtable = Agent::GetInstance()->GetIntfCfgTable();
    CfgIntKey key(MakeUuid(1));
    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->GetIntfCfgTable()->Size());
    CfgIntEntry *cfg_entry;
    TASK_UTIL_EXPECT_NE((CfgIntEntry *)NULL,
                        (cfg_entry =
                         static_cast<CfgIntEntry *>(Agent::GetInstance()->GetIntfCfgTable()->Find(&key))));
    EXPECT_EQ(cfg_entry->GetVersion(), 1);
    DelVmPort(client_service, 1);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->GetIntfCfgTable()->Size());
}

TEST_F(NovaInfoClientServerTest, ReconnectVersionCheck) {
    AddVmPort(client_service, 1, 1, 1);
    ConnectToServer(client_service);
    CfgIntTable *cfgtable = Agent::GetInstance()->GetIntfCfgTable();
    CfgIntKey key(MakeUuid(1));
    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->GetIntfCfgTable()->Size());
    CfgIntEntry *cfg_entry;
    TASK_UTIL_EXPECT_NE((CfgIntEntry *)NULL,
                        (cfg_entry =
                         static_cast<CfgIntEntry *>(Agent::GetInstance()->GetIntfCfgTable()->Find(&key))));
    EXPECT_EQ(cfg_entry->GetVersion(), 1);
    DelVmPort(client_service, 1);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->GetIntfCfgTable()->Size());
}

TEST_F(NovaInfoClientServerTest, MultiPortAddDelete) {
    // Add Multiple ports
    Port port1;
    Port port2;
    Port port3;
    CreatePort(port1, 3, 3, 1);
    CreatePort(port2, 4, 4, 1);
    CreatePort(port3, 5, 5, 1);
    std::vector<Port> pl;
    pl.clear();
    pl.push_back(port1);
    pl.push_back(port2);
    pl.push_back(port3);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port3.port_id, port3.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(3, Agent::GetInstance()->GetIntfCfgTable()->Size());
    // Add again same muliple ports
    pl.clear();
    pl.push_back(port1);
    pl.push_back(port2);
    pl.push_back(port3);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port3.port_id, port3.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(3, Agent::GetInstance()->GetIntfCfgTable()->Size());
    // Delete Multiple ports
    DelVmPort(client_service, 3);
    DelVmPort(client_service, 4);
    DelVmPort(client_service, 5);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->GetIntfCfgTable()->Size());
}

TEST_F(NovaInfoClientServerTest, AddPortWrongIP) {
    // Test negitive inputs
    // Wrong IP address
    Port port;
    std::vector<Port> pl;
    CreatePort(port, 2, 2, 2);
    port.ip_address = "TestIP";
    pl.push_back(port);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->GetIntfCfgTable()->Size());
}

TEST_F(NovaInfoClientServerTest, NullUUIDTest) {
    Port port;
    // Null uuids, we are allowing them
    CreatePort(port, 3, 3, 3);
    tuuid null_tuuid;
    int8_t t_port_id[sizeof(port_id)];
    memcpy(t_port_id, port_id, sizeof(t_port_id));
    null_tuuid.insert(null_tuuid.begin(), t_port_id,
                      t_port_id + (sizeof(t_port_id)/sizeof(int8_t)));
    port.port_id = null_tuuid;
    port.instance_id = null_tuuid;
    port.vn_id = null_tuuid;
    std::vector<Port> pl;
    pl.clear();
    pl.push_back(port);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(1, Agent::GetInstance()->GetIntfCfgTable()->Size());
    client_service->DeletePort(null_tuuid).setCallback(
        boost::bind(&DeletePortCallback, null_tuuid, _1)).setErrback(DeletePortErrback);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->GetIntfCfgTable()->Size());
}

TEST_F(NovaInfoClientServerTest, WrongUUIDTest1) {
    // Send extra bytes in the uuid, and it shouldn't get added
    Port port;
    CreatePort(port, 4, 4, 4);
    tuuid extra_tuuid;
    int8_t t_extraport_id[sizeof(port_id) + 1];
    memcpy(t_extraport_id, port_id, sizeof(port_id));
    extra_tuuid.insert(extra_tuuid.begin(), t_extraport_id,
                       t_extraport_id + (sizeof(t_extraport_id)/sizeof(int8_t)));
    port.port_id = extra_tuuid;
    port.instance_id = extra_tuuid;
    port.vn_id = extra_tuuid;
    std::vector<Port> pl;
    pl.clear();
    pl.push_back(port);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->GetIntfCfgTable()->Size());
}

TEST_F(NovaInfoClientServerTest, WrongUUIDTest2) {
    // Send less number of bytes in uuids, and it shouldn't get added
    Port port;
    CreatePort(port, 5, 5, 5);
    tuuid small_tuuid;
    int8_t s_port_id[sizeof(port_id)];
    memcpy(s_port_id, port_id, sizeof(port_id));
    small_tuuid.insert(small_tuuid.begin(), s_port_id,
                       s_port_id + (sizeof(s_port_id)/sizeof(int8_t) - 1));
    port.port_id = small_tuuid;
    port.instance_id = small_tuuid;
    tuuid vn_tuuid;
    int8_t t_vn_id[sizeof(vn_id)];
    memcpy(t_vn_id, vn_id, sizeof(t_vn_id));
    vn_tuuid.insert(vn_tuuid.begin(), t_vn_id,
                    t_vn_id + (sizeof(t_vn_id)/sizeof(int8_t)));
    port.vn_id = vn_tuuid;
    std::vector<Port> pl;
    pl.clear();
    pl.push_back(port);
    client_service->AddPort(pl).setCallback(
        boost::bind(&AddPortCallback,
                    port.port_id, port.tap_name, _1)).setErrback(AddPortErrback);
    TASK_UTIL_EXPECT_EQ(0, Agent::GetInstance()->GetIntfCfgTable()->Size());
}

TEST_F(NovaInfoClientServerTest, ConnectionDelete) {
    client_evm->Shutdown();
    client_thread->Join();
    delete client_evm;
    delete client_thread;
}

int main (int argc, char **argv) {
    GETUSERARGS();
    client = TestInit(init_file, ksync_init);
    EventManager *evm = Agent::GetInstance()->GetEventManager();
    InstanceInfoServiceServerInit(Agent::GetInstance());
    int ret = RUN_ALL_TESTS();
    client->WaitForIdle();
    TestShutdown();
    delete client;
    return ret;
}


text:
"""
Weibo Api
"""
from django.urls import path

from weibo.views.comment import (
    CommentCreateAPIView,
    CommentListApiView,
    CommentDetailAPIView
)

urlpatterns = [
    # 前缀:/api/v1/weibo/comment/
    path("create", CommentCreateAPIView.as_view(), name="create"),
    path("list", CommentListApiView.as_view(), name="list"),
    path("<int:pk>", CommentDetailAPIView.as_view(), name="detail")
]


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

-->

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <display-name>Flex QA Web Application</display-name>
    <description>Flex Presentation Server qa web application</description>

    <context-param>
        <param-name>brokerURI</param-name>
        <param-value>/WEB-INF/activemq.xml</param-value>
    </context-param>

    <!-- Http Flex Session attribute and binding listener support -->
    <listener>
        <listener-class>flex.messaging.HttpFlexSession</listener-class>
    </listener>

    <!-- Active MQ Spring Context Listener-->
    <listener>
        <listener-class>org.apache.activemq.web.SpringBrokerContextListener</listener-class>
    </listener>

    <!-- Spring Configuration. Uncomment if using Spring.
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> -->

    <!-- MessageBroker Servlet -->
    <servlet>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <display-name>MessageBrokerServlet</display-name>
        <servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
        <init-param>
            <param-name>services.configuration.file</param-name>
            <param-value>/WEB-INF/flex/services-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet>
        <servlet-name>HttpXmlEchoService</servlet-name>
        <display-name>HttpXmlEchoService</display-name>
        <servlet-class>dev.httpservice.HttpXmlEchoService</servlet-class>
    </servlet>

    <servlet>
        <servlet-name>AxisServlet</servlet-name>
        <display-name>Apache-Axis Servlet</display-name>
        <servlet-class>org.apache.axis.transport.http.AxisServlet</servlet-class>
    </servlet>

    <servlet>
        <servlet-name>AdminServlet</servlet-name>
        <display-name>Axis Admin Servlet</display-name>
        <servlet-class>
            org.apache.axis.transport.http.AdminServlet
        </servlet-class>
        <load-on-startup>100</load-on-startup>
    </servlet>

    <!--- Add RDS servlets -->
    <servlet>
        <servlet-name>RDSDispatchServlet</servlet-name>
        <display-name>RDSDispatchServlet</display-name>
        <servlet-class>flex.rds.server.servlet.FrontEndServlet</servlet-class>
        <init-param>
            <param-name>useAppserverSecurity</param-name>
            <param-value>false</param-value>
        </init-param>
        <!-- Must be loaded after MessageBrokerServlet -->
        <load-on-startup>10</load-on-startup>
    </servlet>

    <!-- Flex task Servlet -->
    <servlet>
       <servlet-name>QAAntTaskCompilerServlet</servlet-name>
       <display-name>QAAntTaskCompilerServlet</display-name>
       <servlet-class>qa.utils.mxml.MXMLCServlet</servlet-class>
       <init-param>
            <param-name>ant-debug</param-name>
            <param-value>false</param-value>
       </init-param>
       <!-- use either absolute or relative path to the FLEX_HOME -->
       <init-param>
            <param-name>FLEX_HOME</param-name>
            <param-value>../../..</param-value>
       </init-param>
    </servlet>

    <servlet-mapping id="RDS_DISPATCH_MAPPING">
        <servlet-name>RDSDispatchServlet</servlet-name>
        <url-pattern>/CFIDE/main/ide.cfm</url-pattern>
    </servlet-mapping>
    <!-- End Add RDS servlets -->

    <servlet-mapping>
        <servlet-name>AdminServlet</servlet-name>
        <url-pattern>/servlet/AdminServlet</url-pattern>
     </servlet-mapping>

    <servlet-mapping>
        <servlet-name>AxisServlet</servlet-name>
        <url-pattern>/axis/services/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>AxisServlet</servlet-name>
        <url-pattern>/axis/servlet/AxisServlet</url-pattern>
     </servlet-mapping>

    <servlet-mapping>
        <servlet-name>AxisServlet</servlet-name>
        <url-pattern>*.jws</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>HttpXmlEchoService</servlet-name>
        <url-pattern>/httpxmlechoservice</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <url-pattern>/messagebroker/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>QAAntTaskCompilerServlet</servlet-name>
        <url-pattern>*.mxml</url-pattern>
    </servlet-mapping>

    <!-- for WebSphere deployment, please uncomment -->
    <!--
    <resource-ref>
        <description>Flex Messaging WorkManager</description>
        <res-ref-name>wm/MessagingWorkManager</res-ref-name>
        <res-type>com.ibm.websphere.asynchbeans.WorkManager</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
    -->

    <mime-mapping>
        <extension>wsdl</extension>
        <mime-type>text/xml</mime-type>
    </mime-mapping>

    <mime-mapping>
        <extension>xsd</extension>
        <mime-type>text/xml</mime-type>
    </mime-mapping>

    <mime-mapping>
        <extension>xml</extension>
        <mime-type>text/xml</mime-type>
    </mime-mapping>

    <mime-mapping>
        <extension>swf</extension>
        <mime-type>application/x-shockwave-flash</mime-type>
    </mime-mapping>

</web-app>


text:
import gdb.printing

class Iterator:
  def __iter__(self):
    return self

  # Python 2 compatibility
  def next(self):
    return self.__next__()

  def children(self):
    return self

def escape_bytes(val, l):
  return '"' + val.string(encoding='Latin-1', length=l).encode('unicode_escape').decode() + '"'

class SmallStringPrinter:
  """Print an llvm::SmallString object."""

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

  def to_string(self):
    begin = self.val['BeginX']
    return escape_bytes(begin.cast(gdb.lookup_type('char').pointer()), self.val['Size'])

class StringRefPrinter:
  """Print an llvm::StringRef object."""

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

  def to_string(self):
    return escape_bytes(self.val['Data'], self.val['Length'])

class SmallVectorPrinter(Iterator):
  """Print an llvm::SmallVector object."""

  def __init__(self, val):
    self.val = val
    t = val.type.template_argument(0).pointer()
    self.begin = val['BeginX'].cast(t)
    self.size = val['Size']
    self.i = 0

  def __next__(self):
    if self.i == self.size:
      raise StopIteration
    ret = '[{}]'.format(self.i), (self.begin+self.i).dereference()
    self.i += 1
    return ret

  def to_string(self):
    return 'llvm::SmallVector of Size {}, Capacity {}'.format(self.size, self.val['Capacity'])

  def display_hint (self):
    return 'array'

class ArrayRefPrinter:
  """Print an llvm::ArrayRef object."""

  class _iterator:
    def __init__(self, begin, end):
      self.cur = begin
      self.end = end
      self.count = 0

    def __iter__(self):
      return self

    def next(self):
      if self.cur == self.end:
        raise StopIteration
      count = self.count
      self.count = self.count + 1
      cur = self.cur
      self.cur = self.cur + 1
      return '[%d]' % count, cur.dereference()

    __next__ = next

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

    __next__ = next

  def children(self):
    data = self.val['Data']
    return self._iterator(data, data + self.val['Length'])

  def to_string(self):
    return 'llvm::ArrayRef of length %d' % (self.val['Length'])

  def display_hint (self):
    return 'array'

class ExpectedPrinter(Iterator):
  """Print an llvm::Expected object."""

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

  def __next__(self):
    val = self.val
    if val is None:
      raise StopIteration
    self.val = None
    if val['HasError']:
      return ('error', val['ErrorStorage'].address.cast(
          gdb.lookup_type('llvm::ErrorInfoBase').pointer()).dereference())
    return ('value', val['TStorage'].address.cast(
        val.type.template_argument(0).pointer()).dereference())

  def to_string(self):
    return 'llvm::Expected{}'.format(' is error' if self.val['HasError'] else '')

class OptionalPrinter(Iterator):
  """Print an llvm::Optional object."""

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

  def __next__(self):
    val = self.val
    if val is None:
      raise StopIteration
    self.val = None
    if not val['Storage']['hasVal']:
      raise StopIteration
    return ('value', val['Storage']['storage']['buffer'].address.cast(
        val.type.template_argument(0).pointer()).dereference())

  def to_string(self):
    return 'llvm::Optional{}'.format('' if self.val['Storage']['hasVal'] else ' is not initialized')

class DenseMapPrinter:
  "Print a DenseMap"

  class _iterator:
    def __init__(self, key_info_t, begin, end):
      self.key_info_t = key_info_t
      self.cur = begin
      self.end = end
      self.advancePastEmptyBuckets()
      self.first = True

    def __iter__(self):
      return self

    def advancePastEmptyBuckets(self):
      # disabled until the comments below can be addressed
      # keeping as notes/posterity/hints for future contributors
      return
      n = self.key_info_t.name
      is_equal = gdb.parse_and_eval(n + '::isEqual')
      empty = gdb.parse_and_eval(n + '::getEmptyKey()')
      tombstone = gdb.parse_and_eval(n + '::getTombstoneKey()')
      # the following is invalid, GDB fails with:
      #   Python Exception <class 'gdb.error'> Attempt to take address of value
      #   not located in memory.
      # because isEqual took parameter (for the unsigned long key I was testing)
      # by const ref, and GDB
      # It's also not entirely general - we should be accessing the "getFirst()"
      # member function, not the 'first' member variable, but I've yet to figure
      # out how to find/call member functions (especially (const) overloaded
      # ones) on a gdb.Value.
      while self.cur != self.end and (is_equal(self.cur.dereference()['first'], empty) or is_equal(self.cur.dereference()['first'], tombstone)):
        self.cur = self.cur + 1

    def next(self):
      if self.cur == self.end:
        raise StopIteration
      cur = self.cur
      v = cur.dereference()['first' if self.first else 'second']
      if not self.first:
        self.cur = self.cur + 1
        self.advancePastEmptyBuckets()
        self.first = True
      else:
        self.first = False
      return 'x', v

    __next__ = next

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

  def children(self):
    t = self.val.type.template_argument(3).pointer()
    begin = self.val['Buckets'].cast(t)
    end = (begin + self.val['NumBuckets']).cast(t)
    return self._iterator(self.val.type.template_argument(2), begin, end)

  def to_string(self):
    return 'llvm::DenseMap with %d elements' % (self.val['NumEntries'])

  def display_hint(self):
    return 'map'

class TwinePrinter:
  "Print a Twine"

  def __init__(self, val):
    self._val = val

  def display_hint(self):
    return 'string'

  def string_from_pretty_printer_lookup(self, val):
    '''Lookup the default pretty-printer for val and use it.

    If no pretty-printer is defined for the type of val, print an error and
    return a placeholder string.'''

    pp = gdb.default_visualizer(val)
    if pp:
      s = pp.to_string()

      # The pretty-printer may return a LazyString instead of an actual Python
      # string.  Convert it to a Python string.  However, GDB doesn't seem to
      # register the LazyString type, so we can't check
      # "type(s) == gdb.LazyString".
      if 'LazyString' in type(s).__name__:
        s = s.value().address.string()

    else:
      print(('No pretty printer for {} found. The resulting Twine ' +
             'representation will be incomplete.').format(val.type.name))
      s = '(missing {})'.format(val.type.name)

    return s

  def is_twine_kind(self, kind, expected):
    if not kind.endswith(expected):
      return False
    # apparently some GDB versions add the NodeKind:: namespace
    # (happens for me on GDB 7.11)
    return kind in ('llvm::Twine::' + expected,
                    'llvm::Twine::NodeKind::' + expected)

  def string_from_child(self, child, kind):
    '''Return the string representation of the Twine::Child child.'''

    if self.is_twine_kind(kind, 'EmptyKind') or self.is_twine_kind(kind, 'NullKind'):
      return ''

    if self.is_twine_kind(kind, 'TwineKind'):
      return self.string_from_twine_object(child['twine'].dereference())

    if self.is_twine_kind(kind, 'CStringKind'):
      return child['cString'].string()

    if self.is_twine_kind(kind, 'StdStringKind'):
      val = child['stdString'].dereference()
      return self.string_from_pretty_printer_lookup(val)

    if self.is_twine_kind(kind, 'StringRefKind'):
      val = child['stringRef'].dereference()
      pp = StringRefPrinter(val)
      return pp.to_string()

    if self.is_twine_kind(kind, 'SmallStringKind'):
      val = child['smallString'].dereference()
      pp = SmallStringPrinter(val)
      return pp.to_string()

    if self.is_twine_kind(kind, 'CharKind'):
      return chr(child['character'])

    if self.is_twine_kind(kind, 'DecUIKind'):
      return str(child['decUI'])

    if self.is_twine_kind(kind, 'DecIKind'):
      return str(child['decI'])

    if self.is_twine_kind(kind, 'DecULKind'):
      return str(child['decUL'].dereference())

    if self.is_twine_kind(kind, 'DecLKind'):
      return str(child['decL'].dereference())

    if self.is_twine_kind(kind, 'DecULLKind'):
      return str(child['decULL'].dereference())

    if self.is_twine_kind(kind, 'DecLLKind'):
      return str(child['decLL'].dereference())

    if self.is_twine_kind(kind, 'UHexKind'):
      val = child['uHex'].dereference()
      return hex(int(val))

    print(('Unhandled NodeKind {} in Twine pretty-printer. The result will be '
           'incomplete.').format(kind))

    return '(unhandled {})'.format(kind)

  def string_from_twine_object(self, twine):
    '''Return the string representation of the Twine object twine.'''

    lhs_str = ''
    rhs_str = ''

    lhs = twine['LHS']
    rhs = twine['RHS']
    lhs_kind = str(twine['LHSKind'])
    rhs_kind = str(twine['RHSKind'])

    lhs_str = self.string_from_child(lhs, lhs_kind)
    rhs_str = self.string_from_child(rhs, rhs_kind)

    return lhs_str + rhs_str

  def to_string(self):
    return self.string_from_twine_object(self._val)

pp = gdb.printing.RegexpCollectionPrettyPrinter("LLVMSupport")
pp.add_printer('llvm::SmallString', '^llvm::SmallString<.*>$', SmallStringPrinter)
pp.add_printer('llvm::StringRef', '^llvm::StringRef$', StringRefPrinter)
pp.add_printer('llvm::SmallVectorImpl', '^llvm::SmallVector(Impl)?<.*>$', SmallVectorPrinter)
pp.add_printer('llvm::ArrayRef', '^llvm::(Const)?ArrayRef<.*>$', ArrayRefPrinter)
pp.add_printer('llvm::Expected', '^llvm::Expected<.*>$', ExpectedPrinter)
pp.add_printer('llvm::Optional', '^llvm::Optional<.*>$', OptionalPrinter)
pp.add_printer('llvm::DenseMap', '^llvm::DenseMap<.*>$', DenseMapPrinter)
pp.add_printer('llvm::Twine', '^llvm::Twine$', TwinePrinter)
gdb.printing.register_pretty_printer(gdb.current_objfile(), pp)


text:
@import OBAKit;

@implementation MKMapView (oba_Additions)

- (MKCoordinateSpan)oba_coordinateSpanWithCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate zoomLevel:(NSUInteger)zoomLevel
{
    return [OBAMapHelpers coordinateSpanWithCenterCoordinate:centerCoordinate zoomLevel:zoomLevel viewSize:self.bounds.size];
}

- (void)oba_setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated
{
    // clamp large numbers to 28
    zoomLevel = MIN(zoomLevel, 28);

    // use the zoom level to compute the region
    MKCoordinateSpan span = [self oba_coordinateSpanWithCenterCoordinate:centerCoordinate zoomLevel:zoomLevel];
    MKCoordinateRegion region = MKCoordinateRegionMake(centerCoordinate, span);

    // set the region like normal
    [self setRegion:region animated:animated];
}

@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of CCONJ in UD_Telugu</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Telugu: POS Tags: CCONJ

There are 1 CCONJ lemmas (7%), 5 CCONJ types (0%) and 12 CCONJ tokens (0%).
Out of 14 observed tags, the rank of CCONJ is: 4 in number of lemmas, 14 in number of types and 14 in number of tokens.

The 10 most frequent CCONJ lemmas: _

The 10 most frequent CCONJ types:  గాని, కాకుండా, కాని, గానీ, మధ్య

The 10 most frequent ambiguous lemmas: _ (<tt>PUNCT</tt> 1464, <tt>VERB</tt> 1463, <tt>NOUN</tt> 1440, <tt>PRON</tt> 1107, <tt>ADV</tt> 255, <tt>PROPN</tt> 254, <tt>DET</tt> 161, <tt>NUM</tt> 92, <tt>ADJ</tt> 64, <tt>ADP</tt> 58, <tt>SCONJ</tt> 56, <tt>PART</tt> 23, <tt>INTJ</tt> 16, <tt>CCONJ</tt> 12)

The 10 most frequent ambiguous types:  గాని (<tt>CCONJ</tt> 5, <tt>SCONJ</tt> 3), మధ్య (<tt>ADP</tt> 1, <tt>ADV</tt> 1, <tt>CCONJ</tt> 1)

గాని

<tt>CCONJ</tt> 5: రాము బాగా డబ్బు సంపాయిస్తాడు గాని , పైసా ఖర్చు పెట్టడు .

<tt>SCONJ</tt> 3: మీరు ఉంటే గాని , నేను రాను .

మధ్య

<tt>ADP</tt> 1: తెనాలి బెజవాడల మధ్య అన్ని కాలవల్లోనూ ఈదేను .

<tt>ADV</tt> 1: ఈ మధ్య హైదరాబాద్ వెళ్ళేను .

<tt>CCONJ</tt> 1: యాభై , వంద మధ్య సంపాదిస్తున్నాడట .

Morphology

The form / lemma ratio of CCONJ is 5.000000 (the average of all parts of speech is 153.500000).

The 1st highest number of forms (5) was observed with the lemma "_": కాకుండా, కాని, గాని, గానీ, మధ్య.

CCONJ does not occur with any features.

Relations

CCONJ nodes are attached to their parents using 2 different relations: <tt>cc</tt> (11; 92% instances), <tt>mark</tt> (1; 8% instances)

Parents of CCONJ nodes belong to 4 different parts of speech: <tt>NOUN</tt> (6; 50% instances), <tt>VERB</tt> (3; 25% instances), <tt>PRON</tt> (2; 17% instances), <tt>NUM</tt> (1; 8% instances)

12 (100%) CCONJ nodes are leaves.

The highest child degree of a CCONJ node is 0.

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
package com.evolveum.midpoint.web.page.admin;

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

import javax.xml.namespace.QName;

import com.evolveum.midpoint.schema.util.AdminGuiConfigTypeUtil;
import com.evolveum.midpoint.web.component.prism.*;
import com.evolveum.midpoint.web.component.progress.ProgressPanel;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.Page;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.ajax.AbstractAjaxTimerBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.string.StringValue;

import com.evolveum.midpoint.gui.api.model.LoadableModel;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.RetrieveOption;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.AuthorizationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.ObjectSummaryPanel;
import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel;
import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage;
import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour;
import com.evolveum.midpoint.web.page.admin.users.dto.FocusSubwrapperDto;
import com.evolveum.midpoint.web.util.OnePageParameterEncoder;
import com.evolveum.midpoint.web.util.validation.MidpointFormValidator;
import com.evolveum.midpoint.web.util.validation.SimpleValidationError;
import org.apache.wicket.util.time.Duration;
import org.jetbrains.annotations.NotNull;

/**
 * @author semancik
 */
public abstract class PageAdminObjectDetails<O extends ObjectType> extends PageAdmin
		implements ProgressReportingAwarePage {
	private static final long serialVersionUID = 1L;

	private static final String DOT_CLASS = PageAdminObjectDetails.class.getName() + ".";

	public static final String PARAM_RETURN_PAGE = "returnPage";

	private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject";
	private static final String OPERATION_LOAD_PARENT_ORGS = DOT_CLASS + "loadParentOrgs";
	private static final String OPERATION_LOAD_GUI_CONFIGURATION = DOT_CLASS + "loadGuiConfiguration";
	protected static final String OPERATION_SAVE = DOT_CLASS + "save";
	protected static final String OPERATION_PREVIEW_CHANGES = DOT_CLASS + "previewChanges";
	protected static final String OPERATION_SEND_TO_SUBMIT = DOT_CLASS + "sendToSubmit";

	protected static final String ID_SUMMARY_PANEL = "summaryPanel";
	protected static final String ID_MAIN_PANEL = "mainPanel";
	private static final String ID_PROGRESS_PANEL = "progressPanel";

	private static final Trace LOGGER = TraceManager.getTrace(PageAdminObjectDetails.class);

	private LoadableModel<ObjectWrapper<O>> objectModel;
	private LoadableModel<List<FocusSubwrapperDto<OrgType>>> parentOrgModel;

	private ProgressPanel progressPanel;

	// used to determine whether to leave this page or stay on it (after
	// operation finishing)
	private ObjectDelta<O> delta;

	private AbstractObjectMainPanel<O> mainPanel;
	private boolean saveOnConfigure;		// ugly hack - whether to invoke 'Save' when returning to this page

	private boolean editingFocus = false; 			//before we got isOidParameterExists status depending only on oid parameter existence
													//we should set editingFocus=true not only when oid parameter exists but also
													//when object is given as a constructor parameter

	public boolean isEditingFocus() {
		return editingFocus;
	}

	@Override
	protected void createBreadcrumb() {
		createInstanceBreadcrumb();
	}

	@Override
	protected void onConfigure() {
		super.onConfigure();
		if (saveOnConfigure) {
			saveOnConfigure = false;
			add(new AbstractAjaxTimerBehavior(Duration.milliseconds(100)) {
				@Override
				protected void onTimer(AjaxRequestTarget target) {
					stop(target);
					savePerformed(target);
				}
			});
		}
	}

	@Override
	protected IModel<String> createPageTitleModel() {
		return new LoadableModel<String>() {
			private static final long serialVersionUID = 1L;

			@Override
			protected String load() {
				if (!isOidParameterExists() && !editingFocus) {
					String key = "PageAdminObjectDetails.title.new" + getCompileTimeClass().getSimpleName();
					return createStringResource(key).getObject();
				}

				String name = null;
				if (getObjectWrapper() != null && getObjectWrapper().getObject() != null) {
					name = WebComponentUtil.getName(getObjectWrapper().getObject());
				}

				String key = (getObjectWrapper().isReadonly() ? "PageAdminObjectDetails.title.view" : "PageAdminObjectDetails.title.edit")
						+ getCompileTimeClass().getSimpleName();
				return createStringResource(key, name).getObject();
			}
		};
	}

	public LoadableModel<ObjectWrapper<O>> getObjectModel() {
		return objectModel;
	}

	public LoadableModel<List<FocusSubwrapperDto<OrgType>>> getParentOrgModel() {
		return parentOrgModel;
	}

	protected AbstractObjectMainPanel<O> getMainPanel() {
		return mainPanel;
	}

	public ObjectWrapper<O> getObjectWrapper() {
		return objectModel.getObject();
	}

	public List<FocusSubwrapperDto<OrgType>> getParentOrgs() {
		return parentOrgModel.getObject();
	}

	public ObjectDelta<O> getDelta() {
		return delta;
	}

	public void setDelta(ObjectDelta<O> delta) {
		this.delta = delta;
	}

	public ProgressPanel getProgressPanel() {
		return progressPanel;
	}

	protected void reviveModels() throws SchemaException {
		WebComponentUtil.revive(objectModel, getPrismContext());
		WebComponentUtil.revive(parentOrgModel, getPrismContext());
	}

	public abstract Class<O> getCompileTimeClass();

	public void initialize(final PrismObject<O> objectToEdit) {
		boolean isNewObject = objectToEdit == null;

		initialize(objectToEdit, isNewObject, false);
	}

	public void initialize(final PrismObject<O> objectToEdit, boolean isNewObject) {
		initialize(objectToEdit, isNewObject, false);
	}

	public void initialize(final PrismObject<O> objectToEdit, boolean isNewObject, boolean isReadonly) {
		initializeModel(objectToEdit, isNewObject, isReadonly);
		initLayout();
	}

	protected void initializeModel(final PrismObject<O> objectToEdit, boolean isNewObject, boolean isReadonly) {
		editingFocus = !isNewObject;

		objectModel = new LoadableModel<ObjectWrapper<O>>(false) {
			private static final long serialVersionUID = 1L;

			@Override
			protected ObjectWrapper<O> load() {
				ObjectWrapper<O> wrapper = loadObjectWrapper(objectToEdit, isReadonly);
				wrapper.sort();
				return wrapper;
			}
		};

		parentOrgModel = new LoadableModel<List<FocusSubwrapperDto<OrgType>>>(false) {
			private static final long serialVersionUID = 1L;

			@Override
			protected List<FocusSubwrapperDto<OrgType>> load() {
				return loadOrgWrappers();
			}
		};
	}

	protected List<FocusSubwrapperDto<OrgType>> loadOrgWrappers() {
		// WRONG!! TODO: fix
		return null;
	}

	protected abstract O createNewObject();

	protected void initLayout() {
		initLayoutSummaryPanel();

		mainPanel = createMainPanel(ID_MAIN_PANEL);
		mainPanel.setOutputMarkupId(true);
		add(mainPanel);

		progressPanel = new ProgressPanel(ID_PROGRESS_PANEL);
		add(progressPanel);
	}

	protected abstract ObjectSummaryPanel<O> createSummaryPanel();

	protected void initLayoutSummaryPanel() {

		ObjectSummaryPanel<O> summaryPanel = createSummaryPanel();
		summaryPanel.setOutputMarkupId(true);

		setSummaryPanelVisibility(summaryPanel);
		add(summaryPanel);
	}

    protected void setSummaryPanelVisibility(ObjectSummaryPanel<O> summaryPanel){
        summaryPanel.add(new VisibleEnableBehaviour() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean isVisible() {
                return isOidParameterExists() || editingFocus;
            }
        });
    }

	protected abstract AbstractObjectMainPanel<O> createMainPanel(String id);

	protected String getObjectOidParameter() {
		PageParameters parameters = getPageParameters();
		LOGGER.trace("Page parameters: {}", parameters);
		StringValue oidValue = parameters.get(OnePageParameterEncoder.PARAMETER);
		LOGGER.trace("OID parameter: {}", oidValue);
		if (oidValue == null) {
			return null;
		}
		String oid = oidValue.toString();
		if (StringUtils.isBlank(oid)) {
			return null;
		}
		return oid;
	}

	public boolean isOidParameterExists() {
		return getObjectOidParameter() != null;
	}

	protected ObjectWrapper<O> loadObjectWrapper(PrismObject<O> objectToEdit, boolean isReadonly) {
		Task task = createSimpleTask(OPERATION_LOAD_OBJECT);
		OperationResult result = task.getResult();
		PrismObject<O> object = null;
		Collection<SelectorOptions<GetOperationOptions>> loadOptions = null;
		try {
			if (!isOidParameterExists()) {
				if (objectToEdit == null) {
					LOGGER.trace("Loading object: New object (creating)");
					O focusType = createNewObject();
					getMidpointApplication().getPrismContext().adopt(focusType);
					object = (PrismObject<O>) focusType.asPrismObject();
				} else {
					LOGGER.trace("Loading object: New object (supplied): {}", objectToEdit);
					object = objectToEdit;
				}
			} else {

				loadOptions = SelectorOptions.createCollection(UserType.F_JPEG_PHOTO,
						GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));

				String focusOid = getObjectOidParameter();
				object = WebModelServiceUtils.loadObject(getCompileTimeClass(), focusOid, loadOptions, this, task,
						result);

				LOGGER.trace("Loading object: Existing object (loadled): {} -> {}", focusOid, object);
			}

			result.recordSuccess();
		} catch (Exception ex) {
			result.recordFatalError("Couldn't get object.", ex);
			LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex);
		}

		showResult(result, false);

		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("Loaded object:\n{}", object.debugDump());
		}

		if (object == null) {
			if (isOidParameterExists()) {
				getSession().error(getString("pageAdminFocus.message.cantEditFocus"));
			} else {
				getSession().error(getString("pageAdminFocus.message.cantNewFocus"));
			}
			throw new RestartResponseException(getRestartResponsePage());
		}

		ContainerStatus status = isOidParameterExists() || editingFocus ? ContainerStatus.MODIFYING : ContainerStatus.ADDING;
		ObjectWrapper<O> wrapper;
		ObjectWrapperFactory owf = new ObjectWrapperFactory(this);
		try {
			wrapper = owf.createObjectWrapper("pageAdminFocus.focusDetails", null, object, status, isReadonly, task);
		} catch (Exception ex) {
			result.recordFatalError("Couldn't get user.", ex);
			LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load user", ex);
			try {
				wrapper = owf.createObjectWrapper("pageAdminFocus.focusDetails", null, object, null, null, status, task);
			} catch (SchemaException e) {
				throw new SystemException(e.getMessage(), e);
			}
		}
		wrapper.setLoadOptions(loadOptions);

		showResult(wrapper.getResult(), false);

		loadParentOrgs(wrapper, task, result);

		wrapper.setShowEmpty(!isOidParameterExists() && !editingFocus);
		wrapper.setReadonly(isReadonly);

		if (LOGGER.isTraceEnabled()) {
			LOGGER.trace("Loaded focus wrapper:\n{}", wrapper.debugDump());
		}

		return wrapper;
	}

	private void loadParentOrgs(ObjectWrapper<O> wrapper, Task task, OperationResult result) {
		OperationResult subResult = result.createMinorSubresult(OPERATION_LOAD_PARENT_ORGS);
		PrismObject<O> focus = wrapper.getObject();
		// Load parent organizations (full objects). There are used in the
		// summary panel and also in the main form.
		// Do it here explicitly instead of using resolve option to have ability
		// to better handle (ignore) errors.
		for (ObjectReferenceType parentOrgRef : focus.asObjectable().getParentOrgRef()) {

			PrismObject<OrgType> parentOrg = null;
			try {

				parentOrg = getModelService().getObject(OrgType.class, parentOrgRef.getOid(), null, task,
						subResult);
				LOGGER.trace("Loaded parent org with result {}",
						new Object[] { subResult.getLastSubresult() });
			} catch (AuthorizationException e) {
				// This can happen if the user has permission to read parentOrgRef but it does not have
				// the permission to read target org
				// It is OK to just ignore it.
				subResult.muteLastSubresultError();
				LOGGER.debug("User {} does not have permission to read parent org unit {} (ignoring error)", task.getOwner().getName(), parentOrgRef.getOid());
			} catch (Exception ex) {
				subResult.recordWarning("Cannot load parent org " + parentOrgRef.getOid(), ex);
				LOGGER.warn("Cannot load parent org {}: {}", parentOrgRef.getOid(), ex.getMessage(), ex);
			}

			if (parentOrg != null) {
				wrapper.getParentOrgs().add(parentOrg);
			}
		}
		subResult.computeStatus();
	}

	protected abstract Class<? extends Page> getRestartResponsePage();

	public Object findParam(String param, String oid, OperationResult result) {

		Object object = null;

		for (OperationResult subResult : result.getSubresults()) {
			if (subResult != null && subResult.getParams() != null) {
				if (subResult.getParams().get(param) != null
						&& subResult.getParams().get(OperationResult.PARAM_OID) != null
						&& subResult.getParams().get(OperationResult.PARAM_OID).equals(oid)) {
					return subResult.getParams().get(param);
				}
				object = findParam(param, oid, subResult);

			}
		}
		return object;
	}

	// TODO put this into correct place
	protected boolean previewRequested;

	/**
	 * This will be called from the main form when save button is pressed.
	 */
	public void savePerformed(AjaxRequestTarget target) {
		progressPanel.onBeforeSave();
		OperationResult result = new OperationResult(OPERATION_SAVE);
		previewRequested = false;
		saveOrPreviewPerformed(target, result, false);
	}

	public void previewPerformed(AjaxRequestTarget target) {
		progressPanel.onBeforeSave();
		OperationResult result = new OperationResult(OPERATION_PREVIEW_CHANGES);
		previewRequested = true;
		saveOrPreviewPerformed(target, result, true);
	}

	public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly) {
		saveOrPreviewPerformed(target, result, previewOnly, null);
	}

	public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly, Task task) {
		boolean delegationChangesExist = processDeputyAssignments(previewOnly);

		ObjectWrapper<O> objectWrapper = getObjectWrapper();
		LOGGER.debug("Saving object {}", objectWrapper);

		// todo: improve, delta variable is quickfix for MID-1006
		// redirecting to user list page everytime user is created in repository
		// during user add in gui,
		// and we're not taking care about account/assignment create errors
		// (error message is still displayed)
		delta = null;

		if(task == null) {
		task = createSimpleTask(OPERATION_SEND_TO_SUBMIT);
		}

		ModelExecuteOptions options = getOptions(previewOnly);

		LOGGER.debug("Using execute options {}.", options);

		try {
			reviveModels();

			delta = objectWrapper.getObjectDelta();
			if (objectWrapper.getOldDelta() != null) {
				delta = ObjectDelta.summarize(objectWrapper.getOldDelta(), delta);
			}
			if (LOGGER.isTraceEnabled()) {
				LOGGER.trace("User delta computed from form:\n{}", new Object[] { delta.debugDump(3) });
			}
		} catch (Exception ex) {
			result.recordFatalError(getString("pageUser.message.cantCreateUser"), ex);
			LoggingUtils.logUnexpectedException(LOGGER, "Create user failed", ex);
			showResult(result);
			return;
		}

		switch (objectWrapper.getStatus()) {
			case ADDING:
				try {
					PrismObject<O> objectToAdd = delta.getObjectToAdd();
					WebComponentUtil.encryptCredentials(objectToAdd, true, getMidpointApplication());
					prepareObjectForAdd(objectToAdd);
					getPrismContext().adopt(objectToAdd, getCompileTimeClass());
					if (LOGGER.isTraceEnabled()) {
						LOGGER.trace("Delta before add user:\n{}", new Object[] { delta.debugDump(3) });
					}

					if (!delta.isEmpty()) {
						delta.revive(getPrismContext());

						final Collection<ObjectDelta<? extends ObjectType>> deltas = WebComponentUtil.createDeltaCollection(delta);
						final Collection<SimpleValidationError> validationErrors = performCustomValidation(objectToAdd, deltas);
						if (checkValidationErrors(target, validationErrors)) {
							return;
						}
						progressPanel.executeChanges(deltas, previewOnly, options, task, result, target);
					} else {
						result.recordSuccess();
					}
				} catch (Exception ex) {
					result.recordFatalError(getString("pageFocus.message.cantCreateFocus"), ex);
					LoggingUtils.logUnexpectedException(LOGGER, "Create user failed", ex);
					showResult(result);
				}
				break;

			case MODIFYING:
				try {
					WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication());
					prepareObjectDeltaForModify(delta);

					if (LOGGER.isTraceEnabled()) {
						LOGGER.trace("Delta before modify user:\n{}", new Object[] { delta.debugDump(3) });
					}

					Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<>();
					if (!delta.isEmpty()) {
						delta.revive(getPrismContext());
						deltas.add(delta);
					}

					List<ObjectDelta<? extends ObjectType>> additionalDeltas = getAdditionalModifyDeltas(result);
					if (additionalDeltas != null) {
						for (ObjectDelta additionalDelta : additionalDeltas) {
							if (!additionalDelta.isEmpty()) {
								additionalDelta.revive(getPrismContext());
								deltas.add(additionalDelta);
							}
						}
					}

					if (delta.isEmpty() && ModelExecuteOptions.isReconcile(options)) {
						ObjectDelta emptyDelta = ObjectDelta.createEmptyModifyDelta(getCompileTimeClass(),
								objectWrapper.getObject().getOid(), getPrismContext());
						deltas.add(emptyDelta);

						Collection<SimpleValidationError> validationErrors = performCustomValidation(null, deltas);
						if (checkValidationErrors(target, validationErrors)) {
							return;
						}
						progressPanel.executeChanges(deltas, previewOnly, options, task, result, target);
					} else if (!deltas.isEmpty()) {
						Collection<SimpleValidationError> validationErrors = performCustomValidation(null, deltas);
						if (checkValidationErrors(target, validationErrors)) {
							return;
						}
						progressPanel.executeChanges(deltas, previewOnly, options, task, result, target);
					} else if (previewOnly && delta.isEmpty() && delegationChangesExist){
						progressPanel.executeChanges(deltas, previewOnly, options, task, result, target);
					} else {
						progressPanel.clearProgressPanel();			// from previous attempts (useful only if we would call finishProcessing at the end, but that's not the case now)
						if (!previewOnly) {
							if (!delegationChangesExist) {
								result.recordWarning(getString("PageAdminObjectDetails.noChangesSave"));
								showResult(result);
							}
							redirectBack();
						} else {
							if (!delegationChangesExist) {
								warn(getString("PageAdminObjectDetails.noChangesPreview"));
								target.add(getFeedbackPanel());
							}
						}
					}

				} catch (Exception ex) {
					if (!executeForceDelete(objectWrapper, task, options, result)) {
						result.recordFatalError(getString("pageUser.message.cantUpdateUser"), ex);
						LoggingUtils.logUnexpectedException(LOGGER, getString("pageUser.message.cantUpdateUser"), ex);
					} else {
						result.recomputeStatus();
					}
					showResult(result);
				}
				break;
			// support for add/delete containers (e.g. delete credentials)
			default:
				error(getString("pageAdminFocus.message.unsupportedState", objectWrapper.getStatus()));
		}

//		result.recomputeStatus();
//
//		if (!result.isInProgress()) {
//			LOGGER.trace("Result NOT in progress, calling finishProcessing");
//			finishProcessing(target, result, false);
//		}

		LOGGER.trace("returning from saveOrPreviewPerformed");
	}

	protected boolean processDeputyAssignments(boolean previewOnly){
		return false;
	}

	protected boolean checkValidationErrors(AjaxRequestTarget target, Collection<SimpleValidationError> validationErrors) {
		if (validationErrors != null && !validationErrors.isEmpty()) {
			for (SimpleValidationError error : validationErrors) {
				LOGGER.error("Validation error, attribute: '" + error.printAttribute()
						+ "', message: '" + error.getMessage() + "'.");
				error("Validation error, attribute: '" + error.printAttribute()
						+ "', message: '" + error.getMessage() + "'.");
			}

			target.add(getFeedbackPanel());
			return true;
		}
		return false;
	}

	@Override
	public void startProcessing(AjaxRequestTarget target, OperationResult result) {
		LOGGER.trace("startProcessing called, making main panel invisible");
		mainPanel.setVisible(false);
		target.add(mainPanel);
	}

	@NotNull
	protected ModelExecuteOptions getOptions(boolean previewOnly) {
		ModelExecuteOptions options = mainPanel.getExecuteChangeOptionsDto().createOptions();
		if (previewOnly) {
			options.getOrCreatePartialProcessing().setApprovals(PartialProcessingTypeType.PROCESS);
		}
		return options;
	}

	protected void prepareObjectForAdd(PrismObject<O> object) throws SchemaException {

	}

	protected void prepareObjectDeltaForModify(ObjectDelta<O> objectDelta) throws SchemaException {

	}

	protected List<ObjectDelta<? extends ObjectType>> getAdditionalModifyDeltas(OperationResult result) {
		return null;
	}

	protected boolean executeForceDelete(ObjectWrapper userWrapper, Task task, ModelExecuteOptions options,
			OperationResult parentResult) {
		return isForce();
	}

	protected boolean isForce() {
		return getMainPanel().getExecuteChangeOptionsDto().isForce();
	}

	protected boolean isKeepDisplayingResults() {
		return getMainPanel().getExecuteChangeOptionsDto().isKeepDisplayingResults();
	}

	protected Collection<SimpleValidationError> performCustomValidation(PrismObject<O> object,
			Collection<ObjectDelta<? extends ObjectType>> deltas) throws SchemaException {
		Collection<SimpleValidationError> errors = null;

		if (object == null) {
			if (getObjectWrapper() != null && getObjectWrapper().getObject() != null) {
				object = getObjectWrapper().getObject().clone();		// otherwise original object could get corrupted e.g. by applying the delta below

				for (ObjectDelta delta : deltas) {
					// because among deltas there can be also ShadowType deltas
					if (UserType.class.isAssignableFrom(delta.getObjectTypeClass())) {
						delta.applyTo(object);
					}
				}
			}
		} else {
			object = object.clone();
		}

		performAdditionalValidation(object, deltas, errors);

		for (MidpointFormValidator validator : getFormValidatorRegistry().getValidators()) {
			if (errors == null) {
				errors = validator.validateObject(object, deltas);
			} else {
				errors.addAll(validator.validateObject(object, deltas));
			}
		}

		return errors;
	}

	protected void performAdditionalValidation(PrismObject<O> object,
			Collection<ObjectDelta<? extends ObjectType>> deltas, Collection<SimpleValidationError> errors) throws SchemaException {

	}

	public List<ObjectFormType> getObjectFormTypes() {
		Task task = createSimpleTask(OPERATION_LOAD_GUI_CONFIGURATION);
		OperationResult result = task.getResult();
		AdminGuiConfigurationType adminGuiConfiguration;
		try {
			adminGuiConfiguration = getModelInteractionService().getAdminGuiConfiguration(task, result);
		} catch (ObjectNotFoundException | SchemaException e) {
			throw new SystemException("Cannot load GUI configuration: "+e.getMessage(), e);
		}
		ObjectFormsType objectFormsType = adminGuiConfiguration.getObjectForms();
		if (objectFormsType == null) {
			return null;
		}
		List<ObjectFormType> objectForms = objectFormsType.getObjectForm();
		if (objectForms == null || objectForms.isEmpty()) {
			return objectForms;
		}
		List<ObjectFormType> validObjectForms = new ArrayList<>();
		for (ObjectFormType objectForm: objectForms) {
			if (isSupportedObjectType(objectForm.getType())) {
				validObjectForms.add(objectForm);
			}
		}
		return validObjectForms;
	}

	protected boolean isSupportedObjectType(QName type) {
		ObjectTypes objectType = ObjectTypes.getObjectType(getCompileTimeClass());
		return QNameUtil.match(objectType.getTypeQName(),type);
	}

	public void setSaveOnConfigure(boolean saveOnConfigure) {
		this.saveOnConfigure = saveOnConfigure;
	}

	public boolean isSaveOnConfigure() {
		return saveOnConfigure;
	}

	public boolean isForcedPreview(){
		GuiObjectDetailsPageType objectDetails = AdminGuiConfigTypeUtil.findObjectConfiguration(getCompileTimeClass(), getAdminGuiConfiguration());
		return objectDetails != null && DetailsPageSaveMethodType.FORCED_PREVIEW.equals(objectDetails.getSaveMethod());
	}

}


text:
package de.uni.freiburg.iig.telematik.swat.patterns.logic.patterns;

public abstract class CoExists extends CandDPattern {

	private final String mName = "P CoExists Q";

	private final String mDescription = "The presence of P mandates that Q is also present";

	@Override
	public String getName() {
		return mName;
	}

	@Override
	public String getDescription() {
		return mDescription;
	}

}