text:
var searchbar = require('searchbar/searchbar.js')
var searchbarPlugins = require('searchbar/searchbarPlugins.js')
var searchbarAutocomplete = require('util/autocomplete.js')

var urlParser = require('util/urlParser.js')
var searchEngine = require('util/searchEngine.js')

var ddgAttribution = l('resultsFromDDG')

function removeTags (text) {
  return text.replace(/<.*?>/g, '')
}

// custom instant answers

var instantAnswers = {
  color_code: function (searchText, answer) {
    var data = {
      title: searchText,
      descriptionBlock: answer.replace(/\n/g, ' · ').replace(/\s~\s/g, ' · '),
      attribution: ddgAttribution
    }

    var rgb = answer.split(' ~ ').filter(function (format) {
      return format.startsWith('RGBA')
    })

    if (rgb[0]) {
      data.colorCircle = rgb[0]
    }

    return data
  },
  currency_in: function (searchText, answer) {
    var title = ''
    if (typeof answer === 'string') { // there is only one currency
      title = answer
    } else { // multiple currencies
      var currencyArr = []
      for (var countryCode in answer) {
        currencyArr.push(answer[countryCode] + ' (' + countryCode + ')')
      }

      title = currencyArr.join(', ')
    }

    var descriptionBlock
    if (answer.data) {
      descriptionBlock = answer.data.title
    } else {
      descriptionBlock = l('DDGAnswerSubtitle')
    }

    return {
      title: title,
      descriptionBlock: descriptionBlock,
      attribution: ddgAttribution
    }
  }
}

function showSearchbarInstantAnswers (text, input, event) {
  // only make requests to the DDG api if DDG is set as the search engine
  if (searchEngine.getCurrent().name !== 'DuckDuckGo') {
    return
  }

  // don't make a request if the searchbar has already closed

  if (!searchbar.associatedInput) {
    return
  }

  fetch('https://api.duckduckgo.com/?t=min&skip_disambig=1&no_redirect=1&format=json&q=' + encodeURIComponent(text)).then(function (data) {
    return data.json()
  }).then(function (res) {
    searchbarPlugins.reset('instantAnswers')

    var data

    const hasAnswer = instantAnswers[res.AnswerType] || (res.Answer && typeof res.Answer === 'string')

    // if there is a custom format for the answer, use that
    if (instantAnswers[res.AnswerType]) {
      data = instantAnswers[res.AnswerType](text, res.Answer)

    // use the default format
    } else if (res.Abstract || (res.Answer && typeof res.Answer === 'string')) {
      data = {
        title: (typeof res.Answer === 'string' && removeTags(res.Answer)) || removeTags(res.Heading),
        descriptionBlock: res.Abstract || l('DDGAnswerSubtitle'),
        attribution: ddgAttribution,
        url: res.AbstractURL || text
      }

      if (res.Image && !res.ImageIsLogo) {
        data.image = res.Image
        if (data.image.startsWith('/')) {
          // starting 11/2020, the DDG API returns relative URLs rather than absolute ones
          data.image = 'https://duckduckgo.com' + data.image
        }
      }

    // show a disambiguation
    } else if (res.RelatedTopics) {
      res.RelatedTopics.slice(0, 3).forEach(function (item) {
        // the DDG api returns the entity name inside an <a> tag
        var entityName = item.Result.replace(/.*>(.+?)<.*/g, '$1')

        // the text starts with the entity name, remove it
        var desc = item.Text.replace(entityName, '')

        // try to convert the given url to a wikipedia link
        var entityNameRegex = /https:\/\/duckduckgo.com\/(.*?)\/?$/

        var url
        if (entityNameRegex.test(item.FirstURL)) {
          url = 'https://wikipedia.org/wiki/' + entityNameRegex.exec(item.FirstURL)[1]
        } else {
          url = item.FirstURL
        }

        searchbarPlugins.addResult('instantAnswers', {
          title: entityName,
          descriptionBlock: desc,
          url: url
        }, { allowDuplicates: true })
      })
    }

    if (data) {
      // answers are more relevant, they should be displayed at the top
      if (hasAnswer) {
        searchbarPlugins.setTopAnswer('instantAnswers', data)
      } else {
        searchbarPlugins.addResult('instantAnswers', data, { allowDuplicates: true })
      }
    }

    // suggested site links
    if (searchbarPlugins.getResultCount('places') < 4 && res.Results && res.Results[0] && res.Results[0].FirstURL) {
      var url = res.Results[0].FirstURL

      const suggestedSiteData = {
        icon: 'carbon:earth-filled',
        title: urlParser.basicURL(url),
        url: url,
        classList: ['ddg-answer']
      }

      if (searchbarPlugins.getTopAnswer()) {
        searchbarPlugins.addResult('instantAnswers', suggestedSiteData)
      } else {
        if (event && event.keyCode !== 8) {
          // don't autocomplete if delete key pressed
          const autocompletionType = searchbarAutocomplete.autocompleteURL(input, url)

          if (autocompletionType !== -1) {
            suggestedSiteData.fakeFocus = true
          }
        }
        searchbarPlugins.setTopAnswer('instantAnswers', suggestedSiteData)
      }
    }

    // if we're showing a location, show a "Search on OpenStreetMap" link

    var entitiesWithLocations = ['location', 'country', 'u.s. state', 'protected area']

    if (entitiesWithLocations.indexOf(res.Entity) !== -1) {
      searchbarPlugins.addResult('instantAnswers', {
        icon: 'carbon:search',
        title: res.Heading,
        secondaryText: l('searchWith').replace('%s', 'OpenStreetMap'),
        classList: ['ddg-answer'],
        url: 'https://www.openstreetmap.org/search?query=' + encodeURIComponent(res.Heading)
      })
    }
  }).catch(function (e) {
    console.error(e)
  })
}

function initialize () {
  searchbarPlugins.register('instantAnswers', {
    index: 4,
    trigger: function (text) {
      return text.length > 3 && !urlParser.isPossibleURL(text) && !tabs.get(tabs.getSelected()).private
    },
    showResults: debounce(showSearchbarInstantAnswers, 150)
  })
}

module.exports = { initialize }


text:
package ru.stqa.pft.addressbook.appmanager;

import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.stqa.pft.addressbook.model.EditData;

/**
 * Created by igor on 15.02.2017.
 */
public class EditHelper extends HelperBase{

  public EditHelper(FirefoxDriver wd) {
    super(wd);
  }

  public void reternHomePage() {
      click(By.linkText("home page"));
  }

  public void addEditForm() {
      click(By.xpath("//div[@id='content']/form/input[21]"));
  }

  public void editForm(EditData editData) {
      click(By.name("firstname"));
      type(By.name("firstname"), editData.getFirstname());
      click(By.name("middlename"));
      type(By.name("middlename"), editData.getMiddlename());
      click(By.name("lastname"));
      type(By.name("lastname"), editData.getLastname());
      click(By.name("nickname"));
      type(By.name("nickname"), editData.getNickname());
      click(By.name("title"));
      type(By.name("title"), editData.getTitle());
      click(By.name("company"));
      type(By.name("company"), editData.getCompany());
      click(By.name("address"));
      type(By.name("address"), editData.getAddress());
      click(By.name("home"));
      type(By.name("home"), editData.getHome());
      click(By.name("mobile"));
      type(By.name("mobile"), editData.getMobile());
      click(By.name("work"));
      type(By.name("work"), editData.getWork());
      click(By.name("fax"));
      type(By.name("fax"), editData.getFax());
      click(By.name("email"));
      type(By.name("email"), editData.getEmail());
  }

  public void goToAddNewEdit() {
    click(By.linkText("add new"));
  }

  public void reternHome() {
    click(By.linkText("home"));
  }

  public void selectEdit() {
    click(By.xpath("//input[@id='10']"));
  }

  public void editEdit() {
    click(By.xpath("//table[@id='maintable']/tbody/tr[3]/td[8]/a/img"));
  }

  public void addUpdateEdit() {
    click(By.name("update"));
  }

  public void deleteSelectEdit() {
    click(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
  }

  public void conformEditDeletion() {
    wd.switchTo().alert().accept();
  }
  //public void editEdit() {
  //  click(By.xpath("//table[@id='maintable']/tbody/tr[3]/td[8]/a/img"));
  //}

}

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Framework.Cache;
using Entities;

namespace UI.Security
{
    public class Authorize : ActionFilterAttribute
    {
        private readonly string RoleName;
        public Authorize(string _RoleName)
        {
            RoleName = _RoleName.ToUpper();
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var cookie = filterContext.HttpContext.Request.Cookies.FirstOrDefault(x => x.Key == ".leathergoods");
            var user = (User)Cache.Get(cookie.Value);
            if (user == null)
                redirectToLogin(filterContext, cookie.Value);
            else {
                var valid = false;
                if(user.Roles != null) {
                    foreach(var role in user.Roles)
                    {
                        if(role.Name.ToUpper() == RoleName)
                        {
                            valid = true;
                            break;
                        }
                    }
                }
                if(!valid)
                    redirectToLogin(filterContext, cookie.Value);
                else {
                    filterContext.HttpContext.Items.Add("User", user.UserName);
                    filterContext.HttpContext.Items.Add("Role", user.Roles[0].Name.ToUpper());
                }
            }
        }

