text:
package com.flickr.api.utils;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;

public class IOUtils
{

    private static final int DEFAULT_BUFFER_SIZE = 4096;

    private IOUtils()
    {
    }

    public static final Charset UTF8 = Charset.forName("UTF-8");

    /**
     * Convert a string into a byte array using the UTF-8 charset.
     *
     * @param str The string to convert.
     * @return The corresponding byte array.
     */
    public static byte[] toByteArray(String str)
    {
        return str.getBytes(UTF8);
    }

    /**
     * Close silently a stream.
     *
     * @param closeable The stream to close.
     */
    public static void closeQuietly(Closeable closeable)
    {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * Read a String from an InputStream.
     *
     * @param is The InputStream to read.
     * @param charset The Charset to use.
     * @return The String.
     * @throws IOException Error reading stream.
     */
    public static String toString(InputStream is, String charset) throws IOException
    {
        StringWriter sw = new StringWriter();
        InputStreamReader reader = new InputStreamReader(is, charset);

        char[] buffer = new char[DEFAULT_BUFFER_SIZE];
        long count = 0;
        int n = 0;
        while (-1 != (n = reader.read(buffer))) {
            sw.write(buffer, 0, n);
            count += n;
        }
        return sw.toString();
    }

    /**
     * Copy the content of an {@link InputStream} into a {@link OutputStream}.
     *
     * @param is The stream to read.
     * @param os The output stream.
     * @throws IOException Copy error.
     */
    public static void copy(InputStream is, OutputStream os) throws IOException
    {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int len;
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
    }
}


text:
import { operation } from '@ragg/fleur'
import { HistoryActions } from './actions'
import HistoryStore, { Command } from './HistoryStore'

export const pushHistory = operation((context, { command }: { command: Command }) => {
    context.dispatch(HistoryActions.pushHistory, { command })
})

export const doUndo = operation(context => {
    const command = context.getStore(HistoryStore).getUndoCommand()

    if (command) {
        command.undo(context)
        context.dispatch(HistoryActions.undoing, {})
    }
})

export const doRedo = operation(context => {
    const command = context.getStore(HistoryStore).getRedoCommand()

    if (command) {
        command.redo(context)
        context.dispatch(HistoryActions.redoing, {})
    }
})

redpajama_set_name: RedPajamaGithub


text:
/**
 * SlickGrid/custom/drawGrid.js
 *
 * Custom functions shared by all custom JavaScript files
 * (SlickGrid/custom/*) that create the SlickGrid.
 */

/**
 * This function formats and instantiates elements of the SlickGrid, and then calls the needed
 * SlickGrid creation function based on the current step number in the jWizard interface.
 *
 * @param data  The parsed file data returned from the server side.
 * @param step  The current step number in the jWizard interface.
 */
function drawGrid(data, step) {
    var grid;

    // A custom formatter (see slick.formatters.js) to format the lines for the header line toggle
    // functionality
    var LineNumberFormatter = function (row, cell, value, columnDef, dataContext) {
        if (dataContext.parent != null) { // header row: a parent row is present
            if (dataContext.id == dataContext.parent) { // header row that is the parent row
                // return the appropriate item depending on the current state of the parent
                // (expanded or collapsed)
                if (dataContext._collapsed) {
                    return " " + value;
                } else {
                    return " " + value;
                }
            } else { // header row but not the parent row: do nothing
                return value;
            }
        } else { // no "parent" assigned to the row (it's a data row)
            return value;
        }
    };

    // split data by new line character
    var fileData = data.split(/\r\n|\r|\n/g);

    // create columns[] for SlickGrid (all grid instances will have this column)
    var columns = [
        {
            id: "line_number",
            name: "#",
            field: "line_number",
            width: 45,
            cssClass: "lineNumber",
            headerCssClass: "lineNumber",
            resizable: false
        }

    ];
    var rows = [];

    // call needed function based on the current jWizard step number
    if (step == "2") { // Specify Header Lines
        gridForHeaderRowSelection(grid, fileData, columns, rows, step);
    } else if (step == "3") { // Specify Delimiters
        gridForDelimiterSelection(grid, fileData, columns, rows, LineNumberFormatter);
    } else {  // Specify Variable Attributes
        gridForVariableSpecification(grid, fileData, columns, rows, LineNumberFormatter, step);
    }
}

/**
 * A custom filter used by the SlickGrid dataView to determine how the lines are to be formatted.
 *
 * @param item  The line of data (as an object).
 * @param rows  The populated rows array.
 */
function headerLineFilter(item, rows) {
    if (item.parent != null) {  // if it's a header line

        // weed out the non-parent header lines if the parent is collapsed (since they are not
        // showing, we don't need to format them)
        var parent = rows[item.parent];
        if (parent._collapsed) {
            if (item.parent != item.id) {
                return false;
            }
        }
        // the parent line and the non-prent header lines will be formatted if the parent line
        // isn't collapsed
        parent = rows[parent.parent];
    }
    return true;
}

/**
 * This function listens and binds row events to the SlickGrid.
 * It is responsible for toggling the header lines (expanding
 * or collapsing) based on if the user clicks the toggle icon
 * in the parent header line row.
 *
 * @param grid  The grid to act upon.
 * @param dataView  The data model containing the parsed file data.
 * @param colNumber  The total number of columns in the grid.
 * @param headerLines  The header line number in array format.
 * @param firstHeaderLine  The parent header line.
 */
function bindGridHeaderLineToggleEvent(grid, dataView, colNumber, headerLines, firstHeaderLine) {
    grid.onClick.subscribe(function (e, args) {
        if ($(e.target).hasClass("toggle")) {
            // get the event target (parent header line) and determine its state (expanded or
            // collapsed)
            var item = dataView.getItem(args.row);
            if (!item._collapsed) { // currently expanded
                dataView.getItemMetadata = function (i) {
                    if (i == firstHeaderLine) { // if it is the parent header line, format the row accordingly
                        return {
                            "cssClasses": "headerRow",
                            "columns": {
                                1: {
                                    "colspan": colNumber
                                }
                            }
                        };
                    } else { // not the parent header line: do nothing
                        return null;
                    }
                };
                // toggle the header lines to be collapsed
                item._collapsed = true;
            } else { // currently collapsed
                dataView.getItemMetadata = function (i) {
                    if (jQuery.inArray(i.toString(), headerLines) >= 0) { // format the header line rows
                        return {
                            "cssClasses": "headerRow",
                            "columns": {
                                1: {
                                    "colspan": colNumber
                                }
                            }
                        };
                    }
                };
                // toggle the header lines to be expanded
                item._collapsed = false;
            }
            // update the dataView
            dataView.updateItem(item.id, item);
            checkIfColumnIsDisabled(colNumber, grid);
            e.stopImmediatePropagation();
        }
    });

    // update grid row count
    dataView.onRowCountChanged.subscribe(function (e, args) {
        grid.updateRowCount();
        grid.render();
    });

    // handle row change
    dataView.onRowsChanged.subscribe(function (e, args) {
        grid.invalidateRows(args.rows);
        grid.render();
    });

}

/**
 * This function listens and binds scroll events to the SlickGrid.
 *
 * @param colNumber  The total number of columns in the grid.
 * @param grid  The grid to act upon.
 */
function bindGridScrollEvent(colNumber, grid) {
    grid.onScroll.subscribe(function (e, args) {
        checkIfColumnIsDisabled(colNumber, grid);
    });
}


text:
#include "stdafx.h"
#include <JavaContainer.h>
#include <JavaString.h>
#include <JavaIO.h>

//////////////////////////////////////////////////////////////////////////
// File

void JFile::New(IN JString& path) {
	CallConstructorMethod("java/io/File", "(Ljava/lang/String;)V", path.GetJObject());
}

jboolean JFile::mkdir() {
	return CallBooleanMethod("mkdir", "()Z");;
}

jboolean JFile::mkdirs() {
	return CallBooleanMethod("mkdirs", "()Z");;
}

jboolean JFile::exists() {
	return CallBooleanMethod("exists", "()Z");;
}

JString* JFile::getAbsolutePath() {
	JString* obj = new JString;
	CallObjectMethod(obj, "getAbsolutePath", "()Ljava/lang/String;");
	return obj;
}

JString* JFile::getParent() {
	JString* obj = new JString;
	CallObjectMethod(obj, "getParent", "()Ljava/lang/String;");
	return obj;
}

//////////////////////////////////////////////////////////////////////////
// InputStream

int JInputStream::read() {
	return CallIntMethod("read", "()I");
}

int JInputStream::read(JArray<jbyte>& buffer) {
	return CallIntMethod("read", "([B)I", buffer.GetJObject());
}

int JInputStream::read(JArray<jbyte>& buffer, jint byteOffset, jint byteCount) {
	return CallIntMethod("read", "([BII)I", buffer.GetJObject(), byteOffset, byteCount);
}

void JInputStream::close() {
	CallVoidMethod("close", "()V");
}

long JInputStream::skip(jlong byteCount) {
	return CallLongMethod("skip", "(J)J", byteCount);
}

//////////////////////////////////////////////////////////////////////////
// FileInputStream

void JFileInputStream::New(JFile& file) {
	CallConstructorMethod("java/io/FileInputStream", "(Ljava/io/File;)V", file.GetJObject());
}

void JFileInputStream::New(JString& path) {
	CallConstructorMethod("java/io/FileInputStream", "(Ljava/lang/String;)V", path.GetJObject());
}

//////////////////////////////////////////////////////////////////////////
// OutputStream

void JOutputStream::write(JArray<jbyte>& buffer) {
	CallVoidMethod("write", "([B)V", buffer.GetJObject());
}

void JOutputStream::write(JArray<jbyte>& buffer, int offset, int count) {
	CallVoidMethod("write", "([BII)V", buffer.GetJObject(), offset, count);
}

void JOutputStream::write(jint oneByte) {
	CallVoidMethod("write", "(I)V", oneByte);
}

void JOutputStream::close() {
	CallVoidMethod("close", "()V");
}

//////////////////////////////////////////////////////////////////////////
// FileOutputStream

void JFileOutputStream::New(JFile& file) {
	CallConstructorMethod("java/io/FileOutputStream", "(Ljava/io/File;)V", file.GetJObject());
}

void JFileOutputStream::New(JFile& file, jboolean append) {
	CallConstructorMethod("java/io/FileOutputStream", "(Ljava/io/File;Z)V", file.GetJObject(), append);
}

void JFileOutputStream::New(JString& path) {
	CallConstructorMethod("java/io/FileOutputStream", "(Ljava/lang/String;)V", path.GetJObject());
}

void JFileOutputStream::New(JString& path, jboolean append) {
	CallConstructorMethod("java/io/FileOutputStream", "(Ljava/lang/String;Z)V", path.GetJObject(), append);
}


text:
const { Command } = require('discord.js-commando');
const _sdata = require('../../assets/_data/static_data.json');
const Request = require('../../models/Request');
const { REQUEST_CHANNEL } = require('../../assets/_data/settings.json');

module.exports = class ApproveRequestCommand extends Command {
    constructor(client) {
        super(client, {
            name: 'request-approve',
            aliases: ['req-a'],
            group: 'bot',
            memberName: 'request-approve',
            description: '`AL: full` Approve a requested feature.',
            guarded: true,

            args: [
                {
                    key: 'requestID',
                    prompt: 'which feature request do you want to approve?\n',
                    type: 'integer'
                }
            ]
        });
    }

    hasPermission(msg) {
        return this.client.isOwner(msg.author)
   || this.client.provider.get(msg.author.id, 'userLevel') >= _sdata.aLevel.full;
    }

    async run(msg, { requestID }) {
        if (msg.channel.id !== REQUEST_CHANNEL) {
            return msg.embed({
                color: _sdata.colors.red,
                description: `${msg.author}, this command can only be used in the requests channel.`
            });
        }

        const request = await Request.findById(requestID);
        if (!request) {
            return msg.embed({
                color: _sdata.colors.dark_green,
                description: `${msg.author}, you provided an invalid request id.`
            });
        }
        await request.update({
            processed: true,
            processedBy: msg.author.id,
            approved: true
        });

        await this.client.users.get(request.requester).send({
            embed: {
                color: _sdata.colors.green,
                author: {
                    name: 'Request approved',
                    icon_url: msg.author.displayAvatarURL // eslint-disable-line camelcase
                },
                description: 'Your request has been reviewed and approved!',
                fields: [
                    {
                        name: 'Your request:',
                        value: request.request.length <= 1024 ? request.request : `${request.request.substr(0, 1021)}...` // eslint-disable-line max-len
                    }
                ]
            }
        });

        return msg.embed({
            color: _sdata.colors.green,
            description: `${msg.author}, successfully approved request #${request.id}!`
        })
            .then(async() => {
                const messages = await msg.channel.fetchMessages({ after: msg.id });
                const requestMessage = await msg.channel.fetchMessage(request.requestMessage);
                messages.deleteAll();
                msg.delete();
                requestMessage.delete();
            });
    }
};


text:
package de.plushnikov.intellij.plugin.inspection;

import com.intellij.codeInspection.InspectionProfileEntry;
import com.siyeh.ig.controlflow.PointlessBooleanExpressionInspection;

/**
 * @author Lekanich
 */
public class PointlessBooleanExpressionInspectionTest extends LombokInspectionTest {
  @Override
  protected String getBasePath() {
    return super.getBasePath() + "/" + TEST_DATA_INSPECTION_DIRECTORY + "/pointlessBooleanExpression";
  }

