text:
package smtp;

import config.ConfigurationManager;
import model.mail.Group;
import model.mail.Mail;
import model.mail.Person;

import java.io.*;
import java.net.Socket;

/**
 * Implementation of the ISmtpClient interface to send mails for a prank campaign.
 *
 * @author Mathieu Urstein and Sébastien Boson
 */
public class SmtpClient implements ISmtpClient {
    private ConfigurationManager configManager;

    /**
     * constructor of the class SmtpClient
     *
     * @param configManager ConfigurationManager object for the connection with the smpt server
     */
    public SmtpClient(ConfigurationManager configManager) {
        this.configManager = configManager;
    }

    @Override
    public void sendMail(Person fromPerson, Person witnessToCC, Group toPersons, Mail mail) {
        int indexBoucle;
        String line;

        Socket clientSocket = null;
        PrintWriter writer = null;
        BufferedReader bufferedReader = null;

        try {
            clientSocket = new Socket(configManager.getSmtpServerAddress(), configManager.getSmtpServerPort());

            // true for flush automatically when use printf method
            writer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), ConfigurationManager.EXTENSION_FILE), true);
            bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), ConfigurationManager.EXTENSION_FILE));

            // first response of the server
            line = bufferedReader.readLine();
            System.out.println(line + "\n");

            // initiation
            writer.printf("EHLO res\r\n");

            // read response
            line = bufferedReader.readLine();
            System.out.println(line);

            // error with the SMTP server
            if (!line.startsWith("250")) {
                throw new IOException("SMTP error: " + line);
            }

            while (line.startsWith("250-")) {
                line = bufferedReader.readLine();
                System.out.println(line);
            }

            // mail from
            writer.write("MAIL FROM: ");
            writer.write(fromPerson.getMailAddress());
            writer.write("\r\n");
            writer.flush();

            // read response
            line = bufferedReader.readLine();
            System.out.println("\n" + line + "\n");

            // witness mail to
            writer.write("RCPT TO: ");
            writer.write(witnessToCC.getMailAddress());
            writer.write("\r\n");
            writer.flush();

            // read response
            line = bufferedReader.readLine();
            System.out.println(line + "\n");

            // mail to
            for (int i = 0; i < toPersons.getGroupSize(); i++) {
                writer.write("RCPT TO: ");
                writer.write(toPersons.getPersonAt(i).getMailAddress());
                writer.write("\r\n");
                writer.flush();

                // read response
                line = bufferedReader.readLine();
                System.out.println(line + "\n");
            }

            // data
            writer.printf("DATA\r\n");

            // read response
            line = bufferedReader.readLine();
            System.out.println(line + "\n");

            // specify the content type and the charset
            writer.write("Content-Type: text/plain; charset=\"" + ConfigurationManager.EXTENSION_FILE + "\"\r\n");

            // add from person
            writer.write("From: " + fromPerson.getMailAddress() + "\r\n");

            // add to persons
            writer.write("To: ");

            for (indexBoucle = 0; indexBoucle < toPersons.getGroupSize() - 1; indexBoucle++) {
                writer.write(toPersons.getPersonAt(indexBoucle).getMailAddress() + ", ");
            }

            writer.write(toPersons.getPersonAt(indexBoucle).getMailAddress() + "\r\n");

            // add cc person
            writer.write("Cc: " + witnessToCC.getMailAddress() + "\r\n");

            // add mail subject in utf-8 format (header)
            writer.write("Subject: =?" + ConfigurationManager.EXTENSION_FILE + "?Q?" + mail.getSubject() + "?=\r\n");

            // content of mail
            writer.write(mail.getContent());
            // . for terminate
            writer.write(".\r\n");
            writer.flush();

            // read response
            line = bufferedReader.readLine();
            System.out.println(line + "\n");

            // quit
            writer.printf("QUIT\r\n");

            // read response
            line = bufferedReader.readLine();
            System.out.println(line);

        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        finally {
            if (clientSocket != null){
                try {
                    clientSocket.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            else if (writer != null) {
                writer.close();
            }
            else if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


text:
package com.midi_automator.midi;

import javax.sound.midi.MidiMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.midi_automator.presenter.services.GUIAutomationsService;
import com.midi_automator.utils.MidiUtils;

/**
 * Executes automations by received midi signals.
 *
 * @author aguelle
 *
 */
@Component
@Scope("prototype")
public class MidiINAutomationReceiver extends MidiAutomatorReceiver {

	@Autowired
	private GUIAutomationsService guiAutomationsService;

	@Override
	public void send(MidiMessage message, long timeStamp) {
		super.send(message, timeStamp);

		if (!midiLearnService.isMidiLearning() && interpretedMessage != null
				&& !interpretedSignature.equals(MidiUtils.UNKNOWN_MESSAGE)
				&& !isExecuting) {

			log.debug(name + " checking MIDI trigger for message: "
					+ interpretedSignature);

			guiAutomationsService
					.activateAutomationsByMidiMessage(interpretedMessage);
			isExecuting = false;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @namespace
 */
namespace ZendTest\InfoCard;
use Zend\InfoCard\Cipher\PKI\Adapter;
use Zend\InfoCard\Cipher;

/**
 * @category   Zend
 * @package    Zend_InfoCard
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_InfoCard
 */
class CipherTest extends \PHPUnit_Framework_TestCase
{

    public function testPkiPadding()
    {
        if (!extension_loaded('openssl')) {
            $this->markTestSkipped('The openssl extension is not loaded.');
        }

        $obj = new Adapter\RSA();

        $prv_key = file_get_Contents(__DIR__ . "/_files/ssl_private.cert");

        $result = $obj->decrypt("foo", $prv_key, null, Adapter\AbstractAdapter::NO_PADDING);

        // This is sort of werid, but since we don't have a real PK-encrypted string to test against for NO_PADDING
        // mode we decrypt the string "foo" instead. Mathmatically we will always arrive at the same resultant
        // string so if our hash doesn't match then something broke.
        $this->assertSame(md5($result), "286c1991e1f7040229a6f223065b91b5");
    }

    public function testPkiPaddingWithThrowExceptionOnBadInput()
    {
            if (!extension_loaded('openssl')) {
            $this->markTestSkipped('The openssl extension is not loaded.');
        }

        try {
            $obj = new Adapter\RSA("thiswillbreak");
            $this->fail("Exception not thrown as expected");
        } catch(\Exception $e) {
            /* yay */
        }
    }

    public function testPkiPaddingWithThrowExceptionOnBadInput2()
    {
        if (!extension_loaded('openssl')) {
            $this->markTestSkipped('The openssl extension is not loaded.');
        }

        $obj = new Adapter\RSA();

        $prv_key = file_get_Contents(__DIR__ . "/_files/ssl_private.cert");

        try {
            $obj->decrypt("Foo", $prv_key, null, "foo");
            $this->fail("Expected Exception Not Thrown");
        } catch(\Exception $e) {
            /* yay */
        }

    }

    public function testPKIDecryptThrowsExceptionOnBadKey()
    {
        if (!extension_loaded('openssl')) {
            $this->markTestSkipped('The openssl extension is not loaded.');
        }

        $obj = new Adapter\RSA();

        $this->setExpectedException('Zend\InfoCard\Cipher\Exception\RuntimeException', 'Failed to load private key');
        $obj->decrypt("Foo", "bar");
    }

    public function testCipherFactory()
    {
        if (!defined('MCRYPT_RIJNDAEL_128')) {
            $this->markTestSkipped('Use of the Zend_InfoCard component requires the mcrypt extension to be enabled in PHP');
        }

        $this->assertTrue(Cipher::getInstanceByURI(Cipher::ENC_AES128CBC)
                          instanceof \Zend\InfoCard\Cipher\Symmetric\Adapter\AES128CBC);
        $this->assertTrue(Cipher::getInstanceByURI(Cipher::ENC_RSA)
                          instanceof Adapter\RSA);

    }

    public function testCipherFactoryThrowsExceptionOnBadInput()
    {
        $this->setExpectedException('Zend\InfoCard\Cipher\Exception\InvalidArgumentException', 'Unknown Cipher URI');
        Cipher::getInstanceByURI("Broken");
    }

}


text:
!function() {

  var set_up_lighttable_drag = function() {
    // add tooltips to object images
    $("#record-images .draggable").each(function() {
      $(this).attr('data-placement', 'bottom');
      $(this).attr('data-toggle', 'tooltip');
      $(this).attr('title', 'drag to add to lighttable');
      // data-placement="top" data-toggle="tooltip" title="

    });

    // enable dnd for images --> lighttable div
    var moveImage = function(e) {
      var url = $(this).attr('data-ure-image-url');
      var style = "background-image: url('" + url + "')";
      // add a helper class and hide the text.
      var out = $(this).clone().addClass("image-drag-helper");
      var a = out.find(".image-infobox");
      a.hide();

      return out;
    };
    // droppable is inited in lighttable.js

    $("#record-images .draggable").draggable({
      snap : "#lighttable-thumbs",
      cursor : "move",
      scope : "record-images",
      snap : "#lighttable-links",
      snapTolerance : 1000,
      helper : moveImage
    });
  };

  // fix text anomalies
  var repair = function(sel) {
    $(sel).each(function() {
      var text = $(this).text().replace(/\\'/g, "'");
      $(this).text(text)
    });
  }

  // set up image modal
  var get_caption = function(el) {
    return $(el).find(".caption").html();
  }
  var get_image = function(el) {
    return $(el).attr("data-ure-image-url").replace('/sm/', '/xlarge/');
  }
  var get_prevnext = function(el) {
    var prev = $(el).prev();
    var next = $(el).next();
    // thinks tooltip is next sibling, so only count real siblings
    if (!($(next).is("[data-ure-uri]"))) {
      next = $(el).next().next()
    }
    // rollover -- but we could go on to the next object!
    if (prev.length < 1) {
      prev = $(el).siblings().last()
    }
    if (next.length < 1) {
      next = $(el).siblings().first()
    }

    return [ prev, next ];
  }

  // loaded in header
  $(document).ready(function() {
    set_up_lighttable_drag();
    $("#ure-images").delay(200).fadeIn(200);
    repair(".repair div.col-md-8, .repairdiv");
    imageModal("#record-images .cell", get_image, get_caption, get_prevnext)
  });
  window.ure.meta2 = {
    get_caption : get_caption,
    get_image : get_image,
    get_prevnext : get_prevnext,
    set_up_lighttable_drag : set_up_lighttable_drag

  }

}()


text:
<?php
// needed on all pages
require_once('config.php');

// Page dependencies
require_once('server/database/products.php');

$list_title = "Featured Products";
$list_description = "GLORIOUS PC stocks the best parts for all your computing needs!";

$products = get_featured_products();

require_once('products/list_view.php');
?>


text:
module LiftToToplevel.WhereIn7 where

--A definition can be lifted from a where or let to the top level binding group.
--Lifting a definition widens the scope of the definition.

--In this example, lift 'addthree' defined in 'fun'.
--This example aims to test adding parenthese.

fun x y z =inc addthree
       where inc a =a +1
             addthree=x+y+z


text:
class CodeSerializer < ActiveModel::Serializer
  attributes :title, :id

  def id
    object.code
  end

  def title
    object.formatted_title
  end

end

# == Schema Information
#
# Table name: codes
#
#  code  :string(5)        primary key
#  title :string(2000)
#


text:
package org.sistemafinanciero.dao.impl;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

import org.sistemafinanciero.dao.DAO;
import org.sistemafinanciero.entity.Pais;
import org.sistemafinanciero.entity.PendienteCaja;

/**
 * A minimalistic CRUD implementation. Usually provides the implementation of
 * search methods as well.
 *
 * @author adam-bien.com
 */
@Stateless
@Local(DAO.class)
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public class PaisBeanDAO implements DAO<Object, Pais> {

	@PersistenceContext
	private EntityManager em;

	public Pais create(Pais t) {
		this.em.persist(t);
		return t;
	}

	public void delete(Pais t) {
		t = this.em.merge(t);
		this.em.remove(t);
	}

	public Pais find(Object id) {
		return this.em.find(Pais.class, id);
	}

	public Pais update(Pais t) {
		return this.em.merge(t);
	}

	public List<Pais> findAll() {
		List<Pais> list = null;
		CriteriaQuery cq = this.em.getCriteriaBuilder().createQuery();
		cq.select(cq.from(Pais.class));
		list = this.em.createQuery(cq).getResultList();
		return list;
	}

	public List<Pais> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = this.em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Pais.class));
        javax.persistence.Query q = this.em.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = this.em.getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<Pais> rt = cq.from(Pais.class);
        cq.select(this.em.getCriteriaBuilder().count(rt));
        javax.persistence.Query q = this.em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

	public List<Pais> findByNamedQuery(String namedQueryName) {
		return this.em.createNamedQuery(namedQueryName).getResultList();
	}

	public List<Pais> findByNamedQuery(String namedQueryName,
			Map<String, Object> parameters) {
		return findByNamedQuery(namedQueryName, parameters, 0);
	}

	public List<Pais> findByNamedQuery(String queryName,
			int resultLimit) {
		return this.em.createNamedQuery(queryName).setMaxResults(resultLimit)
				.getResultList();
	}

	public List<Pais> findByNamedQuery(String namedQueryName,
			Map<String, Object> parameters, int resultLimit) {
		Set<Entry<String, Object>> rawParameters = parameters.entrySet();
		Query query = this.em.createNamedQuery(namedQueryName);
		if (resultLimit > 0)
			query.setMaxResults(resultLimit);
		for (Entry<String, Object> entry : rawParameters) {
			query.setParameter(entry.getKey(), entry.getValue());
		}
		return query.getResultList();
	}

	public List<Pais> findByNamedQuery(String namedQueryName, Map<String, Object> parameters, Integer offset, Integer limit) {
		Set<Entry<String, Object>> rawParameters = parameters.entrySet();
		Query query = this.em.createNamedQuery(namedQueryName);
		for (Entry<String, Object> entry : rawParameters) {
			query.setParameter(entry.getKey(), entry.getValue());
		}
		query.setFirstResult(offset != null ? offset : 0);
		if(limit != null)
			query.setMaxResults(limit);
		return query.getResultList();
    }
}


text:
@class BrowserView;
@protocol BrowserViewDelegate <NSObject>

@optional
- (void)browser:(BrowserView *)browser didSelectItem:(TimetableModel *)model;
- (void)browser:(BrowserView *)browser didEndScrollingAtIndex:(NSInteger)index;
//- (void)browser:(BrowserView *)browser didChangeItem:(NSString *)name;

@end

@interface BrowserView : UIView

@property (nonatomic, assign, readwrite) id<BrowserViewDelegate> delegate;
//@property (nonatomic, assign, readonly)  NSInteger currentIndex;

- (instancetype)initWithFrame:(CGRect)frame models:(NSArray *)models currentIndex:(NSInteger)index;

//- (void)setCurrentModelIndex:(NSInteger)index;
@end


text:
import random, re
import anydbm
import os, sys

from flask import Flask, render_template, request, make_response
app = Flask(__name__)

IGNORED = 'ignored'
INTERESTING = 'interesting'

PENDING_FILES = set()

WAV_DIR = 'static/wav'
IGNORED_WAV_DIRS = ('doc-kiwi',
                    'doc-morepork', 'rfpt-15m',
                    'doc-minutes',
                    'doc-interesting',
                    'doc-weka',
                    'snippets',
                )
#WAV_DIR = 'static/wav-test'

CALLS_FOUND = 0
FILES_PROCESSED = 0
FILES_IGNORED = 0
FILES_INTERESTING = 0
UNCONFIRMED_TIMES = {}
REQUESTED_FILES = set()

DEFAULT_DBM_FILE = 'calls.dbm'

def gen_times_from_file(fn):
    f = open(fn)
    for line in f:
        line = line.strip()
        if ' ' in line:
            wav, times = line.split(None, 1)
            yield (wav, sanitise_times(times))
        else:
            yield (line, [])
    f.close()

def load_from_files(fn, ignored=None):
    """This is for when the database crashes."""
    if ignored:
        f = open(ignored)
        for line in f:
            line = line.strip()
            if line:
                DB[line] = IGNORED
        f.close()
    for wav, times in gen_times_from_file(fn):
        DB[wav] = ' '.join(times)

def set_up_dbm_and_file_list(dbm_file, included_wav_dirs=[], included_wavs=None):
    global DB, FILES, CALLS_FOUND, FILES_PROCESSED, FILES_IGNORED, FILES_INTERESTING
    DB = anydbm.open(dbm_file, 'c')
    # sync with filesystem on start up
    for dirpath, dirnames, filenames in os.walk(WAV_DIR, followlinks=True):
        d = re.sub(WAV_DIR + '/?', '', dirpath)
        if included_wav_dirs:
            if d not in included_wav_dirs:
                continue
        elif d in IGNORED_WAV_DIRS:
            continue
        for fn in filenames:
            if fn.endswith('.wav'):
                if included_wavs and fn not in included_wavs:
                    continue
                if d:
                    ffn = d + '/' + fn
                else:
                    ffn = fn
                try:
                    if ffn not in DB or included_wavs:
                        PENDING_FILES.add(ffn)
                except:
                    print >>sys.stderr, "couldn't add %s, stupid dbm" % ffn

    for fn, calls in DB.iteritems():
        if calls == IGNORED:
            FILES_IGNORED += 1
        else:
            FILES_INTERESTING += calls.startswith(INTERESTING)
            FILES_PROCESSED += 1
            CALLS_FOUND += calls.count(' ') // 2
            ffn = os.path.join(WAV_DIR, fn)
            if not os.path.exists(ffn):
                print >> sys.stderr, "%s is missing" % ffn

    #load_from_files('times/results-319.txt', 'times/ignored-319.txt')
    DB.sync()

def sanitise_times(times):
    if not times:
        return []
    if isinstance(times, (str, unicode)):
        times = times.encode('utf-8').strip()
        if ',' in times:
            times = times.split(',')
        else:
            times = times.split()
    if times[0] == INTERESTING:
        times = times[1:]
    if not times:
        return []
    times = [float(x) for x in times if x]
    if len(times) & 1:
        raise ValueError("len(times) is odd: %d" % len(times))

    #so, now times is a possibly empty list of floats
    #split it into pairs
    pairs = [times[i : i + 2] for i in range(0, len(times), 2)]
    for s, e in pairs:
        if e < s:
            raise ValueError("pair %s,%s has end before start" % (s, e))
    pairs.sort()
    ls, le = pairs[0]
    combined = []
    for i in range(1, len(pairs)):
        rs, re = pairs[i]
        if rs <= le: #overlap --> merge
            le = re
        else:
            combined.append(ls)
            combined.append(le)
            ls = rs
            le = re
    combined.append(ls)
    combined.append(le)
    return combined

def save_results():
    global FILES_PROCESSED, FILES_IGNORED, CALLS_FOUND, FILES_INTERESTING
    if request.method == 'POST':
        get = request.form.get
    else:
        get = request.args.get
    wav = get('wav')
    if wav is None:
        return "Hello!"
    wav = wav.encode('utf-8')
    if not wav in PENDING_FILES:
        return "wav file '%s' is unknown" % wav
    if get('skip'):
        return "Skipped '%s'" % wav
    PENDING_FILES.discard(wav)
    if get('ignore'):
        DB[wav] = IGNORED
        FILES_IGNORED += 1
        return "added '%s' to ignored list" % wav
    call_string = get('calls')
    call_times = sanitise_times(call_string)
    time_string = ' '.join("%.2f" % x for x in call_times)
    if get('interesting'):
        FILES_INTERESTING += 1
        interesting_string = INTERESTING + ' '
    else:
        interesting_string = ''
    FILES_PROCESSED += 1
    CALLS_FOUND += len(call_times) // 2
    DB[wav] = interesting_string + time_string
    DB.sync()
    return "saved %d calls in %s" % (len(call_times) / 2, wav)

def get_known_calls(wav):
    if wav is not None:
        basewav = os.path.basename(wav)
        if basewav in UNCONFIRMED_TIMES:
            wav = basewav
    return UNCONFIRMED_TIMES.get(wav, [])

@app.route('/', methods=['GET', 'POST'])
def main_page():
    msg = save_results()
    if PENDING_FILES:
        wav = random.sample(PENDING_FILES, 1)[0]
    else:
        wav = None
    known_calls = ','.join(str(x) for x in get_known_calls(wav))
    return render_template('audio.html', wav=wav, wavdir=WAV_DIR, msg=msg,
                           files_remaining=len(PENDING_FILES),
                           files_processed=FILES_PROCESSED, files_ignored=FILES_IGNORED,
                           files_interesting=FILES_INTERESTING,
                           calls_found=CALLS_FOUND, known_calls=known_calls,
                           species=SPECIES)

@app.route('/results.txt')
def results():
    lines = []
    ignored = []
    interesting = []
    for k, v in DB.iteritems():
        if v == IGNORED:
            ignored.append(k)
        else:
            if v.startswith(INTERESTING):
                interesting.append(k)
            s = ' '.join('%s' % x for x in sanitise_times(v))
            lines.append("%s %s\n" % (k, s))

    lines.sort()
    text = ''.join(lines)
    f = open('results-%d.txt' % len(lines), 'w')
    f.write(text)
    f.close()
    f = open('ignored-%d.txt' % len(lines), 'w')
    f.write('\n'.join(ignored) + '\n')
    f.close()
    f = open('interesting-%d.txt' % len(lines), 'w')
    f.write('\n'.join(interesting) + '\n')
    f.close()

    response = make_response(text)
    response.headers["content-type"] = "text/plain"
    DB.sync()

    return response

def main():
    global SPECIES, UNCONFIRMED_TIMES, DB
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-t', '--load-times',
                        help='load times from here')
    parser.add_argument('-s', '--species', default='morepork',
                        help='species to search for (morepork|weka)')
    parser.add_argument('--world-visible', action='store_true',
                        help='Allow connections from beyond localhost')
    parser.add_argument('--dbm-file', default=DEFAULT_DBM_FILE,
                        help='Use this DBM file')
    parser.add_argument('--include-wav-dir', action='append',
                        help='Use files from this subdirectory of %s' % WAV_DIR)
    parser.add_argument('--timed-files-only', action='store_true',
                        help='Only use the files referenced by --load-times')

    args = parser.parse_args()
    if args.load_times:
        for wav, times in gen_times_from_file(args.load_times):
            REQUESTED_FILES.add(wav)
            if times:
                UNCONFIRMED_TIMES[wav] = times
    SPECIES = args.species
    if args.timed_files_only:
        included_wavs = REQUESTED_FILES
    else:
        included_wavs = None
    try:
        set_up_dbm_and_file_list(args.dbm_file, included_wav_dirs=args.include_wav_dir,
                                 included_wavs=included_wavs)
        if not args.world_visible:
            app.run(debug=True)
        else:
            app.run(host='0.0.0.0')
    except Exception, e:
        print >>sys.stderr, e
    finally:
        DB.close()

if __name__ == '__main__':
    main()


text:
/****************************************************************************/
/* Copyright 2005-2006, Francis Russell                                     */
/*                                                                          */
/* Licensed under the Apache License, Version 2.0 (the License);            */
/* you may not use this file except in compliance with the License.         */
/* You may obtain a copy of the License at                                  */
/*                                                                          */
/*     http://www.apache.org/licenses/LICENSE-2.0                           */
/*                                                                          */
/* Unless required by applicable law or agreed to in writing, software      */
/* distributed under the License is distributed on an AS IS BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and      */
/* limitations under the License.                                           */
/*                                                                          */
/****************************************************************************/

#ifndef DESOLA_PROFILING_PAIRWISE_HPP
#define DESOLA_PROFILING_PAIRWISE_HPP

#include "Desola_profiling_fwd.hpp"
#include <map>

namespace desola
{

namespace detail
{

template<typename exprType, typename T_element>
class PPairwise : public PBinOp<exprType, exprType, exprType, T_element>
{
private:
  const PairwiseOp op;

public:
  PPairwise(const PairwiseOp o, PExprNode<exprType, T_element>& l, PExprNode<exprType, T_element>& r) : PBinOp<exprType, exprType, exprType, T_element>(l, r), op(o)
  {
  }

  bool isEqual(const PPairwise& node, const std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*>& mappings) const
  {
    return PBinOp<exprType, exprType, exprType, T_element>::isEqual(node, mappings) &&
	   op == node.op;
  }

  const PairwiseOp getOperation() const
  {
    return op;
  }

  virtual void accept(PExpressionNodeVisitor<T_element>& visitor)
  {
    visitor.visit(*this);
  }
};

}

}

#endif


text:
from helper import *

@patch('vapptool.load_ovf')
@raises(Exception)
def test_cmd_hosts_with_no_ovfenv(mock_load_ovf):
  mock_load_ovf.side_effect = Exception('Boom!')
  vapptool.cmd_hosts()

@patch('vapptool.load_hosts')
@raises(Exception)
def test_cmd_hosts_with_no_etc_hosts(mock_load_hosts):
  mock_load_hosts.side_effect = Exception('Bam!')
  vapptool.cmd_hosts()

@patch('vapptool.load_ovf')
@patch('vapptool.load_hosts')
def test_cmd_hosts_with_an_unknown_ovfenv(mock_load_hosts, mock_load_ovf):
  mock_load_hosts.return_value = file('tests/fixtures/centos6/hosts.orig', 'r').read()
  mock_load_ovf.return_value   = file('tests/fixtures/ovfenv/legacy-onprem.xml', 'r').read()

  actual = vapptool.cmd_hosts()

  assert actual[0] is not 0,    'cmd_hosts should return a non-zero status when an ovfEnv is found that does not contain Rally vApp properties'
  assert actual[1] is None,     'cmd_hosts should not return stdout when an ovfEnv is found that does not contain Rally vApp properties'
  assert actual[2] is not None, 'cmd_hosts should return stderr when an ovfEnv is found that does not contain Rally vApp properties'

@patch('vapptool.load_ovf')
@patch('vapptool.load_hosts')
def test_cmd_hosts_with_default_hosts_and_a_known_ovfenv(mock_load_hosts, mock_load_ovf):
  mock_load_hosts.return_value = file('tests/fixtures/centos6/hosts.orig', 'r').read()
  mock_load_ovf.return_value   = file('tests/fixtures/ovfenv/alm-core.xml', 'r').read()

  actual = vapptool.cmd_hosts()

  assert actual[0] is 0,    'cmd_hosts should return a zero status when an ovfEnv is found that contains Rally vApp properties'
  assert actual[2] is None, 'cmd_hosts should not return stderr when an ovfEnv is found that contains Rally vApp properties'

  stdout = actual[1]
  assert re.search('127.0.0.1\s+localhost', stdout)                                    is not None, 'cmd_hosts stdout should contain the contents of the original /etc/hosts file'
  assert re.search('10.32.30.29\s+vapp_localhost\s+vapp_localhost.f4tech.com', stdout) is not None, 'cmd_hosts stdout should contain a vapp_localhost entry'
  assert re.search('10.32.30.29\s+vapp_alm\s+vapp_alm.f4tech.com', stdout)             is not None, 'cmd_hosts stdout should contain a vapp_alm entry'
  assert re.search('10.32.30.30\s+vapp_core\s+vapp_core.f4tech.com', stdout)           is not None, 'cmd_hosts stdout should contain a vapp_core entry'

@patch('vapptool.load_ovf')
@patch('vapptool.load_hosts')
def test_cmd_hosts_with_modified_hosts_and_a_known_ovfenv(mock_load_hosts, mock_load_ovf):
  mock_load_hosts.return_value = file('tests/fixtures/centos6/hosts.orig', 'r').read()
  mock_load_ovf.return_value   = file('tests/fixtures/ovfenv/alm-core.xml', 'r').read()

  first_run = vapptool.cmd_hosts()
  mock_load_hosts.return_value = first_run[1]

  actual = vapptool.cmd_hosts()

  assert actual[0] is 0,    'cmd_hosts should return a zero status when an ovfEnv is found that contains Rally vApp properties'
  assert actual[2] is None, 'cmd_hosts should not return stderr when an ovfEnv is found that does not contain Rally vApp properties'

  stdout = actual[1]
  assert re.search('127.0.0.1\s+localhost', stdout)                                          is not None, 'cmd_hosts stdout should contain the contents of the original /etc/hosts file'
  assert len(re.findall('10.32.30.29\s+vapp_localhost\s+vapp_localhost.f4tech.com', stdout)) is 1, 'cmd_hosts stdout should contain only one vapp_localhost entry'
  assert len(re.findall('10.32.30.29\s+vapp_alm\s+vapp_alm.f4tech.com', stdout))             is 1, 'cmd_hosts stdout should contain only one vapp_alm entry'
  assert len(re.findall('10.32.30.30\s+vapp_core\s+vapp_core.f4tech.com', stdout))           is 1, 'cmd_hosts stdout should contain only one vapp_core entry'
  assert stdout.count('\n\n') is 0, 'cmd_hosts stdout should not contain empty lines'

@patch('vapptool.cmd_hosts')
def test_main_hosts(mock_cmd_hosts):
  mock_cmd_hosts.return_value = [ 0, 'stdout', 'stderr' ]

  actual = call_main_with('--hosts')

  assert actual[0] is 0,        '--hosts should exit zero'
  assert 'stdout' in actual[1], '--hosts should print stdout'
  assert 'stderr' in actual[2], '--hosts should not print stderr'

def test_main_hosts_with_wrong_options():
  actual = call_main_with('--hosts', '--wrongopt')

  assert actual[0] is not 0,      '--hosts should exit non-zero when called incorrectly'
  assert actual[1] is None,       '--hosts should not print stdout when called incorrectly'
  assert 'wrongopt' in actual[2], '--hosts should print stderr when called incorrectly'


text:
import Ember from 'ember';
import AuthenticatedRoute from 'ghost/routes/authenticated';
import styleBody from 'ghost/mixins/style-body';

const {
    canInvoke,
    inject: {service}
} = Ember;

export default AuthenticatedRoute.extend(styleBody, {
    titleToken: 'Sign Out',

    classNames: ['ghost-signout'],

    notifications: service(),

    afterModel(model, transition) {
        this.get('notifications').clearAll();
        if (canInvoke(transition, 'send')) {
            transition.send('invalidateSession');
        } else {
            this.send('invalidateSession');
        }
    }
});


text:
package com.amazonaws.services.route53domains.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * ExtraParam includes the following elements.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ExtraParam implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * Name of the additional parameter required by the top-level domain.
     *

     */
    private String name;
    /**
     *

     * Values corresponding to the additional parameter names required by some top-level domains.
     *

     */
    private String value;

    /**
     *

     * Name of the additional parameter required by the top-level domain.
     *

     *
     * @param name
     *        Name of the additional parameter required by the top-level domain.
     * @see ExtraParamName
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * Name of the additional parameter required by the top-level domain.
     *

     *
     * @return Name of the additional parameter required by the top-level domain.
     * @see ExtraParamName
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * Name of the additional parameter required by the top-level domain.
     *

     *
     * @param name
     *        Name of the additional parameter required by the top-level domain.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ExtraParamName
     */

    public ExtraParam withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * Name of the additional parameter required by the top-level domain.
     *

     *
     * @param name
     *        Name of the additional parameter required by the top-level domain.
     * @see ExtraParamName
     */

    public void setName(ExtraParamName name) {
        this.name = name.toString();
    }

    /**
     *

     * Name of the additional parameter required by the top-level domain.
     *

     *
     * @param name
     *        Name of the additional parameter required by the top-level domain.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ExtraParamName
     */

    public ExtraParam withName(ExtraParamName name) {
        setName(name);
        return this;
    }

    /**
     *

     * Values corresponding to the additional parameter names required by some top-level domains.
     *

     *
     * @param value
     *        Values corresponding to the additional parameter names required by some top-level domains.
     */

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

    /**
     *

     * Values corresponding to the additional parameter names required by some top-level domains.
     *

     *
     * @return Values corresponding to the additional parameter names required by some top-level domains.
     */

    public String getValue() {
        return this.value;
    }

    /**
     *

     * Values corresponding to the additional parameter names required by some top-level domains.
     *

     *
     * @param value
     *        Values corresponding to the additional parameter names required by some top-level domains.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ExtraParam withValue(String value) {
        setValue(value);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getValue() != null)
            sb.append("Value: ").append(getValue());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ExtraParam == false)
            return false;
        ExtraParam other = (ExtraParam) obj;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getValue() == null ^ this.getValue() == null)
            return false;
        if (other.getValue() != null && other.getValue().equals(this.getValue()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getValue() == null) ? 0 : getValue().hashCode());
        return hashCode;
    }

    @Override
    public ExtraParam clone() {
        try {
            return (ExtraParam) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.route53domains.model.transform.ExtraParamMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
/*jshint browser:true*/
/*jslint nomen: true*/
/*global define, require*/
define(['jquery', 'underscore', 'oroui/js/tools', 'oroui/js/mediator',
        './map-filter-module-name', './collection-filters-manager'
    ], function ($, _, tools,  mediator, mapFilterModuleName, FiltersManager) {
    'use strict';

    var initialized = false,
        methods = {
            initBuilder: function () {
                this.metadata = _.extend({filters: {}}, this.$el.data('metadata'));
                this.modules = {};
                methods.collectModules.call(this);
                tools.loadModules(this.modules, _.bind(methods.build, this));
            },

            /**
             * Collects required modules
             */
            collectModules: function () {
                var modules = this.modules;
                _.each(this.metadata.filters || {}, function (filter) {
                     var type = filter.type;
                     modules[type] = mapFilterModuleName(type);
                });
            },

            build: function () {
                var options = methods.combineOptions.call(this);
                options.collection = this.collection;
                var filtersList = new FiltersManager(options);
                this.$el.prepend(filtersList.render().$el);
                mediator.trigger('datagrid_filters:rendered', this.collection);
                this.metadata.state.filters = this.metadata.state.filters || [];
                if (this.collection.length === 0 && this.metadata.state.filters.length === 0) {
                    filtersList.$el.hide();
                }
            },

            /**
             * Process metadata and combines options for filters
             *
             * @returns {Object}
             */
            combineOptions: function () {
                var filters= {},
                    modules = this.modules,
                    collection = this.collection;
                _.each(this.metadata.filters, function (options) {
                    if (_.has(options, 'name') && _.has(options, 'type')) {
                        // @TODO pass collection only for specific filters
                        if (options.type == 'selectrow') {
                            options.collection = collection
                        }
                        var Filter = modules[options.type].extend(options);
                        filters[options.name] = new Filter();
                    }
                });
                return {filters: filters};
            }
        },
        initHandler = function (collection, $el) {
            methods.initBuilder.call({$el: $el, collection: collection});
            initialized = true;
        };

    return {
        init: function () {
            initialized = false;

            mediator.once('datagrid_collection_set_after', initHandler);
            mediator.once('hash_navigation_request:start', function() {
                if (!initialized) {
                    mediator.off('datagrid_collection_set_after', initHandler);
                }
            });
        }
    };
});


text:
package com.facebook.buck.rules.keys;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createStrictMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertSame;

import com.facebook.buck.io.ArchiveMemberPath;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.DefaultBuildTargetSourcePath;
import com.facebook.buck.rules.RuleKey;
import com.facebook.buck.rules.SourceRoot;
import com.facebook.buck.util.sha1.Sha1HashCode;
import com.google.common.hash.HashCode;
import java.nio.file.Paths;
import java.util.regex.Pattern;
import org.junit.Test;

public class ForwardingRuleKeyHasherTest {

  private static final RuleKey RULE_KEY_1 = new RuleKey("a002b39af204cdfaa5fdb67816b13867c32ac52c");
  private static final BuildTarget TARGET_1 =
      BuildTargetFactory.newInstance(Paths.get("/root"), "//example/base:one");
  private static final byte[] BYTE_ARRAY = new byte[] {42, 42};
  private static final Pattern PATTERN = Pattern.compile("42");
  private static final SourceRoot SOURCE_ROOT = new SourceRoot("42");

  @Test
  public void testForwarding() {
    String string = "hash";
    HashCode hash = createMock(HashCode.class);

    @SuppressWarnings("unchecked")
    RuleKeyHasher<String> stringHasher = createStrictMock(RuleKeyHasher.class);
    @SuppressWarnings("unchecked")
    RuleKeyHasher<HashCode> guavaHasher = createStrictMock(RuleKeyHasher.class);

    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putKey("42")).andReturn(guavaHasher);
    expect(stringHasher.putKey("42")).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putNull()).andReturn(guavaHasher);
    expect(stringHasher.putNull()).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putBoolean(true)).andReturn(guavaHasher);
    expect(stringHasher.putBoolean(true)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putBoolean(false)).andReturn(guavaHasher);
    expect(stringHasher.putBoolean(false)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putNumber(42)).andReturn(guavaHasher);
    expect(stringHasher.putNumber(42)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putNumber((long) 42)).andReturn(guavaHasher);
    expect(stringHasher.putNumber((long) 42)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putNumber((short) 42)).andReturn(guavaHasher);
    expect(stringHasher.putNumber((short) 42)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putNumber((byte) 42)).andReturn(guavaHasher);
    expect(stringHasher.putNumber((byte) 42)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putNumber((float) 42)).andReturn(guavaHasher);
    expect(stringHasher.putNumber((float) 42)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putNumber((double) 42)).andReturn(guavaHasher);
    expect(stringHasher.putNumber((double) 42)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putString("42")).andReturn(guavaHasher);
    expect(stringHasher.putString("42")).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putBytes(BYTE_ARRAY)).andReturn(guavaHasher);
    expect(stringHasher.putBytes(BYTE_ARRAY)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putPattern(PATTERN)).andReturn(guavaHasher);
    expect(stringHasher.putPattern(PATTERN)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putSha1(Sha1HashCode.of("a002b39af204cdfaa5fdb67816b13867c32ac52c")))
        .andReturn(guavaHasher);
    expect(stringHasher.putSha1(Sha1HashCode.of("a002b39af204cdfaa5fdb67816b13867c32ac52c")))
        .andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putPath(Paths.get("42/42"), HashCode.fromInt(42))).andReturn(guavaHasher);
    expect(stringHasher.putPath(Paths.get("42/42"), HashCode.fromInt(42))).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(
            guavaHasher.putArchiveMemberPath(
                newArchiveMember("42/42", "42/42"), HashCode.fromInt(42)))
        .andReturn(guavaHasher);
    expect(
            stringHasher.putArchiveMemberPath(
                newArchiveMember("42/42", "42/42"), HashCode.fromInt(42)))
        .andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putNonHashingPath("42")).andReturn(guavaHasher);
    expect(stringHasher.putNonHashingPath("42")).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putSourceRoot(SOURCE_ROOT)).andReturn(guavaHasher);
    expect(stringHasher.putSourceRoot(SOURCE_ROOT)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putRuleKey(RULE_KEY_1)).andReturn(guavaHasher);
    expect(stringHasher.putRuleKey(RULE_KEY_1)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putBuildRuleType(BuildRuleType.of("42"))).andReturn(guavaHasher);
    expect(stringHasher.putBuildRuleType(BuildRuleType.of("42"))).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putBuildTarget(TARGET_1)).andReturn(guavaHasher);
    expect(stringHasher.putBuildTarget(TARGET_1)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putBuildTargetSourcePath(new DefaultBuildTargetSourcePath(TARGET_1)))
        .andReturn(guavaHasher);
    expect(stringHasher.putBuildTargetSourcePath(new DefaultBuildTargetSourcePath(TARGET_1)))
        .andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putContainer(RuleKeyHasher.Container.LIST, 42)).andReturn(guavaHasher);
    expect(stringHasher.putContainer(RuleKeyHasher.Container.LIST, 42)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putContainer(RuleKeyHasher.Container.MAP, 42)).andReturn(guavaHasher);
    expect(stringHasher.putContainer(RuleKeyHasher.Container.MAP, 42)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putWrapper(RuleKeyHasher.Wrapper.SUPPLIER)).andReturn(guavaHasher);
    expect(stringHasher.putWrapper(RuleKeyHasher.Wrapper.SUPPLIER)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putWrapper(RuleKeyHasher.Wrapper.OPTIONAL)).andReturn(guavaHasher);
    expect(stringHasher.putWrapper(RuleKeyHasher.Wrapper.OPTIONAL)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putWrapper(RuleKeyHasher.Wrapper.EITHER_LEFT)).andReturn(guavaHasher);
    expect(stringHasher.putWrapper(RuleKeyHasher.Wrapper.EITHER_LEFT)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putWrapper(RuleKeyHasher.Wrapper.EITHER_RIGHT)).andReturn(guavaHasher);
    expect(stringHasher.putWrapper(RuleKeyHasher.Wrapper.EITHER_RIGHT)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putWrapper(RuleKeyHasher.Wrapper.BUILD_RULE)).andReturn(guavaHasher);
    expect(stringHasher.putWrapper(RuleKeyHasher.Wrapper.BUILD_RULE)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putWrapper(RuleKeyHasher.Wrapper.APPENDABLE)).andReturn(guavaHasher);
    expect(stringHasher.putWrapper(RuleKeyHasher.Wrapper.APPENDABLE)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    expect(guavaHasher.putKey("45")).andReturn(guavaHasher);
    expect(stringHasher.putKey("45")).andReturn(stringHasher);
    expect(guavaHasher.putNull()).andReturn(guavaHasher);
    expect(stringHasher.putNull()).andReturn(stringHasher);
    expect(guavaHasher.putBoolean(true)).andReturn(guavaHasher);
    expect(stringHasher.putBoolean(true)).andReturn(stringHasher);
    expect(guavaHasher.putNumber(45)).andReturn(guavaHasher);
    expect(stringHasher.putNumber(45)).andReturn(stringHasher);
    expect(guavaHasher.putString("45")).andReturn(guavaHasher);
    expect(stringHasher.putString("45")).andReturn(stringHasher);
    expect(guavaHasher.putBytes(BYTE_ARRAY)).andReturn(guavaHasher);
    expect(stringHasher.putBytes(BYTE_ARRAY)).andReturn(stringHasher);
    expect(guavaHasher.putPattern(PATTERN)).andReturn(guavaHasher);
    expect(stringHasher.putPattern(PATTERN)).andReturn(stringHasher);
    expect(guavaHasher.putSha1(Sha1HashCode.of("a002b39af204cdfaa5fdb67816b13867c32ac52c")))
        .andReturn(guavaHasher);
    expect(stringHasher.putSha1(Sha1HashCode.of("a002b39af204cdfaa5fdb67816b13867c32ac52c")))
        .andReturn(stringHasher);
    expect(guavaHasher.putPath(Paths.get("45"), HashCode.fromInt(45))).andReturn(guavaHasher);
    expect(stringHasher.putPath(Paths.get("45"), HashCode.fromInt(45))).andReturn(stringHasher);
    expect(guavaHasher.putArchiveMemberPath(newArchiveMember("45", "45"), HashCode.fromInt(45)))
        .andReturn(guavaHasher);
    expect(stringHasher.putArchiveMemberPath(newArchiveMember("45", "45"), HashCode.fromInt(45)))
        .andReturn(stringHasher);
    expect(guavaHasher.putNonHashingPath("45")).andReturn(guavaHasher);
    expect(stringHasher.putNonHashingPath("45")).andReturn(stringHasher);
    expect(guavaHasher.putSourceRoot(SOURCE_ROOT)).andReturn(guavaHasher);
    expect(stringHasher.putSourceRoot(SOURCE_ROOT)).andReturn(stringHasher);
    expect(guavaHasher.putRuleKey(RULE_KEY_1)).andReturn(guavaHasher);
    expect(stringHasher.putRuleKey(RULE_KEY_1)).andReturn(stringHasher);
    expect(guavaHasher.putBuildRuleType(BuildRuleType.of("45"))).andReturn(guavaHasher);
    expect(stringHasher.putBuildRuleType(BuildRuleType.of("45"))).andReturn(stringHasher);
    expect(guavaHasher.putBuildTarget(TARGET_1)).andReturn(guavaHasher);
    expect(stringHasher.putBuildTarget(TARGET_1)).andReturn(stringHasher);
    expect(guavaHasher.putBuildTargetSourcePath(new DefaultBuildTargetSourcePath(TARGET_1)))
        .andReturn(guavaHasher);
    expect(stringHasher.putBuildTargetSourcePath(new DefaultBuildTargetSourcePath(TARGET_1)))
        .andReturn(stringHasher);
    expect(guavaHasher.putContainer(RuleKeyHasher.Container.LIST, 45)).andReturn(guavaHasher);
    expect(stringHasher.putContainer(RuleKeyHasher.Container.LIST, 45)).andReturn(stringHasher);
    expect(guavaHasher.putContainer(RuleKeyHasher.Container.MAP, 45)).andReturn(guavaHasher);
    expect(stringHasher.putContainer(RuleKeyHasher.Container.MAP, 45)).andReturn(stringHasher);
    expect(guavaHasher.putWrapper(RuleKeyHasher.Wrapper.OPTIONAL)).andReturn(guavaHasher);
    expect(stringHasher.putWrapper(RuleKeyHasher.Wrapper.OPTIONAL)).andReturn(stringHasher);
    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    replay(stringHasher, guavaHasher);

    newHasher(guavaHasher, stringHasher).hash();
    newHasher(guavaHasher, stringHasher).putKey("42").hash();
    newHasher(guavaHasher, stringHasher).putNull().hash();
    newHasher(guavaHasher, stringHasher).putBoolean(true).hash();
    newHasher(guavaHasher, stringHasher).putBoolean(false).hash();
    newHasher(guavaHasher, stringHasher).putNumber(42).hash();
    newHasher(guavaHasher, stringHasher).putNumber((long) 42).hash();
    newHasher(guavaHasher, stringHasher).putNumber((short) 42).hash();
    newHasher(guavaHasher, stringHasher).putNumber((byte) 42).hash();
    newHasher(guavaHasher, stringHasher).putNumber((float) 42).hash();
    newHasher(guavaHasher, stringHasher).putNumber((double) 42).hash();
    newHasher(guavaHasher, stringHasher).putString("42").hash();
    newHasher(guavaHasher, stringHasher).putBytes(BYTE_ARRAY).hash();
    newHasher(guavaHasher, stringHasher).putPattern(PATTERN).hash();
    newHasher(guavaHasher, stringHasher)
        .putSha1(Sha1HashCode.of("a002b39af204cdfaa5fdb67816b13867c32ac52c"))
        .hash();
    newHasher(guavaHasher, stringHasher).putPath(Paths.get("42/42"), HashCode.fromInt(42)).hash();
    newHasher(guavaHasher, stringHasher)
        .putArchiveMemberPath(newArchiveMember("42/42", "42/42"), HashCode.fromInt(42))
        .hash();
    newHasher(guavaHasher, stringHasher).putNonHashingPath("42").hash();
    newHasher(guavaHasher, stringHasher).putSourceRoot(SOURCE_ROOT).hash();
    newHasher(guavaHasher, stringHasher).putRuleKey(RULE_KEY_1).hash();
    newHasher(guavaHasher, stringHasher).putBuildRuleType(BuildRuleType.of("42")).hash();
    newHasher(guavaHasher, stringHasher).putBuildTarget(TARGET_1).hash();
    newHasher(guavaHasher, stringHasher)
        .putBuildTargetSourcePath(new DefaultBuildTargetSourcePath(TARGET_1))
        .hash();
    newHasher(guavaHasher, stringHasher).putContainer(RuleKeyHasher.Container.LIST, 42).hash();
    newHasher(guavaHasher, stringHasher).putContainer(RuleKeyHasher.Container.MAP, 42).hash();
    newHasher(guavaHasher, stringHasher).putWrapper(RuleKeyHasher.Wrapper.SUPPLIER).hash();
    newHasher(guavaHasher, stringHasher).putWrapper(RuleKeyHasher.Wrapper.OPTIONAL).hash();
    newHasher(guavaHasher, stringHasher).putWrapper(RuleKeyHasher.Wrapper.EITHER_LEFT).hash();
    newHasher(guavaHasher, stringHasher).putWrapper(RuleKeyHasher.Wrapper.EITHER_RIGHT).hash();
    newHasher(guavaHasher, stringHasher).putWrapper(RuleKeyHasher.Wrapper.BUILD_RULE).hash();
    newHasher(guavaHasher, stringHasher).putWrapper(RuleKeyHasher.Wrapper.APPENDABLE).hash();

    newHasher(guavaHasher, stringHasher)
        .putKey("45")
        .putNull()
        .putBoolean(true)
        .putNumber(45)
        .putString("45")
        .putBytes(BYTE_ARRAY)
        .putPattern(PATTERN)
        .putSha1(Sha1HashCode.of("a002b39af204cdfaa5fdb67816b13867c32ac52c"))
        .putPath(Paths.get("45"), HashCode.fromInt(45))
        .putArchiveMemberPath(newArchiveMember("45", "45"), HashCode.fromInt(45))
        .putNonHashingPath("45")
        .putSourceRoot(SOURCE_ROOT)
        .putRuleKey(RULE_KEY_1)
        .putBuildRuleType(BuildRuleType.of("45"))
        .putBuildTarget(TARGET_1)
        .putBuildTargetSourcePath(new DefaultBuildTargetSourcePath(TARGET_1))
        .putContainer(RuleKeyHasher.Container.LIST, 45)
        .putContainer(RuleKeyHasher.Container.MAP, 45)
        .putWrapper(RuleKeyHasher.Wrapper.OPTIONAL)
        .hash();
  }

  @Test
  public void testHashAndOnHash() {
    final String string = "hash";
    final HashCode hash = createMock(HashCode.class);

    @SuppressWarnings("unchecked")
    RuleKeyHasher<String> stringHasher = createStrictMock(RuleKeyHasher.class);
    @SuppressWarnings("unchecked")
    RuleKeyHasher<HashCode> guavaHasher = createStrictMock(RuleKeyHasher.class);

    expect(guavaHasher.hash()).andReturn(hash);
    expect(stringHasher.hash()).andReturn(string);

    replay(stringHasher, guavaHasher);

    ForwardingRuleKeyHasher<HashCode, String> hasher =
        new ForwardingRuleKeyHasher<HashCode, String>(guavaHasher, stringHasher) {
          @Override
          protected void onHash(HashCode firstHash, String secondHash) {
            assertSame(string, secondHash);
            assertSame(hash, firstHash);
          }
        };
    assertSame(hash, hasher.hash());
  }

  private ArchiveMemberPath newArchiveMember(String archivePath, String memberPath) {
    return ArchiveMemberPath.of(Paths.get(archivePath), Paths.get(memberPath));
  }

  private ForwardingRuleKeyHasher<HashCode, String> newHasher(
      RuleKeyHasher<HashCode> guavaHasher, RuleKeyHasher<String> stringHasher) {
    return new ForwardingRuleKeyHasher<HashCode, String>(guavaHasher, stringHasher) {
      @Override
      protected void onHash(HashCode firstHash, String secondHash) {}
    };
  }
}


