text:
import React from 'react';
import { Link } from 'react-router';
import { shallow } from 'enzyme';
import expect from 'expect';

import { PageNew } from '../PageNew';

import { page } from './fixtures';

const defaultProps = {
  errors: [],
  fieldChanged: false,
  updated: false
};

function setup(props = defaultProps) {
  const actions = {
    putPage: expect.createSpy(),
    updateTitle: expect.createSpy(),
    updateBody: expect.createSpy(),
    updatePath: expect.createSpy(),
    updateDraft: expect.createSpy(),
    clearErrors: expect.createSpy()
  };

  const component = shallow(
    <PageNew {...actions} {...props} />
  );

  return {
    component,
    actions,
    saveButton: component.find('.content-side a'),
    errors: component.find('.error-messages'),
    props
  };
}

describe('Containers::PageNew', () => {
  it('should call clearErrors before mount', () => {
    const { actions } = setup();
    expect(actions.clearErrors).toHaveBeenCalled();
  });

  it('should not render error messages initially', () => {
    const { errors } = setup();
    expect(errors.node).toNotExist();
  });

  it('should render error messages', () => {
    const { errors } = setup(Object.assign({}, defaultProps, {
      errors: ['The path field is required!']
    }));
    expect(errors.node).toExist();
  });

  it('should not call putPage if a field is not changed.', () => {
    const { saveButton, actions } = setup();
    saveButton.simulate('click');
    expect(actions.putPage).toNotHaveBeenCalled();
  });

  it('should call putPage if a field is changed.', () => {
    const { saveButton, actions } = setup(Object.assign({}, defaultProps, {
      fieldChanged: true
    }));
    saveButton.simulate('click');
    expect(actions.putPage).toHaveBeenCalled();
  });
});

redpajama_set_name: RedPajamaGithub


text:
package unversioned

import (
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/apis/extensions"
	"k8s.io/kubernetes/pkg/watch"
)

type PodSecurityPoliciesInterface interface {
	PodSecurityPolicies() PodSecurityPolicyInterface
}

type PodSecurityPolicyInterface interface {
	Get(name string) (result *extensions.PodSecurityPolicy, err error)
	Create(psp *extensions.PodSecurityPolicy) (*extensions.PodSecurityPolicy, error)
	List(opts api.ListOptions) (*extensions.PodSecurityPolicyList, error)
	Delete(name string) error
	Update(*extensions.PodSecurityPolicy) (*extensions.PodSecurityPolicy, error)
	Watch(opts api.ListOptions) (watch.Interface, error)
}

// podSecurityPolicy implements PodSecurityPolicyInterface
type podSecurityPolicy struct {
	client *ExtensionsClient
}

// newPodSecurityPolicy returns a podSecurityPolicy object.
func newPodSecurityPolicy(c *ExtensionsClient) *podSecurityPolicy {
	return &podSecurityPolicy{c}
}

func (s *podSecurityPolicy) Create(psp *extensions.PodSecurityPolicy) (*extensions.PodSecurityPolicy, error) {
	result := &extensions.PodSecurityPolicy{}
	err := s.client.Post().
		Resource("podsecuritypolicies").
		Body(psp).
		Do().
		Into(result)

	return result, err
}

// List returns a list of PodSecurityPolicies matching the selectors.
func (s *podSecurityPolicy) List(opts api.ListOptions) (*extensions.PodSecurityPolicyList, error) {
	result := &extensions.PodSecurityPolicyList{}

	err := s.client.Get().
		Resource("podsecuritypolicies").
		VersionedParams(&opts, api.ParameterCodec).
		Do().
		Into(result)

	return result, err
}

// Get returns the given PodSecurityPolicy, or an error.
func (s *podSecurityPolicy) Get(name string) (*extensions.PodSecurityPolicy, error) {
	result := &extensions.PodSecurityPolicy{}
	err := s.client.Get().
		Resource("podsecuritypolicies").
		Name(name).
		Do().
		Into(result)

	return result, err
}

// Watch starts watching for PodSecurityPolicies matching the given selectors.
func (s *podSecurityPolicy) Watch(opts api.ListOptions) (watch.Interface, error) {
	return s.client.Get().
		Prefix("watch").
		Resource("podsecuritypolicies").
		VersionedParams(&opts, api.ParameterCodec).
		Watch()
}

func (s *podSecurityPolicy) Delete(name string) error {
	return s.client.Delete().
		Resource("podsecuritypolicies").
		Name(name).
		Do().
		Error()
}

func (s *podSecurityPolicy) Update(psp *extensions.PodSecurityPolicy) (result *extensions.PodSecurityPolicy, err error) {
	result = &extensions.PodSecurityPolicy{}
	err = s.client.Put().
		Resource("podsecuritypolicies").
		Name(psp.Name).
		Body(psp).
		Do().
		Into(result)

	return
}


text:
package VMOMI::HostPatchManagerStatusPrerequisitePatch;
use parent 'VMOMI::DynamicData';

use strict;
use warnings;

our @class_ancestors = (
    'DynamicData',
);

our @class_members = (
    ['id', undef, 0, ],
    ['installState', undef, 1, 1],
);

sub get_class_ancestors {
    return @class_ancestors;
}

sub get_class_members {
    my $class = shift;
    my @super_members = $class->SUPER::get_class_members();
    return (@super_members, @class_members);
}

1;


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>org.eclipse.jetty.util.preventers (Jetty :: Aggregate :: All core Jetty 8.1.8.v20121106 API)</title>
<meta name="date" content="2012-11-06">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.eclipse.jetty.util.preventers

Classes

AbstractLeakPreventer

AppContextLeakPreventer

AWTLeakPreventer

DOMLeakPreventer

DriverManagerLeakPreventer

GCThreadLeakPreventer

Java2DLeakPreventer

LDAPLeakPreventer

LoginConfigurationLeakPreventer

SecurityProviderLeakPreventer


text:
package uk.gov.gchq.gaffer.rest.service.v1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import uk.gov.gchq.gaffer.commonutil.iterable.CloseableIterable;
import uk.gov.gchq.gaffer.jobtracker.JobDetail;
import uk.gov.gchq.gaffer.operation.OperationChain;
import uk.gov.gchq.gaffer.operation.OperationChainDAO;
import uk.gov.gchq.gaffer.operation.OperationException;
import uk.gov.gchq.gaffer.operation.impl.job.GetAllJobDetails;
import uk.gov.gchq.gaffer.operation.impl.job.GetJobDetails;
import uk.gov.gchq.gaffer.operation.impl.job.GetJobResults;
import uk.gov.gchq.gaffer.rest.factory.GraphFactory;
import uk.gov.gchq.gaffer.rest.factory.UserFactory;
import uk.gov.gchq.gaffer.store.Context;

import javax.inject.Inject;

/**
 * An implementation of {@link IJobService}. By default it will use a singleton
 * {@link uk.gov.gchq.gaffer.graph.Graph} generated using the {@link uk.gov.gchq.gaffer.rest.factory.GraphFactory}.
 * All operations are simply delegated to the graph.
 * Pre and post operation hooks are available by extending this class and implementing preOperationHook and/or
 * postOperationHook.
 */
public class JobService implements IJobService {
    private static final Logger LOGGER = LoggerFactory.getLogger(JobService.class);

    @Inject
    private GraphFactory graphFactory;

    @Inject
    private UserFactory userFactory;

    @Override
    public JobDetail executeJob(final OperationChainDAO opChain) {
        final Context context = userFactory.createContext();
        preOperationHook(opChain, context);

        try {
            final JobDetail jobDetail = graphFactory.getGraph().executeJob(opChain, context);
            LOGGER.info("Job started = {}", jobDetail);
            return jobDetail;
        } catch (final OperationException e) {
            throw new RuntimeException("Error executing opChain: " + e.getMessage(), e);
        } finally {
            postOperationHook(opChain, context);
        }
    }