  @Override
  protected InspectionProfileEntry getInspection() {
    return new PointlessBooleanExpressionInspection();
  }

  public void testPointlessBooleanExpressionBuilderDefault() {
    doTest();
  }
}


text:
Simple instant visualization of your data, here and now.

## How it works

    click + pandas –> seeing –> matplotlib

`seeing` works by using `click` to communicate with the user and `pandas` to retrieve and manipulate the data. Graphs are then generated using `matplotlib` and opened using your standard image viewer.

`seaborn` is used to make graphs prettier, which are then produced in a aesthetic similar to MATLAB.

## Options

By default, `seeing` plots all columns together (with row numbers on the x axis).
Columns to be graphed can be specified by `-x` and `-y`, using column labels (first row of the data).

Alternatively, it is able to plot each column in a separated subplot using the boolean flag `--subplots/--no-subplots`.

Axes labels can be set with `--xlabel` and `--ylabel`.
A legend can be set on/off with `--legend/--no-legend`.

For a full explanation of all options, run `seeing --help` after installing.


text:
var defaultApiManager = require('./defaultApiManager.js');
var queryUtils = require('../customUtils/queryUtil.js');
var _ = require('lodash');
var responder = require('../../Routes/responder.js');
var productsApiManager = {};

productsApiManager.handler = function (queryObj,params,req,res){
    var query = _.cloneDeep(queryObj);
    queryUtils.addParamsToQuery(query,params);
    defaultApiManager.handler(query,res,this.responseHandler);
};

productsApiManager.responseHandler = function(err,data,res){
    if(data.hits != undefined){
        var result = data.hits.hits[0]._source;
        responder.sendResponse(result,res);
    }
    else {
        var result = data.message;
        responder.sendResponse(result,res);
    }
};

module.exports = productsApiManager;


text:
namespace crashpad {

bool LoggingReadFile(FileHandle file, void* buffer, size_t size) {
  ssize_t expect = base::checked_cast<ssize_t>(size);
  ssize_t rv = ReadFile(file, buffer, size);
  if (rv < 0) {
    PLOG(ERROR) << "read";
    return false;
  }
  if (rv != expect) {
    LOG(ERROR) << "read: expected " << expect << ", observed " << rv;
    return false;
  }

  return true;
}

bool LoggingWriteFile(FileHandle file, const void* buffer, size_t size) {
  ssize_t expect = base::checked_cast<ssize_t>(size);
  ssize_t rv = WriteFile(file, buffer, size);
  if (rv < 0) {
    PLOG(ERROR) << "write";
    return false;
  }
  if (rv != expect) {
    LOG(ERROR) << "write: expected " << expect << ", observed " << rv;
    return false;
  }

  return true;
}

void CheckedReadFile(FileHandle file, void* buffer, size_t size) {
  CHECK(LoggingReadFile(file, buffer, size));
}

void CheckedWriteFile(FileHandle file, const void* buffer, size_t size) {
  CHECK(LoggingWriteFile(file, buffer, size));
}

void CheckedReadFileAtEOF(FileHandle file) {
  char c;
  ssize_t rv = ReadFile(file, &c, 1);
  if (rv < 0) {
    PCHECK(rv == 0) << "read";
  } else {
    CHECK_EQ(rv, 0) << "read";
  }
}

void CheckedCloseFile(FileHandle file) {
  CHECK(LoggingCloseFile(file));
}

}  // namespace crashpad


text:
from StatusBar import *
from FocusWdg import *
from ScriptWdg import *


text:
<!DOCTYPE html>
<html>
<script>
function boom()
{
  var a = document.createElementNS("http://www.w3.org/1999/xhtml", "span");
  var b = document.createElementNS("http://www.w3.org/1999/xhtml", "span");
  var x = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
  var y = document.createElementNS("http://www.w3.org/1999/xhtml", "basefont");
  var z = document.createElementNS("http://www.w3.org/1999/xhtml", "body");
  z.setAttributeNS(null, "link", "#333333");

  document.documentElement.appendChild(a);
  b.appendChild(x);
  b.appendChild(y);
  document.documentElement.offsetHeight;
  a.appendChild(b);
  document.documentElement.offsetHeight;
  document.createElementNS("http://www.w3.org/1999/xhtml", "div").appendChild(y);
  b.appendChild(z);
}
</script>
<body onload="boom();"></body>


text:
<?php

namespace Humbug\Mutator\ReturnValue;

use Humbug\Mutator\MutatorAbstract;
use Humbug\Utility\Tokenizer;

class NewObject extends MutatorAbstract
{