text:
'''
Created on Jun 8, 2017

@author: Andy Zhang
'''

class Parent():
    def __init__(self, last_name, eye_color):
        print("Parent Constructor Called")
        self.last_name = last_name
        self.eye_color = eye_color

    def print_info(self):
        print("Last Name: " + self.last_name)
        print("Eye Color: " + self.eye_color)

class Child(Parent):
    def __init__(self, last_name, eye_color, number_of_toys):
        print("Child Constructor Called")
        Parent.__init__(self, last_name, eye_color)
        self.number_of_toys = number_of_toys

#billy_cyrus = Parent("Cyrus","blue")
#print(billy_cyrus.last_name)

miley_cyrus = Child("Cyrus","Blue",5)

print(miley_cyrus.last_name)
print(miley_cyrus.number_of_toys)
miley_cyrus.print_info()


text:
'use strict';

var Backbone = require('backbone');
var Mn = require('backbone.marionette');
// require('backbone.radio');
var _ = require('underscore');

// var utils = require('../libs/utils');
var ole = require('../libs/ole');

var RadioManager = require('../libs/radio-manager');

/**
 * The Module definition
 * @return {Object} Module
 */
module.exports = function(options) {

  var Base = function() {
    // Add logging capability
    ole.assimilate(this);

    // Add radio communication and event listener capability
    this.radioManager = new RadioManager(this);

    Base.__super__.constructor.apply(this, arguments);
  };

  return Base;

};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ReportResources (Smartsheet Java SDK 2.146.0 API)</title>
<meta name="date" content="2021-11-12">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.smartsheet.api