    @Override
    public CloseableIterable<JobDetail> details() {
        try {
            return graphFactory.getGraph().execute(new GetAllJobDetails(), userFactory.createContext());
        } catch (final OperationException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public JobDetail details(final String id) {
        try {
            return graphFactory.getGraph().execute(
                    new GetJobDetails.Builder()
                            .jobId(id)
                            .build(),
                    userFactory.createContext());
        } catch (final OperationException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public CloseableIterable results(final String id) {
        try {
            return graphFactory.getGraph().execute(
                    new GetJobResults.Builder()
                            .jobId(id)
                            .build(),
                    userFactory.createContext());
        } catch (final OperationException e) {
            throw new RuntimeException(e);
        }
    }

    protected void preOperationHook(final OperationChain<?> opChain, final Context context) {
        // no action by default
    }

    protected void postOperationHook(final OperationChain<?> opChain, final Context context) {
        // no action by default
    }
}


text:
from app import db
import os.path

from config import database_dir

if os.path.exists(database_dir):
	os.remove(database_dir)


text:
"""Config flow for Geofency."""
from homeassistant.helpers import config_entry_flow
from .const import DOMAIN

config_entry_flow.register_webhook_flow(
    DOMAIN,
    "Geofency Webhook",
    {"docs_url": "https://www.home-assistant.io/integrations/geofency/"},
)


text:
typedef uint_least16_t char16_t;
typedef uint_least32_t char32_t;
# endif
typedef float swift_float2  __attribute__((__ext_vector_type__(2)));
typedef float swift_float3  __attribute__((__ext_vector_type__(3)));
typedef float swift_float4  __attribute__((__ext_vector_type__(4)));
typedef double swift_double2  __attribute__((__ext_vector_type__(2)));
typedef double swift_double3  __attribute__((__ext_vector_type__(3)));
typedef double swift_double4  __attribute__((__ext_vector_type__(4)));
typedef int swift_int2  __attribute__((__ext_vector_type__(2)));
typedef int swift_int3  __attribute__((__ext_vector_type__(3)));
typedef int swift_int4  __attribute__((__ext_vector_type__(4)));
#endif

#if !defined(SWIFT_PASTE)
# define SWIFT_PASTE_HELPER(x, y) x##y
# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y)
#endif
#if !defined(SWIFT_METATYPE)
# define SWIFT_METATYPE(X) Class
#endif

#if defined(__has_attribute) && __has_attribute(objc_runtime_name)
# define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X)))
#else
# define SWIFT_RUNTIME_NAME(X)
#endif
#if defined(__has_attribute) && __has_attribute(swift_name)
# define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X)))
#else
# define SWIFT_COMPILE_NAME(X)
#endif
#if !defined(SWIFT_CLASS_EXTRA)
# define SWIFT_CLASS_EXTRA
#endif
#if !defined(SWIFT_PROTOCOL_EXTRA)
# define SWIFT_PROTOCOL_EXTRA
#endif
#if !defined(SWIFT_ENUM_EXTRA)
# define SWIFT_ENUM_EXTRA
#endif
#if !defined(SWIFT_CLASS)
# if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted)
#  define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA
#  define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# else
#  define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
#  define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA
# endif
#endif

#if !defined(SWIFT_PROTOCOL)
# define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
# define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA
#endif

#if !defined(SWIFT_EXTENSION)
# define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__)
#endif

#if !defined(OBJC_DESIGNATED_INITIALIZER)
# if defined(__has_attribute) && __has_attribute(objc_designated_initializer)
#  define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
# else
#  define OBJC_DESIGNATED_INITIALIZER
# endif
#endif
#if !defined(SWIFT_ENUM)
# define SWIFT_ENUM(_type, _name) enum _name : _type _name; enum SWIFT_ENUM_EXTRA _name : _type
# if defined(__has_feature) && __has_feature(generalized_swift_name)
#  define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_EXTRA _name : _type
# else
#  define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) SWIFT_ENUM(_type, _name)
# endif
#endif
#if defined(__has_feature) && __has_feature(modules)
@import Foundation;
@import UIKit;
#endif

#pragma clang diagnostic ignored "-Wproperty-attribute-mismatch"
#pragma clang diagnostic ignored "-Wduplicate-method-arg"

@interface NSData (SWIFT_EXTENSION(RileyLinkKit))
@end

@class UINib;
@class UISwitch;
@class NSCoder;

SWIFT_CLASS("_TtC12RileyLinkKit28RileyLinkDeviceTableViewCell")
@interface RileyLinkDeviceTableViewCell : UITableViewCell
@property (nonatomic, weak) IBOutlet UISwitch * _Null_unspecified connectSwitch;
+ (UINib * _Nonnull)nib;
- (void)prepareForReuse;
- (nonnull instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString * _Nullable)reuseIdentifier OBJC_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER;
@end

@class UITableView;
@class NSIndexPath;
@class NSBundle;

SWIFT_CLASS("_TtC12RileyLinkKit34RileyLinkDeviceTableViewController")
@interface RileyLinkDeviceTableViewController : UITableViewController
- (void)viewDidLoad;
- (void)viewWillAppear:(BOOL)animated;
- (void)viewWillDisappear:(BOOL)animated;
- (NSInteger)numberOfSectionsInTableView:(UITableView * _Nonnull)tableView;
- (NSInteger)tableView:(UITableView * _Nonnull)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell * _Nonnull)tableView:(UITableView * _Nonnull)tableView cellForRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
- (NSString * _Nullable)tableView:(UITableView * _Nonnull)tableView titleForHeaderInSection:(NSInteger)section;
- (BOOL)tableView:(UITableView * _Nonnull)tableView shouldHighlightRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
- (void)tableView:(UITableView * _Nonnull)tableView didSelectRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath;
- (nonnull instancetype)initWithStyle:(UITableViewStyle)style OBJC_DESIGNATED_INITIALIZER;
- (nonnull instancetype)initWithNibName:(NSString * _Nullable)nibNameOrNil bundle:(NSBundle * _Nullable)nibBundleOrNil OBJC_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER;
@end

@interface UITableViewCell (SWIFT_EXTENSION(RileyLinkKit))
@end

#pragma clang diagnostic pop


text:
require 'redis'
require 'redis_support'
require 'resque'
require 'resque_scheduler'

module MapRedus
  include RedisSupport

  class InvalidProcess < NotImplementedError
    def initialize; super("MapRedus QueueProcess: need to have perform method defined");end
  end

  class ProcessSpecificationError < InvalidProcess
    def initialize; super("MapRedus Process: need to have the specification defined");end
  end

  class InvalidMapper < NotImplementedError
    def initialize; super("MapRedus Mapper: need to have map method defined");end
  end

  class InvalidReducer < NotImplementedError
    def initialize; super("MapRedus Reducer: need to have reduce method defined");end
  end

  class InvalidInputStream < NotImplementedError
    def initialize; super("MapRedus InputStream: need to have scan method defined");end
  end

  class InvalidProcess < NotImplementedError
    def initialize; super("MapRedus Process Creation Failed: Specifications were not specified");end
  end

  class RecoverableFail < StandardError
    def initialize; super("MapRedus Operation Failed: but it is recoverable") ;end
  end

  # All Queue Processes should have a function called perform
  # ensuring that when the class is put on the resque queue it can perform its work
  #
  # Caution: defines redis, which is also defined in RedisSupport
  #
  class QueueProcess
    def self.queue; :mapredus; end
    def self.perform(*args); raise InvalidProcess; end
  end

  # TODO: When you send work to a worker using a mapper you define,
  # the worker won't have that class name defined, unless it was started up
  # with the class loaded
  #
  def register_reducer(klass); end;
  def register_mapper(klass); end;

  class Helper
    # resque helpers defines
    #   redis
    #   encode
    #   decode
    #   classify
    #   constantize
    #
    # This is extended here because we want to use the encode and decode function
    # when we interact with resque queues
    extend Resque::Helpers

    # Defines a hash by taking the absolute value of ruby's string
    # hash to rid the dashes since redis keys should not contain any.
    #
    # key - The key to be hashed.
    #
    # Examples
    #
    #   Support::key_hash( key )
    #   # => '8dd8hflf8dhod8doh9hef'
    #
    # Returns the hash.
    def self.key_hash( key )
      key.to_s.hash.abs.to_s(16)
    end

    # Returns the classname of the namespaced class.
    #
    # The full name of the class.
    #
    # Examples
    #
    #   Support::class_get( Super::Long::Namespace::ClassName )
    #   # => 'ClassName'
    #
    # Returns the class name.
    def self.class_get(string)
      constantize(string)
    end
  end
end

require 'mapredus/keys'
require 'mapredus/filesystem'
require 'mapredus/master'
require 'mapredus/mapper'
require 'mapredus/reducer'
require 'mapredus/finalizer'
require 'mapredus/support'
require 'mapredus/outputter'
require 'mapredus/inputter'
require 'mapredus/default_classes'
require 'mapredus/process'


text:
package com.lachesis.mnis.board.entity;

import java.util.Date;

import javax.validation.constraints.NotNull;

/**
 * 小白板剂量
 * @author ThinkPad
 *
 */
public class NwbRecord {
	private String recordId;
	@NotNull(message="项目编号不为空!")
	private String code;
	private String name;
	@NotNull(message="部门编号不为空!")
	private String deptCode;
	/**
	 * 记录对应的模板
	 */
	@NotNull(message="模板编号不为空!")
	private String templateId;
	/**
	 * 文本数据值
	 */
	private String value;
	private String patId;
	private String bedCode;
	private String nurseCode;
	private String nurseName;
	private Date createTime;

	public String getRecordId() {
		return recordId;
	}
	public void setRecordId(String recordId) {
		this.recordId = recordId;
	}
	public String getNurseCode() {
		return nurseCode;
	}
	public void setNurseCode(String nurseCode) {
		this.nurseCode = nurseCode;
	}
	public String getNurseName() {
		return nurseName;
	}
	public void setNurseName(String nurseName) {
		this.nurseName = nurseName;
	}
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDeptCode() {
		return deptCode;
	}
	public void setDeptCode(String deptCode) {
		this.deptCode = deptCode;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	public String getPatId() {
		return patId;
	}
	public void setPatId(String patId) {
		this.patId = patId;
	}
	public String getBedCode() {
		return bedCode;
	}
	public void setBedCode(String bedCode) {
		this.bedCode = bedCode;
	}
	public String getTemplateId() {
		return templateId;
	}
	public void setTemplateId(String templateId) {
		this.templateId = templateId;
	}
}


text:
using namespace std;

int Material::textCount = 0;

Material::Material(std::string n){
	name = n;
	textName = "";
	id = 0;
}

int Material::getTextCount(void){
	return textCount;
}

void Material::setTextCount(int count){
	textCount = count;
}

std::string Material::getName(void){
	return name;
}

float* Material::getDiffuse(void){
	// cout<<"Diffuse"<<endl;
	// cout<<diffuse[0]<<endl;
	// cout<<diffuse[1]<<endl;
	// cout<<diffuse[2]<<endl;
	return diffuse;
}

float* Material::getAmbient(void){
	// cout<<"Ambient"<<endl;
	// cout<<ambient[0]<<endl;
	// cout<<ambient[1]<<endl;
	// cout<<ambient[2]<<endl;
	return ambient;
}

float* Material::getSpecular(void){
	// cout<<"Specular"<<endl;
	// cout<<specular[0]<<endl;
	// cout<<specular[1]<<endl;
	// cout<<specular[2]<<endl;
	return specular;
}

float Material::getShininess(void){
	return shininess;
}

int Material::getID(void){
	return id;
}

std::string Material::getTextName(void){
	return textName;
}

void Material::setDiffuse(float r, float g, float b){
	diffuse[0] = r;
	diffuse[1] = g;
	diffuse[2] = b;
}

void Material::setAmbient(float r, float g, float b){
	ambient[0] = r;
	ambient[1] = g;
	ambient[2] = b;
}

void Material::setSpecular(float r, float g, float b){
	specular[0] = r;
	specular[1] = g;
	specular[2] = b;
}

void Material::setShininess(float n){
	shininess = n;
}

void Material::setD(float d){
	diffuse[3] = d;
	ambient[3] = d;
	specular[3] = d;
}

void Material::setTextName(std::string tn){
	if(textName.empty()){
		textCount++;
	}
	textName = tn;
}

void Material::setID(int i){
	id = i;
}

bool Material::hasText(void){
	return !textName.empty();
}


text:
package io.undertow.protocols.ajp;

import io.undertow.util.HeaderMap;
import io.undertow.util.HttpString;

import java.io.IOException;
import java.nio.ByteBuffer;

import static io.undertow.protocols.ajp.AjpConstants.FRAME_TYPE_END_RESPONSE;
import static io.undertow.protocols.ajp.AjpConstants.FRAME_TYPE_REQUEST_BODY_CHUNK;
import static io.undertow.protocols.ajp.AjpConstants.FRAME_TYPE_SEND_BODY_CHUNK;
import static io.undertow.protocols.ajp.AjpConstants.FRAME_TYPE_SEND_HEADERS;

/**
 * Parser used for the client (i.e. load balancer) side of the AJP connection.
 *
 * @author Stuart Douglas
 */
class AjpResponseParser {

    public static final AjpResponseParser INSTANCE = new AjpResponseParser();

    private static final int AB = ('A' << 8) + 'B';

    //states
    public static final int BEGIN = 0;
    public static final int READING_MAGIC_NUMBER = 1;
    public static final int READING_DATA_SIZE = 2;
    public static final int READING_PREFIX_CODE = 3;
    public static final int READING_STATUS_CODE = 4;
    public static final int READING_REASON_PHRASE = 5;
    public static final int READING_NUM_HEADERS = 6;
    public static final int READING_HEADERS = 7;
    public static final int READING_PERSISTENT_BOOLEAN = 8;
    public static final int READING_BODY_CHUNK_LENGTH = 9;
    public static final int DONE = 10;

    //parser states
    int state;
    byte prefix;
    int numHeaders = 0;
    HttpString currentHeader;

    //final states
    int statusCode;
    String reasonPhrase;
    HeaderMap headers = new HeaderMap();
    int readBodyChunkSize;

    public boolean isComplete() {
        return state == DONE;
    }

    public void parse(final ByteBuffer buf) throws IOException {
        if (!buf.hasRemaining()) {
            return;
        }
        switch (this.state) {
            case BEGIN: {
                IntegerHolder result = parse16BitInteger(buf);
                if (!result.readComplete) {
                    return;
                } else {
                    if (result.value != AB) {
                        throw new IOException("Wrong magic number");
                    }
                }
            }
            case READING_DATA_SIZE: {
                IntegerHolder result = parse16BitInteger(buf);
                if (!result.readComplete) {
                    this.state = READING_DATA_SIZE;
                    return;
                }
            }
            case READING_PREFIX_CODE: {
                if (!buf.hasRemaining()) {
                    this.state = READING_PREFIX_CODE;
                    return;
                } else {
                    final byte prefix = buf.get();
                    this.prefix = prefix;
                    if (prefix == FRAME_TYPE_END_RESPONSE) {
                        this.state = READING_PERSISTENT_BOOLEAN;
                        break;
                    } else if (prefix == FRAME_TYPE_SEND_BODY_CHUNK) {
                        this.state = READING_BODY_CHUNK_LENGTH;
                        break;
                    } else if (prefix != FRAME_TYPE_SEND_HEADERS && prefix != FRAME_TYPE_REQUEST_BODY_CHUNK) {
                        this.state = DONE;
                        return;
                    }
                }
            }
            case READING_STATUS_CODE: {
                //this state is overloaded for the request size
                //when reading state=6 (read_body_chunk requests)

                IntegerHolder result = parse16BitInteger(buf);
                if (result.readComplete) {
                    if (this.prefix == FRAME_TYPE_SEND_HEADERS) {
                        statusCode = result.value;
                    } else {
                        //read body chunk or end result
                        //a bit hacky
                        this.state = DONE;
                        this.readBodyChunkSize = result.value;
                        return;
                    }
                } else {
                    this.state = READING_STATUS_CODE;
                    return;
                }
            }
            case READING_REASON_PHRASE: {
                StringHolder result = parseString(buf, false);
                if (result.readComplete) {
                    reasonPhrase = result.value;
                } else {
                    this.state = READING_REASON_PHRASE;
                    return;
                }
            }
            case READING_NUM_HEADERS: {
                IntegerHolder result = parse16BitInteger(buf);
                if (!result.readComplete) {
                    this.state = READING_NUM_HEADERS;
                    return;
                } else {
                    this.numHeaders = result.value;
                }
            }
            case READING_HEADERS: {
                int readHeaders = this.readHeaders;
                while (readHeaders < this.numHeaders) {
                    if (this.currentHeader == null) {
                        StringHolder result = parseString(buf, true);
                        if (!result.readComplete) {
                            this.state = READING_HEADERS;
                            this.readHeaders = readHeaders;
                            return;
                        }
                        if (result.header != null) {
                            this.currentHeader = result.header;
                        } else {
                            this.currentHeader = HttpString.tryFromString(result.value);
                        }
                    }
                    StringHolder result = parseString(buf, false);
                    if (!result.readComplete) {
                        this.state = READING_HEADERS;
                        this.readHeaders = readHeaders;
                        return;
                    }
                    headers.add(this.currentHeader, result.value);
                    this.currentHeader = null;
                    ++readHeaders;
                }
                break;
            }
        }

        if (state == READING_PERSISTENT_BOOLEAN) {
            if (!buf.hasRemaining()) {
                return;
            }
            currentIntegerPart = buf.get();
            this.state = DONE;
            return;
        } else if (state == READING_BODY_CHUNK_LENGTH) {
            IntegerHolder result = parse16BitInteger(buf);
            if (result.readComplete) {
                this.currentIntegerPart = result.value;
                this.state = DONE;
            }
            return;
        } else {
            this.state = DONE;
        }
    }

    protected HttpString headers(int offset) {
        return AjpConstants.HTTP_HEADERS_ARRAY[offset];
    }

    public HeaderMap getHeaders() {
        return headers;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public String getReasonPhrase() {
        return reasonPhrase;
    }

    public int getReadBodyChunkSize() {
        return readBodyChunkSize;
    }

    public static final int STRING_LENGTH_MASK = 1 << 31;

    /**
     * The length of the string being read
     */
    public int stringLength = -1;

    /**
     * The current string being read
     */
    public StringBuilder currentString;

    /**
     * when reading the first byte of an integer this stores the first value. It is set to -1 to signify that
     * the first byte has not been read yet.
     */
    public int currentIntegerPart = -1;
    boolean containsUrlCharacters = false;
    public int readHeaders = 0;

    public void reset() {

        state = 0;
        prefix = 0;
        numHeaders = 0;
        currentHeader = null;

        statusCode = 0;
        reasonPhrase = null;
        headers = new HeaderMap();
        stringLength = -1;
        currentString = null;
        currentIntegerPart = -1;
        readHeaders = 0;
    }

    protected IntegerHolder parse16BitInteger(ByteBuffer buf) {
        if (!buf.hasRemaining()) {
            return new IntegerHolder(-1, false);
        }
        int number = this.currentIntegerPart;
        if (number == -1) {
            number = (buf.get() & 0xFF);
        }
        if (buf.hasRemaining()) {
            final byte b = buf.get();
            int result = ((0xFF & number) << 8) + (b & 0xFF);
            this.currentIntegerPart = -1;
            return new IntegerHolder(result, true);
        } else {
            this.currentIntegerPart = number;
            return new IntegerHolder(-1, false);
        }
    }

    protected StringHolder parseString(ByteBuffer buf, boolean header) {
        boolean containsUrlCharacters = this.containsUrlCharacters;
        if (!buf.hasRemaining()) {
            return new StringHolder(null, false, false);
        }
        int stringLength = this.stringLength;
        if (stringLength == -1) {
            int number = buf.get() & 0xFF;
            if (buf.hasRemaining()) {
                final byte b = buf.get();
                stringLength = ((0xFF & number) << 8) + (b & 0xFF);
            } else {
                this.stringLength = number | STRING_LENGTH_MASK;
                return new StringHolder(null, false, false);
            }
        } else if ((stringLength & STRING_LENGTH_MASK) != 0) {
            int number = stringLength & ~STRING_LENGTH_MASK;
            stringLength = ((0xFF & number) << 8) + (buf.get() & 0xFF);
        }
        if (header && (stringLength & 0xFF00) != 0) {
            this.stringLength = -1;
            return new StringHolder(headers(stringLength & 0xFF));
        }
        if (stringLength == 0xFFFF) {
            //OxFFFF means null
            this.stringLength = -1;
            return new StringHolder(null, true, false);
        }
        StringBuilder builder = this.currentString;

        if (builder == null) {
            builder = new StringBuilder();
            this.currentString = builder;
        }
        int length = builder.length();
        while (length < stringLength) {
            if (!buf.hasRemaining()) {
                this.stringLength = stringLength;
                this.containsUrlCharacters = containsUrlCharacters;
                return new StringHolder(null, false, false);
            }
            char c = (char) buf.get();
            if(c == '+' || c == '%') {
                containsUrlCharacters = true;
            }
            builder.append(c);
            ++length;
        }

        if (buf.hasRemaining()) {
            buf.get(); //null terminator
            this.currentString = null;
            this.stringLength = -1;
            this.containsUrlCharacters = false;
            return new StringHolder(builder.toString(), true, containsUrlCharacters);
        } else {
            this.stringLength = stringLength;
            this.containsUrlCharacters = containsUrlCharacters;
            return new StringHolder(null, false, false);
        }
    }

    protected static class IntegerHolder {
        public final int value;
        public final boolean readComplete;

        private IntegerHolder(int value, boolean readComplete) {
            this.value = value;
            this.readComplete = readComplete;
        }
    }

    protected static class StringHolder {
        public final String value;
        public final HttpString header;
        public final boolean readComplete;
        public final boolean containsUrlCharacters;

        private StringHolder(String value, boolean readComplete, boolean containsUrlCharacters) {
            this.value = value;
            this.readComplete = readComplete;
            this.containsUrlCharacters = containsUrlCharacters;
            this.header = null;
        }

        private StringHolder(HttpString value) {
            this.value = null;
            this.readComplete = true;
            this.header = value;
            this.containsUrlCharacters = false;
        }
    }
}


text:
package cz.cuni.mff.d3s.spl.probe;

import cz.cuni.mff.d3s.spl.agent.SPL;
import cz.cuni.mff.d3s.spl.core.InvocationFilter;
import cz.cuni.mff.d3s.spl.core.MeasurementConsumer;
import cz.cuni.mff.d3s.spl.core.Probe;
import cz.cuni.mff.d3s.spl.core.ProbeController;
import cz.cuni.mff.d3s.spl.instrumentation.ClassLoaderFilter;
import cz.cuni.mff.d3s.spl.instrumentation.ExtraArguments;
import cz.cuni.mff.d3s.spl.instrumentation.javassist.JavassistSnippet;
import cz.cuni.mff.d3s.spl.instrumentation.javassist.SingleMethodTransformer;

public class SingleMethodInstrumentationProbeController implements ProbeController {
	private InstrumentationProbe probe;
	private JavassistSnippet snippet;
	private SingleMethodTransformer transformer;
	private String probeId;

	public SingleMethodInstrumentationProbeController(
			ClassLoaderFilter loaderFilter,
			InvocationFilter filter, ExtraArguments filterArgs,
			MeasurementConsumer consumer, ExtraArguments consumerArguments,
			String methodName) {
		probe = new InstrumentationProbe(filter, consumer);
		probeId = "probe:" + methodName;
		transformer = new SingleMethodTransformer(methodName, probeId, filterArgs, consumerArguments);
		snippet = new JavassistSnippet(loaderFilter, transformer);
	}

	@Override
	public void activate() {
		SPL.registerInstrumentation(snippet);
		SPL.reloadClass(transformer.getTargetClass());
		SPL.registerProbe(probeId, probe);
	}

	@Override
	public void deactivate() {
		SPL.unregisterInstrumentation(snippet);
		SPL.reloadClass(transformer.getTargetClass());
		SPL.unregisterProbe(probeId);
	}

	@Override
	public Probe getProbe() {
		return probe;
	}

	private class InstrumentationProbe implements Probe {
		private InvocationFilter filter;
		private MeasurementConsumer consumer;

		public InstrumentationProbe(InvocationFilter filter,
				MeasurementConsumer consumer) {
			this.filter = filter;
			this.consumer = consumer;
		}

		@Override
		public boolean isActive(Object... args) {
			return filter.measureThisInvocation(args);
		}

		@Override
		public void submit(long when, long duration, Object... args) {
			consumer.submit(when, duration, args);
		}

	}
}


text:
<?php
/**
* View of home page of provider.
*
* @author Surya
* @version 1.0
*/
?>

<input type="image" name="add" src="<?php echo base_url().'images/add.png'?>" id='add' onClick= "window.location='<?php echo base_url()?>project/provider/add_item'">

<input type="image" name="logout" id='logout' src="<?php echo base_url().'images/logout.png'?>" onClick= "window.location='<?php echo base_url()?>project/logout'">

<?php echo 'Welcome '.$name?>&nbsp &nbsp &nbsp

<?php if($this->session->userdata('edit') == 'false') {?>

<?php } ?>
<?php $this->session->unset_userdata('edit'); ?>

<?php if($this->session->userdata('add_item') == 'true') {?>

<?php } ?>
<?php
$this->session->unset_userdata('edit');
$this->session->unset_userdata('add_item');
?>

<?php if(isset($item_lists))  {?>

			Name
			Description
			Status
			Action

		<?php foreach($item_lists as $item_list) {?>

				<?php echo $item_list->name ?>
				<?php echo $item_list->description ?>

					<?php
						if($item_list->status == 1) {
							echo 'Active';
						} else {
							echo 'Not Active';
						}
					?>

				  <a href="<?php echo base_url().'project/provider/edit_item?pid=' ?><?php echo $item_list->pid;?>">Edit
		    	    <a href="#" class='delete' data-value="<?php echo $item_list->pid;?>">Delete
		    	    <a href="<?php echo base_url().'project/provider/item_details?pid=' ?><?php echo $item_list->pid;?>" >View

		<?php } ?>

<?php }?>

<?php foreach ($links as $link) {
			echo "
". $link."
";
		} ?>


text:
@implementation CCMConnection

- (id)initWithURL:(NSURL *)theServerUrl
{
	[super init];
	serverUrl = [theServerUrl retain];
	return self;
}

- (id)initWithURLString:(NSString *)theServerUrlAsString
{
	return [self initWithURL:[NSURL URLWithString:theServerUrlAsString]];
}

- (void)dealloc
{
	[serverUrl release];
	[super dealloc];
}

- (void)setDelegate:(id)aDelegate
{
	delegate = aDelegate;
}

- (id)delegate
{
	return delegate;
}

- (NSString *)errorStringForError:(NSError *)error
{
	return [NSString stringWithFormat:@"Failed to get status from %@: %@",
		[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey], [error localizedDescription]];
}

- (NSString *)errorStringForResponse:(NSHTTPURLResponse *)response
{
	return [NSString stringWithFormat:@"Failed to get status from %@: %@",
			[response URL], [NSHTTPURLResponse localizedStringForStatusCode:[response statusCode]]];
}

- (NSString *)errorStringForParseError:(NSError *)error
{
	return [NSString stringWithFormat:@"Failed to parse status from %@: %@ (Maybe the server is returning a temporary HTML error page instead of an XML document.)",
                [serverUrl description], [[error localizedDescription] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}

- (BOOL)testConnection
{
	NSURLRequest *request = [NSURLRequest requestWithURL:serverUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
	NSHTTPURLResponse *response = nil;
	NSError *error = nil;
	[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	if(error != nil)
		[NSException raise:@"ConnectionException" format:@"%@", [self errorStringForError:error]];
	int status = [response statusCode];
	return (status >= 200 && status != 404 && status < 500);
}

- (NSArray *)retrieveServerStatus
{
	NSURLRequest *request = [NSURLRequest requestWithURL:serverUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
	NSHTTPURLResponse *response = nil;
	NSError *requestError = nil;
	NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
	if(data == nil)
		[NSException raise:@"ConnectionException" format:@"%@", [self errorStringForError:requestError]];
	if([response statusCode] != 200)
		[NSException raise:@"ConnectionException" format:@"%@", [self errorStringForResponse:response]];
	CCMServerStatusReader *reader = [[[CCMServerStatusReader alloc] initWithServerResponse:data] autorelease];
    NSError *parseError = nil;
	NSArray *infos = [reader readProjectInfos:&parseError];
    if(infos == nil)
		[NSException raise:@"ConnectionException" format:@"%@", [self errorStringForParseError:parseError]];
    return infos;
}

- (void)requestServerStatus
{
	if(urlConnection != nil)
		return;
	NSURLRequest *request = [NSURLRequest requestWithURL:serverUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
	if((urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]) == nil)
		[NSException raise:@"ConfigurationException" format:@"Cannot create connection for URL [%@]", [serverUrl absoluteString]];
	receivedData = [[NSMutableData data] retain];
}

- (void)cleanUpAfterStatusRequest
{
	[urlConnection release];
    [receivedData release];
	urlConnection = nil;
	receivedData = nil;
}

- (void)cancelStatusRequest
{
	if(urlConnection == nil)
		return;
	[urlConnection cancel];
	[self cleanUpAfterStatusRequest];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	// this could be called multiple times, due to redirects for example, so we reset data
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	CCMServerStatusReader *reader = [[[CCMServerStatusReader alloc] initWithServerResponse:receivedData] autorelease];
    [self cleanUpAfterStatusRequest];
    NSError *error = nil;
    NSArray *infos = [reader readProjectInfos:&error];
    if(infos != nil)
        [delegate connection:self didReceiveServerStatus:infos];
    else
        [delegate connection:self hadTemporaryError:[self errorStringForParseError:error]];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[self cleanUpAfterStatusRequest];
	[delegate connection:self hadTemporaryError:[self errorStringForError:error]];
}

@end


text:
# coding: utf-8
#
"""Script filling memcached with a 3D stack chunk by chunk

memcached --listen=127.0.0.1 --memory-limit=65000 --max-item-size=17m --slab-min-size=16m
"""

import json
import io
import itertools
import math

import h5py
import numpy
import bloscpack
from pymemcache.client.base import Client
import silx.io

class NumpySerde(object):
    """Numpy array serializer"""

    def serialize(key, value):
        if isinstance(value, numpy.ndarray):
            with io.BytesIO() as buffer:
                numpy.save(buffer, value)
                return buffer.getvalue(), 2
        else:
            return value, 1

    def deserialize(key, value, flags):
        if flags == 1:
            return value
        elif flags == 2:
            with io.BytesIO(value) as buffer:
                return numpy.load(buffer)
        else:
            raise RuntimeException("Unsupported serialization flags")

class NumpyBloscpackSerde(object):
    """Numpy array serializer"""

    def serialize(key, value):
        if isinstance(value, numpy.ndarray):
            with io.BytesIO() as buffer:
                numpy.save(buffer, value)
                return buffer.getvalue(), 2
        else:
            return value, 1

    def deserialize(key, value, flags):
        if flags == 1:
            return value
        elif flags == 2:
            with io.BytesIO(value) as buffer:
                return numpy.load(buffer)
        else:
            raise RuntimeException("Unsupported serialization flags")

def slice_sender(client, dset):
    """Send slice from dataset to client

    :param Client client:
    :param dset: Array-like of data
    """
    ndigits = math.floor(math.log10(len(dset))) + 1
    template = "slice%%0%dd" % ndigits
    for index, slice_ in enumerate(dset):
        key = template % index
        client.set(key, slice_)
        yield key

def _flatten_slices(slices):
    """Returns a flattened tuple of slices start and stop

    :param List[slice] slices:
    """
    result = []
    for s in slices:
        result.append(s.start)
        result.append(s.stop)
    return tuple(result)

def chunk_sender(client, dset, uid="data", chunks=None):
    """Send chunks from dataset to client

    :param Client client:
    :param dset: Array-like of data (with slicing and a shape attribute)
    :param str uid: Unique ID of the dataset
    :param Union[List[int],None] chunks:
        List of size of the chunk in each dimension.
        As many dimension as the dataset.
        If None, a single chunk is used.
    """
    template = uid + "[" + ",".join(["%d:%d"] * len(dset.shape)) + "]"

    if chunks is None:
        chunks = dset.shape

    # Write header
    client.set(
        uid,
        json.dumps(
            {
                "version": 1,
                "shape": dset.shape,
                "dtype": dset.dtype.str,
                "chunks": chunks,
            }
        ),
    )

    nchunks = numpy.ceil(numpy.array(dset.shape) / numpy.array(chunks)).astype(
        numpy.int
    )
    for index in range(numpy.prod(nchunks)):
        slices = []
        for nchunk_dim, chunk_size, dset_size in zip(
            reversed(nchunks), reversed(chunks), reversed(dset.shape)
        ):
            start = (index % nchunk_dim) * chunk_size
            stop = min(start + chunk_size, dset_size)
            slices.insert(0, slice(start, stop))
            index = index // nchunk_dim

        key = template % tuple(
            itertools.chain.from_iterable((s.start, s.stop) for s in slices)
        )
        client.set(key, dset[tuple(slices)])
        yield key

if __name__ == "__main__":
    import sys

    SERVER = "localhost", 11211

    client = Client(SERVER, serde=NumpySerde)

    url = silx.io.url.DataUrl(sys.argv[1])
    with silx.io.open(url.path()) as dset:
        # for key in slice_sender(client, dset):
        for key in chunk_sender(client, dset, chunks=[1, 512, 512]):
            print("loaded", key)


text:
import OrdersService from '../services/orders/orders';
import SettingsService from '../services/settings/settings';
import PaymentGatewaysService from '../services/settings/paymentGateways';
import PayPalCheckout from './PayPalCheckout';
import LiqPay from './LiqPay';
import StripeElements from './StripeElements';

const getOptions = orderId => {
	return Promise.all([
		OrdersService.getSingleOrder(orderId),
		SettingsService.getSettings()
	]).then(([order, settings]) => {
		if (order && order.payment_method_id) {
			return PaymentGatewaysService.getGateway(
				order.payment_method_gateway
			).then(gatewaySettings => {
				const options = {
					gateway: order.payment_method_gateway,
					gatewaySettings: gatewaySettings,
					order: order,
					amount: order.grand_total,
					currency: settings.currency_code
				};

				return options;
			});
		}
	});
};

const getPaymentFormSettings = orderId => {
	return getOptions(orderId).then(options => {
		switch (options.gateway) {
			case 'paypal-checkout':
				return PayPalCheckout.getPaymentFormSettings(options);
			case 'liqpay':
				return LiqPay.getPaymentFormSettings(options);
			case 'stripe-elements':
				return StripeElements.getPaymentFormSettings(options);
			default:
				return Promise.reject('Invalid gateway');
		}
	});
};

const paymentNotification = (req, res, gateway) => {
	return PaymentGatewaysService.getGateway(gateway).then(gatewaySettings => {
		const options = {
			gateway: gateway,
			gatewaySettings: gatewaySettings,
			req: req,
			res: res
		};

		switch (gateway) {
			case 'paypal-checkout':
				return PayPalCheckout.paymentNotification(options);
			case 'liqpay':
				return LiqPay.paymentNotification(options);
			default:
				return Promise.reject('Invalid gateway');
		}
	});
};

const processOrderPayment = async order => {
	const orderAlreadyCharged = order.paid === true;
	if (orderAlreadyCharged) {
		return true;
	}

	const gateway = order.payment_method_gateway;
	const gatewaySettings = await PaymentGatewaysService.getGateway(gateway);
	const settings = await SettingsService.getSettings();

	switch (gateway) {
		case 'stripe-elements':
			return StripeElements.processOrderPayment({
				order,
				gatewaySettings,
				settings
			});
		default:
			return Promise.reject('Invalid gateway');
	}
};

export default {
	getPaymentFormSettings: getPaymentFormSettings,
	paymentNotification: paymentNotification,
	processOrderPayment: processOrderPayment
};


text:
"""This code example updates the notes of a single proposal specified by ID.

To determine which proposals exist, run get_all_proposals.py."""

# Import appropriate modules from the client library.
from googleads import dfp

PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'

def main(client, proposal_id):
  # Initialize appropriate service.
  proposal_service = client.GetService('ProposalService', version='v201502')

  # Create statement object to select a single proposal by an ID.
  values = [{
      'key': 'proposalId',
      'value': {
          'xsi_type': 'NumberValue',
          'value': proposal_id
      }
  }]
  query = 'WHERE id = :proposalId'

  statement = dfp.FilterStatement(query, values, 1)

  # Get proposals by statement.
  response = proposal_service.getProposalsByStatement(statement.ToStatement())

  if 'results' in response:
    # Update each local proposal object by changing its notes.
    updated_proposals = []
    for proposal in response['results']:
      proposal['notes'] = 'Proposal needs further review before approval.'
      updated_proposals.append(proposal)

    # Update proposals remotely.
    proposals = proposal_service.updateProposals(updated_proposals)

    # Display results.
    if proposals:
      for proposal in proposals:
        print ('Proposal with id \'%s\', name \'%s\', and '
               'notes \'%s\' was updated.'
               % (proposal['id'], proposal['name'], proposal['notes']))
    else:
      print 'No proposals were updated.'
  else:
    print 'No proposals found to update.'

if __name__ == '__main__':
  # Initialize client object.
  dfp_client = dfp.DfpClient.LoadFromStorage()
  main(dfp_client, PROPOSAL_ID)


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

<title>org.apache.poi.hssf.record.pivottable (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

org.apache.poi.hssf.record.pivottable

Classes

DataItemRecord

ExtendedPivotTableViewFieldsRecord

PageItemRecord

StreamIDRecord

ViewDefinitionRecord

ViewFieldsRecord

ViewSourceRecord


text:
import React, { PropTypes, Component } from 'react';
import ReactDOM from 'react-dom';

import autobind from 'autobind-decorator';
import { transform } from 'babel-standalone';

// Import Style
import styles from './ComponentStyler.css';

import styled from 'styled-components';
import CodeMirror from 'react-codemirror';

import { html as htmlBeautifier } from 'js-beautify';

if (typeof navigator !== 'undefined') {
  require('codemirror/mode/jsx/jsx'); // eslint-disable-line global-require
  require('codemirror/mode/htmlmixed/htmlmixed'); // eslint-disable-line global-require
  require('codemirror/mode/css/css'); // eslint-disable-line global-require
}

import ComponentStyledTheme from '../../../../StyledThemer/components/ComponentStyledTheme/ComponentStyledTheme';
import styledThemeDecorator from '../../../../StyledThemer/decorators/styledThemeDecorator';
import libraryThemeDefault from '../libraryTheme/libraryTheme';

const additionalScope = {
  React,
  ReactDOM,
  styled,
  ComponentStyledTheme,
  styledThemeDecorator,
};

const propTypesArray = [{
  key: 'array',
  test: PropTypes.array,
  isRequired: PropTypes.array.isRequired,
}, {
  key: 'boolean',
  test: PropTypes.bool,
  isRequired: PropTypes.bool.isRequired,
}, {
  key: 'function',
  test: PropTypes.func,
  isRequired: PropTypes.func.isRequired,
}, {
  key: 'number',
  test: PropTypes.number,
  isRequired: PropTypes.number.isRequired,
}, {
  key: 'object',
  test: PropTypes.object,
  isRequired: PropTypes.array.isRequired,
}, {
  key: 'string',
  test: PropTypes.string,
  isRequired: PropTypes.string.isRequired,
}, {
  key: 'node',
  test: PropTypes.node,
  isRequired: PropTypes.node.isRequired,
}, {
  key: 'element',
  test: PropTypes.element,
  isRequired: PropTypes.element.isRequired,
}];

const getReactPropType = (propTypeFunc) => {
  let name = 'custom';
  let isRequired = false;

  propTypesArray.some((propType) => {
    if (propTypeFunc === propType.test) {
      name = propType.key;
      return true;
    }
    if (propTypeFunc === propType.isRequired) {
      name = propType.key;
      isRequired = true;
      return true;
    }
    return false;
  });
  return { name, isRequired };
};

const getReactRootHtml = (reactRoot) =>
  reactRoot &&
  reactRoot.childNodes &&
  reactRoot.childNodes.length &&
  reactRoot.childNodes[0].innerHTML ||
  '';

class ComponentStyler extends Component {
  static propTypes = {
    UIComponent: PropTypes.any.isRequired,
    componentName: PropTypes.string.isRequired,
    scope: PropTypes.object.isRequired,
  };

  constructor(...args) {
    super(...args);

    const { componentName } = this.props;

    const lineFormat = (code) => {
      const lines = code.split('\n');

      const firstLineSpace = lines
        .find((line) => /([^\s])/.test(line))
        .match(/^\s*/);

      return lines
        .map((line) => line.replace(new RegExp(`^${firstLineSpace}`), ''))
        .join('\n');
    };

    this.state = {
      generatedHtml: '',
      codeError: false,
      libraryTheme: libraryThemeDefault,
      code: lineFormat(`
        class RootComponent extends React.Component {
          render() {
            const Styled${componentName} = styledThemeDecorator(${componentName});

            return (
              <ComponentStyledTheme componentStyledThemes={libraryTheme}>


text:
package skinny.util

import java.lang.reflect.Modifier

/**
 * Java reflection API utils.
 */
object JavaReflectAPI {

  /**
   * Returns the simple name of the object's class even if invoked on the Scala REPL.
   *
   * @param obj target object
   * @return simple class name
   */
  def classSimpleName(obj: Any): String = {
    try obj.getClass.getSimpleName
    catch {
      case e: InternalError =>
        // working on the Scala REPL
        val clazz = obj.getClass
        val classOfClazz = clazz.getClass
        val getSimpleBinaryName = classOfClazz.getDeclaredMethods.find(_.getName == "getSimpleBinaryName").get
        getSimpleBinaryName.setAccessible(true)
        getSimpleBinaryName.invoke(clazz).toString
    }
  }

  /**
   * Returns all the getter names in the Scala way.
   *
   * @param obj target object
   * @return getter names
   */
  def getterNames(obj: Any): Seq[String] = {
    val privateFieldNames = obj.getClass.getDeclaredFields.toSeq
      .filter(f => Modifier.isPrivate(f.getModifiers) && !Modifier.isStatic(f.getModifiers))
      .map(f => f.getName)
    val getterNames = obj.getClass.getDeclaredMethods.toSeq
      .filter(m => Modifier.isPublic(m.getModifiers) && !Modifier.isStatic(m.getModifiers))
      .map(m => m.getName)
    getterNames.filter(getter => privateFieldNames.contains(getter))
  }

  /**
   * Invokes getter method.
   *
   * @param obj target object
   * @param name getter name
   * @return actual value
   */
  def getter(obj: Any, name: String): Any = {
    val clazz = obj.getClass
    val method = clazz.getDeclaredMethod(name)
    method.setAccessible(true)
    method.invoke(obj)
  }

}


text:
@interface MuPageViewNormal : UIScrollView <UIScrollViewDelegate,MuPageView>
- (id) initWithFrame: (CGRect)frame dialogCreator:(id<MuDialogCreator>)dia updater:(id<MuUpdater>)upd document: (MuDocRef *)aDoc page: (int)aNumber;
- (void) displayImage: (UIImage*)image;
- (void) resizeImage;
- (void) loadPage;
- (void) loadTile;
@end


text:
title: "Dark jacket looking downward"
excerpt: "PaperFaces portrait of @sbach drawn with Paper by 53 on an iPad."
image:
  feature: paperfaces-sbach-twitter-lg.jpg
  thumb: paperfaces-sbach-twitter-150.jpg
tags: [portrait, illustration, Paper by 53]
---

PaperFaces portrait of [@sbach](http://twitter.com/sbach).

{% include boilerplate/paperfaces.html %}


text:
require "tictactoe"

describe Tictactoe::SmartPlayer do
	before :each do
		@sp = Tictactoe::SmartPlayer.new("X")
	end

	it "Debe existir un metodo move" do
		@sp.respond_to?("move").should == true
	end

end


text:
#pragma once

#include "../compiler/parser.h"

class MSZipPackage;
class DotRunParser;
class MZPExtraction;
class TabMZPExtraction;

// MZPExtraction & TabMZPExtraction, for maintaing a table of
//   file extractions so far giving name in .zip and local extracted name
class MZPExtraction
{
public:
	MSTR zip_name;
	MSTR extracted_name;

	MZPExtraction(const MCHAR* zip_name, const MCHAR* extracted_name) :
		zip_name(zip_name), extracted_name(extracted_name) { }
};

class TabMZPExtraction : public Tab<MZPExtraction*>
{
public:
	~TabMZPExtraction();

	const MCHAR* find(const MCHAR* zip_name);
	void   add(const MCHAR* zip_name, const MCHAR* extracted_name);
};

// MSZipPackage: instances represent open .mzp package files
class MSZipPackage : public Value
{
public:
	enum clear_modes { CLEAR_NOW, CLEAR_ON_MAX_EXIT, CLEAR_ON_RESET, KEEP, };   // clear temp modes

	MSTR	file_name;			// zip package file name
	MSTR	package_name;		// parsed from mzp.run file...
	MSTR	description;
	int		version;
	MSTR	extract_dir;		// current extract dir
	MSTR	drop_file;			// primary drop file (if any in found)
	TabMZPExtraction extractions; // currently extracted files
	clear_modes clear_mode;
	WORD	flags;				// flag bits

	MSZipPackage(const MCHAR* file_name) : file_name(file_name), flags(0), clear_mode(CLEAR_ON_MAX_EXIT) { tag = INTERNAL_CLASS_TAG; }

	void	collect();

	// main zip package file in function
	ScripterExport static bool file_in_package(const MCHAR* file_name, MSTR* extract_dir=NULL);
	static int WINAPI output_callback(void*, MCHAR far *buf, unsigned long size);

	// package SearchFile
	ScripterExport static BOOL search_current_package(const MCHAR* file_name, MCHAR* found_path);

	// extraction
	bool	extract_to(const MCHAR* dir);
	const MCHAR*	find_extraction(const MCHAR* zip_name) { return extractions.find(zip_name); }
	void	add_extraction(const MCHAR* zip_name, const MCHAR* extracted_name);

	// directory & file manipulation
	ScripterExport static MSTR	expand_dir(const MSTR& dir);
	ScripterExport static MSTR	expand_file(const MSTR& file_name);
	MSTR	expand_dir_for_extraction(const MSTR& dir);
	MSTR	expand_file_for_extraction(const MSTR& file_name);

	// running
	void	run_all_scripts();
	bool	run_script(const MCHAR* zip_name);
};

// MZP flags
#define MZP_DONT_RUN		0x0001		// just loading, don't run any scripts
#define MZP_HAVE_DROPFILE	0x0002		// 'drop' command encountered
#define MZP_HAVE_OPEN		0x0004		// 'open' command encountered

// interpret copy() function type bits...
#define MZP_COPY		0x00
#define MZP_MOVE		0x01
#define MZP_FILES		0x00
#define MZP_TREE		0x02
#define MZP_NOREPLACE	0x04

// parser specialization to parse & run mzp.run control file
class DotRunParser : public Parser
{
	MSZipPackage* mzp;

public:

	DotRunParser (MSZipPackage* mzp) : mzp(mzp) { }

	// parse & run mzp.run file
	bool	interpret(const MCHAR* src);

	// parser production functions
	void	name();
	void	version();
	void	description();
	void	extract();
	void	run();
	void	drop();
	void	open();
	void	merge();
	void	xref();
	void	import();
	void	copy(BYTE type);
	void	clear();
	void	keep();

	// utils
	void	copy_files(const MCHAR* from, const MCHAR* to, BYTE type);
	ScripterExport static bool	create_dir(const MCHAR* dir);
};


text:
{% extends 'layout.server.view.html' %}

{% block content %}

{% endblock %}


text:
package com.yz.model;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Judge entity.研判信息,部门查证,上报情况
 *
 * @author lq
 */
@Entity
@Table(name = "judge", schema = "dbo", catalog = "dchc")
public class Judge implements java.io.Serializable {

	// Fields

	private Integer id;
	private Clue clue;//所属刑侦线索
	private Injurycase injurycase;//所属重伤案件
	private Person person;//所属人员

	private String reportUnit;//报送部门(多个以,隔开)

	private String reportTime;//上报时间

	private String transactor;//上报人(承办人)

	private String deadline;//开始时间

	private String telphone;//联系方式

	private String judgeRequirement;//研判要求

	private Integer indexNumber;//序号(表示研判顺序)

	private String criminalJudge;//刑技研判

	private String networkJudge;//网技研判

	private String intelligenceJudge;//情报研判

	private String imageJudge;//图帧研判

	private Integer jtype;//1:研判信息  2:部门查证 3:上报情况

	private Integer isNew;

	private String scanImage;//立案决定书扫描件

	private List<Media> medias = new ArrayList<Media>();// 文件

	// Constructors

	/** default constructor */
	public Judge() {
	}

	/** full constructor */
	public Judge(Clue clue, Injurycase injurycase, Person person,
			String reportUnit, String reportTime, String transactor,String deadline,
			String telphone, String judgeRequirement, Integer indexNumber,Integer isNew,
			String criminalJudge, String networkJudge,
			String intelligenceJudge, String imageJudge, Integer jtype, String scanImage,List<Media> medias) {
		this.clue = clue;
		this.injurycase = injurycase;
		this.person = person;
		this.reportUnit = reportUnit;
		this.reportTime = reportTime;
		this.transactor = transactor;
		this.deadline = deadline;
		this.telphone = telphone;
		this.judgeRequirement = judgeRequirement;
		this.indexNumber = indexNumber;
		this.criminalJudge = criminalJudge;
		this.networkJudge = networkJudge;
		this.intelligenceJudge = intelligenceJudge;
		this.imageJudge = imageJudge;
		this.jtype = jtype;
		this.isNew = isNew;
		this.scanImage = scanImage;
		this.medias = medias;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "clid")
	public Clue getClue() {
		return this.clue;
	}

	@Column(name = "criminalJudge")
	public String getCriminalJudge() {
		return this.criminalJudge;
	}

	// Property accessors
	@Id
	@GeneratedValue
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}

	@Column(name = "imageJudge")
	public String getImageJudge() {
		return this.imageJudge;
	}

	@Column(name = "indexNumber")
	public Integer getIndexNumber() {
		return this.indexNumber;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "inid")
	public Injurycase getInjurycase() {
		return this.injurycase;
	}

	@Column(name = "intelligenceJudge")
	public String getIntelligenceJudge() {
		return this.intelligenceJudge;
	}

	@Column(name = "judgeRequirement")
	public String getJudgeRequirement() {
		return this.judgeRequirement;
	}

	@Column(name = "networkJudge")
	public String getNetworkJudge() {
		return this.networkJudge;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "perid")
	public Person getPerson() {
		return this.person;
	}

	@Column(name = "reportTime")
	public String getReportTime() {
		return this.reportTime;
	}

	@Column(name = "reportUnit")
	public String getReportUnit() {
		return this.reportUnit;
	}

	@Column(name = "telphone")
	public String getTelphone() {
		return this.telphone;
	}

	@Column(name = "transactor")
	public String getTransactor() {
		return this.transactor;
	}

	@Column(name = "jtype")
	public Integer getJtype() {
		return this.jtype;
	}

	@Column(name = "deadline")
	public String getDeadline() {
		return deadline;
	}

	@Column(name = "isNew")
	public Integer getIsNew() {
		return isNew;
	}

	@Column(name = "scanImage")
	public String getScanImage() {
		return scanImage;
	}

	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "judge")
	public List<Media> getMedias() {
		return medias;
	}

	public void setMedias(List<Media> medias) {
		this.medias = medias;
	}

	public void setScanImage(String scanImage) {
		this.scanImage = scanImage;
	}

	public void setIsNew(Integer isNew) {
		this.isNew = isNew;
	}

	public void setDeadline(String deadline) {
		this.deadline = deadline;
	}

	public void setClue(Clue clue) {
		this.clue = clue;
	}

	public void setCriminalJudge(String criminalJudge) {
		this.criminalJudge = criminalJudge;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void setImageJudge(String imageJudge) {
		this.imageJudge = imageJudge;
	}

	public void setIndexNumber(Integer indexNumber) {
		this.indexNumber = indexNumber;
	}

	public void setInjurycase(Injurycase injurycase) {
		this.injurycase = injurycase;
	}

	public void setIntelligenceJudge(String intelligenceJudge) {
		this.intelligenceJudge = intelligenceJudge;
	}

	public void setJudgeRequirement(String judgeRequirement) {
		this.judgeRequirement = judgeRequirement;
	}

	public void setNetworkJudge(String networkJudge) {
		this.networkJudge = networkJudge;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public void setReportTime(String reportTime) {
		this.reportTime = reportTime;
	}

	public void setReportUnit(String reportUnit) {
		this.reportUnit = reportUnit;
	}

	public void setTelphone(String telphone) {
		this.telphone = telphone;
	}

	public void setTransactor(String transactor) {
		this.transactor = transactor;
	}

	public void setJtype(Integer jtype) {
		this.jtype = jtype;
	}

}


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

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
	default-init-method="afterPropertiesSet"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
						http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
						http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
						http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

	<context:property-placeholder location="file:///${liferay.home}/portal-ext.properties,file:///${sli.conf}" ignore-resource-not-found="true" />

	<bean id="restClient" class="org.slc.sli.client.RESTClient" >
	    <property name="securityUrl" value="${security.server.url}" />
	</bean>
	<bean id="checklistHelper" class="org.slc.sli.util.CheckListHelper" >
	    <property name="restClient" ref="restClient" />
	</bean>
	<bean id="homePage" class="org.slc.sli.web.controller.HomePageController" >
	    <property name="restClient" ref="restClient" />
	</bean>
</beans>


text:
<?php
namespace Gwa\Wordpress\Template\Zero\Controller;

use Gwa\Wordpress\Template\Zero\Library\AbstractController;

/**
 * Image.
 *
 * @author  GWA
 *
 */
final class Image extends AbstractController
{
    /**
     * {@inheritdoc}
     */
    public function getContext()
    {
        return ['posts' => $this->getPosts()];
    }

    /**
     * {@inheritdoc}
     */
    public function getTemplates()
    {
        return ['image.twig'];
    }
}


text:
title: "`let` ile matematik işlemleri"
date: May 22, 2016 13:34
tags: bash
external_url: http://bash.gelistiriciyiz.biz/2016/05/22/let-ile-matematik-islemleri/
author:
  name: Uğur "vigo" Özyılmazel
  email: ugurozyilmazel@gmail.com
  link: http://ugur.ozyilmazel.com
  bio: Sysop ^ C64 / Amiga Coder | Founder < Scener >
---


text:
namespace blink {
class WebLocalFrame;
}  // namespace blink

namespace test_runner {

TEST_RUNNER_EXPORT std::string DumpLayout(blink::WebLocalFrame* frame,
                                          const LayoutDumpFlags& flags);

}  // namespace test_runner

#endif  // COMPONENTS_TEST_RUNNER_LAYOUT_DUMP_H_


text:
require 'spec_helper'

module Challah
  # TODO make these specs not look like unit tests
  describe Encrypter do

    let(:instance) { Encrypter.new }

    describe ".encrypt" do
      it "encrypts a string" do
        expect(Encrypter.encrypt("testing 123")).to_not be_nil
      end

      it "uses bcrypt to encrypt a string" do
        expect(BCrypt::Password).to receive(:create).with('testing 123', :cost => 10).once
        Encrypter.encrypt("testing 123")
      end
    end

    describe ".compare" do
      it "should compare two encrypted strings quickly" do
        pass = Encrypter.encrypt("test A")

        assert_equal true, Encrypter.compare(pass, "test A")
        assert_equal false, Encrypter.compare("test A", "test A")
      end
    end

    describe ".hash" do
      it "hashes strings" do
        expect(Digest::SHA512).to receive(:hexdigest).exactly(10).times
        Encrypter.hash('hash me')
      end
    end

    describe "#compare" do
      it "should compare a string" do
        pass = instance.encrypt("test A")

        assert_equal true, instance.compare(pass, "test A")
        assert_equal false, instance.compare("test A", "test A")
      end
    end

    describe "#encrypt" do
      it "encrypts a string" do
        pass = instance.encrypt('testing 123')
        expect(pass).to_not be_nil
      end

      it "encrypts a string at a provided cost" do
        instance.cost = 5
        pass = instance.encrypt('testing 456')
        bpass = BCrypt::Password.new(pass)
        expect(bpass.cost).to eq(5)
      end
    end

    describe "#hash" do
      it "hashes some strings a given number of times" do
        expect(Digest::SHA512).to receive(:hexdigest).exactly(10).times
        instance.hash('hash me')
      end
    end

    describe "#md5" do
      it "md5 hashes a batch of strings" do
        expected = Digest::MD5.hexdigest("str1|str2|str3")
        expect(instance.md5('str1', 'str2', 'str3')).to eq(expected)
      end

      it "md5 hashes a batch of strings with a different join" do
        instance.joiner = ' - '
        expected = Digest::MD5.hexdigest("str1 - str2 - str3")
        expect(instance.md5('str1', 'str2', 'str3')).to eq(expected)
      end
    end

  end
end


text:
from mock import patch, Mock

from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.test import TestCase, RequestFactory

from rottweiler import registry
from rottweiler.views import ShowAllRules, ListUrls, ShowPermission
from .stubs import ModelStub

def first_permission(self, user):
    return user.is_superuser or user.is_staff

def second_permission(self, user):
    return user.is_active

class TestShowPermissionView(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.request = self.factory.get("list-urls/project/barkbark/")

    @patch('rottweiler.views.get_user_model')
    @patch('rottweiler.views.Group')
    def test_show_permission(self, group_filter, user_filter):
        url = reverse('rottweiler:all_rules')
        self.request.user = User(is_superuser=True)
        view = ShowPermission.as_view()

        response = view(self.request, codename='change_user', app_label='project')

        self.assertEqual(response.context_data['users'], user_filter().objects.filter().distinct())
        self.assertEqual(response.context_data['user_groups'], group_filter.objects.filter().distinct())
        self.assertEqual(response.context_data['roles'], ['    return True\n', '    return True\n'])

        self.assertEqual(200, response.status_code)

class TestShowAllUrlsView(TestCase):
    def setUp(self):
        self.request = RequestFactory()
        self.request.method = 'GET'

    @patch('rottweiler.view_helpers.Permission.objects.get')
    def test_list_all_urls(self, permission_get):
        permission_get.return_value = Mock(
            codename="lala.lalala",
            content_type=Mock(app_label="lala")
        )
        self.request.user = User(is_superuser=True)
        view = ListUrls.as_view()

        response = view(self.request)

        self.assertEqual(response.context_data['object'],
            [{'module': 'project.views',
              'name': 'RottyView',
              'permission_applabel': 'lala',
              'permission_codename': 'lala.lalala',
              'url': '/rottywookieman/'}])
        self.assertEqual(200, response.status_code)

class TestShowAllRulesView(TestCase):
    def setUp(self):
        self.request = RequestFactory()
        self.request.method = 'GET'

    def test_access_denied_if_user_is_not_superuser(self):
        self.request.user = User(is_superuser=False)
        view = ShowAllRules.as_view()
        with self.assertRaises(PermissionDenied):
            view(self.request)

    def test_returns_200_if_user_is_superuser(self):
        self.request.user = User(is_superuser=True)
        view = ShowAllRules.as_view()
        response = view(self.request)
        self.assertEqual(200, response.status_code)

    def test_assigns_list_of_all_rules_to_object(self):
        registry.register('first_permission', first_permission, ModelStub)
        registry.register('second_permission', second_permission, ModelStub)
        self.request.user = User(is_superuser=True)
        view = ShowAllRules.as_view()
        response = view(self.request)
        model_stub_rule = None
        for rule in response.context_data['object']:
            if rule['model_name'] == 'ModelStub':
                model_stub_rule = rule
                break
        self.assertTrue(model_stub_rule)
        self.assertTrue({'name': 'first_permission',
                         'definition': '    return user.is_superuser or user.is_staff\n'} in
                        model_stub_rule['permissions'])
        self.assertTrue({'name': 'second_permission',
                         'definition': '    return user.is_active\n'} in
                        model_stub_rule['permissions'])


text:
package mcjty.rftools.blocks.storage.sorters;

import mcjty.rftools.blocks.dimlets.DimletSetup;
import mcjty.rftools.items.dimlets.DimletEntry;
import mcjty.rftools.items.dimlets.DimletKey;
import mcjty.rftools.items.dimlets.KnownDimletConfiguration;
import net.minecraft.item.ItemStack;
import org.apache.commons.lang3.tuple.Pair;

import java.util.Comparator;

public class DimletRarityItemSorter implements ItemSorter {
    @Override
    public String getName() {
        return "rarity";
    }

    @Override
    public String getTooltip() {
        return "Sort on dimlet rarity";
    }

    @Override
    public int getU() {
        return 15*16;
    }

    @Override
    public int getV() {
        return 16;
    }

    @Override
    public Comparator<Pair<ItemStack, Integer>> getComparator() {
        return new Comparator<Pair<ItemStack, Integer>>() {
            @Override
            public int compare(Pair<ItemStack, Integer> o1, Pair<ItemStack, Integer> o2) {
                int rarity1 = getRarity(o1);
                int rarity2 = getRarity(o2);

                if (rarity1 == rarity2) {
                    return DimletTypeItemSorter.compareTypes(o1, o2);
                }

                return new Integer(rarity1).compareTo(rarity2);
            }
        };
    }

    private int getRarity(Pair<ItemStack, Integer> object) {
        int rarity = -1;
        if (object.getKey().getItem() == DimletSetup.knownDimlet) {
            DimletKey key = KnownDimletConfiguration.getDimletKey(object.getKey(), null);
            DimletEntry entry = KnownDimletConfiguration.getEntry(key);
            if (entry != null) {
                rarity = entry.getRarity();
            }
        }
        return rarity;
    }

    @Override
    public boolean isSameGroup(Pair<ItemStack, Integer> o1, Pair<ItemStack, Integer> o2) {
        int rarity1 = getRarity(o1);
        int rarity2 = getRarity(o2);
        return rarity1 == rarity2;
    }

    @Override
    public String getGroupName(Pair<ItemStack, Integer> object) {
        int rarity = getRarity(object);
        return "Rarity " + (rarity == -1 ? "unknown" : rarity);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Res. 98(8): 865 (1994)

#### Original name
Dactylella inquisitor Jarow.

### Remarks
null


text:
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;

namespace FluffyDuffyMunchkinCats.Migrations
{
    public partial class CatsTable : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Cats",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Age = table.Column<int>(nullable: false),
                    Breed = table.Column<string>(maxLength: 50, nullable: false),
                    ImageUrl = table.Column<string>(maxLength: 2000, nullable: false),
                    Name = table.Column<string>(maxLength: 50, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Cats", x => x.Id);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Cats");
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Sphaeria ventosaria Linds., 1864

### Remarks
null


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Convay: Dokumentacja klasy Convay.Core.GridChangedEventArgs</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Convay

Metody publiczne |
Właściwości |
Lista wszystkich składowych

Dokumentacja klasy Convay.Core.GridChangedEventArgs

Diagram dziedziczenia dla Convay.Core.GridChangedEventArgs

<map name="_convay_8_core_8_grid_changed_event_args_inherit__map" id="_convay_8_core_8_grid_changed_event_args_inherit__map">
</map>
[legenda]

Diagram współpracy dla Convay.Core.GridChangedEventArgs:

<map name="_convay_8_core_8_grid_changed_event_args_coll__map" id="_convay_8_core_8_grid_changed_event_args_coll__map">
</map>
[legenda]

Metody publiczne

 	GridChangedEventArgs (IGrid grid, IRules rules)

Właściwości

IGrid 	Grid [get]

IRules 	Rules [get, set]

Opis szczegółowy

Definicja w linii 6 pliku StepTakenEventArgs.cs.

Dokumentacja konstruktora i destruktora

§ GridChangedEventArgs()

          Convay.Core.GridChangedEventArgs.GridChangedEventArgs
          (
          IGrid
          grid,

          IRules
          rules

          )

Definicja w linii 8 pliku StepTakenEventArgs.cs.

Dokumentacja właściwości

§ Grid

          IGrid Convay.Core.GridChangedEventArgs.Grid

get

Definicja w linii 14 pliku StepTakenEventArgs.cs.

§ Rules

          IRules Convay.Core.GridChangedEventArgs.Rules

getset

Definicja w linii 16 pliku StepTakenEventArgs.cs.

Dokumentacja dla tej klasy została wygenerowana z pliku:

Convay/EventArgs/StepTakenEventArgs.cs

Convay

Core

GridChangedEventArgs

Wygenerowano przez

     1.8.12


text:
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP #-}
module Codec.Picture.Jpg.Progressive
    ( JpgUnpackerParameter( .. )
    , progressiveUnpack
    ) where

#if !MIN_VERSION_base(4,8,0)
import Control.Applicative( pure, (<$>) )
#endif

import Control.Monad( when, unless, forM_ )
import Control.Monad.ST( ST )
import Control.Monad.Trans( lift )
import Data.Bits( (.&.), (.|.), unsafeShiftL )
import Data.Int( Int16, Int32 )
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.Vector as V
import qualified Data.Vector.Storable as VS
import Data.Vector( (!) )
import qualified Data.Vector.Mutable as M
import qualified Data.Vector.Storable.Mutable as MS

import Codec.Picture.Types
import Codec.Picture.BitWriter
import Codec.Picture.Jpg.Common
import Codec.Picture.Jpg.Types
import Codec.Picture.Jpg.DefaultTable

createMcuLineIndices :: JpgComponent -> Int -> Int -> V.Vector (VS.Vector Int)
createMcuLineIndices param imgWidth mcuWidth =
 V.fromList $ VS.fromList <$> [indexSolo, indexMulti]
  where compW = fromIntegral $ horizontalSamplingFactor param
        compH = fromIntegral $ verticalSamplingFactor param
        imageBlockSize = (imgWidth + 7) `div` 8

        indexSolo =
            [y * mcuWidth * compW + x
                | y <- [0 .. compH - 1], x <- [0 .. imageBlockSize - 1]]

        indexMulti =
            [(mcu + y * mcuWidth) * compW + x
                | mcu <- [0 .. mcuWidth - 1]
                , y <- [0 .. compH - 1]
                , x <- [0 .. compW - 1] ]

decodeFirstDC :: JpgUnpackerParameter
              -> MS.STVector s Int16
              -> MutableMacroBlock s Int16
              -> Int32
              -> BoolReader s Int32
decodeFirstDC params dcCoeffs block eobrun = unpack >> pure eobrun
  where unpack = do
          (dcDeltaCoefficient) <- dcCoefficientDecode $ dcHuffmanTree params
          previousDc <- lift $ dcCoeffs `MS.unsafeRead` componentIndex params
          let neoDcCoefficient = previousDc + dcDeltaCoefficient
              approxLow = fst $ successiveApprox params
              scaledDc = neoDcCoefficient `unsafeShiftL` approxLow
          lift $ (block `MS.unsafeWrite` 0) scaledDc
          lift $ (dcCoeffs `MS.unsafeWrite` componentIndex params) neoDcCoefficient

decodeRefineDc :: JpgUnpackerParameter
               -> a
               -> MutableMacroBlock s Int16
               -> Int32
               -> BoolReader s Int32
decodeRefineDc params _ block eobrun = unpack >> pure eobrun
  where approxLow = fst $ successiveApprox params
        plusOne = 1 `unsafeShiftL` approxLow
        unpack = do
            bit <- getNextBitJpg
            when bit . lift $ do
                v <- block `MS.unsafeRead` 0
                (block `MS.unsafeWrite` 0) $ v .|. plusOne

decodeFirstAc :: JpgUnpackerParameter
              -> a
              -> MutableMacroBlock s Int16
              -> Int32
              -> BoolReader s Int32
decodeFirstAc _params _ _block eobrun | eobrun > 0 = pure $ eobrun - 1
decodeFirstAc params _ block _ = unpack startIndex
  where (startIndex, maxIndex) = coefficientRange params
        (low, _) = successiveApprox params
        unpack n | n > maxIndex = pure 0
        unpack n = do
            rrrrssss <- decodeRrrrSsss $ acHuffmanTree params
            case rrrrssss of
                (0xF, 0) -> unpack $ n + 16
                (  0, 0) -> return 0
                (  r, 0) -> eobrun <$> unpackInt r
                    where eobrun lowBits = (1 `unsafeShiftL` r) - 1 + lowBits
                (  r, s) -> do
                    let n' = n + r
                    val <- (`unsafeShiftL` low) <$> decodeInt s
                    lift . (block `MS.unsafeWrite` n') $ fromIntegral val
                    unpack $ n' + 1

decodeRefineAc :: forall a s. JpgUnpackerParameter
               -> a
               -> MutableMacroBlock s Int16
               -> Int32
               -> BoolReader s Int32
decodeRefineAc params _ block eobrun
        | eobrun == 0 = unpack startIndex
        | otherwise   = performEobRun startIndex >> return (eobrun - 1)
  where (startIndex, maxIndex) = coefficientRange params
        (low, _) = successiveApprox params
        plusOne = 1 `unsafeShiftL` low
        minusOne = (-1) `unsafeShiftL` low

        getBitVal = do
            v <- getNextBitJpg
            pure $ if v then plusOne else minusOne

        performEobRun idx | idx > maxIndex = pure ()
        performEobRun idx = do
          coeff <- lift $ block `MS.unsafeRead` idx
          if coeff /= 0 then do
            bit <- getNextBitJpg
            case (bit, (coeff .&. plusOne) == 0) of
               (False, _)    -> performEobRun $ idx + 1
               (True, False) -> performEobRun $ idx + 1
               (True, True) -> do
                   let newVal | coeff >= 0 = coeff + plusOne
                              | otherwise = coeff + minusOne
                   lift $ (block `MS.unsafeWrite` idx) newVal
                   performEobRun $ idx + 1
          else
            performEobRun $ idx + 1

        unpack idx | idx > maxIndex = pure 0
        unpack idx = do
            rrrrssss <- decodeRrrrSsss $ acHuffmanTree params
            case rrrrssss of
              (0xF, 0) -> do
                idx' <- updateCoeffs 0xF idx
                unpack $ idx' + 1

              (  r, 0) -> do
                  lowBits <- unpackInt r
                  let newEobRun = (1 `unsafeShiftL` r) + lowBits - 1
                  performEobRun idx
                  pure newEobRun

              (  r, _) -> do
                  val <- getBitVal
                  idx' <- updateCoeffs (fromIntegral r) idx
                  when (idx' <= maxIndex) $
                       lift $ (block `MS.unsafeWrite` idx') val
                  unpack $ idx' + 1

        updateCoeffs :: Int -> Int -> BoolReader s Int
        updateCoeffs r idx
            | r   < 0        = pure $ idx - 1
            | idx > maxIndex = pure idx
        updateCoeffs r idx = do
          coeff <- lift $ block `MS.unsafeRead` idx
          if coeff /= 0 then do
            bit <- getNextBitJpg
            when (bit && coeff .&. plusOne == 0) $ do
              let writeCoeff | coeff >= 0 = coeff + plusOne
                             | otherwise = coeff + minusOne
              lift $ (block `MS.unsafeWrite` idx) writeCoeff
            updateCoeffs r $ idx + 1
          else
            updateCoeffs (r - 1) $ idx + 1

type Unpacker s =
    JpgUnpackerParameter -> MS.STVector s Int16 -> MutableMacroBlock s Int16 -> Int32
        -> BoolReader s Int32

prepareUnpacker :: [([(JpgUnpackerParameter, a)], L.ByteString)]
                -> ST s ( V.Vector (V.Vector (JpgUnpackerParameter, Unpacker s))
                        , M.STVector s BoolState)
prepareUnpacker lst = do
    let boolStates = V.fromList $ map snd infos
    vec <- V.unsafeThaw boolStates
    return (V.fromList $ map fst infos, vec)
  where infos = map prepare lst
        prepare ([], _) = error "progressiveUnpack, no component"
        prepare (whole@((param, _) : _) , byteString) =
         (V.fromList $ map (\(p,_) -> (p, unpacker)) whole, boolReader)
           where unpacker = selection (successiveApprox param) (coefficientRange param)
                 boolReader = initBoolStateJpg . B.concat $ L.toChunks byteString

                 selection (_, 0) (0, _) = decodeFirstDC
                 selection (_, 0) _      = decodeFirstAc
                 selection _      (0, _) = decodeRefineDc
                 selection _      _      = decodeRefineAc

data ComponentData s = ComponentData
    { componentIndices    :: V.Vector (VS.Vector Int)
    , componentBlocks     :: V.Vector (MutableMacroBlock s Int16)
    , componentId         :: !Int
    , componentBlockCount :: !Int
    }

-- | Iteration from to n in monadic context, without data
-- keeping.
lineMap :: (Monad m) => Int -> (Int -> m ()) -> m ()
{-# INLINE lineMap #-}
lineMap count f = go 0
  where go n | n >= count = return ()
        go n = f n >> go (n + 1)

progressiveUnpack :: (Int, Int)
                  -> JpgFrameHeader
                  -> V.Vector (MacroBlock Int16)
                  -> [([(JpgUnpackerParameter, a)], L.ByteString)]
                  -> ST s (MutableImage s PixelYCbCr8)
progressiveUnpack (maxiW, maxiH) frame quants lst = do
    (unpackers, readers) <- prepareUnpacker lst
    allBlocks <- mapM allocateWorkingBlocks . zip [0..] $ jpgComponents frame
                    :: ST s [ComponentData s]
    let scanCount = length lst
        restartIntervalValue = case lst of
                ((p,_):_,_): _ -> restartInterval p
                _ -> -1
    dcCoeffs <- MS.replicate imgComponentCount 0
    eobRuns <- MS.replicate (length lst) 0
    workBlock <- createEmptyMutableMacroBlock
    writeIndices <- MS.replicate imgComponentCount (0 :: Int)
    restartIntervals <- MS.replicate scanCount restartIntervalValue
    let elementCount = imgWidth * imgHeight * fromIntegral imgComponentCount
    img <- MutableImage imgWidth imgHeight <$> MS.replicate elementCount 128

    let processRestartInterval =
          forM_ [0 .. scanCount - 1] $ \ix -> do
            v <- restartIntervals `MS.read` ix
            if v == 0 then do
              -- reset DC prediction
              when (ix == 0) (MS.set dcCoeffs 0)
              reader <- readers `M.read` ix
              (_, updated) <- runBoolReaderWith reader $
                  byteAlignJpg >> decodeRestartInterval
              (readers `M.write` ix) updated
              (eobRuns `MS.unsafeWrite` ix) 0
              (restartIntervals `MS.unsafeWrite` ix) $ restartIntervalValue - 1
            else
              (restartIntervals `MS.unsafeWrite` ix) $ v - 1

    lineMap imageMcuHeight $ \mmY -> do
      -- Reset all blocks to 0
      forM_ allBlocks $ V.mapM_ (`MS.set` 0) .  componentBlocks
      MS.set writeIndices 0

      lineMap imageMcuWidth $ \_mmx -> do
        processRestartInterval
        V.forM_ unpackers $ V.mapM_ $ \(unpackParam, unpacker) -> do
            boolState <- readers `M.read` readerIndex unpackParam
            eobrun <- eobRuns `MS.read` readerIndex unpackParam
            let componentNumber = componentIndex unpackParam
            writeIndex <- writeIndices `MS.read` componentNumber
            let componentData = allBlocks !! componentNumber
                indexVector =
                    componentIndices componentData ! indiceVector unpackParam
                maxIndexLength = VS.length indexVector
            unless (writeIndex + blockIndex unpackParam >= maxIndexLength) $ do
               let realIndex = indexVector VS.! (writeIndex + blockIndex unpackParam)
                   writeBlock = componentBlocks componentData ! realIndex
               (eobrun', state) <-
                   runBoolReaderWith boolState $
                       unpacker unpackParam dcCoeffs writeBlock eobrun

               (readers `M.write` readerIndex unpackParam) state
               (eobRuns `MS.write` readerIndex unpackParam) eobrun'

        -- Update the write indices
        forM_ allBlocks $ \comp -> do
          writeIndex <- writeIndices `MS.read` componentId comp
          let newIndex = writeIndex + componentBlockCount comp
          (writeIndices `MS.write` componentId comp) newIndex

      forM_ allBlocks $ \compData -> do
        let compBlocks = componentBlocks compData
            cId = componentId compData
            comp = jpgComponents frame !! cId
            quantId =
                fromIntegral $ quantizationTableDest comp
            table = quants ! min 3 quantId
            compW = fromIntegral $ horizontalSamplingFactor comp
            compH = fromIntegral $ verticalSamplingFactor comp
            cw8 = maxiW - fromIntegral (horizontalSamplingFactor comp) + 1
            ch8 = maxiH - fromIntegral (verticalSamplingFactor comp) + 1

        rasterMap (imageMcuWidth * compW) compH $ \rx y -> do
            let ry = mmY * maxiH + y
                block = compBlocks ! (y * imageMcuWidth * compW + rx)
            transformed <- decodeMacroBlock table workBlock block
            unpackMacroBlock imgComponentCount
                    cw8 ch8 cId (rx * cw8) ry
                    img transformed

    return img

  where imgComponentCount = length $ jpgComponents frame

        imgWidth = fromIntegral $ jpgWidth frame
        imgHeight = fromIntegral $ jpgHeight frame

        imageBlockWidth = (imgWidth + 7) `div` 8
        imageBlockHeight = (imgHeight + 7) `div` 8

        imageMcuWidth = (imageBlockWidth + (maxiW - 1)) `div` maxiW
        imageMcuHeight = (imageBlockHeight + (maxiH - 1)) `div` maxiH

        allocateWorkingBlocks (ix, comp) = do
            let blockCount = hSample * vSample * imageMcuWidth
            blocks <- V.replicateM blockCount createEmptyMutableMacroBlock
            return ComponentData
                { componentBlocks = blocks
                , componentIndices = createMcuLineIndices comp imgWidth imageMcuWidth
                , componentBlockCount = hSample * vSample
                , componentId = ix
                }
            where hSample = fromIntegral $ horizontalSamplingFactor comp
                  vSample = fromIntegral $ verticalSamplingFactor comp


text:
#ifndef __SymbianEGLSupport_H__
#define __SymbianEGLSupport_H__

#include "OgreEGLSupport.h"

namespace Ogre {
    class _OgrePrivate SymbianEGLSupport : public EGLSupport
    {
		protected:
			virtual EGLWindow* createEGLWindow( EGLSupport * support);
        public:
            SymbianEGLSupport();
            virtual ~SymbianEGLSupport();

			virtual GLESPBuffer* createPBuffer(PixelComponentType format,
				size_t width, size_t height);
			virtual void switchMode(uint& width, uint& height, short& frequency);

			virtual RenderWindow* newWindow(const String &name,
				unsigned int width, unsigned int height,
				bool fullScreen,
				const NameValuePairList *miscParams = 0);

	};
}

#endif


text:
<?php

namespace LearnCleanCode\CaseStudies\Bowling;

/**
 * Class FrameIterator
 * @package LearnCleanCode\CaseStudies\Bowling
 */
class FrameIterator implements \Iterator
{
    /**
     * @var int
     */
    private $position = 0;

    /**
     * @var FrameCollection
     */
    private $frameCollection;

    /**
     * @param FrameCollection $frameCollection
     */
    public function __construct(FrameCollection $frameCollection)
    {
        $this->frameCollection = $frameCollection;
    }

    /**
     * @return Frame
     */
    public function current(): Frame
    {
        return $this->frameCollection->getFrame($this->position);
    }

    /**
     * Move forward to next element
     */
    public function next()
    {
        $this->position++;
    }

    /**
     * @return int
     */
    public function key()
    {
        return $this->position;
    }

    /**
     * @return bool
     */
    public function valid()
    {
        return !($this->current() instanceof NullFrame);
    }

    /**
     * Rewind the Iterator to the first element
     */
    public function rewind()
    {
        $this->position = 0;
    }
}


text:
FROM mediachain/concat-dependencies

# Clone concat repo
RUN mkdir -p /go/src/github.com/mediachain
RUN rm -rf /go/src/github.com/mediachain/concat
ARG concat_ref=master
RUN echo "checking out concat at ${concat_ref}" && git clone https://github.com/mediachain/concat /go/src/github.com/mediachain/concat
WORKDIR /go/src/github.com/mediachain/concat
RUN git checkout ${concat_ref}

# Build the project
RUN /go/src/github.com/mediachain/concat/install.sh

# Copy the test identities to /integration-test/mcnode and /integration-test/mcdir
VOLUME /integration-test
COPY ./test-identities/mcnode /integration-test/mcnode
COPY ./test-identities/mcdir /integration-test/mcdir

# expose ports
EXPOSE 9000 9001 9002


text:
module.exports = (req, res, next) => {
  const body = req.body
  const match = [
    '_tournament',
    '_registration',
    'name'
  ]

  return global.models.create(
    global.db.registrations.RegistrationInstitutions,
    body,
    match,
    res
  )
}


text:
from operator import attrgetter

from django.test import TestCase

from models import Post, Question, Answer

class OrderWithRespectToTests(TestCase):
    def test_basic(self):
        q1 = Question.objects.create(text="Which Beatle starts with the letter 'R'?")
        q2 = Question.objects.create(text="What is your name?")

        Answer.objects.create(text="John", question=q1)
        Answer.objects.create(text="Jonno", question=q2)
        Answer.objects.create(text="Paul", question=q1)
        Answer.objects.create(text="Paulo", question=q2)
        Answer.objects.create(text="George", question=q1)
        Answer.objects.create(text="Ringo", question=q1)

        # The answers will always be ordered in the order they were inserted.
        self.assertQuerysetEqual(
            q1.answer_set.all(), [
                "John", "Paul", "George", "Ringo",
            ],
            attrgetter("text"),
        )

        # We can retrieve the answers related to a particular object, in the
        # order they were created, once we have a particular object.
        a1 = Answer.objects.filter(question=q1)[0]
        self.assertEqual(a1.text, "John")
        a2 = a1.get_next_in_order()
        self.assertEqual(a2.text, "Paul")
        a4 = list(Answer.objects.filter(question=q1))[-1]
        self.assertEqual(a4.text, "Ringo")
        self.assertEqual(a4.get_previous_in_order().text, "George")

        # Determining (and setting) the ordering for a particular item is also
        # possible.
        id_list = [o.pk for o in q1.answer_set.all()]
        self.assertEqual(a2.question.get_answer_order(), id_list)

        a5 = Answer.objects.create(text="Number five", question=q1)

        # It doesn't matter which answer we use to check the order, it will
        # always be the same.
        self.assertEqual(
            a2.question.get_answer_order(), a5.question.get_answer_order()
        )

        # The ordering can be altered:
        id_list = [o.pk for o in q1.answer_set.all()]
        x = id_list.pop()
        id_list.insert(-1, x)
        self.assertNotEqual(a5.question.get_answer_order(), id_list)
        a5.question.set_answer_order(id_list)
        self.assertQuerysetEqual(
            q1.answer_set.all(), [
                "John", "Paul", "George", "Number five", "Ringo"
            ],
            attrgetter("text")
        )

    def test_recursive_ordering(self):
        p1 = Post.objects.create(title='1')
        p2 = Post.objects.create(title='2')
        p1_1 = Post.objects.create(title="1.1", parent=p1)
        p1_2 = Post.objects.create(title="1.2", parent=p1)
        p2_1 = Post.objects.create(title="2.1", parent=p2)
        p1_3 = Post.objects.create(title="1.3", parent=p1)
        self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])