    /**
     * Replace (return new Something(anything);) with (new Something(anything); return null;)
     * The object creation must be preserved or behaviour may change beyond the scope
     * of the mutation.
     *
     * @param array $tokens
     * @param int $index
     * @return array
     */
    public static function getMutation(array &$tokens, $index)
    {
        $replace = [];
        $last = null;
        $tokenCount = count($tokens);
        for ($i=$index+1; $i < $tokenCount; $i++) {
            if (is_array($tokens[$i]) && $tokens[$i][0] == T_WHITESPACE) {
                continue;
            } elseif (is_array($tokens[$i]) && $tokens[$i][0] == T_NEW) {
                // collect statement tokens (skipping one whitespace after 'return')
                for ($j=$index+2; $j < $tokenCount; $j++) {
                    if (!is_array($tokens[$j]) && $tokens[$j] == ';') {
                        $last = $j - 1;
                        break;
                    }
                    $replace[$j] = $tokens[$j];
                }
                // replace them all with blanks and set last to 'null'
                foreach ($replace as $k => $t) {
                    if ($k == $last) {
                        $tokens[$k] = [
                            T_STRING,
                            'null'
                        ];
                    } else {
                        $tokens[$k] = '';
                    }
                }
                // shift the instantiation prior to the return statement to
                // preserve instantiation behaviour without overwriting anything
                // and without upsetting line count.
                $replace[] = ';';
                $replace[] = [T_WHITESPACE, ' '];
                $string = ['-1' => Tokenizer::reconstructFromTokens($replace)];
                array_splice($tokens, $index, 0, $string);
                break;
            }
        }
    }