Interface ReportResources

public interface ReportResources

This interface provides methods to access Report resources.

Thread Safety: Implementation of this interface must be thread safe.

Method Summary

All Methods Instance Methods Abstract Methods Deprecated Methods

Modifier and Type
Method and Description

ReportPublish
getPublishStatus(long id)

Get the publish status of a report.

Report
getReport(long reportId,
         EnumSet<ReportInclusion> includes,
         Integer pageSize,
         Integer page)

Get a report.

Report
getReport(long reportId,
         EnumSet<ReportInclusion> includes,
         Integer pageSize,
         Integer page,
         Integer level)

Get a report.

void
getReportAsCsv(long id,
              OutputStream outputStream)

Get a Report as an csv file.

void
getReportAsExcel(long id,
                OutputStream outputStream)

Get a Report as an excel file.

PagedResult<Report>
listReports(PaginationParameters parameters)

Deprecated.

PagedResult<Report>
listReports(PaginationParameters parameters,
           Date modifiedSince)

List all reports.

void
sendReport(long reportId,
          SheetEmail email)

Send a sheet as a PDF attachment via Email To the designated recipients.

ShareResources
shareResources()

Creates an object of ShareResources.

ReportPublish
updatePublishStatus(long id,
                   ReportPublish reportPublish)