        private void redirectToLogin(ActionExecutingContext filterContext, string cookie)
        {
            filterContext.HttpContext.Items.Remove("User");
            filterContext.HttpContext.Items.Remove("Role");
            Cache.Remove(cookie);
            var fullname = filterContext.Controller.GetType().Name;
            var controller = fullname.Substring(0, fullname.Length - 10);
            filterContext.Result = new RedirectToActionResult("Login", "Home", new { redirectTo = controller });
        }
    }
}


text:
title: Introducing GraphiQL
---

In this guide, you'll be learning to use something called Graph_i_QL, a tool that helps you structure GraphQL queries correctly.

## What is Graph_i_QL?

Graph_i_QL is the GraphQL integrated development environment (IDE). It's a powerful (and all-around awesome) tool
you'll use often while building Gatsby websites.

You can access it when your site's development server is running--normally at
<http://localhost:8000/___graphql>.

## Example of using Graph_i_QL

When you have <http://localhost:8000/___graphql> open, it will look something like what this video shows. In the video below, watch someone poke around the built-in `Site` "type" and see what fields are available
on it—including the `siteMetadata` object.

<video controls="controls" autoplay="true" loop="true">
  <source type="video/mp4" src="/graphiql-explore.mp4"></source>

Your browser does not support the video element.

</video>

## How to use Graph_i_QL

When the development server is running for one of your Gatsby sites, open Graph_i_QL at <http://localhost:8000/___graphql> and play with your data! Press Ctrl + Space (or use Shift + Space as an alternate keyboard shortcut) to bring up the autocomplete window and Ctrl + Enter to run the GraphQL query.

Make sure to check out the Graph_i_QL docs in the upper right-hand corner of the IDE. It's easy to miss them, but they're worth visiting!

![A diagram pointing out where to find the GraphiQl docs](images/graphiql-docs.png)

## Other resources

- See [Tutorial Part 5: Source Plugins](/tutorial/part-five/) for a more complete example of using Graph_i_QL
- See the [READme for Graph_i_QL](https://github.com/graphql/graphiql)


text:
/**
 *
 */
package com.greengrid;

import org.apache.log4j.Logger;

/**
 * @author user
 *
 */
public class TestMessageListener implements MessageListener{

	private static final Logger log = Logger.getLogger(TestMessageListener.class);

	public void messageReceived(MessageEvent event) {
		log.info("messageReceived");
	}

}


text:
#import <XXUnknownSuperclass.h> // Unknown library

@class NSString;

__attribute__((visibility("hidden")))
@interface Model_db_survival_category : XXUnknownSuperclass {
	NSString* _name;
	int _cid;
}
@property(assign, nonatomic) int cid;
@property(copy, nonatomic) NSString* name;
- (void).cxx_destruct;
@end


text:
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
//   contributors may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//

namespace NLog
{
    using System;

    /// <summary>
    /// Nested Diagnostics Context - for log4net compatibility.
    /// </summary>
    [Obsolete("Use NestedDiagnosticsContext")]
    public static class NDC
    {
        /// <summary>
        /// Gets the top NDC message but doesn't remove it.
        /// </summary>
        /// <returns>The top message. .</returns>
        public static string TopMessage
        {
            get { return NestedDiagnosticsContext.TopMessage; }
        }

        /// <summary>
        /// Gets the top NDC object but doesn't remove it.
        /// </summary>
        /// <returns>The object from the top of the NDC stack, if defined; otherwise <c>null</c>.</returns>
        public static object TopObject
        {
            get { return NestedDiagnosticsContext.TopObject; }
        }

        /// <summary>
        /// Pushes the specified text on current thread NDC.
        /// </summary>
        /// <param name="text">The text to be pushed.</param>
        /// <returns>An instance of the object that implements IDisposable that returns the stack to the previous level when IDisposable.Dispose() is called. To be used with C# using() statement.</returns>
        public static IDisposable Push(string text)
        {
            return NestedDiagnosticsContext.Push(text);
        }

        /// <summary>
        /// Pops the top message off the NDC stack.
        /// </summary>
        /// <returns>The top message which is no longer on the stack.</returns>
        public static string Pop()
        {
            return NestedDiagnosticsContext.Pop();
        }

        /// <summary>
        /// Pops the top object off the NDC stack. The object is removed from the stack.
        /// </summary>
        /// <returns>The top object from the NDC stack, if defined; otherwise <c>null</c>.</returns>
        public static object PopObject()
        {
            return NestedDiagnosticsContext.PopObject();
        }

        /// <summary>
        /// Clears current thread NDC stack.
        /// </summary>
        public static void Clear()
        {
            NestedDiagnosticsContext.Clear();
        }

        /// <summary>
        /// Gets all messages on the stack.
        /// </summary>
        /// <returns>Array of strings on the stack.</returns>
        public static string[] GetAllMessages()
        {
            return NestedDiagnosticsContext.GetAllMessages();
        }

        /// <summary>
        /// Gets all objects on the NDC stack. The objects are not removed from the stack.
        /// </summary>
        /// <returns>Array of objects on the stack.</returns>
        public static object[] GetAllObjects()
        {
            return NestedDiagnosticsContext.GetAllObjects();
        }
    }
}


text:
import { expect } from 'chai';
import * as sinon from 'sinon';
import { animationFrameScheduler, Subscription, merge } from 'rxjs';
import { delay } from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';
import { observableMatcher } from '../helpers/observableMatcher';
import { animationFrameProvider } from 'rxjs/internal/scheduler/animationFrameProvider';
import { intervalProvider } from 'rxjs/internal/scheduler/intervalProvider';

const animationFrame = animationFrameScheduler;

/** @test {Scheduler} */
describe('Scheduler.animationFrame', () => {
  let testScheduler: TestScheduler;

  beforeEach(() => {
    testScheduler = new TestScheduler(observableMatcher);
  });

  it('should exist', () => {
    expect(animationFrame).exist;
  });

  it('should act like the async scheduler if delay > 0', () => {
    testScheduler.run(({ animate, cold, expectObservable, time }) => {
      animate('         ----------x--');
      const a = cold('  a            ');
      const ta = time(' ----|        ');
      const b = cold('  b            ');
      const tb = time(' --------|    ');
      const expected = '----a---b----';

      const result = merge(
        a.pipe(delay(ta, animationFrame)),
        b.pipe(delay(tb, animationFrame))
      );
      expectObservable(result).toBe(expected);
    });
  });

  it('should cancel animationFrame actions when delay > 0', () => {
    testScheduler.run(({ animate, cold, expectObservable, flush, time }) => {
      const requestSpy = sinon.spy(animationFrameProvider, 'requestAnimationFrame');
      const setSpy = sinon.spy(intervalProvider, 'setInterval');
      const clearSpy = sinon.spy(intervalProvider, 'clearInterval');

      animate('         ----------x--');
      const a = cold('  a            ');
      const ta = time(' ----|        ');
      const subs = '    ^-!          ';
      const expected = '-------------';

      const result = merge(
        a.pipe(delay(ta, animationFrame))
      );
      expectObservable(result, subs).toBe(expected);

      flush();
      expect(requestSpy).to.have.not.been.called;
      expect(setSpy).to.have.been.calledOnce;
      expect(clearSpy).to.have.been.calledOnce;
      requestSpy.restore();
      setSpy.restore();
      clearSpy.restore();
    });
  });

  it('should schedule an action to happen later', (done: MochaDone) => {
    let actionHappened = false;
    animationFrame.schedule(() => {
      actionHappened = true;
      done();
    });
    if (actionHappened) {
      done(new Error('Scheduled action happened synchronously'));
    }
  });

  it('should execute recursively scheduled actions in separate asynchronous contexts', (done: MochaDone) => {
    let syncExec1 = true;
    let syncExec2 = true;
    animationFrame.schedule(function (index) {
      if (index === 0) {
        this.schedule(1);
        animationFrame.schedule(() => { syncExec1 = false; });
      } else if (index === 1) {
        this.schedule(2);
        animationFrame.schedule(() => { syncExec2 = false; });
      } else if (index === 2) {
        this.schedule(3);
      } else if (index === 3) {
        if (!syncExec1 && !syncExec2) {
          done();
        } else {
          done(new Error('Execution happened synchronously.'));
        }
      }
    }, 0, 0);
  });

  it('should cancel the animation frame if all scheduled actions unsubscribe before it executes', (done: MochaDone) => {
    let animationFrameExec1 = false;
    let animationFrameExec2 = false;
    const action1 = animationFrame.schedule(() => { animationFrameExec1 = true; });
    const action2 = animationFrame.schedule(() => { animationFrameExec2 = true; });
    expect(animationFrame.scheduled).to.exist;
    expect(animationFrame.actions.length).to.equal(2);
    action1.unsubscribe();
    action2.unsubscribe();
    expect(animationFrame.actions.length).to.equal(0);
    expect(animationFrame.scheduled).to.equal(undefined);
    animationFrame.schedule(() => {
      expect(animationFrameExec1).to.equal(false);
      expect(animationFrameExec2).to.equal(false);
      done();
    });
  });

  it('should execute the rest of the scheduled actions if the first action is canceled', (done: MochaDone) => {
    let actionHappened = false;
    let secondSubscription: Subscription | null = null;

    const firstSubscription = animationFrame.schedule(() => {
      actionHappened = true;
      if (secondSubscription) {
        secondSubscription.unsubscribe();
      }
      done(new Error('The first action should not have executed.'));
    });

    secondSubscription = animationFrame.schedule(() => {
      if (!actionHappened) {
        done();
      }
    });

    if (actionHappened) {
      done(new Error('Scheduled action happened synchronously'));
    } else {
      firstSubscription.unsubscribe();
    }
  });

  it('should not execute rescheduled actions when flushing', (done: MochaDone) => {
    let flushCount = 0;
    let scheduledIndices: number[] = [];

    let originalFlush = animationFrame.flush;
    animationFrame.flush = (...args) => {
      ++flushCount;
      originalFlush.apply(animationFrame, args);
      if (flushCount === 2) {
        animationFrame.flush = originalFlush;
        try {
          expect(scheduledIndices).to.deep.equal([0, 1]);
          done();
        } catch (error) {
          done(error);
        }
      }
    };

    animationFrame.schedule(function (index) {
      if (flushCount < 2) {
        this.schedule(index! + 1);
        scheduledIndices.push(index! + 1);
      }
    }, 0, 0);
    scheduledIndices.push(0);
  });
});


text:
using System.IO;
using OpenSage.Data.Ini;
using OpenSage.FileFormats;

namespace OpenSage.Logic.Object
{
    public sealed class SupplyWarehouseCreate : CreateModule
    {
        internal override void Load(BinaryReader reader)
        {
            var version = reader.ReadVersion();
            if (version != 1)
            {
                throw new InvalidDataException();
            }

            base.Load(reader);
        }
    }

    /// <summary>
    /// Ensures the object acts as a source for supply collection.
    /// </summary>
    public sealed class SupplyWarehouseCreateModuleData : CreateModuleData
    {
        internal static SupplyWarehouseCreateModuleData Parse(IniParser parser) => parser.ParseBlock(FieldParseTable);

        private static readonly IniParseTable<SupplyWarehouseCreateModuleData> FieldParseTable = new IniParseTable<SupplyWarehouseCreateModuleData>();

        internal override BehaviorModule CreateModule(GameObject gameObject, GameContext context)
        {
            return new SupplyWarehouseCreate();
        }
    }
}


text:
class CreatePages < ActiveRecord::Migration[5.0]
  def change
    create_table :pages do |t|
      t.string :image
      t.string :attachment

      t.timestamps
    end
  end
end


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

namespace HL7v23Store.Model
{
    class MFN
    {
        public decimal MessageControlId { get; set; }
        public decimal DoctorNumber { get; set; }
        public char PlanId { get; set; }
        public decimal InsuranceCompanyNumber { get; set; }
    }
}


text:
import functools
import pkg_resources

from setuptools import setup, find_packages

from pip.req import parse_requirements as parse_reqs

# Compatibility with older versions of pip
pip_dist = pkg_resources.get_distribution('pip')
pip_version = tuple(map(int, pip_dist.version.split('.')))

# Use a base partial that will be updated depending on the version of pip
parse_requirements = functools.partial(parse_reqs, options=None)

if pip_version < (1, 2):
    # pip versions before 1.2 require an options keyword for using it outside
    # of invoking a pip shell command
    from pip.baseparser import parser
    parse_requirements.keywords['options'] = parser.parse_args()[0]

if pip_version >= (1, 5):
    # pip 1.5 introduced a session kwarg that is required in later versions
    from pip.download import PipSession
    parse_requirements.keywords['session'] = PipSession()

setup(
    name='helga-facts',
    version='0.2.1',
    description=("A helga plugin that can be used to store responses "
                 "that can be returned from a question"),
    classifiers=[
        'Development Status :: 4 - Beta',
        'Topic :: Communications :: Chat :: Internet Relay Chat',
        'Framework :: Twisted',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    keywords='helga facts',
    author="Shaun Duncan",
    author_email="shaun.duncan@gmail.com",
    url="https://github.com/shaunduncan/helga-facts",
    packages=find_packages(),
    py_modules=['helga_facts'],
    include_package_data=True,
    install_requires=[
        str(req.req) for req in parse_requirements('requirements.txt')
    ],
    zip_safe=True,
    entry_points=dict(
        helga_plugins=[
            'facts = helga_facts:facts',
        ],
    ),
)


text:
/*!
  \author Roberto Cavada
  \brief Public interface of class 'ConjSet'

  \todo: Missing description

*/

#ifndef __NUSMV_CORE_RBC_CONJ_SET_H__
#define __NUSMV_CORE_RBC_CONJ_SET_H__

#include "nusmv/core/rbc/rbc.h"

#include "nusmv/core/utils/utils.h"

/*!
  \struct ConjSet
  \brief Definition of the public accessor for class ConjSet

  A ConjSet holds the associations between variables
	and the corresponding expression each variable can be substituted with.
	A ConjSet is internally used by RBC inlining. In particular it is used
	by class InlineResult
*/
typedef struct ConjSet_TAG*  ConjSet_ptr;

/*!
  \brief To cast and check instances of class ConjSet

  These macros must be used respectively to cast and to check
  instances of class ConjSet
*/
#define CONJ_SET(self) \
         ((ConjSet_ptr) self)

/*!
  \brief \todo Missing synopsis

  \todo Missing description
*/
#define CONJ_SET_CHECK_INSTANCE(self) \
         (nusmv_assert(CONJ_SET(self) != CONJ_SET(NULL)))

/**AutomaticStart*************************************************************/

/*---------------------------------------------------------------------------*/
/* Function prototypes                                                       */
/*---------------------------------------------------------------------------*/

/*!
  \methodof ConjSet
  \brief The ConjSet class constructor

  The ConjSet class constructor

  \sa ConjSet_destroy
*/
ConjSet_ptr ConjSet_create(Rbc_Manager_t* rbcm);

/*!
  \methodof ConjSet
  \brief The ConjSet class destructor

  The ConjSet class destructor

  \sa ConjSet_create
*/
void ConjSet_destroy(ConjSet_ptr self);

/*!
  \methodof ConjSet
  \brief Copy constructor

*/
ConjSet_ptr ConjSet_copy(const ConjSet_ptr self);

/*!
  \methodof ConjSet
  \brief Adds a new variable assignment to set

  Will be kept onlt if 'better' then the possibly
  previous assigment
*/
void ConjSet_add_var_assign(ConjSet_ptr self,
                     Rbc_t* var, Rbc_t* expr);

/*!
  \methodof ConjSet
  \brief Inherits as much as possible (provided that what it
  inherits is not worse than what it has collected so far) from the given
  ConjSet

*/
void ConjSet_inherit_from(ConjSet_ptr self,
                       const ConjSet_ptr other);

/*!
  \methodof ConjSet
  \brief Makes the ConjSet flattened.

  Flattens the ConjSet, making minimal the graph of
  dependencies. A flatten ConjSet can then be used to substitute
  an expression
*/
void ConjSet_flattenize(ConjSet_ptr self);

/*!
  \methodof ConjSet
  \brief Substitutes all variables occurring into f that belong
        to self with the corresponding expression.

  If self was previously flattened, the resulting RBC
        will be flattened as well, but only about those parts that has
        the same language of self
*/
Rbc_t* ConjSet_substitute(ConjSet_ptr self, Rbc_t* f);

/*!
  \methodof ConjSet
  \brief Returns the conjuction of self with the given formula

  Returns a formula like:
            for all v,exp belonging to self,
          (/\ (v <-> exp)) /\ f

*/
Rbc_t* ConjSet_conjoin(ConjSet_ptr self, Rbc_t* f);

/*!
  \methodof ConjSet
  \brief Prints debugging information about self

*/
void ConjSet_print(const ConjSet_ptr self, FILE* file);

/**AutomaticEnd***************************************************************/

#endif /* __NUSMV_CORE_RBC_CONJ_SET_H__ */


text:
package org.rarefiedredis.concurrency;

import org.junit.Test;
import org.junit.Before;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;

import org.rarefiedredis.RandomKey;
import org.rarefiedredis.redis.RedisMock;
import org.rarefiedredis.redis.IRedisClient;
import org.rarefiedredis.redis.WrongTypeException;
import org.rarefiedredis.redis.NotImplementedException;
import org.rarefiedredis.redis.SyntaxErrorException;
import org.rarefiedredis.redis.adapter.jedis.JedisIRedisClient;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;

public class RedisCheckAndSetTest {

    private IRedisClient client, other;
    private RandomKey rander;

    @Before public void initClient() {
        rander = new RandomKey();
        String integration = System.getProperty("integration");
        if (integration != null && integration.equals("true")) {
            client = new JedisIRedisClient(new JedisPool(new JedisPoolConfig(), "localhost"));
            other = new JedisIRedisClient(new JedisPool(new JedisPoolConfig(), "localhost"));
        }
        else {
            RedisMock mock = new RedisMock();
            client = mock.createClient();
            other = mock.createClient();
        }
    }

    @Test public void checkAndSetShouldCheckAndSetAnUnchangingKey() throws WrongTypeException, NotImplementedException, SyntaxErrorException {
        RedisCheckAndSet cas = new RedisCheckAndSet(client);
        String k = rander.randkey();
        final String v = "v", v2 = "v2";
        client.set(k, v);
        List<Object> replies = cas.checkAndSet(new IRedisCheckAndSet<String>() {
                @Override public String get(IRedisClient client, String key) {
                    try {
                        return client.get(key);
                    }
                    catch (Exception e) {
                        return null;
                    }
                }
                @Override public IRedisClient set(IRedisClient multi, String key, String get) {
                    try {
                        multi.set(key, v2);
                    }
                    catch (Exception e) {
                    }
                    return multi;
                }
            }, k);
        assertEquals(true, replies != null);
        assertEquals(1, replies.size());
        assertEquals("OK", (String)replies.get(0));
        assertEquals(v2, client.get(k));
    }

    @Test public void checkAndSetShouldFailIfAKeyChangesBeforeTheMultiIsExecd() throws WrongTypeException, NotImplementedException, SyntaxErrorException {
        RedisCheckAndSet cas = new RedisCheckAndSet(client);
        final String k = rander.randkey();
        final String v = "v", v2 = "v2", v3 = "v3";
        client.set(k, v);
        List<Object> replies = cas.checkAndSet(new IRedisCheckAndSet<String>() {
                @Override public String get(IRedisClient client, String key) {
                    try {
                        return client.get(key);
                    }
                    catch (Exception e) {
                        return null;
                    }
                }
                @Override public IRedisClient set(IRedisClient multi, String key, String get) {
                    try {
                        other.set(k, v3);
                        multi.set(key, v2);
                    }
                    catch (Exception e) {
                    }
                    return multi;
                }
            }, k);
        assertEquals(null, replies);
    }

}


text:
{% extends "layout.html" %}
{% block styles %}
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='stylesheet.css') }}" />
{% endblock %}
{% block scripts %}