    public static function mutates(array &$tokens, $index)
    {
        $t = $tokens[$index];
        if (is_array($t) && $t[0] == T_RETURN) {
            $has = false;
            $tokenCount = count($tokens);
            for ($i=$index+1; $i < $tokenCount; $i++) {
                if (is_array($tokens[$i]) && $tokens[$i][0] == T_WHITESPACE) {
                    continue;
                } elseif (is_array($tokens[$i]) && $tokens[$i][0] == T_NEW) {
                    $has = true;
                    continue;
                } elseif (!is_array($tokens[$i]) && $tokens[$i] == ';') {
                    // return statement terminated
                    if ($has === true) {
                        return true;
                    }
                    return false;
                } elseif ($has === false) {
                    return false;
                }
            }
        }
        return false;
    }
}


text:
//
//  CH13MasterViewController.m
//  CocoaHeads Rennes #13
//
//  Created by Olivier Halligon on 08/09/13.
//  Copyright (c) 2013 AliSoftware. All rights reserved.
//

#import "CH13MasterViewController.h"
#import "CH13SessionDetailViewController.h"

#import "Session.h"
#import "City.h"
#import "Person.h"

@interface CH13MasterViewController ()
@property (strong, nonatomic) IBOutlet UIView *actionsView;
@end

@implementation CH13MasterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"MagicalRecord";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