Sets the publish status of a report and returns the new status, including the URLs of any
 enabled publishing.

Method Detail

getReport

Report getReport(long reportId,
                 EnumSet<ReportInclusion> includes,
                 Integer pageSize,
                 Integer page)
          throws SmartsheetException

Get a report.

It mirrors to the following Smartsheet REST API method: GET /report/{reportId}

Parameters:

reportId - the reportId of the report

includes - used To specify the optional objects to include.

pageSize - page size parameter for pagination

page - page parameter for pagination

Returns:

the report (note that if there is no such resource, this method will throw ResourceNotFoundException
 rather than returning null)

Throws:

IllegalArgumentException - if any argument is null or empty string

InvalidRequestException - if there is any problem with the REST API request

AuthorizationException - if there is any problem with  the REST API authorization (access token)

ResourceNotFoundException - if the resource cannot be found

ServiceUnavailableException - if the REST API service is not available (possibly due to rate limiting)

SmartsheetException - if there is any other error during the operation

getReport

Report getReport(long reportId,
                 EnumSet<ReportInclusion> includes,
                 Integer pageSize,
                 Integer page,
                 Integer level)
          throws SmartsheetException

Get a report.

It mirrors to the following Smartsheet REST API method: GET /report/{reportId}

Parameters:

reportId - the reportId of the report