{% endblock %}
{% block body %}

Admin Stuff

There are {{ users }} users and {{ mods }} mods.

Newest Users

        {% for user in new_users %}

            {{ user.username }}

        {% endfor %}

New Blog Post

    <form role="form" action="/blog/post" method="POST">

            Title
            <input type="text" class="form-control" id="post-title" name="post-title" placeholder="Title">

            Body Markdown supported
            <textarea name="post-body" id="post-body" class="form-control input-block-level" rows=10></textarea>

        <input type="submit" class="btn btn-primary btn-block" value="Publish">
    </form>

Email Everyone

    <form role="form" action="/admin/email" method="POST">

This will send an email to loads of people, be careful.

                <input type="checkbox" name="modders-only" id="modders-only" style="position: relative; top: -3px">
                Email published modders only

            Subject
            <input type="text" class="form-control" id="subject" name="subject" placeholder="Subject">

            Body
            <textarea name="body" id="body" class="form-control input-block-level" rows=10></textarea>

        <input type="submit" class="btn btn-primary btn-block" value="Send">
    </form>

Game Versions

    {% if len(versions) == 0 %}

You have not added any game versions. Modders will not be able to create mods until you add at least one.

    {% else %}

Currently aware of these versions:

        {% for v in versions %}

            {{ v.friendly_version }}

        {% endfor %}

    {% endif %}
    <form role="form" action="/versions/create" method="POST">

                <input type="text" id="friendly_version" name="friendly_version" class="form-control input-block-level" placeholder="Version name...">

                <input type="submit" class="btn btn-primary btn-block" value="Add Version">

    </form>

