text:
import json
import os
import sys

from collections import defaultdict

from twisted.conch import manhole, manhole_ssh
from twisted.cred import checkers, portal
from twisted.internet import reactor, ssl
from twisted.internet import task
from twisted.python import log
from twisted.words import service

from luckystrike import util
from luckystrike import config
from luckystrike.user import LuckyStrikeIRCFactory

def setup_config():
    """
    Easier walkthrough for user to setup .luckystrike/config
    """
    print 'Please input domain, without tld, for example.com, input example'
    domain = raw_input('Domain: ')
    user = raw_input('IRC nickname: ')
    password = util.generate_password()
    api_key = raw_input('Campfire API key: ')

    d = defaultdict()
    d['domain'] = domain
    d['users'] = {user : password}
    d['api_key'] = api_key

    print 'Your username:%s, and password: %s' % (user, password)

    directory = os.path.expanduser('~') + '/.luckystrike'
    if not os.path.exists(directory):
        os.makedirs(directory)

    print 'Writing config to %sconfig.json' % directory

    with open(directory + '/config.json', 'w') as config_file:
        json.dump(d, config_file)

def getManholeFactory(namespace, **passwords):
    """
    Return a Manhole SSH factory for debug purposes
    """
    realm = manhole_ssh.TerminalRealm()

    def getManhole(_):
        return manhole.Manhole(namespace)

    realm.chainedProtocolFactory.protocolFactory = getManhole
    p = portal.Portal(realm)
    p.registerChecker(checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwords))
    f = manhole_ssh.ConchFactory(p)

    return f

def watchdog():
    """
    Track last message received per room, call periodically in a reactor loop
    """
    for room in config.rooms.itervalues():
        if room['streaming']:
            log.msg('Last timestamp from %s is %s' % (room['channel'],
                room['heartbeat']))

if __name__ == '__main__':
    if config.args.setup_config:
        setup_config()
        sys.exit(0)

    log.startLogging(sys.stdout)

    try:
        # Store pid file first thing
        pidfile = config.configuration.get('pidfile', None)
        if pidfile is not None:
            with open(pidfile, 'w+') as pf:
                pf.write("%s\n" % str(os.getpid()))

        for room in config.campfire.rooms():
            config.rooms[room['id']] = room
            config.rooms[room['id']]['channel'] = util.campNameToString(room['name'])
            config.rooms[room['id']]['stream'] = None
            config.rooms[room['id']]['streaming'] = False
            config.rooms[room['id']]['heartbeat'] = None

            log.msg('Adding %s to IRC as %s' % (room['name'],
                config.rooms[room['id']]['channel']))

            config.irc_realm.addGroup(service.Group(config.rooms[room['id']]['channel']))

        user_db = checkers.InMemoryUsernamePasswordDatabaseDontUse(**config.users)
        irc_portal = portal.Portal(config.irc_realm, [user_db])

        # Start IRC and Manhole
        reactor.listenTCP(int(config.configuration.get('port', 6667)),
                LuckyStrikeIRCFactory(config.irc_realm, irc_portal))

        if config.args.debug:
            admin_password = util.generate_password()
            log.msg('Staring ManHole with admin password: %s' % admin_password)
            reactor.listenTCP(
                    int(config.configuration.get('manhole_port', 2222)),
                    getManholeFactory(globals(), admin=admin_password),
                    interface='127.0.0.1'
            )

        if (os.path.exists(config.configuration.get('ssl_crt', '')) and
            os.path.exists(config.configuration.get('ssl_key', ''))):

            reactor.listenSSL(int(config.configuration.get('ssl_port', 6697)),
                    LuckyStrikeIRCFactory(config.irc_realm, irc_portal),
                    ssl.DefaultOpenSSLContextFactory(
                        config.configuration['ssl_key'],
                        config.configuration['ssl_crt'])
                    )

        if config.args.debug:
            t = task.LoopingCall(watchdog)
            t.start(240)

        reactor.run()

    except:
        log.err()
    finally:
        if pidfile is not None:
            os.unlink(pidfile)