    self.tableView.tableHeaderView = self.actionsView;
}

///////////////////////////////////////////////////////////////////////////////////////
#pragma mark - CH13ListBaseProtocol

static NSString* const kDefaultCityName = @"Rennes";
static NSString* const kDefaultSessionName = @"Nouvelle Session";

- (void)insertNewObject
{
    City* defaultCity = [self findOrCreateCityWithName:kDefaultCityName];
    NSManagedObject* newSession = [self newSessionWithSubject:kDefaultSessionName date:[NSDate date] summary:nil lecturer:nil];
    [newSession setValue:defaultCity forKey:@"city"];
    [newSession.managedObjectContext save:nil];
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    Session *session = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.textLabel.text = session.subject;
    cell.detailTextLabel.text = session.dateString;
}

- (void)showObjectDetails:(id)object
{
    CH13SessionDetailViewController* vc = [CH13SessionDetailViewController new];
    vc.session = object;
    [self.navigationController pushViewController:vc animated:YES];
}

///////////////////////////////////////////////////////////////////////////////////////
#pragma mark - CoreData Mess

- (IBAction)fillObjectGraph
{
    // Fill database with some default objects
    NSDateFormatter* df = [NSDateFormatter new];
    df.dateFormat = @"dd/MM/yy";

    /* Rennes */
    Person* isoftom = [self findOrCreatePersonWithFirstName:@"Thomas" lastName:@"Dupont"];
    NSManagedObject* rennes13a = [self newSessionWithSubject:@"CocoaPods"
                                                        date:[df dateFromString:@"19/09/13"]
                                                     summary:@"CocoaPods, la meilleure façon de gérer les librairies et dépendances"
                                                    lecturer:isoftom];

    Person* alisoftware = [self findOrCreatePersonWithFirstName:@"Olivier" lastName:@"Halligon"];
    NSManagedObject* rennes13b = [self newSessionWithSubject:@"MagicalRecord"
                                                        date:[df dateFromString:@"19/09/13"]
                                                     summary:@"MagicalRecord, simplifions Core Data"
                                                    lecturer:alisoftware];

    City* rennes = [self findOrCreateCityWithName:@"Rennes"];
    [rennes addSessions:[NSSet setWithArray:@[rennes13a, rennes13b]]];

    /* Toulouse */
    Person* macmation = [self findOrCreatePersonWithFirstName:@"Guillaume" lastName:@"Cerquant"];
    NSManagedObject* toulouse0913a = [self newSessionWithSubject:@"CocoaPods"
                                                            date:[df dateFromString:@"19/09/13"]
                                                         summary:@"CocoaPods, un outil permettant d'intégrer facilement des librairies externes dans nos projets"
                                                        lecturer:macmation];

    NSManagedObject* toulouse0313 = [self newSessionWithSubject:@"Accessibilité"
                                                           date:[df dateFromString:@"14/03/13"]
                                                        summary:@"L'Accessibilité avec Cocoa"
                                                       lecturer:macmation];

    Person* dvial = [self findOrCreatePersonWithFirstName:@"Dominique" lastName:@"Vial"];
    NSManagedObject* toulouse0913b = [self newSessionWithSubject:@"Novae"
                                                            date:[df dateFromString:@"19/09/13"]
                                                         summary:@"Chronique de la création d'un jeu iOS"
                                                        lecturer:dvial];

    City* toulouse = [self findOrCreateCityWithName:@"Toulouse"];
    [toulouse addSessions:[NSSet setWithArray:@[toulouse0313, toulouse0913a, toulouse0913b]]];

    /* Paris */
    Person* mgodard = [self findOrCreatePersonWithFirstName:@"Mathieu" lastName:@"Godard"];
    NSManagedObject* paris37b = [self newSessionWithSubject:@"CocoaPods"
                                                       date:[df dateFromString:@"18/02/13"]
                                                    summary:@"SmallTalk d'Introduction à CocoaPods"
                                                   lecturer:mgodard];

    City* paris = [self findOrCreateCityWithName:@"Paris"];
    [paris addSessions:[NSSet setWithArray:@[paris37b]]];

    [self.fetchedResultsController.managedObjectContext save:nil];
}