{% endblock %}


text:
import cgi
import imghdr
import os
import tempfile
import uuid

import mock
from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_utils import timeutils
import six
from six.moves import cStringIO
from six.moves import range
from webob import exc

from murano.api.v1 import catalog
from murano.api.v1 import PKG_PARAMS_MAP
from murano.common import exceptions as common_exc
from murano.db.catalog import api as db_catalog_api
from murano.db import models
from murano.packages import exceptions
from murano.packages import load_utils
import murano.tests.unit.api.base as test_base
import murano.tests.unit.utils as test_utils

CONF = cfg.CONF

class TestCatalogApi(test_base.ControllerTest, test_base.MuranoApiTestCase):

    def setUp(self):
        super(TestCatalogApi, self).setUp()
        self.controller = catalog.Controller()
        _, self.test_package = self._test_package()

    def _add_pkg(self, tenant_name, public=False, classes=None, **kwargs):
        package_to_upload = self.test_package.copy()
        package_to_upload['is_public'] = public
        package_to_upload['fully_qualified_name'] = str(uuid.uuid4())
        if classes:
            package_to_upload['class_definitions'] = classes
        else:
            package_to_upload['class_definitions'] = []
        package_to_upload.update(kwargs)
        return db_catalog_api.package_upload(
            package_to_upload, tenant_name)

    def test_packages_filtering_admin(self):
        self.is_admin = True
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        for dummy in range(7):
            self.expect_policy_check('get_package')
            self.expect_policy_check('manage_public_package')

        pkg = self._add_pkg('test_tenant', type='Library')
        self._add_pkg('test_tenant')
        self._add_pkg('test_tenant2', public=True, type='Library')
        self._add_pkg('test_tenant3')

        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'False',
                                             'owned': 'False'}))
        self.assertEqual(4, len(result['packages']))
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'False',
                                             'owned': 'True'}))
        self.assertEqual(2, len(result['packages']))

        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'True',
                                             'owned': 'False'}))
        self.assertEqual(3, len(result['packages']))
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'True',
                                             'owned': 'True'}))
        self.assertEqual(2, len(result['packages']))

        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={
                'owned': 'True',
                'fqn': pkg.fully_qualified_name}))
        self.assertEqual(1, len(result['packages']))
        self.assertEqual(pkg.fully_qualified_name,
                         result['packages'][0]['fully_qualified_name'])

        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={
                'owned': 'True',
                'type': 'Library'}))
        self.assertEqual(1, len(result['packages']))
        self.assertEqual(pkg.fully_qualified_name,
                         result['packages'][0]['fully_qualified_name'])

        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={
                'type': 'Library'}))
        self.assertEqual(2, len(result['packages']))

    def test_packages_filtering_non_admin(self):
        self.is_admin = False
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        for dummy in range(8):
            self.expect_policy_check('get_package')
            self.expect_policy_check('manage_public_package')

        pkg = self._add_pkg('test_tenant', type='Library')
        self._add_pkg('test_tenant')
        self._add_pkg('test_tenant2', public=True, type='Library')
        self._add_pkg('test_tenant3')

        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'False',
                                             'owned': 'False'}))
        self.assertEqual(3, len(result['packages']))
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'False',
                                             'owned': 'True'}))
        self.assertEqual(2, len(result['packages']))
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'True',
                                             'owned': 'False'}))
        self.assertEqual(3, len(result['packages']))
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'True',
                                             'owned': 'True'}))
        self.assertEqual(2, len(result['packages']))

        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={
                'owned': 'True',
                'fqn': pkg.fully_qualified_name}))
        self.assertEqual(1, len(result['packages']))
        self.assertEqual(pkg.fully_qualified_name,
                         result['packages'][0]['fully_qualified_name'])

        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={
                'owned': 'True',
                'type': 'Library'}))
        self.assertEqual(1, len(result['packages']))
        self.assertEqual(pkg.fully_qualified_name,
                         result['packages'][0]['fully_qualified_name'])

        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={
                'type': 'Library'}))
        self.assertEqual(2, len(result['packages']))

        self._set_policy_rules({'get_package': '',
                                'manage_public_package': '!'})
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'False'}))
        self.assertEqual(2, len(result['packages']))

    def test_packages_filter_by_id(self):
        """Test that packages are filtered by ID

        GET /catalog/packages with parameter "id" returns packages
        filtered by id.
        """
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        _, package1_data = self._test_package()
        _, package2_data = self._test_package()

        package1_data['fully_qualified_name'] += '_1'
        package1_data['name'] += '_1'
        package1_data['class_definitions'] = (u'test.mpl.v1.app.Thing1',)
        package2_data['fully_qualified_name'] += '_2'
        package2_data['name'] += '_2'
        package2_data['class_definitions'] = (u'test.mpl.v1.app.Thing2',)

        expected_package = db_catalog_api.package_upload(package1_data, '')
        db_catalog_api.package_upload(package2_data, '')

        req = self._get('/catalog/packages',
                        params={'id': expected_package.id})
        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')

        res = req.get_response(self.api)
        self.assertEqual(200, res.status_code)

        self.assertEqual(1, len(res.json['packages']))

        found_package = res.json['packages'][0]

        self.assertEqual(expected_package.id, found_package['id'])

    def test_packages_filter_by_in_category(self):
        """Test that packages are filtered by in:cat1,cat2,cat3

        GET /catalog/packages with parameter "category=in:cat1,cat2,cat3"
        returns packages filtered by category.
        """
        names = ['cat1', 'cat2', 'cat3', 'cat4']
        for name in names:
            db_catalog_api.category_add(name)
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        _, package1_data = self._test_package()
        _, package2_data = self._test_package()
        _, package3_data = self._test_package()

        package1_data['fully_qualified_name'] += '_1'
        package1_data['name'] += '_1'
        package1_data['class_definitions'] = (u'test.mpl.v1.app.Thing1',)
        package1_data['categories'] = ('cat1', 'cat2')

        package2_data['fully_qualified_name'] += '_2'
        package2_data['name'] += '_2'
        package2_data['class_definitions'] = (u'test.mpl.v1.app.Thing2',)
        package2_data['categories'] = ('cat2', 'cat3')

        package3_data['fully_qualified_name'] += '_3'
        package3_data['name'] += '_3'
        package3_data['class_definitions'] = (u'test.mpl.v1.app.Thing3',)
        package3_data['categories'] = ('cat2', 'cat4')

        expected_packages = [db_catalog_api.package_upload(package1_data, ''),
                             db_catalog_api.package_upload(package2_data, '')]
        db_catalog_api.package_upload(package3_data, '')

        categories_in = "in:cat1,cat3"

        req = self._get('/catalog/packages',
                        params={'category': categories_in})
        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')

        res = req.get_response(self.api)
        self.assertEqual(200, res.status_code)
        self.assertEqual(2, len(res.json['packages']))

        found_packages = res.json['packages']

        self.assertEqual([pack.id for pack in expected_packages],
                         [pack['id'] for pack in found_packages])

    def test_packages_filter_by_in_tag(self):
        """Test that packages are filtered by in:tag1,tag2,tag3

        GET /catalog/packages with parameter "tag=in:tag1,tag2,tag3"
        returns packages filtered by category.
        """
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        _, package1_data = self._test_package()
        _, package2_data = self._test_package()
        _, package3_data = self._test_package()

        package1_data['fully_qualified_name'] += '_1'
        package1_data['name'] += '_1'
        package1_data['class_definitions'] = (u'test.mpl.v1.app.Thing1',)
        package1_data['tags'] = ('tag1', 'tag2')

        package2_data['fully_qualified_name'] += '_2'
        package2_data['name'] += '_2'
        package2_data['class_definitions'] = (u'test.mpl.v1.app.Thing2',)
        package2_data['tags'] = ('tag2', 'tag3')

        package3_data['fully_qualified_name'] += '_3'
        package3_data['name'] += '_3'
        package3_data['class_definitions'] = (u'test.mpl.v1.app.Thing3',)
        package3_data['tags'] = ('tag2', 'tag4')

        expected_packages = [db_catalog_api.package_upload(package1_data, ''),
                             db_catalog_api.package_upload(package2_data, '')]
        db_catalog_api.package_upload(package3_data, '')

        tag_in = "in:tag1,tag3"

        req = self._get('/catalog/packages',
                        params={'tag': tag_in})
        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')

        res = req.get_response(self.api)
        self.assertEqual(200, res.status_code)
        self.assertEqual(2, len(res.json['packages']))

        found_packages = res.json['packages']

        self.assertEqual([pack.id for pack in expected_packages],
                         [pack['id'] for pack in found_packages])

    def test_packages_filter_by_in_id(self):
        """Test that packages are filtered by in:id1,id2,id3

        GET /catalog/packages with parameter "id=in:id1,id2" returns packages
        filtered by id.
        """
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        _, package1_data = self._test_package()
        _, package2_data = self._test_package()
        _, package3_data = self._test_package()

        package1_data['fully_qualified_name'] += '_1'
        package1_data['name'] += '_1'
        package1_data['class_definitions'] = (u'test.mpl.v1.app.Thing1',)
        package2_data['fully_qualified_name'] += '_2'
        package2_data['name'] += '_2'
        package2_data['class_definitions'] = (u'test.mpl.v1.app.Thing2',)
        package3_data['fully_qualified_name'] += '_3'
        package3_data['name'] += '_3'
        package3_data['class_definitions'] = (u'test.mpl.v1.app.Thing3',)

        expected_packages = [db_catalog_api.package_upload(package1_data, ''),
                             db_catalog_api.package_upload(package2_data, '')]
        db_catalog_api.package_upload(package3_data, '')

        id_in = "in:" + ",".join(pack.id for pack in expected_packages)

        req = self._get('/catalog/packages',
                        params={'id': id_in})
        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')

        res = req.get_response(self.api)
        self.assertEqual(200, res.status_code)

        self.assertEqual(2, len(res.json['packages']))

        found_packages = res.json['packages']

        self.assertEqual([pack.id for pack in expected_packages],
                         [pack['id'] for pack in found_packages])

    def test_packages_filter_by_in_id_empty(self):
        """Test that packages are filtered by "id=in:"

        GET /catalog/packages with parameter "id=in:" returns packages
        filtered by id, in this case no packages should be returned.
        """
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        _, package1_data = self._test_package()

        db_catalog_api.package_upload(package1_data, '')

        req = self._get('/catalog/packages', params={'id': "in:"})
        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')

        res = req.get_response(self.api)
        self.assertEqual(200, res.status_code)

        self.assertEqual(0, len(res.json['packages']))

    def test_packages_filter_by_name(self):
        """Test that packages are filtered by name

        GET /catalog/packages with parameter "name" returns packages
        filtered by name.
        """
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )

        expected_pkg1 = self._add_pkg("test_tenant", name="test_pkgname_1")
        expected_pkg2 = self._add_pkg("test_tenant", name="test_pkgname_2")

        req_pkgname1 = self._get('/catalog/packages',
                                 params={'name': expected_pkg1.name})
        req_pkgname2 = self._get('/catalog/packages',
                                 params={'name': expected_pkg2.name})

        for dummy in range(2):
            self.expect_policy_check('get_package')
            self.expect_policy_check('manage_public_package')

        res_pkgname1 = req_pkgname1.get_response(self.api)
        self.assertEqual(200, res_pkgname1.status_code)
        self.assertEqual(1, len(res_pkgname1.json['packages']))
        self.assertEqual(expected_pkg1.name,
                         res_pkgname1.json['packages'][0]['name'])

        res_pkgname2 = req_pkgname2.get_response(self.api)
        self.assertEqual(200, res_pkgname2.status_code)
        self.assertEqual(1, len(res_pkgname2.json['packages']))
        self.assertEqual(expected_pkg2.name,
                         res_pkgname2.json['packages'][0]['name'])

    def test_packages_filter_by_type(self):
        """Test that packages are filtered by type

        GET /catalog/packages with parameter "type" returns packages
        filtered by type.
        """
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        excepted_pkg1 = self._add_pkg("test_tenant", type='Library')
        excepted_pkg2 = self._add_pkg("test_tenant", type='Library')
        excepted_pkg3 = self._add_pkg("test_tenant", type='Application')

        # filter by type=Library can see 2 pkgs
        req_lib = self._get('/catalog/packages',
                            params={'type': 'Library'})

        # filter by type=Application only see 1 pkgs
        req_app = self._get('/catalog/packages',
                            params={'type': 'Application'})

        for dummy in range(2):
            self.expect_policy_check('get_package')
            self.expect_policy_check('manage_public_package')

        res_lib = req_lib.get_response(self.api)

        self.assertEqual(200, res_lib.status_code)
        self.assertEqual(2, len(res_lib.json['packages']))

        self.assertEqual('Library', res_lib.json['packages'][0]['type'])
        self.assertEqual(excepted_pkg1.name,
                         res_lib.json['packages'][0]['name'])

        self.assertEqual('Library', res_lib.json['packages'][1]['type'])
        self.assertEqual(excepted_pkg2.name,
                         res_lib.json['packages'][1]['name'])

        res_app = req_app.get_response(self.api)

        self.assertEqual(200, res_app.status_code)
        self.assertEqual(1, len(res_app.json['packages']))

        self.assertEqual('Application', res_app.json['packages'][0]['type'])
        self.assertEqual(excepted_pkg3.name,
                         res_app.json['packages'][0]['name'])

    @mock.patch('murano.api.v1.catalog.LOG')
    def test_packages_filter_by_order_by(self, mock_log):
        warnings = []
        mock_log.warning = lambda msg: warnings.append(msg)

        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        self._add_pkg("test_tenant", type='Library')

        # Test whether a valid order by value works.
        order_by = 'name'
        request = self._get('/catalog/packages',
                            params={'order_by': order_by})

        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')

        self.controller.search(request)
        self.assertEqual(len(warnings), 0)

        # Test wheter an invalid order by value fails.
        order_by = 'TEST ORDER BY'
        request = self._get('/catalog/packages', params={'order_by': order_by})

        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')

        self.controller.search(request)
        self.assertEqual(len(warnings), 1)
        self.assertIn('parameter is not valid', warnings[0])

    def test_packages_filter_by_limit(self):
        """Test that packages are filtered by limit."""
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        pkg = self._add_pkg("test_tenant", type='Library')

        request = self._get('/catalog/packages', params={'limit': '1'})
        self.expect_policy_check('get_package')

        self.expect_policy_check('manage_public_package')
        res = self.controller.search(request)

        self.assertIn('next_marker', res)
        self.assertEqual(res['next_marker'], pkg['id'])

    def test_packages_filter_by_limit_negative_cases(self):
        """Test whether invalid limit values throw expected exceptions."""
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        self._add_pkg("test_tenant", type='Library')

        # Test wheter non-number value throws exception
        request = self._get('/catalog/packages',
                            params={'limit': 'not a number'})
        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')
        e = self.assertRaises(exc.HTTPBadRequest, self.controller.search,
                              request)
        self.assertEqual(e.explanation, 'Limit param must be an integer')

        # Test whether below-zero value throws exception
        request = self._get('/catalog/packages', params={'limit': '-1'})
        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')
        e = self.assertRaises(exc.HTTPBadRequest, self.controller.search,
                              request)
        self.assertEqual(e.explanation, 'Limit param must be positive')

    @mock.patch('murano.common.utils.split_for_quotes')
    @mock.patch('murano.api.v1.catalog.LOG')
    def test_packages_filter_handle_value_error(self, mock_log, mock_func):
        warnings = []
        mock_func.side_effect = ValueError
        mock_log.warning = lambda msg: warnings.append(msg)

        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        self._add_pkg("test_tenant", type='Library')
        tag_in = "in:tag1,tag3"
        self._get('/catalog/packages', params={'tag': tag_in})
        request = self._get('/catalog/packages',
                            params={'tag': tag_in})

        self.expect_policy_check('get_package')
        self.expect_policy_check('manage_public_package')

        self.controller.search(request)
        self.assertEqual(len(warnings), 1)
        self.assertIn("Search by parameter 'tag' caused an  error",
                      warnings[0])

    def test_packages(self):
        self._set_policy_rules(
            {'get_package': '',
             'manage_public_package': ''}
        )
        for dummy in range(9):
            self.expect_policy_check('get_package')
            self.expect_policy_check('manage_public_package')
        result = self.controller.search(self._get('/v1/catalog/packages/'))
        self.assertEqual(0, len(result['packages']))

        self._add_pkg('test_tenant')
        self._add_pkg('test_tenant')
        self._add_pkg('other_tenant')
        self._add_pkg('other_tenant')

        # non-admin should only see 2 pkgs he can edit.
        self.is_admin = False
        result = self.controller.search(self._get('/v1/catalog/packages/'))
        self.assertEqual(2, len(result['packages']))
        # can only deploy his + public
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'True'}))
        self.assertEqual(2, len(result['packages']))

        # admin can edit anything
        self.is_admin = True
        result = self.controller.search(self._get('/v1/catalog/packages/'))
        self.assertEqual(4, len(result['packages']))
        # admin can only deploy his + public
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'True'}))
        self.assertEqual(2, len(result['packages']))

        self._add_pkg('test_tenant', public=True)
        self._add_pkg('other_tenant', public=True)

        # non-admin are allowed to edit public packages by policy
        self.is_admin = False
        result = self.controller.search(self._get('/v1/catalog/packages/'))
        self.assertEqual(4, len(result['packages']))
        # can deploy mine + other public
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'True'}))
        self.assertEqual(4, len(result['packages']))

        # admin can edit anything
        self.is_admin = True
        result = self.controller.search(self._get('/v1/catalog/packages/'))
        self.assertEqual(6, len(result['packages']))
        # can deploy mine + public
        result = self.controller.search(self._get(
            '/v1/catalog/packages/', params={'catalog': 'True'}))
        self.assertEqual(4, len(result['packages']))

    def _test_package(self, manifest='manifest.yaml'):
        package_dir = os.path.abspath(
            os.path.join(
                __file__,
                '../../../packages/test_packages/test.mpl.v1.app',
            )
        )
        pkg = load_utils.load_from_dir(
            package_dir, filename=manifest
        )
        package = {
            'fully_qualified_name': pkg.full_name,
            'type': pkg.package_type,
            'author': pkg.author,
            'supplier': pkg.supplier,
            'name': pkg.display_name,
            'description': pkg.description,
            'is_public': True,
            'tags': pkg.tags,
            'logo': pkg.logo,
            'supplier_logo': pkg.supplier_logo,
            'ui_definition': pkg.ui,
            'class_definitions': tuple(pkg.classes),
            'archive': pkg.blob,
            'categories': [],
        }
        return pkg, package

    def test_modify_package_tags(self):
        self._set_policy_rules(
            {'modify_package': '',
             'manage_public_package': '',
             'publicize_package': ''}
        )
        saved_package = self._add_pkg('test_tenant')
        saved_package_pub = self._add_pkg('test_tenant', public=True)
        self.expect_policy_check('modify_package',
                                 {'package_id': saved_package.id})

        url = '/v1/catalog/packages/' + str(saved_package.id)

        data = []
        data.append({'op': 'add', 'path': ['tags'], 'value': ["foo", "bar"]})

        req = self._patch(url, jsonutils.dump_as_bytes(data))
        result = self.controller.update(req, data, saved_package.id)

        self.assertIn('foo', result['tags'])
        self.assertIn('bar', result['tags'])

        self.expect_policy_check('modify_package',
                                 {'package_id': saved_package_pub.id})
        self.expect_policy_check('manage_public_package', {})
        url = '/v1/catalog/packages/' + str(saved_package_pub.id)

        data = []
        data.append({'op': 'add', 'path': ['tags'], 'value': ["foo", "bar"]})

        req = self._patch(url, jsonutils.dump_as_bytes(data))
        result = self.controller.update(req, data, saved_package_pub.id)

        self.assertIn('foo', result['tags'])
        self.assertIn('bar', result['tags'])

    def test_modify_package_name(self):
        self._set_policy_rules(
            {'modify_package': ''}
        )
        saved_package = self._add_pkg('test_tenant')
        self.expect_policy_check('modify_package',
                                 {'package_id': saved_package.id})
        url = '/v1/catalog/packages/' + str(saved_package.id)

        data = []
        data.append({'op': 'replace', 'path': ['name'], 'value': 'test_name'})
        req = self._patch(url, jsonutils.dump_as_bytes(data))
        result = self.controller.update(req, data, saved_package.id)
        self.assertEqual('test_name', result['name'])
        self.expect_policy_check('modify_package',
                                 {'package_id': saved_package.id})

        data = []
        data.append({'op': 'replace', 'path': ['name'], 'value': 'a'*81})
        req = self._patch(url, jsonutils.dump_as_bytes(data))
        self.assertRaises(exc.HTTPBadRequest, self.controller.update,
                          req, data, saved_package.id)

    def test_modify_package_no_body(self):
        self._set_policy_rules(
            {'modify_package': ''}
        )
        saved_package = self._add_pkg('test_tenant')
        self.expect_policy_check('modify_package',
                                 {'package_id': saved_package.id})
        url = '/v1/catalog/packages/' + str(saved_package.id)
        req = self._patch(url, jsonutils.dump_as_bytes(None))
        self.assertRaises(exc.HTTPBadRequest, self.controller.update,
                          req, None, saved_package.id)

    def test_modify_package_is_public(self):
        self._set_policy_rules(
            {'modify_package': '',
             'manage_public_package': '',
             'publicize_package': ''}
        )
        saved_package = self._add_pkg('test_tenant')
        url = '/v1/catalog/packages/' + str(saved_package.id)
        self.expect_policy_check('modify_package',
                                 {'package_id': saved_package.id})
        self.expect_policy_check('publicize_package', {})
        data = []
        data.append({'op': 'replace', 'path': ['is_public'], 'value': True})
        req = self._patch(url, jsonutils.dump_as_bytes(data))
        result = self.controller.update(req, data, saved_package.id)
        self.assertTrue(result['is_public'])

    def test_modify_package_bad_content_type(self):
        self._set_policy_rules(
            {'modify_package': '',
             'manage_public_package': '',
             'publicize_package': ''}
        )
        saved_package = self._add_pkg('test_tenant')
        url = '/v1/catalog/packages/' + str(saved_package.id)
        self.expect_policy_check('modify_package',
                                 {'package_id': saved_package.id})
        self.expect_policy_check('publicize_package', {})
        data = []
        data.append({'op': 'replace', 'path': ['is_public'], 'value': True})
        req = self._patch(url, jsonutils.dump_as_bytes(data))
        result = self.controller.update(req, data, saved_package.id)
        self.assertTrue(result['is_public'])

    def test_modify_package_with_incorrect_content_type(self):
        self._set_policy_rules(
            {'modify_package': ''}
        )
        saved_package = self._add_pkg('test_tenant')
        self.expect_policy_check('modify_package',
                                 {'package_id': saved_package.id})
        url = '/v1/catalog/packages/' + str(saved_package.id)
        data = []
        data.append({'op': 'replace', 'path': ['name'], 'value': 'test_name'})

        req = self._patch(url, jsonutils.dump_as_bytes(data))
        req.get_content_type = mock.MagicMock(
            side_effect=common_exc.UnsupportedContentType)
        self.assertRaises(exc.HTTPBadRequest,
                          self.controller.update, req, data, saved_package.id)

    def test_not_valid_logo(self):
        self.assertRaises(exceptions.PackageLoadError,
                          self._test_package, 'manifest_with_broken_logo.yaml')

    def test_load_package_with_supplier_info(self):
        self._set_policy_rules(
            {'get_package': '@'}
        )
        _, package = self._test_package()

        saved_package = db_catalog_api.package_upload(package, '')

        self.expect_policy_check('get_package',
                                 {'package_id': saved_package.id})

        req = self._get('/v1/catalog/packages/%s' % saved_package.id)
        result = self.controller.get(req, saved_package.id)

        self.assertEqual(package['supplier'], result['supplier'])

        req = self._get(
            '/v1/catalog/packages/%s/supplier_logo' % saved_package.id
        )
        result = self.controller.get_supplier_logo(req, saved_package.id)

        self.assertEqual('png', imghdr.what('', result))

    def test_download_package(self):
        self._set_policy_rules(
            {'download_package': '@'}
        )
        _, package = self._test_package()

        saved_package = db_catalog_api.package_upload(package, '')

        self.expect_policy_check('download_package',
                                 {'package_id': saved_package.id})

        req = self._get_with_accept('/catalog/packages/%s/download'
                                    % saved_package.id,
                                    accept='application/octet-stream')

        result = req.get_response(self.api)

        self.assertEqual(200, result.status_code)

    def test_download_package_negative(self):

        _, package = self._test_package()

        saved_package = db_catalog_api.package_upload(package, '')

        req = self._get_with_accept('/catalog/packages/%s/download'
                                    % saved_package.id,
                                    accept='application/foo')

        result = req.get_response(self.api)

        self.assertEqual(406, result.status_code)
        self.assertTrue(b'Acceptable response can not be provided'
                        in result.body)

    @mock.patch('murano.api.v1.catalog._validate_body')
    @mock.patch('murano.common.policy.check')
    def test_upload_package_with_invalid_schema(self, mock_policy_check,
                                                mock_validate_body):
        invalid_pkg_upload_schema = {"type": None}
        mock_policy_check.return_value = True
        mock_validate_body.return_value = (None, invalid_pkg_upload_schema)
        mock_request = mock.MagicMock(context={})
        e = self.assertRaises(exc.HTTPBadRequest, self.controller.upload,
                              mock_request)
        self.assertIn(
            "Package schema is not valid",
            e.explanation
        )

    @mock.patch('murano.api.v1.catalog._validate_body')
    @mock.patch('murano.common.policy.check')
    def test_upload_package_with_invalid_file_content(self, mock_policy_check,
                                                      mock_validate_body):
        with tempfile.NamedTemporaryFile(delete=True) as temp_file:
            mock_policy_check.return_value = True
            mock_validate_body.return_value = (mock.MagicMock(file=temp_file),
                                               None)
            mock_request = mock.MagicMock(context={})
            e = self.assertRaises(exc.HTTPBadRequest, self.controller.upload,
                                  mock_request)
            self.assertIn(
                "Uploading file can't be empty",
                e.explanation
            )

    @mock.patch('murano.api.v1.catalog.PKG_PARAMS_MAP')
    @mock.patch('murano.packages.load_utils.load_from_file')
    @mock.patch('murano.api.v1.catalog._validate_body')
    @mock.patch('murano.common.policy.check')
    def test_upload_package_with_oversized_file_name(self, mock_policy_check,
                                                     mock_validate_body,
                                                     mock_load_from_file,
                                                     mock_pkg_params_map):
        mock_policy_check.return_value = True
        mock_load_from_file.return_value = mock.MagicMock(
            __exit__=lambda obj, type, value, tb: False)
        mock_pkg_params_map.return_value = {}
        mock_request = mock.MagicMock(context=mock.MagicMock(
            tenant=self.tenant))
        test_package_meta = {'name': 'a'*81}
        with tempfile.NamedTemporaryFile(delete=True) as temp_file:
            temp_file.write(b"Random test content\n")
            temp_file.seek(0)
            mock_validate_body.return_value = \
                (mock.MagicMock(file=temp_file), test_package_meta)
            e = self.assertRaises(exc.HTTPBadRequest, self.controller.upload,
                                  mock_request)
            self.assertIn(
                "Package name should be 80 characters maximum",
                e.explanation
            )

    @mock.patch('murano.packages.load_utils.load_from_file')
    @mock.patch('murano.api.v1.catalog._validate_body')
    @mock.patch('murano.common.policy.check')
    def test_upload_package_handle_package_load_error(self, mock_policy_check,
                                                      mock_validate_body,
                                                      mock_load_from_file):
        pkg_to_upload = mock.MagicMock(
            __exit__=lambda obj, type, value, tb: False)
        mock_request = mock.MagicMock(context=mock.MagicMock(
            tenant=self.tenant))
        mock_load_from_file.return_value = pkg_to_upload
        mock_load_from_file.side_effect = exceptions.PackageLoadError
        mock_policy_check.return_value = True
        with tempfile.NamedTemporaryFile(delete=True) as temp_file:
            temp_file.write(b"Random test content\n")
            temp_file.seek(0)
            mock_validate_body.return_value = \
                (mock.MagicMock(file=temp_file), None)
            e = self.assertRaises(exc.HTTPBadRequest, self.controller.upload,
                                  mock_request)
            self.assertIn(
                "Couldn't load package from file",
                e.explanation
            )

    @mock.patch('murano.packages.load_utils.load_from_file')
    @mock.patch('murano.api.v1.catalog._validate_body')
    @mock.patch('murano.common.policy.check')
    def test_upload_package_handle_duplicate_exception(self, mock_policy_check,
                                                       mock_validate_body,
                                                       mock_load_from_file):
        """Test whether duplicate error is correctly thrown."""
        # Save the first package entry to the DB
        test_package_meta = self.test_package.copy()
        test_package_meta['name'] = 'test_package'
        test_package_meta['fully_qualified_name'] = str(uuid.uuid4())
        test_package_meta['description'] = 'test_description'
        test_package_meta['enabled'] = False
        test_package_meta['is_public'] = False
        db_catalog_api.package_upload(test_package_meta, self.tenant)

        # Reverse the operation performed by upload for copying values from
        # pkg_to_upload into package_meta dict.
        pkg_to_upload = mock.MagicMock(
            __exit__=lambda obj, type, value, tb: False)
        for k, v in six.iteritems(PKG_PARAMS_MAP):
            if v in test_package_meta.keys():
                val = test_package_meta[v]
                setattr(pkg_to_upload.__enter__(), k, val)

        # Delete extra properties so validation in upload passes.
        for attr in ['fully_qualified_name', 'ui_definition', 'author',
                     'supplier_logo', 'supplier', 'logo', 'type', 'archive']:
            if attr in test_package_meta.keys():
                del test_package_meta[attr]

        mock_request = mock.MagicMock(context=mock.MagicMock(
            tenant=self.tenant))
        mock_load_from_file.return_value = pkg_to_upload
        mock_policy_check.return_value = True

        with tempfile.NamedTemporaryFile(delete=True) as temp_file:
            temp_file.write(b"Random test content\n")
            temp_file.seek(0)
            mock_validate_body.return_value = \
                (mock.MagicMock(file=temp_file), test_package_meta)
            e = self.assertRaises(exc.HTTPConflict, self.controller.upload,
                                  mock_request)
            self.assertIn(
                "Package with specified full name is already registered",
                e.detail
            )

    @mock.patch('murano.common.policy.check')
    def test_upload_package_with_oversized_body(self, mock_policy_check):
        mock_policy_check.return_value = True
        packages_to_upload = {'a': 0, 'b': 1, 'c': 2}
        mock_request = mock.MagicMock(context={})
        e = self.assertRaises(exc.HTTPBadRequest, self.controller.upload,
                              mock_request, body=packages_to_upload)
        self.assertIn(
            "'multipart/form-data' request body should contain 1 or 2 "
            "parts: json string and zip archive.",
            e.explanation
        )

    @mock.patch('murano.common.policy.check')
    def test_upload_package_with_empty_body(self, mock_policy_check):
        mock_policy_check.return_value = True
        packages_to_upload = {}
        mock_request = mock.MagicMock(context={})
        e = self.assertRaises(exc.HTTPBadRequest, self.controller.upload,
                              mock_request, body=packages_to_upload)
        self.assertEqual(
            'There is no file package with application description',
            e.explanation)

    def test_get_ui_definition(self):
        self._set_policy_rules(
            {'get_package': '@'}
        )
        _, package = self._test_package()

        saved_package = db_catalog_api.package_upload(package, '')

        self.expect_policy_check('get_package',
                                 {'package_id': saved_package.id})

        req = self._get_with_accept('/catalog/packages/%s/ui'
                                    % saved_package.id,
                                    accept="text/plain")

        result = req.get_response(self.api)

        self.assertEqual(200, result.status_code)

    def test_get_ui_definition_negative(self):
        _, package = self._test_package()

        saved_package = db_catalog_api.package_upload(package, '')

        req = self._get_with_accept('/catalog/packages/%s/ui'
                                    % saved_package.id,
                                    accept='application/foo')

        result = req.get_response(self.api)

        self.assertEqual(406, result.status_code)
        self.assertTrue(b'Acceptable response can not be provided'
                        in result.body)

    def test_get_logo(self):
        self._set_policy_rules(
            {'get_package': '@'}
        )
        _, package = self._test_package()

        saved_package = db_catalog_api.package_upload(package, '')

        self.expect_policy_check('get_package',
                                 {'package_id': saved_package.id})

        req = self._get_with_accept('/catalog/packages/%s/logo'
                                    % saved_package.id,
                                    accept="application/octet-stream")

        result = req.get_response(self.api)

        self.assertEqual(200, result.status_code)
        self.assertEqual(package['logo'], result.body)

    def test_get_logo_negative(self):
        _, package = self._test_package()

        saved_package = db_catalog_api.package_upload(package, '')

        req = self._get_with_accept('/catalog/packages/%s/logo'
                                    % saved_package.id,
                                    accept='application/foo')

        result = req.get_response(self.api)

        self.assertEqual(406, result.status_code)
        self.assertTrue(b'Acceptable response can not be provided'
                        in result.body)

    def test_add_public_unauthorized(self):
        self._set_policy_rules({
            'upload_package': '@',
            'publicize_package': 'is_admin:True',
            'delete_package': 'is_admin:True',
        })

        self.expect_policy_check('upload_package')
        self.expect_policy_check('delete_package', mock.ANY)
        self.expect_policy_check('upload_package')
        self.expect_policy_check('publicize_package')
        self.expect_policy_check('upload_package')
        self.expect_policy_check('publicize_package')

        file_obj_str = cStringIO("This is some dummy data")
        file_obj = mock.MagicMock(cgi.FieldStorage)
        file_obj.file = file_obj_str
        package_from_dir, _ = self._test_package()

        body_fmt = '''\

--BOUNDARY
Content-Disposition: form-data; name="__metadata__"

{0}
--BOUNDARY
Content-Disposition: form-data; name="ziparchive"; filename="file.zip"

This is a fake zip archive
--BOUNDARY--'''

        def format_body(content):
            content = jsonutils.dumps(content)
            body = body_fmt.format(content)
            if six.PY3:
                body = body.encode('utf-8')
            return body

        with mock.patch('murano.packages.load_utils.load_from_file') as lff:
            ctxmgr = mock.Mock()
            ctxmgr.__enter__ = mock.Mock(return_value=package_from_dir)
            ctxmgr.__exit__ = mock.Mock(return_value=False)
            lff.return_value = ctxmgr

            # Uploading a non-public package
            req = self._post(
                '/catalog/packages',
                format_body({'is_public': False}),
                content_type='multipart/form-data; ; boundary=BOUNDARY',
            )
            res = req.get_response(self.api)
            self.assertEqual(200, res.status_code)

            self.is_admin = True
            app_id = jsonutils.loads(res.body)['id']
            req = self._delete('/catalog/packages/{0}'.format(app_id))
            res = req.get_response(self.api)

            self.is_admin = False
            # Uploading a public package fails
            req = self._post(
                '/catalog/packages',
                format_body({'is_public': True}),
                content_type='multipart/form-data; ; boundary=BOUNDARY',
            )
            res = req.get_response(self.api)
            self.assertEqual(403, res.status_code)

            # Uploading a public package passes for admin
            self.is_admin = True
            req = self._post(
                '/catalog/packages',
                format_body({'is_public': True}),
                content_type='multipart/form-data; ; boundary=BOUNDARY',
            )
            res = req.get_response(self.api)
            self.assertEqual(200, res.status_code)

    def test_add_category(self):
        """Check that category added successfully"""

        self._set_policy_rules({'add_category': '@'})
        self.expect_policy_check('add_category')

        fake_now = timeutils.utcnow()
        timeutils.utcnow.override_time = fake_now

        expected = {
            'name': 'new_category',
            'created': timeutils.isotime(fake_now)[:-1],
            'updated': timeutils.isotime(fake_now)[:-1],
            'package_count': 0,
        }

        body = {'name': 'new_category'}
        req = self._post('/catalog/categories', jsonutils.dump_as_bytes(body))
        result = req.get_response(self.api)
        processed_result = jsonutils.loads(result.body)
        self.assertIn('id', processed_result.keys())
        expected['id'] = processed_result['id']
        self.assertEqual(expected, processed_result)

    def test_get_category(self):
        """Check that get category executed successfully"""

        self._set_policy_rules({'add_category': '@', 'get_category': '@'})
        self.expect_policy_check('add_category')

        fake_now = timeutils.utcnow()
        timeutils.utcnow.override_time = fake_now

        expected = {
            'name': 'new_category',
            'created': timeutils.isotime(fake_now)[:-1],
            'updated': timeutils.isotime(fake_now)[:-1],
            'package_count': 0,
            'packages': []
        }

        body = {'name': 'new_category'}
        req = self._post('/catalog/categories', jsonutils.dump_as_bytes(body))
        result = req.get_response(self.api)
        expected['id'] = jsonutils.loads(result.body)['id']

        self.expect_policy_check('get_category')
        req = self._get('/catalog/categories/%s' % expected['id'])
        retrieved_category = jsonutils.loads(req.get_response(self.api).body)
        self.assertEqual(retrieved_category, expected)

    def test_show_categories(self):
        """Check that show categories executed successfully"""

        self._set_policy_rules({'add_category': '@', 'get_category': '@'})
        self.expect_policy_check('add_category')

        body = {'name': 'new_category'}
        req = self._post('/catalog/categories', jsonutils.dump_as_bytes(body))
        req.get_response(self.api)

        self.expect_policy_check('get_category')
        req = self._get('/catalog/categories')
        retrieved_categories = self.controller.show_categories(req)
        self.assertEqual(len(retrieved_categories), 1)
        self.assertIn('new_category', retrieved_categories['categories'])

    def test_delete_category(self):
        """Check that category deleted successfully"""
        self._set_policy_rules({'delete_category': '@'})
        self.expect_policy_check('delete_category',
                                 {'category_id': '12345'})

        fake_now = timeutils.utcnow()
        expected = {'name': 'new_category',
                    'created': fake_now,
                    'updated': fake_now,
                    'id': '12345'}

        e = models.Category(**expected)
        test_utils.save_models(e)

        req = self._delete('/catalog/categories/12345')
        processed_result = req.get_response(self.api)
        self.assertEqual(b'', processed_result.body)
        self.assertEqual(200, processed_result.status_code)

    @mock.patch('murano.db.catalog.api.category_get')
    def test_delete_category_with_packages_negative(self, mock_get_category):
        """Check that deleting category that has assigned packages fails."""
        mock_get_category.return_value = mock.MagicMock(
            packages=['test_package'])

        self._set_policy_rules({'delete_category': '@'})
        self.expect_policy_check('delete_category',
                                 {'category_id': '12345'})

        fake_now = timeutils.utcnow()
        expected = {'name': 'new_category',
                    'created': fake_now,
                    'updated': fake_now,
                    'id': '12345'}

        category = models.Category(**expected)
        test_utils.save_models(category)

        req = self._delete('/catalog/categories/12345')
        e = self.assertRaises(exc.HTTPForbidden,
                              self.controller.delete_category, req, '12345')
        self.assertEqual(e.explanation,
                         "It's impossible to delete categories assigned to the"
                         " package, uploaded to the catalog")

    def test_add_category_without_name(self):
        """Test whether adding a category without a name throws exception."""
        self._set_policy_rules({'add_category': '@'})
        self.expect_policy_check('add_category')

        body = {'name': ''}
        req = self._post('/catalog/categories', jsonutils.dump_as_bytes(body))
        e = self.assertRaises(exc.HTTPBadRequest, self.controller.add_category,
                              req, body)
        self.assertEqual("Please, specify a name of the category to create",
                         e.explanation)

    def test_add_category_handle_duplicate_exception(self):
        """Test whether creating duplicate categories throws exception."""
        self._set_policy_rules({'add_category': '@'})
        self.expect_policy_check('add_category')
        self.expect_policy_check('add_category')

        body = {'name': 'new_category'}
        req = self._post('/catalog/categories', jsonutils.dump_as_bytes(body))
        self.controller.add_category(req, body)

        req = self._post('/catalog/categories', jsonutils.dump_as_bytes(body))
        e = self.assertRaises(exc.HTTPConflict, self.controller.add_category,
                              req, body)
        self.assertEqual("Category with specified name is already exist",
                         e.explanation)

    def test_add_category_failed_for_non_admin(self):
        """Check that non admin user couldn't add new category"""
        self._set_policy_rules({'add_category': 'role:context_admin'})
        self.is_admin = False
        self.expect_policy_check('add_category')

        fake_now = timeutils.utcnow()
        timeutils.utcnow.override_time = fake_now

        body = {'name': 'new_category'}
        req = self._post('/catalog/categories', jsonutils.dump_as_bytes(body))
        result = req.get_response(self.api)
        self.assertEqual(403, result.status_code)

    def test_add_long_category(self):
        """Test that category name does not exceed 80 characters

        Check that a category that contains more then 80 characters
        fails to be added
        """

        self._set_policy_rules({'add_category': '@'})
        self.expect_policy_check('add_category')

        fake_now = timeutils.utcnow()
        timeutils.utcnow.override_time = fake_now

        body = {'name': 'cat' * 80}
        req = self._post('/catalog/categories', jsonutils.dump_as_bytes(body))
        result = req.get_response(self.api)
        self.assertEqual(400, result.status_code)
        result_message = result.text.replace('\n', '')
        self.assertIn('Category name should be 80 characters maximum',
                      result_message)

    def test_list_category(self):
        names = ['cat1', 'cat2']
        for name in names:
            db_catalog_api.category_add(name)

        self._set_policy_rules({'get_category': '@'})
        self.expect_policy_check('get_category')

        req = self._get('/catalog/categories')
        result = req.get_response(self.api)
        self.assertEqual(200, result.status_code)
        result_categories = jsonutils.loads(result.body)['categories']
        self.assertEqual(2, len(result_categories))
        self.assertEqual(names, [c['name'] for c in result_categories])

        params = {'sort_keys': 'created,  id'}
        req = self._get('/catalog/categories', params)
        self.expect_policy_check('get_category')
        result = req.get_response(self.api)
        self.assertEqual(200, result.status_code)
        result_categories = jsonutils.loads(result.body)['categories']
        self.assertEqual(names, [c['name'] for c in result_categories])

        names.reverse()

        params = {'sort_dir': 'desc'}
        req = self._get('/catalog/categories', params)
        self.expect_policy_check('get_category')
        result = req.get_response(self.api)
        self.assertEqual(200, result.status_code)
        result_categories = jsonutils.loads(result.body)['categories']
        self.assertEqual(names, [c['name'] for c in result_categories])

    def test_list_category_negative(self):
        self._set_policy_rules({'get_category': '@'})
        self.expect_policy_check('get_category')

        req = self._get('/catalog/categories', {'sort_dir': 'test'})
        result = req.get_response(self.api)
        self.assertEqual(400, result.status_code)

        self.expect_policy_check('get_category')
        req = self._get('/catalog/categories', {'sort_keys': 'test'})
        result = req.get_response(self.api)
        self.assertEqual(400, result.status_code)

        self.expect_policy_check('get_category')
        req = self._get('/catalog/categories', {'test': ['test']})
        result = req.get_response(self.api)
        self.assertEqual(400, result.status_code)