text:
namespace YAMP
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    /// <summary>
    /// Represents a container for expressions and corresponding operators.
    /// </summary>
    public class ContainerExpression : Expression
    {
        #region Fields

        Expression[] _expressions;
        Operator _operator;

        #endregion

        #region ctors

        /// <summary>
        /// Creates a new expression container.
        /// </summary>
        public ContainerExpression()
        {
        }

        /// <summary>
        /// Creates a new expression container.
        /// </summary>
        /// <param name="expression">The (1) expression to contain.</param>
        public ContainerExpression(Expression expression)
        {
            _expressions = new Expression[] { expression };
            _operator = null;
        }

        /// <summary>
        /// Creates a new expression container.
        /// </summary>
        /// <param name="expression">The (1) expression to contain.</param>
        /// <param name="operator">The assigned operator for the expression.</param>
        public ContainerExpression(Expression expression, Operator @operator)
        {
            _expressions = new Expression[] { expression };
            _operator = @operator;
        }

        /// <summary>
        /// Creates a new expression container.
        /// </summary>
        /// <param name="leftExpression">The left expression to evaluate.</param>
        /// <param name="rightExpression">The right expression to evaluate.</param>
        /// <param name="operator">The operator that connects the expressions.</param>
        public ContainerExpression(Expression leftExpression, Expression rightExpression, Operator @operator)
        {
            _expressions = new Expression[] { leftExpression, rightExpression };
            _operator = @operator;
        }

        /// <summary>
        /// Creates a new expression container.
        /// </summary>
        /// <param name="expressions">The expressions to evaluate.</param>
        /// <param name="operator">The operator that connects the expressions.</param>
        public ContainerExpression(Expression[] expressions, Operator @operator)
        {
            _expressions = expressions;
            _operator = @operator;
        }

        /// <summary>
        /// Creates a new expression container.
        /// </summary>
        /// <param name="container">The container which contains expressions and an operator.</param>
        public ContainerExpression(ContainerExpression container)
        {
            _expressions = container._expressions;
            _operator = container._operator;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets a value if the interpreter has any content (can do interpretation).
        /// </summary>
        public Boolean HasContent
        {
            get { return _expressions != null && _expressions.Length > 0; }
        }

        /// <summary>
        /// Gets the operator used for this parse tree (can be null).
        /// </summary>
        public Operator Operator
        {
            get { return _operator; }
            set { _operator = value; }
        }

        /// <summary>
        /// Gets the array with all found expressions in the parse tree.
        /// </summary>
        public Expression[] Expressions
        {
            get { return _expressions; }
            set { _expressions = value; }
        }

        /// <summary>
        /// Gets a value if the container holds an assignment.
        /// </summary>
        public Boolean IsAssignment
        {
            get
            {
                if (_operator != null)
                {
                    return _operator is AssignmentOperator;
                }

                if (_expressions == null || Expressions.Length != 1)
                {
                    return false;
                }

                if (Expressions[0] is ContainerExpression)
                {
                    return ((ContainerExpression)Expressions[0]).IsAssignment;
                }

                return false;
            }
        }

        /// <summary>
        /// Gets a value indicating if the parse tree consists only of symbols that
        /// are seperated by columns (commas).
        /// </summary>
        public Boolean IsSymbolList
        {
            get
            {
                if (Expressions == null)
                {
                    return false;
                }

                if (Operator != null && (!(Operator is ColumnOperator) && !(Operator is CommaOperator)))
                {
                    return false;
                }

                foreach (var expression in Expressions)
                {
                    if (expression is ContainerExpression)
                    {
                        if (((ContainerExpression)expression).IsSymbolList)
                            continue;
                    }
                    else if (expression is SymbolExpression)
                    {
                        continue;
                    }

                    return false;
                }

                return true;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Registers the element in the beginning.
        /// </summary>
        public override void RegisterElement(IElementMapping elementMapping)
        {
            //Nothing here
        }

        /// <summary>
        /// Interprets the container expression.
        /// </summary>
        /// <param name="symbols">External symbols to be used.</param>
        /// <returns>The evaluated value.</returns>
        public override Value Interpret(IDictionary<String, Value> symbols)
        {
            if (_operator != null)
            {
                return _operator.Evaluate(_expressions, symbols);
            }
            else if (_expressions != null && _expressions.Length > 0)
            {
                return _expressions[0].Interpret(symbols);
            }

            return null;
        }

        /// <summary>
        /// Scans the input of the current parse engine.
        /// </summary>
        /// <param name="engine">The engine to use.</param>
        /// <returns>Null, since container expressions cannot be scanned.</returns>
        public override Expression Scan(ParseEngine engine)
        {
            return null;
        }

        #endregion

        #region String Representations

        /// <summary>
        /// Transforms the content into a string.
        /// </summary>
        /// <returns>The representative.</returns>
        public override String ToString()
        {
            if (_expressions != null)
            {
                if (_expressions.Length == 1 && _operator == null)
                {
                    return String.Format(" [ {0} ] ", _expressions[0]);
                }
                else if (_operator != null)
                {
                    if (_expressions.Length == 1)
                    {
                        return String.Format(" [ {0} {1} ] ", _expressions[0], _operator);
                    }
                    else if (_expressions.Length == 2)
                    {
                        return String.Format(" [ {0} {1} {2} ] ", _expressions[0], _operator, _expressions[1]);
                    }
                }
            }

            return String.Empty;
        }

        /// <summary>
        /// Transforms the contained expressions and operators into a valid part of a YAMP query.
        /// </summary>
        /// <returns>The code.</returns>
        public override string ToCode()
        {
            var sb = new StringBuilder();

            if (_expressions != null)
            {
                if (_expressions.Length > 0)
                    sb.Append(_expressions[0].ToCode());

                if (_operator != null)
                    sb.Append(_operator.ToCode());

                if (_expressions.Length > 1)
                    sb.Append(_expressions[1].ToCode());
            }

            return sb.ToString();
        }

        /// <summary>
        /// Returns a string to allow visualization of a Expression tree
        /// </summary>
        /// <returns>The string that represents the part of the expression tree element.</returns>
        public override String ToDebug(int padLeft, int tabsize)
        {
            string pad = new string(' ', padLeft);

            //string containerType = GetType().Name.RemoveExpressionConvention();
            string containerType = GetType().Name;

            if (_expressions != null)
            {
                if (_expressions.Length == 1 && _operator == null)
                {
                    return String.Format(
                        "{0}[{1}(exp)" + Environment.NewLine +
                        "{2}" + Environment.NewLine +
                        "{0}]",
                        pad, containerType,
                        _expressions[0].ToDebug(padLeft + tabsize, tabsize));
                }
                else if (_operator != null)
                {
                    if (_expressions.Length == 1)
                    {
                        return String.Format(
                            "{0}[{1}(exp,op)" + Environment.NewLine +
                            "{2}" + Environment.NewLine +
                            "{3}" + Environment.NewLine +
                            "{0}]",
                            pad, containerType,
                            _expressions[0].ToDebug(padLeft + tabsize, tabsize),
                            _operator.ToDebug(padLeft + tabsize, tabsize));
                    }
                    else if (_expressions.Length == 2)
                    {
                        return String.Format(
                            "{0}[{1}(exp1,op,exp2)" + Environment.NewLine +
                            "{2}" + Environment.NewLine +
                            "{3}" + Environment.NewLine +
                            "{4}" + Environment.NewLine +
                            "{0}]",
                            pad, containerType,
                            _expressions[0].ToDebug(padLeft + tabsize, tabsize),
                            _operator.ToDebug(padLeft + tabsize, tabsize),
                            _expressions[1].ToDebug(padLeft + tabsize, tabsize));
                    }
                }
            }

            return String.Empty;
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
# Treehouse authentication

Authentication module written in TypeScript providing authentication utilities and JWT methods.

[![npm version](https://badge.fury.io/js/tree-house-authentication.svg)](https://badge.fury.io/js/tree-house-authentication)
[![Dependencies](https://david-dm.org/icapps/tree-house-authentication.svg)](https://david-dm.org/icapps/tree-house-authentication.svg)
[![Build Status](https://travis-ci.org/icapps/tree-house-authentication.svg?branch=master)](https://travis-ci.org/icapps/tree-house-authentication)
[![Coverage Status](https://coveralls.io/repos/github/icapps/tree-house-authentication/badge.svg)](https://coveralls.io/github/icapps/tree-house-authentication)

## Installation

Install via npm

```shell
npm install @icapps/tree-house-authentication
```

or via yarn

```shell
yarn add @icapps/tree-house-authentication
```

## Usage

```javascript
const authenticator = require('@icapps/tree-house-authentication')
```

```javascript
import * as authenticator from '@icapps/tree-house-authentication'
```

## JWT

### Configuration

```javascript
const jwtSettings = {
  algorithm: 'HS256',
  expiresIn: '7d',
  audience: 'TREEHOUSE-AUTH',
  issuer: 'treehouse-authentication',
  secretOrKey: '5kZxE|gZu1ODB183s772)/3:l_#5hU3Gn5O|2ux3&lhN@LQ6g+"i$zqB_C<6',
};
```

> You can find all possible configuration options at [Github: node-jsonwebtoken](https://github.com/auth0/node-jsonwebtoken)

### createJwt(payload, jwtSettings)

Returns a json webtoken with the provided payload and configuration. (**Asynchronous**)

### authenticateJwt(token, jwtSettings)

Returns a decoded jwt token when the provided token is still valid. (**Asynchronous**)

### decodeJwt(token)

Returns a decoded json webtoken. This does not validate the token. (**Synchronous**)

## Sessions

### getSession(options)

Returns an express middleware function to use on session based routes using the `express-session` module. (**Synchronous**)

```javascript
const app = express();

const session = getSession({
  secret: 'mySuperSecretSecret'
});

app.use(session);
```

- [All available express-session options](https://github.com/expressjs/session)

## Two-factor authentication

Two-factor authentication functions using the `speakeasy` module.

### generate2FAKey(options)

Returns two-factor authentication key with base32 and otp-authentication url needed for QR code generation

```javascript
const { otpauth_url, base32, ... } = generate2FAKey();
```

- [All available speakeasy options](https://github.com/speakeasyjs/speakeasy)

### generateQrCode(options)

Returns QR code image data, user secret, and url (if you wish to have a custom qr code implementation)

```javascript
const { imageData, secret, url } = generateQrCode(options);
```

- [All available speakeasy options](https://github.com/speakeasyjs/speakeasy)

### verifyToken(secret, token)

Verify whether a token is valid depending on a provided user secret (returns true/false)

```javascript
const isValidCode = verifyToken('userSecret', 021214);
```

## LDAP

### CreateLdapClient(clientOptions, dnString, password)

- [All available ldapClient options](http://ldapjs.org/client.html)

WARNING !! : unbind function does not work in node 10
See (https://github.com/joyent/node-ldapjs/issues/483)

### searchUsers(ldapClient, dnString, filterOptions)

- [All available filter options](http://ldapjs.org/client.html)

#### Example

```javascript
const clientOptions = {
  url: 'ldap://ldap.forumsys.com',
  port: '389',
};
const dnString = 'cn=read-only-admin,dc=example,dc=com';
const password = 'password';

// create a client instance that is connected with the directory server
const client = createLdapClient(clientOptions, dnString, password);

const searchDn = 'dc=example,dc=com';
const filterOptions = {
        filter: '(objectClass=*)',
        scope: 'sub',
      };

//Search users in the directory server
const users = await searchUsers(client,searchDn, filterOptions)
```

## SAML

### createLoginRequest(serviceProvider, identityProvider, binding)

Returns a login url to the identity provider

### parseSAMLResponse(serviceProvider, identityProvider, request)

Parses the SAML request to a JSON object

### createLogout(serviceProvider, identityProvider, user, redirectUrl?)

Creates an SSO logout url for the given user (sp initiated)

### createServiceProvider(xmlMetaData: string | Buffer, args: ServiceProviderSettings = {})

Creates a service provider object to interact with.

- [All service provider options](https://samlify.js.org/#/sp)

### createIdentityProvider(xmlMetaData: string | Buffer, args: IdentityProviderSettings = {})

Creates an identityProvider object to interact with

- [All identity provider options](https://samlify.js.org/#/sp)

#### Example

```javascript
 const serviceProvider = createServiceProvider(...);
 const identityProvider = createIdentityProvider(...);

  // Login
  async (req, res) => {
    const loginUrl = createLoginRequest(serviceProvider, identityProvider, 'redirect')
    res.redirect(loginUrl);
  }

  // The identity provider will send SAML response upon successful authentication
  // We will validate the response
  async (req, res) => {
    const user = parseSAMLResponse(serviceProvider, identityProvider, req);
    if (user) { /* business logic} */ }
  }

  // Logout
  async (req, res) => {
    const logoutUrl = createLogout(serviceProvider, identityProvider, user, redirectUrl)
    res.redirect(logoutUrl)
  }

```

- [All available samlify options](https://github.com/tngan/samlify)

## Utilities

### generateRandomHash(algorithm (optional), secret (optional))

Returns a random hash (can be used for tokens) (**Synchronous**)

### getHashedPassword(password, saltCount)

Returns a hashed password. (**Asynchronous**)

### comparePassword(password, hashedPw)

Check whether a password is valid compared with a hashed password. (**Asynchronous**)

### hashPassword(password, options = { algorithm, key, iv})

Hash a password. (**Asynchronous**)

### dehashPassword(password, options = { algorithm, key, iv})

Dehash a password. (**Asynchronous**)

## Tests

  You can run `npm run test` to run all tests
  You can run `npm run test:coverage` to run all tests with coverage report

## Authors

See the list of [contributors](https://github.com/icapps/tree-house-authentication/contributors) who participated in this project.

## License

This project is licensed under the ISC License - see the [LICENSE.md](LICENSE.md) file for details


text:
from __future__ import unicode_literals
import re
import string
from urlparse import urlparse, parse_qs
from mopidy import backend
from mopidy.models import SearchResult, Track, Album, Artist
import pykka
import pafy
import requests
import unicodedata
from mopidy_youtube import logger

yt_api_endpoint = 'https://www.googleapis.com/youtube/v3/'
yt_key = 'AIzaSyAl1Xq9DwdE_KD4AtPaE4EJl3WZe2zCqg4'

def resolve_track(track, stream=False):
    logger.debug("Resolving Youtube for track '%s'", track)
    if hasattr(track, 'uri'):
        return resolve_url(track.comment, stream)
    else:
        return resolve_url(track.split('.')[-1], stream)

def safe_url(uri):
    valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
    safe_uri = unicodedata.normalize(
        'NFKD',
        unicode(uri)
    ).encode('ASCII', 'ignore')
    return re.sub(
        '\s+',
        ' ',
        ''.join(c for c in safe_uri if c in valid_chars)
    ).strip()

def resolve_url(url, stream=False):
    video = pafy.new(url)
    if not stream:
        uri = 'youtube:video/%s.%s' % (
            safe_url(video.title), video.videoid
        )
    else:
        uri = video.getbestaudio()
        if not uri:  # get video url
            uri = video.getbest()
        logger.debug('%s - %s %s %s' % (
            video.title, uri.bitrate, uri.mediatype, uri.extension))
        uri = uri.url
    if not uri:
        return

    if '-' in video.title:
        title = video.title.split('-')
        track = Track(
            name=title[1].strip(),
            comment=video.videoid,
            length=video.length*1000,
            artists=[Artist(name=title[0].strip())],
            album=Album(
                name='Youtube',
                images=[video.bigthumb, video.bigthumbhd]
            ),
            uri=uri
        )
    else:
        track = Track(
            name=video.title,
            comment=video.videoid,
            length=video.length*1000,
            album=Album(
                name='Youtube',
                images=[video.bigthumb, video.bigthumbhd]
            ),
            uri=uri
        )
    return track

def search_youtube(q):
    query = {
        'part': 'id',
        'maxResults': 15,
        'type': 'video',
        'q': q,
        'key': yt_key
    }
    pl = requests.get(yt_api_endpoint+'search', params=query)
    playlist = []
    for yt_id in pl.json().get('items'):
        try:
            track = resolve_url(yt_id.get('id').get('videoId'))
            playlist.append(track)
        except Exception as e:
            logger.info(e.message)
    return playlist

def resolve_playlist(url):
    logger.info("Resolving Youtube for playlist '%s'", url)
    query = {
        'part': 'snippet',
        'maxResults': 50,
        'playlistId': url,
        'fields': 'items/snippet/resourceId',
        'key': yt_key
    }
    pl = requests.get(yt_api_endpoint+'playlistItem', params=query)
    playlist = []
    for yt_id in pl.json().get('items'):
        try:
            yt_id = yt_id.get('snippet').get('resourceId').get('videoId')
            playlist.append(resolve_url(yt_id))
        except Exception as e:
            logger.info(e.message)
    return playlist

class YoutubeBackend(pykka.ThreadingActor, backend.Backend):

    def __init__(self, config, audio):
        super(YoutubeBackend, self).__init__()
        self.config = config
        self.library = YoutubeLibraryProvider(backend=self)
        self.playback = YoutubePlaybackProvider(audio=audio, backend=self)

        self.uri_schemes = ['youtube', 'yt']

class YoutubeLibraryProvider(backend.LibraryProvider):

    def lookup(self, track):
        if 'yt:' in track:
            track = track.replace('yt:', '')

        if 'youtube.com' in track:
            url = urlparse(track)
            req = parse_qs(url.query)
            if 'list' in req:
                return resolve_playlist(req.get('list')[0])
            else:
                return [resolve_url(track)]
        else:
            return [resolve_url(track)]

    def search(self, query=None, uris=None):
        if not query:
            return

        if 'uri' in query:
            search_query = ''.join(query['uri'])
            url = urlparse(search_query)
            if 'youtube.com' in url.netloc:
                req = parse_qs(url.query)
                if 'list' in req:
                    return SearchResult(
                        uri='youtube:search',
                        tracks=resolve_playlist(req.get('list')[0])
                    )
                else:
                    logger.info(
                        "Resolving Youtube for track '%s'", search_query)
                    return SearchResult(
                        uri='youtube:search',
                        tracks=[resolve_url(search_query)]
                    )
        else:
            search_query = '|'.join(query.values()[0])
            logger.info("Searching Youtube for query '%s'", search_query)
            return SearchResult(
                uri='youtube:search',
                tracks=search_youtube(search_query)
            )

class YoutubePlaybackProvider(backend.PlaybackProvider):

    def play(self, track):
        track = resolve_track(track, True)
        return super(YoutubePlaybackProvider, self).play(track)


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

namespace Vertica.Utilities.Collections
{
	public class Tree<TModel, TKey> : Tree<TModel, TModel, TKey>
	{
		protected internal Tree(IEnumerable<TModel> items, Func<TModel, TKey> key, Func<TModel, Parent, Parent.Key> parentKey, IEqualityComparer<TKey> comparer = null)
			: base(items, key, parentKey, x => x, comparer)
		{
		}
	}

	public class Tree<TItem, TModel, TKey> : IEnumerable<TreeNode<TModel>>
	{
	    private readonly Dictionary<TKey, Node> _tree;
		private readonly List<TKey> _root;
		private readonly HashSet<TKey> _orphans;

		protected internal Tree(IEnumerable<TItem> items, Func<TItem, TKey> key, Func<TItem, Parent, Parent.Key> parentKey, Func<TItem, TModel> projection, IEqualityComparer<TKey> comparer = null)
		{
			if (items == null) throw new ArgumentNullException("items");
			if (key == null) throw new ArgumentNullException("key");
			if (parentKey == null) throw new ArgumentNullException("parentKey");
			if (projection == null) throw new ArgumentNullException("projection");

			// Optimize by setting the initial count to the number of items (if item is List, Collection, Array)
            _tree = new Dictionary<TKey, Node>(TreeCapacityOr(items as ICollection<TModel>, 0), comparer);

            _root = new List<TKey>();
			_orphans = new HashSet<TKey>(comparer);

			var parentHelper = new Parent();

			// Initialize Tree with all items
			foreach (TItem item in items)
			{
				TKey itemKey = key(item);

			    Node itemNode;
			    if (!_tree.TryGetValue(itemKey, out itemNode))
			        _tree[itemKey] = itemNode = new Node(itemKey, projection(item));

                Parent.Key itemParentKey = parentKey(item, parentHelper);

                if (itemParentKey != null)
			        itemNode.Parents.Add(itemParentKey);
			}

			// Relate children to their parents
            foreach (Node item in _tree.Values)
			{
				// Test if we have a parent
				if (item.Parents.Count > 0)
				{
				    bool isOrphan = true;

				    foreach (var itemParentKey in item.Parents)
				    {
                        Node parent;
                        if (_tree.TryGetValue(itemParentKey.Value, out parent))
                        {
                            parent.Children.Add(item.Key);
                            isOrphan = false;
                        }
                    }

                    if (isOrphan)
                        _orphans.Add(item.Key);
                }
				else
				{
					_root.Add(item.Key);
				}
			}
		}

		private static int TreeCapacityOr(ICollection<TModel> collection, int defaultCapacity)
		{
			return collection != null ? collection.Count : defaultCapacity;
		}

		public TreeNode<TModel> this[int index]
		{
			get { return Get(_root[index]); }
		}

		public TreeNode<TModel> Get(TKey key)
		{
			TreeNode<TModel> node;
			if (!TryGet(key, out node))
				throw new KeyNotFoundException(String.Format(@"Node with key {0} was not found.", key));

			return node;
		}

		public bool TryGet(TKey key, out TreeNode<TModel> node)
		{
			node = null;

			Node item;
			if (!_orphans.Contains(key) && _tree.TryGetValue(key, out item))
			{
				node = new TreeNode<TModel>(
					_tree[key].Model,
					() => GetEnumerator(item.Children),
 					index => Get(item.Children[index]),
					item.Parents.Select(x => Get(x.Value)));
			}

			return node != null;
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public IEnumerator<TreeNode<TModel>> GetEnumerator()
		{
			return GetEnumerator(_root);
		}

		public IEnumerable<TModel> Orphans()
		{
			return _orphans.Select(x => _tree[x].Model);
		}

		public int Count
		{
			get { return _tree.Count - _orphans.Count; }
		}

		private IEnumerator<TreeNode<TModel>> GetEnumerator(List<TKey> nodes)
		{
			if (nodes == null) throw new ArgumentNullException("nodes");

			return nodes
				.Select(x =>
				{
					TreeNode<TModel> node;
					TryGet(x, out node);
					return node;
				})
				.Where(x => x != null)
				.GetEnumerator();
		}

	    private class Node
	    {
	        public Node(TKey key, TModel model)
	        {
	            Key = key;
	            Model = model;

                // No way to optimize/guess the initial capacity of the lists
                Parents = new List<Parent.Key>();
                Children = new List<TKey>();
            }

	        public TKey Key { get; private set; }
	        public TModel Model { get; private set; }

	        public List<Parent.Key> Parents { get; private set; }
            public List<TKey> Children { get; private set; }
	    }

		public class Parent
		{
			public Key Value(TKey key)
			{
				return new Key(key);
			}

			public Key None { get { return null; } }

			public class Key
			{
				internal Key(TKey key)
				{
					Value = key;
				}

				internal TKey Value { get; private set; }
			}
		}
	}

	public class TreeNode<TModel> : IEnumerable<TreeNode<TModel>>
	{
		private readonly Func<IEnumerator<TreeNode<TModel>>> _children;
		private readonly Func<int, TreeNode<TModel>> _childNodeAt;
		private readonly IEnumerable<TreeNode<TModel>> _parents;

		internal TreeNode(TModel model, Func<IEnumerator<TreeNode<TModel>>> children, Func<int, TreeNode<TModel>> childNodeAt, IEnumerable<TreeNode<TModel>> parents)
		{
			Model = model;
			_children = children;
			_childNodeAt = childNodeAt;
			_parents = parents;
		}

		public TreeNode<TModel> this[int index]
		{
			get { return _childNodeAt(index); }
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public IEnumerator<TreeNode<TModel>> GetEnumerator()
		{
			return _children();
		}

	    public IEnumerable<TreeNode<TModel>> Parents
	    {
	        get { return _parents; }
	    }

	    public TreeNode<TModel> Parent
		{
			get { return Parents.FirstOrDefault(); }
		}

	    public TModel Model { get; private set; }

		public TModel[] Breadcrumb()
		{
			var stack = new Stack<TModel>();

			TreeNode<TModel> current = this;

			while (current != null)
			{
				stack.Push(current.Model);
				current = current.Parent;
			}

			return stack.ToArray();
		}
	}
}


text:
package com.google.gwt.editor.client.adapters;

import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.view.client.HasData;

import java.util.Collections;

/**
 * Adapts the HasData interface to the Editor framework.
 *
 * @param <T> the type of data to be edited
 */
public class HasDataEditor<T> extends ListEditor<T, LeafValueEditor<T>> {
  static class HasDataEditorSource<T> extends EditorSource<LeafValueEditor<T>> {
    private final HasData<T> data;

    public HasDataEditorSource(HasData<T> data) {
      this.data = data;
    }

    @Override
    public IndexedEditor<T> create(int index) {
      return new IndexedEditor<T>(index, data);
    }

    @Override
    public void dispose(LeafValueEditor<T> subEditor) {
      data.setRowCount(data.getRowCount() - 1);
    }

    @Override
    public void setIndex(LeafValueEditor<T> editor, int index) {
      ((IndexedEditor<T>) editor).setIndex(index);
    }
  }

  static class IndexedEditor<Q> implements LeafValueEditor<Q> {
    private int index;
    private Q value;
    private final HasData<Q> data;

    IndexedEditor(int index, HasData<Q> data) {
      this.index = index;
      this.data = data;
    }

    public Q getValue() {
      return value;
    }

    public void setIndex(int index) {
      this.index = index;
      push();
    }

    public void setValue(Q value) {
      this.value = value;
      push();
    }

    private void push() {
      data.setRowData(index, Collections.singletonList(value));
    }
  }

  /**
   * Create a HasDataEditor backed by a HasData.
   *
   * @param <T> the type of data to be edited
   * @param data the HasData that is displaying the data
   * @return a instance of a HasDataEditor
   */
  public static <T> HasDataEditor<T> of(HasData<T> data) {
    return new HasDataEditor<T>(data);
  }

  /**
   * Prevent subclassing.
   */
  HasDataEditor(HasData<T> data) {
    super(new HasDataEditorSource<T>(data));
  }
}


text:
<?php

namespace thinker_g\HermesMailing\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;

/**
 * MailController implements the CRUD actions for HermesMail model.
 * @property \thinker_g\HermesMailing\Module $module
 */
class MailController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all HermesMail models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = Yii::createObject($this->module->searchModelClass);

        $dataProvider = new ActiveDataProvider([
            'query' => $searchModel->find(),
            'pagination' => ['pageSize' => 10]
        ]);

        $searchModel->load(Yii::$app->request->queryParams);
        if ($searchModel->validate()) {
            foreach ($searchModel->attributes as $key => $value) {
                $dataProvider->query->andFilterWhere(['like', $key, $value]);
            }
        }

        return $this->render($this->module->indexView, [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single HermesMail model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render($this->module->viewView, [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new HermesMail model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = Yii::createObject($this->module->modelClass);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render($this->module->createView, [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing HermesMail model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render($this->module->updateView, [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing HermesMail model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the HermesMail model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return HermesMail the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        $modelClass = $this->module->modelClass;
        if (($model = $modelClass::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
import librosa, librosa.core, librosa.display
import pandas as pd
import numpy as np
from pyvad import vad #, trim, split
from skimage.util.shape import view_as_windows
import speechpy
import soundfile as sf
import os
import zipfile
import tempfile
import pickle
import keras

class warpqMetric(object):
    '''
    warpqModel: Main class of WARP-Q metric to estimate quality scores.
    It contains the required subfunctions and evaluation process.
    '''

    def __init__(self, args):
        '''
        Initialize the object's state
        Inputs:
        1) The self
        2) args:
            - mode: predict_csv or predict_file
            - csv_input: input csv file name for predict_csv mode
            - csv_ourput: output csv file name for predict_csv mode
            - org: original speech file for predict_file mode
            - deg: degraded speech file for predict_file mode
            - sr: sampling frequency, Hz
            - n_mfcc: number of MFCCs
            - fmax: cutoff frequency
            - patch_size: size of each patch in seconds
            - sigma: step size conditon for DTW
            - apply_vad: condition for using vad algorithm
            - mapping_model: file name of pretrained model for score mapping
        '''

        self.args = args

        if not self.args['sr'] in (8000, 16000):
            print("Sampling rate of audio files should be either 8 kHz or 16 kHz.")
            exit()

        # MFCC and DTW parameters
        self.win_length = int(0.032*self.args['sr']) #32 ms frame
        self.hop_length = int(0.004*self.args['sr']) #4 ms overlap
        #self.hop_length = int(0.016*self.sr)
        self.dtw_metric = 'euclidean'
        self.n_fft = 2*self.win_length
        self.lifter = 3

        # VAD Parameters
        self.hop_size_vad = 30
        self.sr_vad = self.args['sr']
        self.aggresive = 0

        # some prints
        print('\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
        print('    WARP-Q: Quality Prediction For Generative Neural Speech Codecs       ')
        print('+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
        print('\nRun WARP-Q metric with:')
        print('- sr = ' + str(self.args['sr']) + ' Hz')
        print('- ' + str(self.args['mode']) + ' mode')

        # Load mapping model
        print('- mapping raw quality scores onto MOS using a ML model')
        self.load_model(args['mapping_model'])

    def load_model(self, zip_path):
        '''
        Load trained mapping model with its data scaler
        '''
        print('\nLoading mapping model and data scaler from ' + zip_path + ':')

        # Create a temp dir
        with tempfile.TemporaryDirectory() as tmpdirname:

            # Extract the zip file
            with zipfile.ZipFile(zip_path) as thezip:
                thezip.extractall(tmpdirname)
                #print('The zip file of the model has been extracted in a temp directory')

            # Read model
            isH5Exist = os.path.exists(os.path.join(tmpdirname, 'mapping_model.h5'))

            if isH5Exist:
                try:
                    self.mapping_model =  keras.models.load_model(os.path.join(tmpdirname, 'mapping_model.h5'))
                except Exception as e:
                    print(e)
                    exit()
                self.mapping_model_type = 'dnn_sequential'
                print('Model is based on deep neural networks with a sequential stack regressor from Keras. It is trained using ' + os.path.basename(zip_path)[0:-4] + ' database \n')
                self.mapping_model.summary()
                print('\n')

            else:
                try:
                    self.mapping_model =  pickle.load(open(os.path.join(tmpdirname, 'mapping_model.pkl'), 'rb'))
                except Exception as e:
                    print(e)
                    exit()
                self.mapping_model_type = 'random_forest'
                print("Model is based on a random forest regressor from Sklearn. It is trained using " + os.path.basename(zip_path)[0:-4] + ' database \n')
                #print('\n')

            try: # Read data scaler
                self.data_scaler = pickle.load(open(os.path.join(tmpdirname, 'data_scaler.pkl'), 'rb'))
            except Exception as e:
                print(e)
                exit()

    def load_audio(self, ref_path, test_path):
        ''' Load speech files '''

        # 1) Load reference audio
        if ref_path[-4:] == '.wav':
            speech_Ref, sr_Ref = librosa.load(ref_path, sr=self.args['sr'])
        else:
            if ref_path[-4:] == '.SRC': #For ITUT database if applicable
                speech_Ref, sr_Ref  = sf.read(ref_path, format='RAW', channels=1, samplerate=16000,
                               subtype='PCM_16', endian='LITTLE')
                if sr_Ref != self.args.sr:
                    speech_Ref = librosa.resample(speech_Ref, sr_Ref, self.args['sr'])

        # 2) Load coded audio
        if test_path[-4:] == '.wav':
            speech_Coded, sr_Coded = librosa.load(test_path,sr=self.args['sr'])
        else:
            if test_path[-4:] == '.OUT': #For ITUT database if applicable
                speech_Coded, sr_Coded  = sf.read(test_path, format='RAW', channels=1, samplerate=16000,
                               subtype='PCM_16', endian='LITTLE')
                if sr_Coded != self.args.sr:
                    speech_Coded = librosa.resample(speech_Coded, sr_Coded, self.args['sr'])

        # Make sure amplitudes are in the range of [-1, 1] otherwise clipping to -1 to 1
        # after resampling (if applicable). We experienced this issue for the TCD-VOIP database only
        speech_Ref[speech_Ref>1]=1.0
        speech_Ref[speech_Ref<-1]=-1.0

        speech_Coded[speech_Coded>1]=1.0
        speech_Coded[speech_Coded<-1]=-1.0

        return speech_Ref, speech_Coded

    def compute_alignment_cost(self, patch, mfcc_Ref):
        '''
        Compute the alignment cost between two spectral representations using
        Subsequence DTW. For more details, please see Subsection 3.3 of our paper
        "W. A. Jassim, J. Skoglund, M. Chinen, and A. Hines, "Speech quality assessment
        with WARP‐Q: From similarity to subsequence dynamic time warp cost,
        IET Signal Processing, 1– 21 (2022)". Available on:
        https://ietresearch.onlinelibrary.wiley.com/doi/pdfdirect/10.1049/sil2.12151
        '''

        D, P = librosa.sequence.dtw(X = patch,
                                    Y = mfcc_Ref,
                                    metric = self.dtw_metric,
                                    step_sizes_sigma = self.args['sigma'],
                                    weights_mul = np.array([1, 1, 1]),
                                    band_rad = 0.25,
                                    subseq = True,
                                    backtrack = True)
        P_librosa = P[::-1, :]
        b_ast = P_librosa[-1, 1]

        return D[-1, b_ast] / D.shape[0]

    def get_feaures_for_score_mapping(self, Acc):
        '''
        Extract features from alignment costs vector to map raw WARP-Q scores
        onto MOS. For more details, please see Section 8 of our paper
        "W. A. Jassim, J. Skoglund, M. Chinen, and A. Hines, "Speech quality assessment
        with WARP‐Q: From similarity to subsequence dynamic time warp cost,
        IET Signal Processing, 1– 21 (2022)". Available on:
        https://ietresearch.onlinelibrary.wiley.com/doi/pdfdirect/10.1049/sil2.12151
        '''

        Acc_df = pd.DataFrame({'Acc':Acc})

        Acc_fea = dict()
        Acc_fea['warpq_count']    = Acc_df['Acc'].count()
        Acc_fea['warpq_mean']     = Acc_df['Acc'].mean()
        Acc_fea['warpq_median']   = Acc_df['Acc'].median()
        Acc_fea['warpq_var']      = Acc_df['Acc'].var()
        Acc_fea['warpq_std']      = Acc_df['Acc'].std()
        Acc_fea['warpq_min']      = Acc_df['Acc'].min()
        Acc_fea['warpq_max']      = Acc_df['Acc'].max()

        quantile = Acc_df.quantile([.25,.5,.75])

        Acc_fea['warpq_25%']      = quantile.iloc[0,0]
        Acc_fea['warpq_50%']      = quantile.iloc[1,0]
        Acc_fea['warpq_75%']      = quantile.iloc[2,0]
        Acc_fea['warpq_skewness'] = Acc_df['Acc'].skew()
        Acc_fea['warpq_kurtosis'] = Acc_df['Acc'].kurtosis()

        return pd.DataFrame.from_dict([Acc_fea])

    def evaluate(self, ref_path, test_path):
        '''
        Compute WARP-Q score between two input speech signals
        Inputs:
        1) The self
        2) refPath: path of reference speech
        3) disPath: path pf degraded speech

        Output:
        WARP-Q quality score between refPath and disPath
        '''

        # Load speech files
        speech_Ref, speech_Coded = self.load_audio(ref_path, test_path)

        if self.args['apply_vad']:
            # VAD for Ref speech
            vact1 = vad(speech_Ref,
                        self.args['sr'],
                        fs_vad = self.sr_vad,
                        hop_length = self.hop_size_vad,
                        vad_mode = self.aggresive)

            speech_Ref = speech_Ref[vact1==1]

            # VAD for Coded speech
            vact2 = vad(speech_Coded,
                        self.args['sr'],
                        fs_vad = self.sr_vad,
                        hop_length = self.hop_size_vad,
                        vad_mode = self.aggresive)

            speech_Coded = speech_Coded[vact2==1]

        # Compute MFCC features for the two signals
        mfcc_Ref = librosa.feature.mfcc(y = speech_Ref,
                                        sr = self.args['sr'],
                                        n_mfcc = self.args['n_mfcc'],
                                        fmax = self.args['fmax'],
                                        n_fft = self.n_fft,
                                        win_length = self.win_length,
                                        hop_length = self.hop_length,
                                        lifter = self.lifter)

        mfcc_Coded = librosa.feature.mfcc(y = speech_Coded,
                                          sr = self.args['sr'],
                                          n_mfcc = self.args['n_mfcc'],
                                          fmax = self.args['fmax'],
                                          n_fft = self.n_fft,
                                          win_length = self.win_length,
                                          hop_length = self.hop_length,
                                          lifter = self.lifter)

        # Feature Normalisation using CMVNW method
        mfcc_Ref = speechpy.processing.cmvnw(mfcc_Ref.T,
                                             win_size = 201,
                                             variance_normalization = True).T

        mfcc_Coded = speechpy.processing.cmvnw(mfcc_Coded.T,
                                               win_size = 201,
                                               variance_normalization = True).T

        # Divid MFCC features of Coded speech into patches
        cols = int(self.args['patch_size']/(self.hop_length/self.args['sr']))
        window_shape = (np.size(mfcc_Ref,0), cols)
        step  = int(cols/2)

        mfcc_Coded_patch = view_as_windows(mfcc_Coded, window_shape, step)

        Acc =[]
        #band_rad = 0.25
        #weights_mul = np.array([1, 1, 1])

        # Compute alignment cost between each patch and Ref MFCCs
        for i in range(mfcc_Coded_patch.shape[1]):

            patch = mfcc_Coded_patch[0][i]
            score = self.compute_alignment_cost(patch, mfcc_Ref)
            Acc.append(score)

        # Raw quality score
        rawScore = round(np.median(Acc), 3) #Eq. 3 in [1]

        # Map raw score onto MOS
        fea = self.get_feaures_for_score_mapping(Acc)
        fea_scaled = self.data_scaler.transform(fea)

        if self.mapping_model_type == 'dnn_sequential':
            prediction  = self.mapping_model.predict(fea_scaled, verbose=0)
        else:
            prediction  = self.mapping_model.predict(fea_scaled)

        # remove unstable values
        mappedScore = round(prediction.item(), 3)
        if mappedScore > 5:
            mappedScore = 5
        if mappedScore < 1:
            mappedScore = 1

        # Return scores
        return rawScore, mappedScore


text:
package cop.raml.mocks;

import javax.annotation.processing.Filer;
import javax.lang.model.element.Element;
import javax.tools.FileObject;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import java.io.IOException;

/**
 * @author Oleg Cherednik
 * @since 24.01.2017
 */
public class FilerMock implements Filer {
    private final FileObjectMock resource = new FileObjectMock();

    public FileObjectMock getResource() {
        return resource;
    }

    // ========== Filer ==========

    @Override
    public JavaFileObject createSourceFile(CharSequence name, Element... originatingElements) throws IOException {
        return null;
    }

    @Override
    public JavaFileObject createClassFile(CharSequence name, Element... originatingElements) throws IOException {
        return null;
    }

    @Override
    public FileObject createResource(JavaFileManager.Location location, CharSequence pkg, CharSequence relativeName, Element... originatingElements)
            throws IOException {
        return resource;
    }

    @Override
    public FileObject getResource(JavaFileManager.Location location, CharSequence pkg, CharSequence relativeName) throws IOException {
        return resource;
    }
}


text:
__author__ = 'Robin Gottfried <google@kebet.cz>'

from os.path import basename
import sys

try:
    from OpenSSL.crypto import load_pkcs12, dump_privatekey, FILETYPE_PEM
except ImportError:
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        raise

    print """OpenSSL library not found. Please install pyOpenSSL."""
    try:
        import pip
    except ImportError:
        pass
    else:
        print "I found that you have pip installed, would you like me to install pyOpenSSL for you? [y/n]"
        answer = raw_input()
        if answer.lower() in ['y', 'yes', 'yeah', 'yeah!']:
            pip.main(['install', 'pyOpenSSL'])
            from OpenSSL.crypto import load_pkcs12, dump_privatekey, FILETYPE_PEM
            print "\n\n\nOpenSSL library installed.\n\n\n"
        else:
            print "Exitting.\n\nYou must install pyOpenSSL manually to use this utility.\n(ie. by running `pip install pyOpenSSL`\n\n"

def _usage():
    print """USAGE: %s <pkcs12_file> [<pem_file>]
    pkcs12_file ... the key you downloaded from Google Console
    pem_file    ... the key to be used in this library

    If no pem_file is specified as argument, it will be written to std out.
""" % basename(sys.argv[0])

def main(*args):
    if len(args) < 2:
        _usage()
        sys.exit(1)
    archive = load_pkcs12(open(args[1], 'rb').read(), 'notasecret')
    key = archive.get_privatekey()
    pem = dump_privatekey(FILETYPE_PEM, key)
    if len(args) > 2:
        f = open(args[2], 'wb')
        f.write(pem)
        f.close()
        return ''
    else:
        return pem

if __name__ == '__main__':
    print main(*sys.argv)


text:
package ecscni

import (
	"io/ioutil"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

const (
	// ECSCNIVersion, ECSCNIGitHash, VPCCNIGitHash needs to be updated every time CNI plugin is updated.
	currentECSCNIVersion = "2020.09.0"
	currentECSCNIGitHash = "db5864722987c34ba309e6e7a7628fd1ccad1520"
	currentVPCCNIGitHash = "199bfc65cced4951cbb6a38e6e828afa8c2b023c"
)

// Asserts that CNI plugin version matches the expected version
func TestCNIPluginVersionNumber(t *testing.T) {
	versionStr := getCNIVersionString(t)
	assert.Equal(t, currentECSCNIVersion, versionStr)
}

// Asserts that CNI plugin version is upgraded when new commits are made to CNI plugin submodule
func TestCNIPluginVersionUpgrade(t *testing.T) {
	versionStr := getCNIVersionString(t)
	cmd := exec.Command("git", "submodule")
	versionInfo, err := cmd.Output()
	assert.NoError(t, err, "Error running the command: git submodule")
	versionInfoStrList := strings.Split(string(versionInfo), "\n")
	// If a new commit is added, version should be upgraded
	if currentECSCNIGitHash != strings.Split(versionInfoStrList[0], " ")[1] {
		assert.NotEqual(t, currentECSCNIVersion, versionStr)
	}
	assert.Equal(t, currentVPCCNIGitHash, strings.Split(versionInfoStrList[1], " ")[1])
}

// Returns the version in CNI plugin VERSION file as a string
func getCNIVersionString(t *testing.T) string {
	// ../../amazon-ecs-cni-plugins/VERSION
	versionFilePath := filepath.Clean(filepath.Join("..", "..", "amazon-ecs-cni-plugins", "VERSION"))
	versionStr, err := ioutil.ReadFile(versionFilePath)
	assert.NoError(t, err, "Error reading the CNI plugin version file")
	return strings.TrimSpace(string(versionStr))
}


text:
. `dirname $0`/saenv.sh

$SA_JAVA_CMD sun.jvm.hotspot.tools.StackTrace $*


text:
#ifndef RenderSVGResourceLinearGradient_h
#define RenderSVGResourceLinearGradient_h

#include "core/rendering/svg/RenderSVGResourceGradient.h"
#include "core/svg/LinearGradientAttributes.h"

namespace blink {

class SVGLinearGradientElement;

class RenderSVGResourceLinearGradient final : public RenderSVGResourceGradient {
public:
    explicit RenderSVGResourceLinearGradient(SVGLinearGradientElement*);
    virtual ~RenderSVGResourceLinearGradient();

    virtual const char* renderName() const override { return "RenderSVGResourceLinearGradient"; }

    static const RenderSVGResourceType s_resourceType = LinearGradientResourceType;
    virtual RenderSVGResourceType resourceType() const override { return s_resourceType; }

    virtual SVGUnitTypes::SVGUnitType gradientUnits() const override { return m_attributes.gradientUnits(); }
    virtual void calculateGradientTransform(AffineTransform& transform) override { transform = m_attributes.gradientTransform(); }
    virtual bool collectGradientAttributes(SVGGradientElement*) override;
    virtual void buildGradient(GradientData*) const override;

    FloatPoint startPoint(const LinearGradientAttributes&) const;
    FloatPoint endPoint(const LinearGradientAttributes&) const;

    virtual void trace(Visitor*) override;

private:
    LinearGradientAttributes m_attributes;
};

} // namespace blink

#endif // RenderSVGResourceLinearGradient_h


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use JMS\Serializer\Annotation\ExclusionPolicy,
    JMS\Serializer\Annotation\Expose,
    JMS\Serializer\Annotation\SerializedName;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * Notification
 *
 * @ORM\Table(name="notification")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\NotificationRepository")
 * @ExclusionPolicy("all")
 */
class Notification
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="guid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     * @Expose()
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     * @Expose()
     * @Assert\NotBlank(message="le title est obligatoire")
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="type", type="string", length=255)
     * @Expose()
     * @Assert\NotBlank(message="le type est obligatoire")
     */
    private $type;

    /**
     * @var string
     *
     * @ORM\Column(name="idType", type="string", length=255)
     * @Expose()
     * @SerializedName("idType")
     * @Assert\NotBlank(message="l'id du type est obligatoire")
     */
    private $idType;

    /**
     * @var string
     *
     * @ORM\Column(name="message", type="text")
     * @Expose()
     * @Assert\NotBlank(message="le message est obligatoire")
     */
    private $message;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateNotification", type="datetime",nullable=true)
     * @Expose()
     * @SerializedName("dateNotification")
     */
    private $dateNotification;

    /**
     * @ORM\ManyToOne(targetEntity="User")
     * @ORM\JoinColumn(nullable=false)
     * @Assert\NotNull(message="Le user est obligatoire")
     */
    private $user;

    /**
     * Notification constructor.
     * @param int $id
     */
    public function __construct()
    {
        $this->dateNotification = new \DateTime();
    }

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

    /**
     * Set title
     *
     * @param string $title
     *
     * @return Notification
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set message
     *
     * @param string $message
     *
     * @return Notification
     */
    public function setMessage($message)
    {
        $this->message = $message;

        return $this;
    }

    /**
     * Get message
     *
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * Set user
     *
     * @param \AppBundle\Entity\User $user
     *
     * @return Notification
     */
    public function setUser(\AppBundle\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \AppBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set type
     *
     * @param string $type
     *
     * @return Notification
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set idType
     *
     * @param string $idType
     *
     * @return Notification
     */
    public function setIdType($idType)
    {
        $this->idType = $idType;

        return $this;
    }

    /**
     * Get idType
     *
     * @return string
     */
    public function getIdType()
    {
        return $this->idType;
    }
}


text:
**Lists**
- [Wikipedia List of datasets for machine learning research](https://en.wikipedia.org/wiki/List_of_datasets_for_machine_learning_research)
- [Awesome Public Datasets](https://github.com/caesar0301/awesome-public-datasets)
- [UCI Machine Learning Repository](http://archive.ics.uci.edu/ml/datasets.html)
- [sklearn.datasets](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.datasets)
- [Rdatasets list](http://vincentarelbundock.github.io/Rdatasets/datasets.html)
- [17 places to find datasets for data science projects](http://www.dataquest.io/blog/free-datasets-for-projects/)
- [Machine Learning Data Set Repository](http://mldata.org/)
- [The Greatest Public Datasets for AI](https://medium.com/startup-grind/fueling-the-ai-gold-rush-7ae438505bc2)
- [AWS Public Datasets Home](https://aws.amazon.com/datasets/)
- [AWS Public Datasets](https://aws.amazon.com/public-datasets/)
- [100+ Interesting Data Sets for Statistics](http://rs.io/100-interesting-data-sets-for-statistics/)
- [Kaggle Datasets](https://www.kaggle.com/datasets)
- [FiveThirtyEight data](https://github.com/fivethirtyeight/data)
- [Google BigQuery Public Datasets](https://cloud.google.com/bigquery/public-data/)
- [Stanford Large Network Dataset Collection](http://snap.stanford.edu/data/#!)
- [THE MNIST DATABASE of handwritten digits](http://yann.lecun.com/exdb/mnist/)
- [THE Wikipedia Corpus](http://corpus.byu.edu/wiki/)
- [Deep learning datasets](http://deeplearning.net/datasets/)
- [Open Data for Deep Learning](https://deeplearning4j.org/opendata)
- [Datasets for Data Mining and Data Science](http://www.kdnuggets.com/datasets/index.html)
- [100+ Interesting Data Sets for Statistics](http://rs.io/100-interesting-data-sets-for-statistics/)
- [NYC OpenData](https://data.cityofnewyork.us/browse)
- [Data.gov](https://www.data.gov/)
- [FiveThirtyEight datasets and code](https://github.com/fivethirtyeight/data)
- [data.world](https://data.world/)
- [Great IoT, Sensor and other Data Sets Repositories](https://www.datasciencecentral.com/profiles/blogs/great-sensor-datasets-to-prepare-your-next-career-move-in-iot-int)
- [Quora - Where can I find large datasets open to the public?](https://www.quora.com/Where-can-I-find-large-datasets-open-to-the-public)
- [Subreddit](https://www.reddit.com/r/datasets/)
- [AI and Deep Learning in 2017 – A Year in Review - Datasets section](http://www.wildml.com/2017/12/ai-and-deep-learning-in-2017-a-year-in-review/)
- [70 Amazing Free Data Sources You Should Know](https://www.kdnuggets.com/2017/12/big-data-free-sources.html)
- [25 Open Datasets for Deep Learning Every Data Scientist Must Work With](https://www.analyticsvidhya.com/blog/2018/03/comprehensive-collection-deep-learning-datasets/)
- [The 50 Best Free Datasets for Machine Learning](https://gengo.ai/articles/the-50-best-free-datasets-for-machine-learning/)
- [Announcing Open Images V4 and the ECCV 2018 Open Images Challenge](https://ai.googleblog.com/2018/04/announcing-open-images-v4-and-eccv-2018.html)

**Dataset By Category**
- Streaming Open Data
    + [Satori](https://www.satori.com) - Live streaming open data
- Classification
    + http://archive.ics.uci.edu/ml/datasets/Wine+Quality
    + http://archive.ics.uci.edu/ml/datasets/Wine
    + http://archive.ics.uci.edu/ml/datasets/User+Knowledge+Modeling
    + http://archive.ics.uci.edu/ml/datasets/Student+Performance
    + http://archive.ics.uci.edu/ml/datasets/seeds
    + http://archive.ics.uci.edu/ml/datasets/Iris
    + http://archive.ics.uci.edu/ml/datasets/Dow+Jones+Index
    + http://archive.ics.uci.edu/ml/datasets/BLOGGER
- Clustering
    + http://archive.ics.uci.edu/ml/datasets/User+Knowledge+Modeling
    + http://archive.ics.uci.edu/ml/datasets/Sponge
    + http://archive.ics.uci.edu/ml/datasets/seeds
    + http://archive.ics.uci.edu/ml/datasets/Dow+Jones+Index
- Recommendender
    + http://grouplens.org/datasets/movielens/
    + http://www2.informatik.uni-freiburg.de/~cziegler/BX/
    + http://grouplens.org/datasets/hetrec-2011/
    + https://en.wikipedia.org/wiki/Wikipedia:Database_download#English-language_Wikipedia
    + http://planet.openstreetmap.org/planet/full-history/
    + http://webscope.sandbox.yahoo.com/catalog.php?datatype=r
    + http://www.cs.cornell.edu/people/pabo/movie-review-data/
    + http://archive.ics.uci.edu/ml/datasets/Entree+Chicago+Recommendation+Data
- Regression
    + http://archive.ics.uci.edu/ml/datasets/Wine+Quality
    + http://archive.ics.uci.edu/ml/datasets/Student+Performance
    + http://archive.ics.uci.edu/ml/datasets/Automobile
    + http://archive.ics.uci.edu/ml/datasets/Auto+MPG
- Computer Vision and Recognition
    + http://www.cvpapers.com/datasets.html
    + http://www.image-net.org/
    + https://storage.googleapis.com/openimages/web/index.html
- IoT

**Specific Data Sets**
- [3 Million Instacart Orders, Open Sourced](https://www.instacart.com/datasets/grocery-shopping-2017)

## Data Portals and Meta portals
- [DataPortals.org](http://dataportals.org/)
- [Open Data Monitor](https://opendatamonitor.eu/frontend/web/index.php?r=dashboard%2Findex)
- [Quandl](https://www.quandl.com/)

## Data Marketplaces and Monetization
- [Dawex](https://www.dawex.com/en/)


text:
package org.spongepowered.common.data.processor.value.entity;

import com.flowpowered.math.vector.Vector3d;
import net.minecraft.entity.item.EntityArmorStand;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.value.ValueContainer;
import org.spongepowered.api.data.value.immutable.ImmutableValue;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.common.data.processor.common.AbstractSpongeValueProcessor;
import org.spongepowered.common.data.util.DataConstants;
import org.spongepowered.common.data.value.mutable.SpongeValue;
import org.spongepowered.common.util.VecHelper;

import java.util.Optional;

public class ChestRotationValueProcessor extends AbstractSpongeValueProcessor<EntityArmorStand, Vector3d, Value<Vector3d>> {

    public ChestRotationValueProcessor() {
        super(EntityArmorStand.class, Keys.CHEST_ROTATION);
    }

    @Override
    public DataTransactionResult removeFrom(ValueContainer<?> container) {
        return DataTransactionResult.failNoData();
    }

    @Override
    protected Value<Vector3d> constructValue(Vector3d actualValue) {
        return new SpongeValue<>(Keys.CHEST_ROTATION, DataConstants.DEFAULT_CHEST_ROTATION, actualValue);
    }

    @Override
    protected boolean set(EntityArmorStand container, Vector3d value) {
        container.setBodyRotation(VecHelper.toRotation(value));
        return true;
    }

    @Override
    protected Optional<Vector3d> getVal(EntityArmorStand container) {
        return Optional.of(VecHelper.toVector(container.getBodyRotation()));
    }

    @Override
    protected ImmutableValue<Vector3d> constructImmutableValue(Vector3d value) {
        return constructValue(value).asImmutable();
    }

}


text:
scala-intro-dojo
================

This repository contains the code for the [Scala Dojo April 2014](http://www.meetup.com/scala-vienna/events/171745922/) of the Scala User Group Vienna.


text:
[![Build Status](https://travis-ci.org/simplabs/rails_api_auth.svg)](https://travis-ci.org/simplabs/rails_api_auth)

Rails API Auth is a lightweight Rails Engine that __implements the _"Resource
Owner Password Credentials Grant"_ OAuth 2.0 flow
([RFC 6749](http://tools.ietf.org/html/rfc6749#section-4.3)) as well as
Facebook and Google authentication for API projects__.

It uses __Bearer tokens__ ([RFC 6750](http://tools.ietf.org/html/rfc6750)) to
authorize requests coming in from clients.

## Installation

To install the engine simply add to the application's `Gemfile`

```ruby
gem 'rails_api_auth'
```

 and run:
```bash
bundle install
```

__Rails API Auth also adds a migration__ to the application so run

```bash
rake db:migrate
```

as well to migrate the database.

## Usage

__Rails API Auth stores a user's credentials as well as the tokens in a `Login`
model__ so that this data remains separated from the application's `User` model
(or `Account` or whatever the application chose to store profile data in).

After installing the engine you can add the relation from your user model to
the `Login` model:

```ruby
class User < ActiveRecord::Base

  has_one :login # this could be has_many as well of course

end
```

When creating a new `User` in the host application, make sure to create a
related `Login` as well, e.g.:

```ruby
class UsersController < ApplicationController

  def create
    user = User.new(user_params)
    if user.save && user.create_login(login_params)
      head 200
    else
      head 422 # you'd actually want to return validation errors here
    end
  end

  private

    def user_params
      params.require(:user).permit(:first_name, :last_name)
    end

    def login_params
      params.require(:user).permit(:identification, :password, :password_confirmation)
    end

end
```

__The engine adds 2 routes to the application__ that implement the endpoints
for acquiring and revoking Bearer tokens:

```
token  POST /token(.:format)  oauth2#create
revoke POST /revoke(.:format) oauth2#destroy
```

These endpoints are fully implemented in the engine and will issue or revoke
Bearer tokens.

In order to authorize incoming requests the engine provides the
__`authenticate!` helper that can be used in controllers__ to make sure the
request includes a valid Bearer token in the `Authorization` header (e.g.
`Authorization: Bearer d5086ac8457b9db02a13`):

```ruby
class AuthenticatedController < ApplicationController

  include RailsApiAuth::Authentication

  before_action :authenticate!

  def index
    render json: { success: true }
  end

end

```

If no valid Bearer token is provided the client will see a 401 response.

The engine also provides the `current_login` helper method that will return the
`Login` model authorized with the sent Bearer token.

You can also invoke `authenticate!` with a block to perform additional checks
on the current login, e.g. making sure the login's associated account has a
certain role:

```ruby
class AuthenticatedController < ApplicationController

  include RailsApiAuth::Authentication

  before_action :authenticate_admin!

  def index
    render json: { success: true }
  end

  private

    def authenticate_admin!
      authenticate! do
        current_login.account.admin?
      end
    end

end

```

See the [demo project](https://github.com/simplabs/rails_api_auth-demo) for further details.

## Configuration

The Engine can be configured by simply setting some attributes on its main
module:

```ruby
RailsApiAuth.tap do |raa|
  raa.user_model_relation = :account # this will set up the belongs_to relation from the Login model to the Account model automatically (of course if your application uses a User model this would be :user)

  # Facebook configurations
  raa.facebook_app_id       = '<your Facebook app id>'
  raa.facebook_app_secret   = '<your Facebook app secret>'
  raa.facebook_redirect_uri = '<your Facebook app redirect uri>'

  # Google configurations
  raa.google_client_id = '<your Google client id>'
  raa.google_client_secret = '<your Google client secret>'
  raa.google_redirect_uri = '<your app redirect uri>'

end

```

## License

Rails API Auth is developed by and ©
[simplabs GmbH](http://simplabs.com) and contributors. It is released under the
[MIT License](https://github.com/simplabs/ember-simple-auth/blob/master/LICENSE).


text:
@extends('layouts.master')

@section('header')

{{ $title }}

@endsection

@section('breadcrumb')

        My Work Requests

@endsection

@section('content')

                    New Work Request

            @if($workOrders->count() > 0)
                @include('public.work-orders.table', [
                    'workOrders' => $workOrders
                ])
            @else

You have no submitted work requests to display.

            @endif

@endsection


text:
module PerfectMoneyMerchant
	class BasicError < StandardError
		attr_reader :errors

		def add_error(name, value)
			@errors ||= Hashie::Mash.new
			@errors[name] = value # TODO: add I18n
		end
	end
end


text:
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width initial-scale=1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{{ page.title }}</title>
    <meta name="description" content="{{ site.description }}">
    <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
    <link rel="canonical"
          href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
    {% include analytics.html %}
</head>


text:
package org.apache.camel.component.file.remote.integration;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertNull;

/**
 * Test to verify that the polling consumer delivers an empty Exchange when the sendEmptyMessageWhenIdle property is set
 * and a polling event yields no results.
 */
public class FtpPollingConsumerIdleMessageIT extends FtpServerTestSupport {

    @Test
    public void testConsumeIdleMessages() throws Exception {
        Thread.sleep(110);
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMinimumMessageCount(2);
        assertMockEndpointsSatisfied();
        assertNull(mock.getExchanges().get(0).getIn().getBody());
        assertNull(mock.getExchanges().get(1).getIn().getBody());
    }

    @BeforeEach
    public void setup() {
        ftpFile("polling").toFile().mkdirs();
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from("ftp://admin@localhost:{{ftp.server.port}}/polling?password=admin&delay=50"
                     + "&sendEmptyMessageWhenIdle=true").to("mock:result");
            }
        };
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="DataSourceManagerImpl" format="xml" multifile-model="true">
    <data-source source="LOCAL" name="MariaDB - higenius@localhost" uuid="41ff7634-8020-4ca7-a292-dc27e12d23c5">
      <driver-ref>mariadb</driver-ref>
      <synchronize>true</synchronize>
      <jdbc-driver>org.mariadb.jdbc.Driver</jdbc-driver>
      <jdbc-url>jdbc:mariadb://localhost:3306/higenius</jdbc-url>
    </data-source>
  </component>
</project>


text:
describe('Large Format Dialog', () => {
  before(() => {
    cy.visit('/dialog-medium-format');
    cy.get('.page-loader').should('not.exist', { timeout: 20000 });
  });

  it('should open and close dialog', () => {
    cy.contains('button', 'Open Medium Dialog').click();

    cy.get('ngx-medium-format-dialog-content').within(() => {
      cy.get('.dialog-container__header h1').should('contain', 'Title');
      cy.get('.dialog-container__body').should('contain', 'Content');
      cy.get('.dialog-container__header button').should('contain', 'Close').click();
    });
    cy.get('ngx-medium-format-dialog-content').should('not.exist');
  });

  it('should scroll with content', () => {
    cy.contains('button', 'Open Medium Dialog and Content').click();

    cy.get('ngx-medium-format-dialog-content').within(() => {
      cy.get('.dialog-container__header h1').should('contain', 'Title');
    });
    cy.get('ngx-medium-format-dialog-content').invoke('outerHeight').should('be.lt', 500);

    cy.get('ngx-medium-format-dialog-content').within(() => {
      cy.get('ngx-large-format-dialog-header-title').should('be.visible');
      cy.get('.dialog-container__body').invoke('outerHeight').should('be.lt', 450);
      cy.get('.anchor-bottom').scrollIntoView();
      cy.get('ngx-large-format-dialog-header-title').should('be.visible');
    });

    cy.get('ngx-medium-format-dialog-content').ngxClose();
    cy.get('ngx-medium-format-dialog-content').should('not.exist');
  });

  it('should close dialog with testing lib', () => {
    cy.contains('button', 'Open Medium Dialog w/ Footer').click();
    cy.get('ngx-medium-format-dialog-content').ngxClose();
    cy.get('ngx-medium-format-dialog-content').should('not.exist');
  });

  it('should scroll with content and footer', () => {
    cy.contains('button', 'Open Medium Dialog w/ Footer and Content').click();

    cy.get('ngx-medium-format-dialog-content').within(() => {
      cy.get('.dialog-container__header h1').should('contain', 'Title');
    });
    cy.get('ngx-medium-format-dialog-content').invoke('outerHeight').should('be.lt', 500);

    cy.get('ngx-medium-format-dialog-content').within(() => {
      cy.get('ngx-medium-format-dialog-footer').should('be.visible');
      cy.get('.dialog-container__body').invoke('outerHeight').should('be.lt', 450);
      cy.get('.anchor-bottom').scrollIntoView();
      cy.get('ngx-medium-format-dialog-footer').should('be.visible');
    });

    cy.get('ngx-medium-format-dialog-content').ngxClose();
    cy.get('ngx-medium-format-dialog-content').should('not.exist');
  });
});


text:
package com.amazonaws.services.ec2.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * EnableImageDeprecationRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EnableImageDeprecationRequestMarshaller implements Marshaller<Request<EnableImageDeprecationRequest>, EnableImageDeprecationRequest> {

    public Request<EnableImageDeprecationRequest> marshall(EnableImageDeprecationRequest enableImageDeprecationRequest) {

        if (enableImageDeprecationRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<EnableImageDeprecationRequest> request = new DefaultRequest<EnableImageDeprecationRequest>(enableImageDeprecationRequest, "AmazonEC2");
        request.addParameter("Action", "EnableImageDeprecation");
        request.addParameter("Version", "2016-11-15");
        request.setHttpMethod(HttpMethodName.POST);

        if (enableImageDeprecationRequest.getImageId() != null) {
            request.addParameter("ImageId", StringUtils.fromString(enableImageDeprecationRequest.getImageId()));
        }

        if (enableImageDeprecationRequest.getDeprecateAt() != null) {
            request.addParameter("DeprecateAt", StringUtils.fromDate(enableImageDeprecationRequest.getDeprecateAt()));
        }

        return request;
    }

}


text:
package com.skubit.bitid.services;

import com.skubit.AccountSettings;

import android.content.Context;

import retrofit.RequestInterceptor;

public class CookieInterceptor implements RequestInterceptor {

    private final String mAccount;

    private final Context mContext;

    public CookieInterceptor(String account, Context context) {
        mAccount = account;
        this.mContext = context;
    }

    @Override
    public void intercept(RequestFacade request) {
        String cookie = AccountSettings.get(mContext).retrieveToken();

        request.addHeader("Content-Type", "application/json");
        // request.addHeader("Cookie", cookie);
        request.addHeader("Cookie", "skubit=" + cookie);
        // If cookie expired, get another
    }

}


text:
<?php namespace Arcanedev\Moduly;

use Arcanedev\Moduly\Contracts\ModulyInterface;
use Arcanedev\Moduly\Entities\Module;
use Arcanedev\Moduly\Entities\ModulesCollection;
use Illuminate\Config\Repository as Config;
use Illuminate\Foundation\Application;

/**
 * Class     Moduly
 *
 * @package  Arcanedev\Moduly
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class Moduly implements ModulyInterface
{
    /* ------------------------------------------------------------------------------------------------
     |  Properties
     | ------------------------------------------------------------------------------------------------
     */
    /** @var Application */
    private $app;

    /** @var Config */
    private $config;

    /**
     * Base path
     *
     * @var string
     */
    protected $basePath = '';

    /**
     * @var ModulesCollection
     */
    protected $modules;

    /* ------------------------------------------------------------------------------------------------
     |  Constructor
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * Create Moduly instance.
     *
     * @param Application $app
     */
    public function __construct(Application $app)
    {
        $this->app     = $app;
        $this->config  = $app['config'];
        $this->modules = new ModulesCollection;

        $this->setBasePath($this->config->get('moduly.path'));
    }

    /* ------------------------------------------------------------------------------------------------
     |  Getters & Setters
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * Get modules base path
     *
     * @return string
     */
    public function getBasePath()
    {
        return $this->basePath;
    }

    /**
     * Get namespace
     *
     * @return string
     */
    public function getNamespace()
    {
        return $this->config->get('moduly.namespace');
    }

    /**
     * Set modules base path
     *
     * @param  string  $basePath
     *
     * @return self
     */
    private function setBasePath($basePath)
    {
        $this->basePath = $basePath;

        return $this;
    }

    /**
     * Get module path
     *
     * @param  string  $module
     *
     * @return string
     */
    public function getModulePath($module)
    {
        $module = str_slug($module);

        return $this->basePath . "/{$module}/";
    }

    /**
     * Get all modules
     *
     * @return \Arcanedev\Moduly\Entities\ModulesCollection
     */
    protected function modules()
    {
        // Reload all modules
        $this->modules->load($this->basePath);

        return $this->modules;
    }

    /* ------------------------------------------------------------------------------------------------
     |  Main Functions
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * Register all modules
     */
    public function register()
    {
        $this->all()->each(function(Module $module) {
            if ($module->hasProvider()) {
                $this->app->register($module->getProvider());
            }
        });
    }

    /**
     * Get all modules
     *
     * @return \Arcanedev\Moduly\Entities\ModulesCollection
     */
    public function all()
    {
        return $this->modules();
    }

    /**
     * Get all module slugs
     *
     * @return array
     */
    public function slugs()
    {
        return $this->modules()->slugs();
    }

    /**
     * Get a module
     *
     * @param  string  $module
     *
     * @return \Arcanedev\Moduly\Entities\Module
     */
    public function get($module)
    {
        return $this->where('slug', $module)->first();
    }

    /**
     * Get modules based on where clause.
     *
     * @param  string  $key
     * @param  mixed   $value
     *
     * @return \Arcanedev\Support\Collection
     */
    public function where($key, $value)
    {
        return $this->modules()->where($key, $value);
    }

    /**
     * Check if the given module exists.
     *
     * @param  string  $name
     *
     * @return bool
     */
    public function exists($name)
    {
        $name = str_slug($name);

        return $this->modules()->has($name);
    }

    /**
     * Returns count of all modules.
     *
     * @return int
     */
    public function count()
    {
        return $this->modules()->count();
    }

    /**
     * Gets all enabled modules.
     *
     * @return \Arcanedev\Moduly\Entities\ModulesCollection
     */
    public function enabled()
    {
        return $this->modules()->enabled();
    }

    /**
     * Gets all disabled modules.
     *
     * @return \Arcanedev\Moduly\Entities\ModulesCollection
     */
    public function disabled()
    {
        return $this->modules()->disabled();
    }

    /**
     * Enables the specified module.
     *
     * @param  string  $name
     *
     * @return bool
     */
    public function enable($name)
    {
        return $this->modules()->enable($name);
    }

    /**
     * Disables the specified module.
     *
     * @param  string  $name
     *
     * @return bool
     */
    public function disable($name)
    {
        return $this->modules()->disable($name);
    }

    /* ------------------------------------------------------------------------------------------------
     |  Check Functions
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * Check if module is enabled
     *
     * @param  string  $name
     *
     * @return bool
     */
    public function isEnabled($name)
    {
        return $this->modules()->isEnabled($name);
    }

    /**
     * Check if specified module is disabled.
     *
     * @param  string  $name
     *
     * @return bool
     */
    public function isDisabled($name)
    {
        return $this->modules()->isDisabled($name);
    }
}


text:
package org.jboss.qa.brms.performance.configuration;

import org.optaplanner.core.config.localsearch.decider.acceptor.LocalSearchAcceptorConfig;
import org.optaplanner.core.config.localsearch.decider.acceptor.AcceptorType;

import java.util.Collections;

public class AcceptorConfigurations {

    public static LocalSearchAcceptorConfig createHillClimbingAcceptor() {
        LocalSearchAcceptorConfig localSearchAcceptorConfig = new LocalSearchAcceptorConfig();
        localSearchAcceptorConfig.setAcceptorTypeList(Collections.singletonList(AcceptorType.HILL_CLIMBING));
        return localSearchAcceptorConfig;
    }

    public static LocalSearchAcceptorConfig createLateAcceptanceAcceptor(Integer lateAcceptanceSize) {
        LocalSearchAcceptorConfig localSearchAcceptorConfig = new LocalSearchAcceptorConfig();
        localSearchAcceptorConfig.setLateAcceptanceSize(lateAcceptanceSize);
        return localSearchAcceptorConfig;
    }

    public static LocalSearchAcceptorConfig createTabuSearchAcceptor(Double entityRatio) {
        LocalSearchAcceptorConfig localSearchAcceptorConfig = new LocalSearchAcceptorConfig();
        localSearchAcceptorConfig.setEntityTabuRatio(entityRatio);
        return localSearchAcceptorConfig;
    }

    public static LocalSearchAcceptorConfig createSimulatedAnnealingAcceptor(String startingTemperature) {
        LocalSearchAcceptorConfig localSearchAcceptorConfig = new LocalSearchAcceptorConfig();
        localSearchAcceptorConfig.setSimulatedAnnealingStartingTemperature(startingTemperature);
        return localSearchAcceptorConfig;
    }

    public static LocalSearchAcceptorConfig createStepCountHillClimbingAcceptor(Integer stepCountHillClimbingSize) {
        LocalSearchAcceptorConfig localSearchAcceptorConfig = new LocalSearchAcceptorConfig();
        localSearchAcceptorConfig.setStepCountingHillClimbingSize(stepCountHillClimbingSize);
        return localSearchAcceptorConfig;
    }

}


text:
package io.katharsis.client.http.okhttp;

import okhttp3.OkHttpClient.Builder;

public class OkHttpAdapterListenerBase implements OkHttpAdapterListener {

	@Override
	public void onBuild(Builder builder) {
		// nothing to do
	}
}


text:
<?php
$root = $_SERVER['DOCUMENT_ROOT'];
require_once($root.'/models/front/Layout_Model.php');
$model	= new Layout_Model();

$pictures = $model->getGalleryBySection('Testimonials');
?>
	<!DOCTYPE html>

			<title>Villa Aqua Rental - Main Slider</title>
			<link rel="shortcut icon" href="favicon.ico" />
			<link rel="icon" type="image/gif" href="/images/favicon.png" />
			<meta charset="utf-8" />
			<meta name="viewport" content="width=device-width, initial-scale=1">
			<meta name="description" content="Des">
        	<meta name="keywords" content="Key">
            <meta name="author" content="Where to GO">
            <meta name="generator" content="By my great hand" />
            <meta property="og:type" content="website" />
            <meta property="og:site_name" content="Villa Aqua Rental"/>
            <meta property="og:url" content="http://villaaqua.com/" />
            <meta name="format-detection" content="telephone=no" />
				        	<link rel='stylesheet' id='layerslider-css' href='/css/layerslider.css?ver=5.4.0' type='text/css' media='all' />
	    <link rel='stylesheet' id='contact-form-7-css' href='/css/styles.css?ver=4.2.2' type='text/css' media='all' />
	    <link rel='stylesheet' id='normalize-css' href='/css/normalize.css?ver=2.0' type='text/css' media='all' />
	    <link rel='stylesheet' id='bootstrap.min-css' href='/css/bootstrap.min.css?ver=2.0' type='text/css' media='all' />
	    <link rel='stylesheet' id='font-awesome.min-css' href='/css/font-awesome.min.css' type='text/css' media='all' />
	    <link rel='stylesheet' id='icomoon-css' href='/css/icomoon.css?ver=2.0' type='text/css' media='all' />
	    <link rel='stylesheet' id='owl-carousel-css' href='/css/owl.carousel.css?ver=2.0' type='text/css' media='all' />
	    <link rel='stylesheet' id='jquery-fancybox-css' href='/css/jquery.fancybox.css?ver=2.0' type='text/css' media='all' />
	    <link rel='stylesheet' id='amber-style-css' href='/css/style-amber.css?ver=4.2.5' type='text/css' media='all' />
	    <link rel='stylesheet' id='js_composer_front-css' href='/css/js_composer.css?ver=4.6.2' type='text/css' media='all' />
	    <link rel='stylesheet' id='ult-icons-css' href='/css/icons.css?ver=3.13.2' type='text/css' media='' />
	    <link rel='stylesheet' id='bsf-Defaults-css' href='/css/Defaults.css?ver=4.2.5' type='text/css' media='all' />
	    <link rel='stylesheet' id='bsf-icomoon-css' href='/fonts/icomoon.css?ver=4.2.5' type='text/css' media='all' />
	    <link rel='stylesheet' id='ultimate-style-min-css' href='/css/ultimate.min.css?ver=3.13.2' type='text/css' media='all' />
	    <link rel='stylesheet' id='ultimate-style-min-css' href='/css/back.css' type='text/css' media='all' />

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

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

                        </button>

                                Rates

                                Reviews

                                Testimonials

                                Sections

                                Log Out

                                            <input type="hidden" id="sectionPage" value="Testimonials">

Testimonials

												(618 * 800 px)

													Upload

													<?php
													if ($pictures)
													{
														foreach($pictures as $g)
														{
														?>
														<div class="image-box" id="cgid-<?php echo $g['picture_id']; ?>">

																<img src="/images/media/thumb/<?php echo $g['picture']; ?>" />

															<a href="javascript:void(0);" cgid="<?php echo $g['picture_id']; ?>" class="deleteGallery" >delete

														<?php
														}
													}
													?>

	        Book Now