_BOOKMARK_
- (IBAction)emptyGraphObject
{
    [City truncateAll];
    [Session truncateAll];
    [Person truncateAll];
}

_BOOKMARK_
- (NSManagedObject*)newSessionWithSubject:(NSString*)subject
                                     date:(NSDate*)date
                                  summary:(NSString*)summary
                                 lecturer:(Person*)lecturer
{
    Session* session = [Session createEntity];
    session.subject = subject;
    session.date = date;
    session.summary = summary;
    session.lecturer = lecturer;
    return session;
}

_BOOKMARK_
- (City*)findOrCreateCityWithName:(NSString*)cityName
{
    City* foundCity = [City findFirstByAttribute:@"name" withValue:cityName];
    if (!foundCity)
    {
        foundCity = [City createEntity];
        foundCity.name = cityName;
    }
    return foundCity;
}

_BOOKMARK_
- (Person*)findOrCreatePersonWithFirstName:(NSString*)firstName lastName:(NSString*)lastName
{
    NSPredicate* personPredicate = [NSPredicate predicateWithFormat:@"firstname == %@ AND lastname == %@", firstName, lastName];
    Person* person = [Person findFirstWithPredicate:personPredicate];
    if (!person)
    {
        person = [Person createEntity];
        person.firstname = firstName;
        person.lastname = lastName;
    }
    return person;
}

_BOOKMARK_
- (NSFetchedResultsController *)buildFetchedResultsController
{
    return [Session fetchAllSortedBy:@"city.name,date" ascending:NO withPredicate:nil groupBy:@"city.name" delegate:self];
}

@end


text:
package tabletserver

import (
	"fmt"
	"html/template"
	"math/rand"
	"reflect"
	"strings"
	"testing"
	"time"

	"github.com/youtube/vitess/go/sqldb"
	"github.com/youtube/vitess/go/vt/dbconfigs"
	"github.com/youtube/vitess/go/vt/mysqlctl"
	"github.com/youtube/vitess/go/vt/vttest/fakesqldb"
)

type dummyChecker struct {
}

func (dummyChecker) CheckMySQL() {}

var DummyChecker = dummyChecker{}

type fakeCallInfo struct {
	remoteAddr string
	username   string
	text       string
	html       string
}

func (fci *fakeCallInfo) RemoteAddr() string {
	return fci.remoteAddr
}

func (fci *fakeCallInfo) Username() string {
	return fci.username
}

func (fci *fakeCallInfo) Text() string {
	return fci.text
}