includes - used To specify the optional objects to include.

pageSize - page size parameter for pagination

page - page parameter for pagination

level - compatibility level

Returns:

the report (note that if there is no such resource, this method will throw ResourceNotFoundException
 rather than returning null)

Throws:

IllegalArgumentException - if any argument is null or empty string

InvalidRequestException - if there is any problem with the REST API request

AuthorizationException - if there is any problem with  the REST API authorization (access token)

ResourceNotFoundException - if the resource cannot be found

ServiceUnavailableException - if the REST API service is not available (possibly due to rate limiting)

SmartsheetException - if there is any other error during the operation

sendReport

void sendReport(long reportId,
                SheetEmail email)
         throws SmartsheetException

Send a sheet as a PDF attachment via Email To the designated recipients.

It mirrors to the following Smartsheet REST API method: POST /reports/{reportId}/emails

Parameters:

reportId - the reportId of the report

email - email of designated recipient.

Throws:

IllegalArgumentException - if any argument is null or empty string

InvalidRequestException - if there is any problem with the REST API request

AuthorizationException - if there is any problem with  the REST API authorization (access token)

ResourceNotFoundException - if the resource cannot be found

ServiceUnavailableException - if the REST API service is not available (possibly due to rate limiting)

SmartsheetException - if there is any other error during the operation