text:
import logging
class NullHandler(logging.Handler):
    def emit(self, record):
        pass
log = logging.getLogger('IpMoteConnectorInternal')
log.setLevel(logging.ERROR)
log.addHandler(NullHandler())

from   SmartMeshSDK.SerialConnector import SerialConnector
from   SmartMeshSDK.ApiDefinition   import IpMoteDefinition

class IpMoteConnectorInternal(SerialConnector.SerialConnector):
    '''
    \ingroup ApiConnector

    \brief Internal class for HART mote connector, over Serial.
    '''

    def __init__(self, maxQSize=100):
        api_def = IpMoteDefinition.IpMoteDefinition()
        SerialConnector.SerialConnector.__init__(self,api_def, maxQSize)

    #======================== TX ==============================================

    def _buildTxHeader(self,cmdId,isResponse,serializedFields):
        txHeader = []

        txHeader.append(cmdId)                     # command ID
        txHeader.append(len(serializedFields))     # length
        txHeader.append(self._setFlags(isResponse))# flags
        if isResponse:
            txHeader.append(0)                     # RC (always 0)

        return txHeader

    def _setFlags(self,isResponse):
        self.paramLock.acquire()
        flags      = 0
        if isResponse:
           flags  |= 0x01
           flags  |= self.RxPacketId<<1
        else:
           self._incrementTxPacketId()
           flags  |= self.TxPacketId<<1
           if self.syncNeeded :
               self.syncNeeded = False
               flags  |= 1 << 3
        self.paramLock.release()

        return flags

    def _ackIfNeeded(self,cmdId,isResponse):
        if isResponse:
            # I received a response

            return False
        else:
            # I received a request

            self._sendInternal(cmdId,True,[])
            return True

    #======================== RX ==============================================

    def _parseRxHeader(self,frameRx):

        cmdId           = frameRx[0]
        length          = frameRx[1]
        flags           = frameRx[2]
        payload         = frameRx[3:]

        # parse flag byte
        isResponse      = ((flags&0x01)>>0==1)
        packetId        =  (flags&0x02)>>1
        self.dontUseId  = ((flags&0x04)>>2==1)
        self.sync       = ((flags&0x08)>>3==1)

        return cmdId,length,isResponse,packetId,payload

    def isValidPacketId(self,cmdId,isResponse,packetId):
        self.paramLock.acquire()
        result = True
        isRepeatId = False
        updateRxPacketId  = True
        if self.RxPacketId==None:
            result = True
        else:
            result = not  (
                                isResponse==False         and
                            self.dontUseId==False         and
                                 self.sync==False         and
                                  packetId==self.RxPacketId
                        )
        self.paramLock.release()
        return (result, isRepeatId, updateRxPacketId)

    #======================== packetId ========================================

    def _incrementTxPacketId(self):
        if self.TxPacketId==0:
            self.TxPacketId=1
        else:
            self.TxPacketId=0

        if log.isEnabledFor(logging.DEBUG):
            log.debug("TxPacketId={0}".format(self.TxPacketId))