func (fci *fakeCallInfo) HTML() template.HTML {
	return template.HTML(fci.html)
}

type testUtils struct{}

func newTestUtils() *testUtils {
	return &testUtils{}
}

func (util *testUtils) checkEqual(t *testing.T, expected interface{}, result interface{}) {
	if !reflect.DeepEqual(expected, result) {
		t.Fatalf("expect to get: %v, but got: %v", expected, result)
	}
}

func (util *testUtils) checkTabletErrorWithRecover(t *testing.T, tabletErrType int, tabletErrStr string) {
	err := recover()
	if err == nil {
		t.Fatalf("should get error")
	}
	util.checkTabletError(t, err, tabletErrType, tabletErrStr)
}

func (util *testUtils) checkTabletError(t *testing.T, err interface{}, tabletErrType int, tabletErrStr string) {
	tabletError, ok := err.(*TabletError)
	if !ok {
		t.Fatalf("should return a TabletError, but got err: %v", err)
	}
	if tabletError.ErrorType != tabletErrType {
		t.Fatalf("should return a TabletError with error type: %s", util.getTabletErrorString(tabletErrType))
	}
	if !strings.Contains(tabletError.Error(), tabletErrStr) {
		t.Fatalf("expect the tablet error should contain string: '%s', but it does not. Got tablet error: '%s'", tabletErrStr, tabletError.Error())
	}
}

func (util *testUtils) getTabletErrorString(tabletErrorType int) string {
	switch tabletErrorType {
	case ErrFail:
		return "ErrFail"
	case ErrRetry:
		return "ErrRetry"
	case ErrFatal:
		return "ErrFatal"
	case ErrTxPoolFull:
		return "ErrTxPoolFull"
	case ErrNotInTx:
		return "ErrNotInTx"
	}
	return ""
}

func (util *testUtils) newMysqld(dbconfigs *dbconfigs.DBConfigs) mysqlctl.MysqlDaemon {
	return mysqlctl.NewMysqld(
		"",
		"",
		mysqlctl.NewMycnf(0, 6802),
		&dbconfigs.Dba,
		&dbconfigs.App.ConnParams,
		&dbconfigs.Repl,
	)
}

func (util *testUtils) newDBConfigs(db *fakesqldb.DB) dbconfigs.DBConfigs {
	appDBConfig := dbconfigs.DBConfig{
		ConnParams: sqldb.ConnParams{Engine: db.Name},
		Keyspace:   "test_keyspace",
		Shard:      "0",
	}
	return dbconfigs.DBConfigs{
		App: appDBConfig,
	}
}

func (util *testUtils) newQueryServiceConfig() Config {
	randID := rand.Int63()
	config := DefaultQsConfig
	config.StatsPrefix = fmt.Sprintf("Stats-%d-", randID)
	config.DebugURLPrefix = fmt.Sprintf("/debug-%d-", randID)
	config.RowCache.StatsPrefix = fmt.Sprintf("Stats-%d-", randID)
	config.PoolNamePrefix = fmt.Sprintf("Pool-%d-", randID)
	config.StrictMode = true
	config.RowCache.Binary = "ls"
	config.RowCache.Connections = 100
	config.EnablePublishStats = false
	return config
}

func (util *testUtils) newConnPool() *ConnPool {
	return NewConnPool(
		"ConnPool",
		100,
		10*time.Second,
		false,
		NewQueryServiceStats("", false),
		DummyChecker,
	)
}

func newTestSchemaInfo(
	queryCacheSize int,
	reloadTime time.Duration,
	idleTimeout time.Duration,
	enablePublishStats bool) *SchemaInfo {
	randID := rand.Int63()
	name := fmt.Sprintf("TestSchemaInfo-%d-", randID)
	queryServiceStats := NewQueryServiceStats(name, enablePublishStats)
	return NewSchemaInfo(
		name,
		DummyChecker,
		queryCacheSize,
		reloadTime,
		idleTimeout,
		newTestSchemaInfoCachePool(enablePublishStats, queryServiceStats),
		map[string]string{
			debugQueryPlansKey: fmt.Sprintf("/debug/query_plans_%d", randID),
			debugQueryStatsKey: fmt.Sprintf("/debug/query_stats_%d", randID),
			debugTableStatsKey: fmt.Sprintf("/debug/table_stats_%d", randID),
			debugSchemaKey:     fmt.Sprintf("/debug/schema_%d", randID),
		},
		enablePublishStats,
		queryServiceStats,
	)
}


text:
<!DOCTYPE html>

    <title>Pattern Lab</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width" />

    <link rel="stylesheet" href="/assets/../components/css/pattern-scaffolding.css?1493209668" media="all" />
    <link rel="stylesheet" href="/assets/style.css?1493209668" media="all" />