listReports

PagedResult<Report> listReports(PaginationParameters parameters,
                                Date modifiedSince)
                         throws SmartsheetException

List all reports.

It mirrors to the following Smartsheet REST API method: GET /reports

 Exceptions:
   - InvalidRequestException : if there is any problem with the REST API request
   - AuthorizationException : if there is any problem with the REST API authorization(access token)
   - ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
   - SmartsheetRestException : if there is any other REST API related error occurred during the operation
   - SmartsheetException : if there is any other error occurred during the operation

Parameters:

parameters - pagination parameters for paging result

modifiedSince - restrict results to sheets modified on or after this date

Returns:

all sheets (note that empty list will be returned if there is none)

Throws:

SmartsheetException - the smartsheet exception

listReports

@Deprecated
PagedResult<Report> listReports(PaginationParameters parameters)
                                      throws SmartsheetException

Deprecated.

List all reports.

It mirrors to the following Smartsheet REST API method: GET /reports

 Exceptions:
   - InvalidRequestException : if there is any problem with the REST API request
   - AuthorizationException : if there is any problem with the REST API authorization(access token)
   - ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
   - SmartsheetRestException : if there is any other REST API related error occurred during the operation
   - SmartsheetException : if there is any other error occurred during the operation

Parameters:

parameters - pagination parameters for paging result

Returns:

all sheets (note that empty list will be returned if there is none)

Throws:

SmartsheetException - the smartsheet exception

getReportAsExcel

void getReportAsExcel(long id,
                      OutputStream outputStream)
               throws SmartsheetException

Get a Report as an excel file.

It mirrors to the following Smartsheet REST API method: GET /reports/{id} with "application/vnd.ms-excel" Accept
 HTTP header

 Exceptions:
   IllegalArgumentException : if outputStream is null
   InvalidRequestException : if there is any problem with the REST API request
   AuthorizationException : if there is any problem with the REST API authorization(access token)
   ResourceNotFoundException : if the resource can not be found
   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
   SmartsheetRestException : if there is any other REST API related error occurred during the operation
   SmartsheetException : if there is any other error occurred during the operation

Parameters:

id - the id

outputStream - the OutputStream to which the Excel file will be written

Throws:

SmartsheetException - the smartsheet exception

getReportAsCsv

void getReportAsCsv(long id,
                    OutputStream outputStream)
             throws SmartsheetException

Get a Report as an csv file.

It mirrors to the following Smartsheet REST API method: GET /reports/{id} with "application/vnd.ms-excel" Accept
 HTTP header

 Exceptions:
   IllegalArgumentException : if outputStream is null
   InvalidRequestException : if there is any problem with the REST API request
   AuthorizationException : if there is any problem with the REST API authorization(access token)
   ResourceNotFoundException : if the resource can not be found
   ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting)
   SmartsheetRestException : if there is any other REST API related error occurred during the operation
   SmartsheetException : if there is any other error occurred during the operation

Parameters:

id - the id

outputStream - the OutputStream to which the Excel file will be written

Throws:

SmartsheetException - the smartsheet exception

getPublishStatus

ReportPublish getPublishStatus(long id)
                        throws SmartsheetException

Get the publish status of a report.

It mirrors to the following Smartsheet REST API method: GET /reports/{id}/publish

Parameters:

id - the ID of the report

Returns:

the report publish status (note that if there is no such resource, this method will
     throw ResourceNotFoundException rather than returning null).

Throws:

IllegalArgumentException - if any argument is null or empty string

InvalidRequestException - if there is any problem with the REST API request

AuthorizationException - if there is any problem with  the REST API authorization (access token)

ResourceNotFoundException - if the resource cannot be found

ServiceUnavailableException - if the REST API service is not available (possibly due to rate limiting)

SmartsheetException - if there is any other error during the operation

updatePublishStatus

ReportPublish updatePublishStatus(long id,
                                  ReportPublish reportPublish)
                           throws SmartsheetException

Sets the publish status of a report and returns the new status, including the URLs of any
 enabled publishing.

It mirrors to the following Smartsheet REST API method: PUT /reports/{id}/publish

Parameters:

id - the ID of the report

reportPublish - the ReportPublish object

Returns:

the updated ReportPublish (note that if there is no such resource, this method will
     throw ResourceNotFoundException rather than returning null)

Throws:

IllegalArgumentException - if any argument is null or empty string

InvalidRequestException - if there is any problem with the REST API request

AuthorizationException - if there is any problem with  the REST API authorization (access token)

ResourceNotFoundException - if the resource cannot be found

ServiceUnavailableException - if the REST API service is not available (possibly due to rate limiting)

SmartsheetException - if there is any other error during the operation

shareResources

ShareResources shareResources()

Creates an object of ShareResources.

Returns:

the created ShareResources object

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2014–2021 Smartsheet. All rights reserved.


text:
import CoCollapse from './collapse';
import CoCollapsePanel from './collapse-panel';
import CoCollapseTransition from './collapse-transition';

export { CoCollapse, CoCollapsePanel, CoCollapseTransition };


text:
'use strict';

/**
* Create an iterator which returns evenly spaced numbers according to a specified increment.
*
* @module @stdlib/iter/incrspace
*
* @example
* var iterIncrspace = require( '@stdlib/iter/incrspace' );
*
* var iter = iterIncrspace( 0, 100, 2 );
*
* var v = iter.next().value;
* // returns 0
*
* v = iter.next().value;
* // returns 2
*
* v = iter.next().value;
* // returns 4
*
* // ...
*/

// MODULES //

var main = require( './main.js' );

// EXPORTS //

module.exports = main;


text:
<?php

namespace Pharel\Nodes;

class Assignment extends Binary {
}


text:
require 'chef/knife/vm_base'
require 'knife/vm/vm'