text: docker run --rm -v %cd%:/srv/jekyll jekyll/jekyll jekyll build


text:
namespace RKon.Alexa.NET46.Types
{
    /// <summary>
    /// Valid Types for Grants
    /// </summary>
    public class GrantTypes
    {
        /// <summary>
        /// The only supported descendant for grant is type OAuth2.AuthorizationCode, which provides a code property that specifies an OAuth2 authorization code.
        /// </summary>
        public const string OAUTH_AUTHORIZATIONCODE = "OAuth2.AuthorizationCode";
    }
}


text:
package config;

import utils.POSXMLReader;

public class POSSQLConfig {
	private static POSXMLReader spxr = new POSXMLReader("src/config/files/pos_sql_config.xml");
	public static String getSQLUsername() {
		return spxr.getResultByPath("/sql_credentials/sql_username");
	}
	public static String getSQLPassword() {
		return spxr.getResultByPath("/sql_credentials/sql_password");
	}
}


text:
- Fixes logger formatting [#166][166]. reported by [@psnively][@psnively]

  [166]: https://github.com/eed3si9n/scalaxb/issues/166
  [@psnively]: https://github.com/psnively


text:
<template>

${heading}

About me

    <fieldset>
      Name:
      ${sidebar.contactInfo.name}
      Email:
       ${sidebar.contactInfo.email}
      About:
      ${sidebar.contactInfo.about}
    </fieldset>

Articles

${article.title}

${article.abstract}

      Read more

</template>


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150130_100410_review extends Migration
{
    public function up()
    {
        $this->createTable('review', [
            'id' => 'pk',
            'from_user_id' => Schema::TYPE_INTEGER . ' NOT NULL COMMENT "who writes this review"',
            'to_user_id'  => Schema::TYPE_INTEGER . ' NOT NULL COMMENT "whom write this review"',
            'date' => Schema::TYPE_TIMESTAMP . ' NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "when this was created"',
            'message' => Schema::TYPE_TEXT . ' DEFAULT NULL COMMENT "review content"',
            'rating' => Schema::TYPE_SMALLINT . ' DEFAULT NULL COMMENT "rating affixed user rating"'
        ]);
        $this->addForeignKey('fk_review_fromUser', 'review', 'from_user_id', 'user', 'id', 'RESTRICT', 'RESTRICT');
        $this->addForeignKey('fk_review_toUser', 'review', 'to_user_id', 'user', 'id', 'RESTRICT', 'RESTRICT');
    }

    public function down()
    {
        $this->dropForeignKey('fk_review_fromUser', 'review');
        $this->dropForeignKey('fk_review_toUser', 'review');
        $this->dropTable('review');
    }
}


text:
package com.google.android.agera;

/**
 * Called when when an event has occurred. Can be added to {@link Observable}s to be notified
 * of {@link Observable} events.
 */
public interface Updatable {

  /**
   * Called when an event has occurred.
   */
  void update();
}