<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

<link rel="stylesheet" href="../../styleguide/css/styleguide.min.css?1493209668" media="all">
<link rel="stylesheet" href="../../styleguide/css/prism-typeahead.min.css?1493209668" media="all" />

  Sed porttitor lectus nibh. Nulla quis lorem ut libero malesuada feugiat. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Donec sollicitudin molestie malesuada. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Nulla porttitor accumsan tincidunt. Donec sollicitudin molestie malesuada. Quisque velit nisi, pretium ut lacinia in, elementum id enim.


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'BuildRecord.finished'
        db.add_column('repomgmt_buildrecord', 'finished',
                      self.gf('django.db.models.fields.DateTimeField')(db_index=True, null=True, blank=True),
                      keep_default=False)

    def backwards(self, orm):
        # Deleting field 'BuildRecord.finished'
        db.delete_column('repomgmt_buildrecord', 'finished')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'repomgmt.architecture': {
            'Meta': {'object_name': 'Architecture'},
            'builds_arch_all': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'primary_key': 'True'})
        },
        'repomgmt.buildnode': {
            'Meta': {'object_name': 'BuildNode'},
            'cloud': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.Cloud']"}),
            'cloud_node_id': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'primary_key': 'True'}),
            'signing_key_id': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'state': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'})
        },
        'repomgmt.buildrecord': {
            'Meta': {'unique_together': "(('series', 'source_package_name', 'version', 'architecture'),)", 'object_name': 'BuildRecord'},
            'architecture': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.Architecture']"}),
            'build_node': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.BuildNode']", 'null': 'True', 'blank': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'finished': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'priority': ('django.db.models.fields.IntegerField', [], {'default': '100'}),
            'series': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.Series']"}),
            'source_package_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'state': ('django.db.models.fields.SmallIntegerField', [], {'default': '8'}),
            'version': ('django.db.models.fields.CharField', [], {'max_length': '200'})
        },
        'repomgmt.chroottarball': {
            'Meta': {'unique_together': "(('architecture', 'series'),)", 'object_name': 'ChrootTarball'},
            'architecture': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.Architecture']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_refresh': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
            'series': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.UbuntuSeries']"}),
            'state': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'})
        },
        'repomgmt.cloud': {
            'Meta': {'object_name': 'Cloud'},
            'endpoint': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
            'flavor_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'image_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'primary_key': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'region': ('django.db.models.fields.CharField', [], {'max_length': '200', 'blank': 'True'}),
            'tenant_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'user_name': ('django.db.models.fields.CharField', [], {'max_length': '200'})
        },
        'repomgmt.keypair': {
            'Meta': {'unique_together': "(('cloud', 'name'),)", 'object_name': 'KeyPair'},
            'cloud': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.Cloud']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'private_key': ('django.db.models.fields.TextField', [], {}),
            'public_key': ('django.db.models.fields.TextField', [], {})
        },
        'repomgmt.packagesource': {
            'Meta': {'object_name': 'PackageSource'},
            'code_url': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'flavor': ('django.db.models.fields.CharField', [], {'default': "'OpenStack'", 'max_length': '200'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_seen_code_rev': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'last_seen_pkg_rev': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'packaging_url': ('django.db.models.fields.CharField', [], {'max_length': '200'})
        },
        'repomgmt.repository': {
            'Meta': {'object_name': 'Repository'},
            'contact': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'primary_key': 'True'}),
            'signing_key_id': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'uploaders': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'symmetrical': 'False'})
        },
        'repomgmt.series': {
            'Meta': {'unique_together': "(('name', 'repository'),)", 'object_name': 'Series'},
            'base_ubuntu_series': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.UbuntuSeries']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'numerical_version': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'repository': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.Repository']"}),
            'state': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'})
        },
        'repomgmt.subscription': {
            'Meta': {'object_name': 'Subscription'},
            'counter': ('django.db.models.fields.IntegerField', [], {}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'source': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.PackageSource']"}),
            'target_series': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repomgmt.Series']"})
        },
        'repomgmt.tarballcacheentry': {
            'Meta': {'object_name': 'TarballCacheEntry'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'project_name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'project_version': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'rev_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'db_index': 'True'})
        },
        'repomgmt.ubuntuseries': {
            'Meta': {'object_name': 'UbuntuSeries'},
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'primary_key': 'True'})
        },
        'repomgmt.uploaderkey': {
            'Meta': {'object_name': 'UploaderKey'},
            'key_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'primary_key': 'True'}),
            'uploader': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        }
    }

    complete_apps = ['repomgmt']