class Chef
  class Knife
    class VmServerCreate < Knife

      include Knife::VmBase

      deps do
        require 'chef/knife/bootstrap'
        Chef::Knife::Bootstrap.load_deps
      end

      banner "knife vm server create NAME (options)"

      # option :hostname,
      #   :short => "-H HOST",
      #   :long => "--hostname HOST",
      #   :description => "Hostname of VM",
      #   :proc => Proc.new { |key| Chef::Config[:knife][:hostname] = key }

      option :box,
        :long => "--box BOX",
        :description => "Vagrant box name",
        :proc => Proc.new { |key| Chef::Config[:knife][:box] = key }

      option :box_url,
        :long => "--box-url BOX",
        :description => "Vagrant box URL",
        :proc => Proc.new { |key| Chef::Config[:knife][:box_url] = key }

      option :chef_node_name,
        :short => "-N NAME",
        :long => "--node-name NAME",
        :description => "The Chef node name for your new node",
        :proc => Proc.new { |key| Chef::Config[:knife][:chef_node_name] = key }

      option :ssh_user,
        :short => "-x USERNAME",
        :long => "--ssh-user USERNAME",
        :description => "The ssh username",
        :default => "vagrant"

      option :ssh_password,
        :short => "-P PASSWORD",
        :long => "--ssh-password PASSWORD",
        :description => "The ssh password",
        :default => "vagrant"

      option :identity_file,
        :short => "-i IDENTITY_FILE",
        :long => "--identity-file IDENTITY_FILE",
        :description => "The SSH identity file used for authentication"

      option :prerelease,
        :long => "--prerelease",
        :description => "Install the pre-release chef gems"

      option :bootstrap_version,
        :long => "--bootstrap-version VERSION",
        :description => "The version of Chef to install",
        :proc => Proc.new { |v| Chef::Config[:knife][:bootstrap_version] = v }

      option :distro,
        :short => "-d DISTRO",
        :long => "--distro DISTRO",
        :description => "Bootstrap a distro using a template; default is 'chef-full'",
        :proc => Proc.new { |d| Chef::Config[:knife][:distro] = d }

      option :template_file,
        :long => "--template-file TEMPLATE",
        :description => "Full path to location of template to use",
        :proc => Proc.new { |t| Chef::Config[:knife][:template_file] = t },
        :default => false

      option :run_list,
        :short => "-r RUN_LIST",
        :long => "--run-list RUN_LIST",
        :description => "Comma separated list of roles/recipes to apply",
        :proc => lambda { |o| o.split(/[\s,]+/) }

      option :json_attributes,
        :short => "-j JSON",
        :long => "--json-attributes JSON",
        :description => "A JSON string to be added to the first run of chef-client",
        :proc => lambda { |o| JSON.parse(o) }

      option :hint,
        :long => "--hint HINT_NAME[=HINT_FILE]",
        :description => "Specify Ohai Hint to be set on the bootstrap target.  Use multiple --hint options to specify multiple hints.",
        :proc => Proc.new { |h|
          Chef::Config[:knife][:hints] ||= {}
          name, path = h.split("=")
          Chef::Config[:knife][:hints][name] = path ? JSON.parse(::File.read(path)) : Hash.new
        }

      def run
        unless config[:chef_node_name] || name_args.size >= 1
          ui.fatal "You did not provide a valid 'Node Name' value."
          show_usage
          exit 1
        end

        node_bootstrap.run
      end

      def node_bootstrap(ip)
        bootstrap = Chef::Knife::Bootstrap.new
        bootstrap.name_args = [ip]
        bootstrap.config[:run_list] = locate_config_value(:run_list) || []
        bootstrap.config[:ssh_user] = config[:ssh_user]
        bootstrap.config[:ssh_port] = config[:ssh_port]
        bootstrap.config[:identity_file] = config[:identity_file]
        bootstrap.config[:chef_node_name] = locate_config_value(:chef_node_name)
        bootstrap.config[:prerelease] = config[:prerelease]
        bootstrap.config[:bootstrap_version] = locate_config_value(:bootstrap_version)
        bootstrap.config[:first_boot_attributes] = locate_config_value(:json_attributes) || {}
        bootstrap.config[:distro] = locate_config_value(:distro) || "chef-full"
        bootstrap.config[:use_sudo] = true unless config[:ssh_user] == 'root'
        bootstrap.config[:template_file] = locate_config_value(:template_file)
        bootstrap.config[:environment] = config[:environment]
        bootstrap
      end

    end
  end
end


text:
'use strict';

var FirstMiddleware = function(req, res, next) {
  next();
};
var SecondMiddleware = function(req, res, next) {
  next();
};

var ThirdMiddleware = function(req, res, next) {
  next();
};

module.exports = {

  middlewares: {
    all: [ FirstMiddleware ],
    get: [ FirstMiddleware, SecondMiddleware ],
    post: ThirdMiddleware
  },

  get: function(req, res) {
    res.send('get');
  },

  post: function(req, res) {
    res.send('post');
  }
};


text:
@interface UIImage (CropFaceOutOfImage)

+ (UIImage *)cropFaceFromImage:(UIImage *)image;

@end


text:
class vogleditor_stateTreeContextInfoDiffableItem : public vogleditor_stateTreeItem
{
public:
    vogleditor_stateTreeContextInfoDiffableItem(QString name, QString value, vogleditor_stateTreeItem* parent)
        : vogleditor_stateTreeItem(name, value, parent),
          m_pDiffBaseState(NULL)
    {
    }

    void set_diff_base_state(const vogl_context_info* pBaseState) {
        m_pDiffBaseState = pBaseState;
    }

    virtual bool hasChanged() const = 0;
protected:
    const vogl_context_info* m_pDiffBaseState;
};

class vogleditor_stateTreeContextInfoBoolItem : public vogleditor_stateTreeContextInfoDiffableItem
{
public:
    vogleditor_stateTreeContextInfoBoolItem(QString name, bool (vogl_context_info::* func)(void) const, vogleditor_stateTreeItem* parent, const vogl_context_info& info);
    virtual ~vogleditor_stateTreeContextInfoBoolItem() { m_pState = NULL; }

    const vogl_context_info* get_context_info() const { return m_pState; }
    virtual bool hasChanged() const;
    virtual QString getDiffedValue() const;

private:
    const vogl_context_info* m_pState;
    bool (vogl_context_info::* m_pFunc)(void) const;
};

class vogleditor_stateTreeContextInfoUIntItem : public vogleditor_stateTreeContextInfoDiffableItem
{
public:
    vogleditor_stateTreeContextInfoUIntItem(QString name, uint (vogl_context_info::* func)(void) const, vogleditor_stateTreeItem* parent, const vogl_context_info& info);
    virtual ~vogleditor_stateTreeContextInfoUIntItem() { m_pState = NULL; }

    const vogl_context_info* get_context_info() const { return m_pState; }
    virtual bool hasChanged() const;
    virtual QString getDiffedValue() const;

 private:
    const vogl_context_info* m_pState;
    uint (vogl_context_info::* m_pFunc)(void) const;
};

class vogleditor_stateTreeContextInfoStringItem : public vogleditor_stateTreeContextInfoDiffableItem
{
public:
    vogleditor_stateTreeContextInfoStringItem(QString name, const vogl::dynamic_string& (vogl_context_info::* func)(void) const, vogleditor_stateTreeItem* parent, const vogl_context_info& info);
    virtual ~vogleditor_stateTreeContextInfoStringItem() { m_pState = NULL;}

    const vogl_context_info* get_context_info() const { return m_pState; }
    virtual bool hasChanged() const;
    virtual QString getDiffedValue() const;

 private:
    const vogl_context_info* m_pState;
    dynamic_string m_value;
    const vogl::dynamic_string& (vogl_context_info::* m_pFunc)(void) const;
};

class vogleditor_stateTreeContextInfoExtensionItem : public vogleditor_stateTreeContextInfoDiffableItem
{
public:
    vogleditor_stateTreeContextInfoExtensionItem(QString name, const vogl::dynamic_string extensionName, vogleditor_stateTreeItem* parent, const vogl_context_info& info)
        : vogleditor_stateTreeContextInfoDiffableItem(name, QString(extensionName.c_str()), parent),
          m_pState(&info),
          m_extensionName(extensionName)
    {
        setValue(QString(extensionName.c_str()));
    }

    virtual ~vogleditor_stateTreeContextInfoExtensionItem() { m_pState = NULL; }

    const vogl_context_info* get_context_info() const { return m_pState; }
    virtual bool hasChanged() const
    {
        if (m_pDiffBaseState == NULL)
        {
            return false;
        }

        // if the current extension is in the base list, then don't flag this as having changed
        const dynamic_string_array& baseExtensions = m_pDiffBaseState->get_extensions();
        for (const vogl::dynamic_string* iter = baseExtensions.begin(); iter != baseExtensions.end(); iter++)
        {
            if ((*iter) == m_extensionName)
            {
                return false;
            }
        }

        // if we've made it through the entire list, then this extension was not in the base context, so it is new (has changed).
        return true;
    }

    // if an extension shows up as having changed, that means it didn't exist in the previous snapshot
    virtual QString getDiffedValue() const { return "non-existent"; }

 private:
    const vogl_context_info* m_pState;
    dynamic_string m_extensionName;
};

class vogleditor_stateTreeContextInfoItem : public vogleditor_stateTreeItem
{
public:
    vogleditor_stateTreeContextInfoItem(QString name, QString value, vogleditor_stateTreeItem* parent, const vogl_context_info& info);
    virtual ~vogleditor_stateTreeContextInfoItem()
    {
        m_pState = NULL; m_pDiffBaseState = NULL;
    }

    const vogl_context_info* get_context_info() const { return m_pState; }

    void set_diff_base_state(const vogl_context_info* pBaseState) {
        m_pDiffBaseState = pBaseState;
        for (vogleditor_stateTreeContextInfoDiffableItem** iter = m_diffableItems.begin(); iter != m_diffableItems.end(); iter++)
        {
            (*iter)->set_diff_base_state(pBaseState);
        }
    }
    virtual bool hasChanged() const;

 private:
    const vogl_context_info* m_pState;
    const vogl_context_info* m_pDiffBaseState;
    vogl::vector<vogleditor_stateTreeContextInfoDiffableItem*> m_diffableItems;
};

#endif // VOGLEDITOR_STATETREECONTEXTINFOITEM_H


text:
package eu.bcvsolutions.idm.core.model.service.impl;

import eu.bcvsolutions.idm.core.api.dto.DelegationTypeDto;
import java.util.List;
import java.util.UUID;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import eu.bcvsolutions.idm.core.api.dto.IdmDelegationDefinitionDto;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmDelegationDefinitionFilter;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmDelegationFilter;
import eu.bcvsolutions.idm.core.api.entity.AbstractEntity_;
import eu.bcvsolutions.idm.core.api.service.AbstractEventableDtoService;
import eu.bcvsolutions.idm.core.api.service.DelegationManager;
import eu.bcvsolutions.idm.core.api.service.EntityEventManager;
import eu.bcvsolutions.idm.core.api.service.IdmDelegationDefinitionService;
import eu.bcvsolutions.idm.core.api.service.IdmDelegationService;
import eu.bcvsolutions.idm.core.api.utils.RepositoryUtils;
import eu.bcvsolutions.idm.core.eav.api.service.DelegationType;
import eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission;
import eu.bcvsolutions.idm.core.model.entity.IdmDelegationDefinition;
import eu.bcvsolutions.idm.core.model.entity.IdmDelegationDefinition_;
import eu.bcvsolutions.idm.core.model.repository.IdmDelegationDefinitionRepository;
import eu.bcvsolutions.idm.core.security.api.dto.AuthorizableType;
import java.time.LocalDate;
import org.modelmapper.internal.util.Assert;
import org.springframework.transaction.annotation.Transactional;

/**
 * CRUD service for a definition of delegation.
 *
 * @author Vít Švanda
 * @since 10.4.0
 *
 */
@Service("delegationDefinitionService")
public class DefaultIdmDelegationDefinitionService extends
		AbstractEventableDtoService<IdmDelegationDefinitionDto, IdmDelegationDefinition, IdmDelegationDefinitionFilter> implements IdmDelegationDefinitionService {

	@Autowired
	private IdmDelegationService delegationService;
	@Autowired
	private DelegationManager delegationManager;

	@Autowired
	public DefaultIdmDelegationDefinitionService(IdmDelegationDefinitionRepository repository, EntityEventManager entityEventManager) {
		super(repository, entityEventManager);
	}

	@Override
	public AuthorizableType getAuthorizableType() {
		return new AuthorizableType(CoreGroupPermission.DELEGATIONDEFINITION, getEntityClass());
	}

	@Override
	protected IdmDelegationDefinitionDto toDto(IdmDelegationDefinition entity, IdmDelegationDefinitionDto dto, IdmDelegationDefinitionFilter filter) {
		dto = super.toDto(entity, dto, filter);
		if (dto != null && dto.getType() != null) {
			// Add delegation type DTO to the delegation definition.
			DelegationType delegateType = delegationManager.getDelegateType(dto.getType());
			if (delegateType != null) {
				DelegationTypeDto delegationTypeDto = delegationManager.convertDelegationTypeToDto(delegateType);
				// I cannot use a key "type", because EnumSelect on FE try to use complex value from embedded.
				dto.getEmbedded().put(DelegationManager.WORKFLOW_DELEGATION_TYPE_KEY, delegationTypeDto);
			}
		}

		return dto;
	}

	@Override
	public boolean supportsToDtoWithFilter() {
		return true;
	}

	@Override
	@Transactional
	public void deleteInternal(IdmDelegationDefinitionDto dto) {
		Assert.notNull(dto.getId(), "ID cannot be null!");

		// Referential integrity - delete all delegations for that definition.
		IdmDelegationFilter delegationFilter = new IdmDelegationFilter();
		delegationFilter.setDelegationDefinitionId(dto.getId());

		delegationService.find(delegationFilter, null).getContent()
				.forEach(delegation -> delegationService.delete(delegation));

		super.deleteInternal(dto);
	}

	@Override
	protected List<Predicate> toPredicates(Root<IdmDelegationDefinition> root, CriteriaQuery<?> query, CriteriaBuilder builder,
			IdmDelegationDefinitionFilter filter) {
		List<Predicate> predicates = super.toPredicates(root, query, builder, filter);

		UUID delegateId = filter.getDelegateId();
		if (delegateId != null) {
			predicates.add(builder.equal(root.get(IdmDelegationDefinition_.delegate).get(AbstractEntity_.id), delegateId));
		}

		UUID delegatorId = filter.getDelegatorId();
		if (delegatorId != null) {
			predicates.add(builder.equal(root.get(IdmDelegationDefinition_.delegator).get(AbstractEntity_.id), delegatorId));
		}

		UUID delegatorContractId = filter.getDelegatorContractId();
		if (delegatorContractId != null) {
			predicates.add(builder.equal(root.get(IdmDelegationDefinition_.delegatorContract).get(AbstractEntity_.id), delegatorContractId));
		}

		String type = filter.getType();
		if (type != null) {
			predicates.add(builder.equal(root.get(IdmDelegationDefinition_.type), type));
		}

		if (filter.getValid() != null) {
			final LocalDate today = LocalDate.now();
			//
			if (filter.getValid()) {
				predicates.add(
						builder.and(
								RepositoryUtils.getValidPredicate(root, builder, today)
						)
				);
			} else {
				throw new UnsupportedOperationException();
			}
		}

		return predicates;
	}

}


text:
package com.hazelcast.nio;

import java.nio.ByteBuffer;

import static com.hazelcast.impl.Constants.IO.KILO_BYTE;

public interface SocketReader {
    public static final int RECEIVE_SOCKET_BUFFER_SIZE = 32 * KILO_BYTE;

    void read(ByteBuffer bb) throws Exception;
}


text:
'use strict';

/**
 * Contains information about sanctuary targets
 */
class Simaris {
  /**
   * @param   {Object}             data            The sanctuary data
   * @param   {Object}             deps            The dependencies object
   * @param   {MarkdownSettings}   deps.mdConfig   The markdown settings
   * @param   {Translator}         deps.translator The string translator
   */
  constructor(data, { mdConfig, translator }) {
    /**
     * The markdown settings
     * @type {MarkdownSettings}
     * @private
     */
    this.mdConfig = mdConfig;
    Object.defineProperty(this, 'mdConfig', { enumerable: false, configurable: false });

    /**
     * The sanctuary target
     * @type {string}
     */
    this.target = translator.languageString(data.LastCompletedTargetType) || 'N/a';

    /**
     * Whether or not the target is currently active
     * @type {Boolean}
     */
    this.isTargetActive = !(data.LastCompletedTargetType);

    /**
     * A string representation of the current sanctuary status
     * @type {string}
     */
    this.asString = this.toString();
  }

  /**
   * Returns a string representation of the current sanctuary status
   * @returns {string}
   */
  toString() {
    return `Simaris's ${this.isTargetActive ? 'current' : 'previous'} objective `
      + `${this.isTargetActive ? 'is' : 'was'} ${this.target}`;
  }
}

module.exports = Simaris;


text:
@interface TailoredSecurityInfobarBannerOverlayMediator
    : InfobarBannerOverlayMediator
@end

#endif  // IOS_CHROME_BROWSER_UI_OVERLAYS_INFOBAR_BANNER_TAILORED_SECURITY_TAILORED_SECURITY_INFOBAR_BANNER_OVERLAY_MEDIATOR_H_


text:
<?php

namespace frontend\modules\admin\models;

use yii\base\InvalidParamException;
use yii\base\Model;
use Yii;
use frontend\modules\admin\models\User;

/**
 * Password reset form
 */
class PasswordChangeForm extends Model
{
    public $currentPassword;
    public $newPassword;
    public $newPasswordRepeat;

    /**
     * @var User
     */
    public $_user;

    /**
     * @param User $user
     * @param array $config
     * @throws \yii\base\InvalidParamException
     */
//    public function __construct(User $user, $config = [])
    public function __construct($id, $config = [])
    {
//        if (empty($user)) {
//            throw new InvalidParamException('User is empty.');
//        }
        $user = User::findOne($id);
        $this->_user = $user;
        parent::__construct($config);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['currentPassword', 'newPassword', 'newPasswordRepeat'], 'required'],
            ['currentPassword', 'validatePassword'],
            ['newPassword', 'string', 'min' => 6],
            ['newPasswordRepeat', 'compare', 'compareAttribute' => 'newPassword'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'newPassword' => 'Новый пароль',
            'newPasswordRepeat' => 'Новый пароль ещё раз',
            'currentPassword' => 'Ваш пароль',
        ];
    }

    /**
     * @param string $attribute
     * @param array $params
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if (!$this->_user->validatePassword($this->$attribute)) {
                $this->addError($attribute, Yii::t('app', 'ERROR_WRONG_CURRENT_PASSWORD'));
            }
        }
    }

    /**
     * @return boolean
     */
    public function changePassword()
    {
        $user = $this->_user;
        $user->setPassword($this->newPassword);
        $result = $user->save();
        return $result;
    }
}


text:
@interface FDVideoErrorView : UIView

@end


text:
package org.apereo.cas.support.saml.web.idp.metadata;

import org.apereo.cas.support.saml.SamlIdPConstants;
import org.apereo.cas.support.saml.idp.metadata.generator.SamlIdPMetadataGenerator;
import org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPMetadataLocator;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * The {@link SamlIdPMetadataController} will attempt
 * to produce saml metadata for CAS as an identity provider.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@Controller("samlIdPMetadataController")
@Slf4j
@RequiredArgsConstructor
public class SamlIdPMetadataController implements InitializingBean {
    private static final String CONTENT_TYPE = "text/xml;charset=UTF-8";

    private final SamlIdPMetadataGenerator metadataAndCertificatesGenerationService;
    private final SamlIdPMetadataLocator samlIdPMetadataLocator;

    @Override
    public void afterPropertiesSet() {
        this.metadataAndCertificatesGenerationService.generate();
    }

    /**
     * Displays the identity provider metadata.
     * Checks to make sure metadata exists, and if not, generates it first.
     *
     * @param response servlet response
     * @throws IOException the iO exception
     */
    @GetMapping(path = SamlIdPConstants.ENDPOINT_IDP_METADATA)
    public void generateMetadataForIdp(final HttpServletResponse response) throws IOException {
        this.metadataAndCertificatesGenerationService.generate();
        val md = this.samlIdPMetadataLocator.getMetadata().getInputStream();
        val contents = IOUtils.toString(md, StandardCharsets.UTF_8);
        response.setContentType(CONTENT_TYPE);
        response.setStatus(HttpServletResponse.SC_OK);
        try (val writer = response.getWriter()) {
            LOGGER.debug("Producing metadata for the response");
            writer.write(contents);
            writer.flush();
        }
    }
}