text:
require 'spec_helper'
require 'apollo_fresh/model'

describe ApolloFresh::Model do

  subject do
    klass = Class.new(ApolloFresh::Model)
    klass.send(:store_in, '_testing_apollo_fresh_model')
    klass
  end

  let!(:test_api) do
    Class.new(ApolloFresh::Api)
  end

  let!(:parent) do
    ApolloFresh::Model
  end

  let(:all_invoices) do
    fresh_sample(:invoices, 40, 40, 1, 1..40)['invoice'].index_by {|obj| obj['invoice_id']}
  end

  before(:each) do
    subject.resource = 'invoice'
  end

  it "Should automatically add model to auto update" do
    ApolloFresh::Update.auto_update?(subject).should === true
  end

  it "Should include Mongoid::Document" do
    subject.included_modules.should include(Mongoid::Document)
  end

  before(:each) do
    subject.model = ApolloFresh::Api
  end

  describe "#self.population_formatters" do
    context "When formatters are present on both child and parent" do

      let!(:child_formatter) do
        flexmock('child-formatter', {
          :format! => '',
          :instance_methods => ['format!']
        })
      end

      let!(:parent_formatter) do
        flexmock('parent-formatter', {
          :format! => '',
          :instance_methods => ['format!']
        })
      end

      after do
        parent.remove_formatter(parent_formatter)
        subject.remove_formatter(child_formatter)
        subject.remove_formatter(parent_formatter)
      end

      before do
        parent.attach_formatter(parent_formatter, {:parent => true})
        subject.attach_formatter(child_formatter, {:child => true})
        subject.attach_formatter(parent_formatter, {:child => true})

        @formatters = subject.population_formatters
      end

      it "Should return an Array of formatters [{formatter => options}, etc...]" do
        @formatters.is_a?(Array).should be_true
      end

      it "Should have parent formatter with :parent => true in parent" do
        expected = {parent_formatter => {:parent => true}}
        @formatters.should include(expected)
      end

      it "Should have child formatter with :child => true in child" do
        expected = {child_formatter => {:child => true}}
        @formatters.should include(expected)
      end

      it "Should have parent formatter with child => true in child" do
        expected = {parent_formatter => {:child => true}}
        @formatters.should include(expected)
      end

    end
  end

  describe "#self.attach_formatter" do

    after do
      subject.remove_formatter(formatter)
    end

    let(:formatter) do
      flexmock('formatter-attach', {
        :format! => '',
        :instance_methods => ['format!']
      })
    end

    it "Should raise an exception when providing an object without a format! instance method" do
      lambda { subject.attach_formatter(Class.new)  }.should raise_error /must provide format!/
    end

    it "Should attach formatter to object" do
      subject.attach_formatter(formatter, {:yey => true})
      subject.should have_formatter(formatter)
    end

    context "When formatter has self.model_include function" do
      let!(:formatter) do
        Class.new do

          def initialize(record, options = {})

          end

          def format!()

          end

          class << self
            def attached

            end
          end
        end
      end

      after do
        subject.remove_formatter(formatter)
      end

      it "Should call model include method when attached with model class as an argument" do
        flexmock(formatter).should_receive(:attached).with(subject, {:options => true}).once
        subject.attach_formatter(formatter, :options => true)
      end

    end

    context "When attaching from base object children should inherit formatters" do
      before do
        parent.attach_formatter(formatter)
      end

      after do
        parent.remove_formatter(formatter)
      end

      it "Should have formatter in parent" do
        parent.should have_formatter(formatter)
      end

      it "Should have formatter in child" do
        subject._formatters.should have_key(formatter)
      end
    end

    context "When attaching formatter to child, sibling and parent should not inherit" do
      let!(:sibling) do
        Class.new(parent)
      end

      after do
        subject.remove_formatter(formatter)
      end

      before do
        subject.attach_formatter(formatter)
      end

      it "Should not have added formatter to sibling" do
        sibling.should_not have_formatter(formatter)
      end

      it "Should not have added formatter to parent" do
        sibling.should_not have_formatter(formatter)
      end

      it "Should have attached formatter to self" do
        subject.should have_formatter(formatter)
      end

    end

  end

  context "#self.remove_formatter" do
    let(:formatter) do
      flexmock('formatter-remove', {
        :format! => '',
        :instance_methods => ['format!']
      })
    end

    after do
      subject.remove_formatter(formatter)
      parent.remove_formatter(formatter)
    end

    context "When removing formatter from child" do
      before do
        subject.attach_formatter(formatter)
      end

      after do
        subject.remove_formatter(formatter)
      end

      it "Should have formatter" do
        subject.should have_formatter(formatter)
      end

      it "Should not have formatter after removal" do
        subject.remove_formatter(formatter)
        subject.should_not have_formatter(formatter)
      end
    end

    context "When removing parent formatter from children" do
      before do
        parent.attach_formatter(formatter)
        subject.remove_formatter(formatter)
      end

      it "Should still have formatter on parent" do
        parent.should have_formatter(formatter)
      end

      it "Should not have formatter on child" do
        subject.should_not have_formatter(formatter)
      end

    end

  end

  describe "#self.api" do
    it "Should return ApolloFresh::Model instance" do
      subject.api.should == ApolloFresh::Api
    end
  end

  describe "#self.model" do
    before(:each) { subject.model = test_api }

    it "Should allow override of model" do
      subject.model.should == test_api
    end

    it "Should also have set api to new model" do
      subject.api.should == test_api
    end
  end

  describe "#self.resource" do
    before(:each) { subject.resource = 'resource_name' }

    it "Should allow us to set the resource" do
      subject.resource.should == 'resource_name'
    end

    it "Should call key when setting resource using \#{resource}_id" do
      model = flexmock(subject)
      model.should_receive(:key).with('invoice_id').once
      model.resource = 'invoice'
    end
  end

  describe "#self.populate!" do
    context "When loading all data into the model for the first time" do
      before(:each) do
        @api = flexmock(subject.api).should_receive(:all!).and_return(all_invoices)
      end

      it "Should populate collection with records from :all!" do
        @api.once
        subject.populate!
        count = subject.count()
        all = subject.all
        invoices = all_invoices.clone

        count.should == 40
        all.each do |object|
          invoices.should have_key(object.id)
          invoices.delete(object.id)
        end
        invoices.length.should == 0
      end
    end

    context "When updating collection and records have been removed from API" do
      let(:invoices) do
        fresh_sample(:invoices, 20, 20, 1, 1..20)['invoice'].index_by {|obj| obj['invoice_id']}
      end
      before(:each) do
        @api = flexmock(subject.api)
        @api.should_receive(:all!).and_return(all_invoices).once.ordered(:populate)
        @api.should_receive(:all!).and_return(invoices).once.ordered(:populate)

        subject.populate!.should be_true

      end

      it "Should only have records returned by the most recent all when success" do
        subject.populate!.should be_true
        all = subject.all
        count = subject.count
        invoices = self.invoices.clone

        count.should == 20
        all.each do |object|
          invoices.should have_key(object.id)
          invoices.delete(object.id)
        end
        invoices.length.should == 0
      end
    end

    context "With formatting by ApolloFresh::Format::DateComponents" do
      let(:invoices) do
        fresh_sample(:invoices, 20, 20, 1, 1..20)['invoice'].index_by {|obj| obj['invoice_id']}
      end

      let!(:formatters) do
        [{ApolloFresh::Format::DateComponents => {:fields => [:date]}}, {ApolloFresh::Format::HashedArray => {}}]
      end

      before do
        @api = flexmock(subject.api)
        @api.should_receive(:all!).and_return(invoices).once.ordered(:populate)
        flexmock(subject).should_receive(:population_formatters).once.and_return(formatters)
        subject.populate!
      end

      it "Should have added date_dc to records" do
        subject.first.date_dc.is_a?(Hash).should be_true
      end
    end

    context "With formatting by ApolloFresh::Format::HashedArray" do
      let(:invoices) do
        fresh_sample(:invoices, 20, 20, 1, 1..20)['invoice'].index_by {|obj| obj['invoice_id']}
      end

      let!(:formatters) do
        [{ApolloFresh::Format::HashedArray => {}}]
      end

      before do
        @api = flexmock(subject.api)
        @api.should_receive(:all!).and_return(invoices).once.ordered(:populate)
        flexmock(subject).should_receive(:population_formatters).once.and_return(formatters)
        subject.populate!
      end

      it "Should have removed the hash wrapper around lines" do
        subject.first.lines.is_a?(Array).should be_true
      end

    end

  end

  describe "#self.populate" do
    before(:each) do
      @api = flexmock(subject.api)
      @api.should_receive(:all!).and_return(all_invoices).once.ordered(:populate)
      subject.populate!
    end

    it "Should update record in database when populating" do
      original = subject.find(:first, :conditions => {:id => '1'})

      populate_with = fresh_sample(:invoice, '1')
      populate_with['number'] = '10000001'

      subject.populate({'1' => populate_with})

      current = subject.find(:first, :conditions => {:id => '1'})

      current.id.should == original.id
      current.number.should == '10000001'
    end

  end

  context "When testing Mongo Capabilities" do

    let(:invoice) do
      fresh_sample(:invoice, '55')
    end

    context "When querying test row" do
      before(:each) do
        subject.create!(invoice.merge('mongo_test' => '1'))
        @object = subject.find(:first, :conditions => {'mongo_test' => '1'})
      end

      it "Lines should equal invoice.lines" do
        @object.lines.should == invoice['lines']
      end

      it "Should have id equal to invoice and and 55" do
        @object.id.should == '55'
        @object.id.should == @object.invoice_id
      end
    end
  end

end


text:
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace Khipu.Model {

  /// <summary>
  ///
  /// </summary>
  [DataContract]
  public class BankItem {

    /// <summary>
    /// Identificador del banco
    /// </summary>
    /// <value>Identificador del banco</value>
    [DataMember(Name="bank_id", EmitDefaultValue=false)]
    public string BankId { get; set; }

    /// <summary>
    /// Nombre del banco
    /// </summary>
    /// <value>Nombre del banco</value>
    [DataMember(Name="name", EmitDefaultValue=false)]
    public string Name { get; set; }

    /// <summary>
    /// Mensaje con particularidades del banco
    /// </summary>
    /// <value>Mensaje con particularidades del banco</value>
    [DataMember(Name="message", EmitDefaultValue=false)]
    public string Message { get; set; }

    /// <summary>
    /// Monto mínimo que acepta el banco en un pago
    /// </summary>
    /// <value>Monto mínimo que acepta el banco en un pago</value>
    [DataMember(Name="min_amount", EmitDefaultValue=false)]
    public double? MinAmount { get; set; }

    /// <summary>
    /// Tipo de banco
    /// </summary>
    /// <value>Tipo de banco</value>
    [DataMember(Name="type", EmitDefaultValue=false)]
    public string Type { get; set; }

    /// <summary>
    /// Identificador del banco padre (si un banco tiene banca personas y empresas, el primero será el padre del segundo)
    /// </summary>
    /// <value>Identificador del banco padre (si un banco tiene banca personas y empresas, el primero será el padre del segundo)</value>
    [DataMember(Name="parent", EmitDefaultValue=false)]
    public string Parent { get; set; }

    /// <summary>
    /// Get the string presentation of the object
    /// </summary>
    /// <returns>String presentation of the object</returns>
    public override string ToString()  {
      var sb = new StringBuilder();
      sb.Append("class BankItem {\n");

      sb.Append("  BankId: ").Append(BankId).Append("\n");

      sb.Append("  Name: ").Append(Name).Append("\n");

      sb.Append("  Message: ").Append(Message).Append("\n");

      sb.Append("  MinAmount: ").Append(MinAmount).Append("\n");

      sb.Append("  Type: ").Append(Type).Append("\n");

      sb.Append("  Parent: ").Append(Parent).Append("\n");

      sb.Append("}\n");
      return sb.ToString();
    }

    /// <summary>
    /// Get the JSON string presentation of the object
    /// </summary>
    /// <returns>JSON string presentation of the object</returns>
    public string ToJson() {
      return JsonConvert.SerializeObject(this, Formatting.Indented);
    }

}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Diagnostics;
using System.Linq;
using Chiro.CiviCrm.Api.DataContracts.Filters;
using Newtonsoft.Json;

namespace Chiro.CiviCrm.Api.Converters
{
    public class FilterConverter: JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var filter = value as IFilter;
            string civiOperator;
            string rhs;

            Debug.Assert(filter != null);

            var first = filter.Objects.FirstOrDefault();
            if (first == null)
            {
                if (filter.Operator != WhereOperator.IsNotNull && filter.Operator != WhereOperator.IsNull)
                {
                    // no RHS only possible for is (not) null.
                    throw new InvalidOperationException();
                }
                rhs = String.Empty;
            }
            else if (filter.Objects.Skip(1).FirstOrDefault() == null)
            {
                // Only one object. Easy.
                Object obj = filter.Objects.First();
                if (obj is DateTime && ((DateTime) obj) == DateTime.MinValue)
                {
                    // Work around #92. If you use this in a create-operation, you can remove the existing
                    // datetime by passing DateTime.MinValue.
                    obj = 0;
                }

                rhs = JsonConvert.SerializeObject(obj);
            }
            else
            {
                // More than one object. Check for (not) in and (not) between.
                if (filter.Operator == WhereOperator.Between || filter.Operator == WhereOperator.NotBetween)
                {
                    if (filter.Objects.Skip(2).FirstOrDefault() != null)
                    {
                        // More than 2 objects does not make sense for between.
                        throw new InvalidOperationException();
                    }
                }
                else if (filter.Operator != WhereOperator.In && filter.Operator != WhereOperator.NotIn)
                {
                    throw new InvalidOperationException();
                }
                rhs = JsonConvert.SerializeObject(filter.Objects);
            }

            switch (filter.Operator)
            {
                case WhereOperator.None:
                    writer.WriteRawValue(rhs);
                    return;
                case WhereOperator.Eq:
                    civiOperator = "=";
                    break;
                case WhereOperator.Lte:
                    civiOperator = "<=";
                    break;
                case WhereOperator.Gte:
                    civiOperator = ">=";
                    break;
                case WhereOperator.Lt:
                    civiOperator = "<";
                    break;
                case WhereOperator.Gt:
                    civiOperator = ">";
                    break;
                case WhereOperator.Like:
                    civiOperator = "LIKE";
                    break;
                case WhereOperator.Ne:
                    civiOperator = "<>";
                    break;
                case WhereOperator.NotLike:
                    civiOperator = "NOT LIKE";
                    break;
                case WhereOperator.In:
                    civiOperator = "IN";
                    break;
                case WhereOperator.NotIn:
                    civiOperator = "NOT IN";
                    break;
                case WhereOperator.Between:
                    civiOperator = "BETWEEN";
                    break;
                case WhereOperator.NotBetween:
                    civiOperator = "NOT BETWEEN";
                    break;
                case WhereOperator.IsNotNull:
                    writer.WriteRawValue("{\"IS NOT NULL\":1}");
                    return;
                case WhereOperator.IsNull:
                    writer.WriteRawValue("{\"IS NULL\":1}");
                    return;
                default:
                    throw new InvalidOperationException();
            }
            writer.WriteRawValue(String.Format("{{\"{0}\":{1}}}", civiOperator, rhs));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // We only use this converter for requests, so
            // we'll never have to deserialize such a thing.
            throw new NotImplementedException();
        }

        public override bool CanConvert(Type objectType)
        {
            return (objectType.IsGenericType &&
                    objectType.GetGenericTypeDefinition() == typeof (Filter<>));
        }
    }
}


text:
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */

#ifndef __LINUX_LIST_H
#define __LINUX_LIST_H

#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
        struct list_head name = LIST_HEAD_INIT(name)

#define POISON_POINTER_DELTA 0
#define LIST_POISON1  ((void *) 0x100 + POISON_POINTER_DELTA)
#define LIST_POISON2  ((void *) 0x200 + POISON_POINTER_DELTA)

static inline void INIT_LIST_HEAD(struct list_head *list)
{
        list->next = list;
        list->prev = list;
}

static inline void __list_add(struct list_head *new,
                              struct list_head *prev,
                              struct list_head *next)
{
        next->prev = new;
        new->next = next;
        new->prev = prev;
        prev->next = new;
}

/**
 * list_add - add a new entry
 * @new: new entry to be added
 * @head: list head to add it after
 *
 * Insert a new entry after the specified head.
 * This is good for implementing stacks.
 */
static inline void list_add(struct list_head *new, struct list_head *head)
{
        __list_add(new, head, head->next);
}

/*
 * Delete a list entry by making the prev/next entries
 * point to each other.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
        next->prev = prev;
        prev->next = next;
}

/**
 * list_del - deletes entry from list.
 * @entry: the element to delete from the list.
 * Note: list_empty() on entry does not return true after this, the entry is
 * in an undefined state.
 */
static inline void __list_del_entry(struct list_head *entry)
{
        __list_del(entry->prev, entry->next);
}

static inline void list_del(struct list_head *entry)
{
        __list_del(entry->prev, entry->next);
        entry->next = LIST_POISON1;
        entry->prev = LIST_POISON2;
}

static inline int list_empty(const struct list_head *head)
{
	return head->next == head;
}

#define list_entry(ptr, type, member) \
        container_of(ptr, type, member)
#define list_first_entry(ptr, type, member) \
        list_entry((ptr)->next, type, member)
#define list_next_entry(pos, member) \
        list_entry((pos)->member.next, typeof(*(pos)), member)
#define list_for_each_entry(pos, head, member) \
	for (pos = list_first_entry(head, typeof(*pos), member); \
	     &pos->member != (head); \
	     pos = list_next_entry(pos, member))

#endif


text:
package robocode;

import net.sf.robocode.peer.IRobotStatics;
import net.sf.robocode.security.SafeComponent;
import net.sf.robocode.serialization.ISerializableHelper;
import net.sf.robocode.serialization.RbSerializer;
import robocode.robotinterfaces.IBasicRobot;
import robocode.robotinterfaces.IInteractiveEvents;
import robocode.robotinterfaces.IInteractiveRobot;

import java.awt.*;
import java.nio.ByteBuffer;

/**
 * A MouseReleasedEvent is sent to {@link Robot#onMouseReleased(java.awt.event.MouseEvent)
 * onMouseReleased()} when the mouse is released inside the battle view.
 *
 * @see MouseClickedEvent
 * @see MousePressedEvent
 * @see MouseEnteredEvent
 * @see MouseExitedEvent
 * @see MouseMovedEvent
 * @see MouseDraggedEvent
 * @see MouseWheelMovedEvent
 *
 * @author Pavel Savara (original)
 * @author Flemming N. Larsen (contributor)
 *
 * @since 1.6.1
 */
public final class MouseReleasedEvent extends MouseEvent {
	private static final long serialVersionUID = 1L;
	private final static int DEFAULT_PRIORITY = 98;

	/**
	 * Called by the game to create a new MouseReleasedEvent.
	 *
	 * @param source the source mouse event originating from the AWT.
	 */
	public MouseReleasedEvent(java.awt.event.MouseEvent source) {
		super(source);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	final int getDefaultPriority() {
		return DEFAULT_PRIORITY;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	final void dispatch(IBasicRobot robot, IRobotStatics statics, Graphics2D graphics) {
		if (statics.isInteractiveRobot()) {
			IInteractiveEvents listener = ((IInteractiveRobot) robot).getInteractiveEventListener();

			if (listener != null) {
				listener.onMouseReleased(getSourceEvent());
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	byte getSerializationType() {
		return RbSerializer.MouseReleasedEvent_TYPE;
	}

	static ISerializableHelper createHiddenSerializer() {
		return new SerializableHelper();
	}

	private static class SerializableHelper implements ISerializableHelper {

		public int sizeOf(RbSerializer serializer, Object object) {
			return RbSerializer.SIZEOF_TYPEINFO + 6 * RbSerializer.SIZEOF_INT + RbSerializer.SIZEOF_LONG;
		}

		public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) {
			MouseReleasedEvent obj = (MouseReleasedEvent) object;
			java.awt.event.MouseEvent src = obj.getSourceEvent();

			serializer.serialize(buffer, src.getButton());
			serializer.serialize(buffer, src.getClickCount());
			serializer.serialize(buffer, src.getX());
			serializer.serialize(buffer, src.getY());
			serializer.serialize(buffer, src.getID());
			serializer.serialize(buffer, src.getModifiersEx());
			serializer.serialize(buffer, src.getWhen());
		}

		public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {
			int button = buffer.getInt();
			int clickCount = buffer.getInt();
			int x = buffer.getInt();
			int y = buffer.getInt();
			int id = buffer.getInt();
			int modifiersEx = buffer.getInt();
			long when = buffer.getLong();

			return new MouseReleasedEvent(
					new java.awt.event.MouseEvent(SafeComponent.getSafeEventComponent(), id, when, modifiersEx, x, y,
					clickCount, false, button));
		}
	}
}


text:
package org.apache.isis.core.webapp.content;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import org.apache.isis.core.commons.lang.InputStreamExtensions;
import org.apache.isis.core.commons.lang.ResourceUtil;
import org.apache.isis.core.commons.lang.StringExtensions;

public class ResourceServlet extends HttpServlet {

    private static final Logger LOG = LoggerFactory.getLogger(ResourceServlet.class);
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    private void processRequest(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        final String servletPath = StringExtensions.stripLeadingSlash(request.getServletPath());
        if (LOG.isDebugEnabled()) {
            LOG.debug("request: " + servletPath);
        }

        // try to load from filesystem
        final InputStream is2 = getRealPath(request);
        if (is2 != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("request: " + servletPath + " loaded from filesystem");
            }
            writeContentType(request, response);
            InputStreamExtensions.copyTo(is2, response.getOutputStream());
            is2.close();
            return;
        }

        // otherwise, try to load from classpath
        final InputStream is = ResourceUtil.getResourceAsStream(servletPath);
        if (is != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("request: " + servletPath + " loaded from classpath");
            }
            writeContentType(request, response);
            InputStreamExtensions.copyTo(is, response.getOutputStream());
            is.close();
            return;
        }

        LOG.warn("failed to load resource from classpath or file system: " + servletPath);
    }

    private static void writeContentType(final HttpServletRequest request, final HttpServletResponse response) {
        final String contentType = guessContentType(request.getServletPath());
        if(contentType != null) {
            response.setContentType(contentType);
        }
    }

    private static String guessContentType(String servletPath) {
        if(servletPath.endsWith(".css")) {
            return "text/css";
        } else if(servletPath.endsWith(".png")) {
            return "image/png";
        } else if(servletPath.endsWith(".jpg")) {
            return "image/jpeg";
        } else if(servletPath.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if(servletPath.endsWith(".gif")) {
            return "image/gif";
        } else if(servletPath.endsWith(".svg")) {
            return "image/svg+xml";
        } else if(servletPath.endsWith(".js")) {
            return "application/x-javascript";
        } else if(servletPath.endsWith(".html")) {
            return "text/html";
        } else if(servletPath.endsWith(".swf")) {
            return "application/x-shockwave-flash";
        }
        return null;
    }

    private FileInputStream getRealPath(final HttpServletRequest request) {
        final String realPath = request.getSession().getServletContext().getRealPath(request.getServletPath());
        if (realPath == null) {
            return null;
        }
        try {
            return new FileInputStream(realPath);
        } catch (final FileNotFoundException e) {
            return null;
        }
    }
}


text:
package org.hibernate.validator.test.engine.groups.redefiningdefaultgroup;

import javax.validation.GroupSequence;
import javax.validation.groups.Default;

/**
 * @author Hardy Ferentschik
 */
@GroupSequence({ Default.class, CarChecks.class, DriverChecks.class })
public interface OrderedChecks {
}


text:
def new_random_groups(numgroup)
    studentname = IO.readlines('public/names.txt').map{ |element| element.chomp}.shuffle
	numgroup = 1 #How to doesn't put this value without an error?
	numstudent = studentname.length
	groups = (1..numgroup).zip(*studentname.each_slice(numgroup))
	groups.each do |index, *items|
    	items.compact! #remove nils
	end
	studentname.shuffle
end


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001package com.github.sarxos.webcam;
002
003import java.util.List;
004
005import javax.swing.JComboBox;
006
007
008public class WebcamPicker extends JComboBox {
009
010        private static final long serialVersionUID = 1L;
011
012        private static final WebcamPickerCellRenderer RENDERER = new WebcamPickerCellRenderer();
013
014        public WebcamPicker() {
015                this(Webcam.getWebcams());
016        }
017
018        public WebcamPicker(List<Webcam> webcams) {
019                super(new WebcamPickerModel(webcams));
020                setRenderer(RENDERER);
021        }
022
023        public Webcam getSelectedWebcam() {
024                return (Webcam) getSelectedItem();
025        }
026}


text:
<!doctype html>

        <title>jQuery.Gantt - Test Suite 01</title>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1" >
        <link rel="stylesheet" href="../css/style.css" />
        <link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" />
        <link rel="stylesheet" href="http://taitems.github.com/UX-Lab/core/css/prettify.css" />

				jQuery.Gantt
				— Test Suite 01

				Expected behaviour: Gantt bar should run from "now" until 2 hours from now.

				Errors:

Hour views (1/3/6/9 hours) are all docked left


text:
package processing.app;

import java.io.*;

public class TestHelper {

  public static String inputStreamToString(InputStream is) throws IOException {
    StringWriter sw = new StringWriter();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    String line;
    try {
      while ((line = reader.readLine()) != null) {
        sw.append(line).append('\n');
      }
      return sw.toString();
    } finally {
      is.close();
    }
  }
}


text:
namespace mo {

template<typename Datum = std::vector<unsigned char>, typename Label = unsigned char>
class KNearestNeighbor
{
public:
    KNearestNeighbor(const int k, const std::string& datadir, const DataType dt = DataType::mnist
            , const bool show_result = true, const DistanceType disttp = DistanceType::l2);
    void eval();
    const Label classify(const Datum& datum);

private:
    int k_;
    std::unique_ptr<DataHandler<std::vector<unsigned char>, unsigned char>> pdh_;
    bool show_result_;
    DistanceType disttp_;

    const Label count_majority_label(const std::map<double, Label>& dist_label);
};

//------------------
template<typename Datum, typename Label>
KNearestNeighbor<Datum, Label>::KNearestNeighbor(const int k, const std::string& datadir, const DataType dt
                                                 , const bool show_result, const DistanceType disttp):
    k_ {k}, show_result_ {show_result}, pdh_{create_imgdata_handler(dt)}, disttp_{disttp}
{
    pdh_->read(datadir);
    if(show_result_) pdh_->show_traindata();

    std::cout << "[INFO] init k=" << k << ", datadir=" << datadir << ", data type=" << static_cast<int>(dt)
              << ", show result=" << show_result << ", distance type=" << static_cast<int>(disttp) << "\n";
}

//------------------
template<typename Datum, typename Label>
const Label KNearestNeighbor<Datum, Label>::classify(const Datum& datum){
    std::map<double, Label> dist_label;
    const std::vector<Datum>& train_data = pdh_->train_data();
    const std::vector<Label>& train_labels = pdh_->train_labels();
    assert(train_data.size() == train_labels.size());

    for(int i=0; i<train_data.size(); ++i){
        double dist = distance(datum, train_data[i], disttp_);
        dist_label.insert( std::pair<double, Label>(dist, train_labels[i]) );
    }

    //todo: add reject option
    if(show_result_){
        std::cout << "min normalized dist= " << dist_label.begin()->first / pdh_->train_data()[0].size();
    }

    return count_majority_label(dist_label);
}

//-------------------
template<typename Datum, typename Label>
const Label KNearestNeighbor<Datum, Label>::count_majority_label(const std::map<double, Label>& dist_label)try{
    assert(k_ < dist_label.size());

    std::map<Label, int> label_occurences;
    auto it = dist_label.begin();
    for(int i=0; i<k_; ++i){
        ++label_occurences[it->second];
        ++it;
    }

    auto it2 = std::max_element(label_occurences.begin(), label_occurences.end(),
                                [](const std::pair<Label,int>& p1, const std::pair<Label,int>& p2){return p1.second < p2.second;});

    return it2->first;

}catch(...){
throw;
}

//--------------------
template<typename Datum, typename Label>
void KNearestNeighbor<Datum, Label>::eval(){
    std::cout << "[INFO] enter " << __func__ << '\n';
    assert(pdh_->test_data().size() == pdh_->test_labels().size());

    int num_correct=0;
    int num_testdata = pdh_->test_data().size();
    for(int i=0; i<num_testdata; ++i){
        if(show_result_){
            std::cout << "test " << i << ": ";
        }

        clock_t beg = clock();
        Label lbl = classify(pdh_->test_data()[i]);
        clock_t end = clock();

        if(lbl == pdh_->test_labels()[i]) ++num_correct;

        if(show_result_){
            std::cout << ", computed label= " << static_cast<int>(lbl)
                      << ", true label= " << static_cast<int>(pdh_->test_labels()[i])
                      << ", computation time=" << float(end - beg)/CLOCKS_PER_SEC << "[s]\n" << std::flush;

            char ch = pdh_->show(pdh_->test_data()[i], "test image");
            switch (ch) {
            case 'p':
            case 'b':
                i-=2;
                break;
            case 'q':
                destroy_window("test image");
                show_result_ = false;
                break;
            default:
                break;
            }
        }
    }

    std::cout << "correct classification= " << num_correct * 100.0 / num_testdata << '\n';
}

} // namespace mo

#endif // KNEARESTNEIGHBOR_H


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Node.cs" company="Cyrille DUPUYDAUBY">
//   Copyright 2013 Cyrille DUPUYDAUBY
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
// <summary>
//   Defines the Node type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace RAFTiNG
{
    using System;

    using log4net;

    using Michonne.Interfaces;

    using RAFTiNG.Commands;
    using RAFTiNG.Messages;
    using RAFTiNG.Services;
    using RAFTiNG.States;

    /// <summary>
    /// Implements a Node as described by the RAFT algorithm.
    /// The nodes aggregates a persisted state object that must be kept synchronized with a persistent storage.
    /// The node also aggregates a <see cref="State"/> subclass instance to implement the active state rules.
    /// </summary>
    /// <typeparam name="T">Command type for the middleware state machine.</typeparam>
    public sealed class Node<T> : IDisposable
    {
        #region fields

        private readonly ISequencer sequencer;

        private readonly ILog logger;

        private readonly IMiddleware internalMiddleware;

        private readonly IStateMachine<T> stateMachine;

        private NodeSettings settings;

        private State<T> currentState;

        private int lastCommit = -1;

        #endregion

        #region constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="Node{T}"/> class.
        /// </summary>
        /// <param name="sequencer"><see cref="ISequencer"/>to use for execution.</param>
        /// <param name="settings">
        /// The node settings.
        /// </param>
        /// <param name="middleware">Middleware used to exchange message.
        /// </param>
        /// <param name="machine">Hosted state machine.</param>
        public Node(ISequencer sequencer, NodeSettings settings, IMiddleware middleware, IStateMachine<T> machine)
        {
            this.Id = settings.NodeId;
            this.settings = settings;
            this.internalMiddleware = middleware;
            this.stateMachine = machine;
            this.sequencer = sequencer;
            this.Status = NodeStatus.Initializing;
            this.State = new PersistedState<T>();
            this.logger = LogManager.GetLogger(string.Format("Node[{0}]", this.Id));
        }

        #endregion

        #region properties

        /// <summary>
        /// Gets the current status for this node.
        /// </summary>
        public NodeStatus Status { get; private set; }

        /// <summary>
        /// Gets the node address.
        /// </summary>
        /// <value>
        /// The address.
        /// </value>
        public string Id { get; private set; }

        /// <summary>
        /// Gets the messages count.
        /// </summary>
        /// <value>
        /// The messages count.
        /// </value>
        public int MessagesCount { get; private set; }

        /// <summary>
        /// Gets the persisted state.
        /// </summary>
        public PersistedState<T> State { get; private set; }

        /// <summary>
        /// Gets the next commit index.
        /// </summary>
        /// <value>
        /// The next commit.
        /// </value>
        public int LastCommit
        {
            get
            {
                return this.lastCommit;
            }
        }

        internal ILog Logger
        {
            get
            {
                return this.logger;
            }
        }

        /// <summary>
        /// Gets the RAFTiNG settings.
        /// </summary>
        internal NodeSettings Settings
        {
            get
            {
                return this.settings;
            }
        }

        /// <summary>
        /// Gets or sets the leader id.
        /// </summary>
        /// <value>
        /// The leader id.
        /// </value>
        internal string LeaderId { get; set; }

        #endregion

        #region methods

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        public void Initialize()
        {
            if (this.internalMiddleware == null)
            {
                throw new InvalidOperationException("Must call SetInternalMiddleware first!");
            }

            // TODO: restore persisted state
            if (this.Status != NodeStatus.Initializing)
            {
                throw new InvalidOperationException("Node is already initialized.");
            }

            this.logger.InfoFormat("Middleware registration to address {0}.", this.Id);
            this.internalMiddleware.RegisterEndPoint(this.Id, this.MessageReceived);

            this.SwitchTo(
                this.settings.OtherNodes().Count == 0 ? NodeStatus.Leader : NodeStatus.Follower);
        }

        /// <summary>
        /// Adds an entry to this node.
        /// </summary>
        /// <param name="command">The command.</param>
        public void AddEntry(T command)
        {
            this.sequencer.Dispatch(() => this.State.AddEntry(command));
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (this.logger.IsInfoEnabled)
            {
                this.logger.Info("Stopping Node.");
            }

            if (this.currentState == null)
            {
                return;
            }
            this.currentState.ExitState();
            this.currentState = null;
        }

        /// <summary>
        /// Sends the command into the cluster.
        /// </summary>
        /// <param name="command">The command to be processed.</param>
        /// <returns>true if the command was send, which means the cluster has a leader.</returns>
        public bool SendCommand(T command)
        {
            if (String.IsNullOrEmpty(this.LeaderId))
            {
                // no leader
                return false;
            }

            this.Sequence(
                () =>
                {
                    if (String.IsNullOrEmpty(this.LeaderId))
                    {
                        // leader has disapeared
                        return;
                    }

                    var message = new SendCommand<T>(command);
                    if (this.LeaderId == this.Id)
                    {
                        this.SequencedMessageReceived(message);
                    }
                    else
                    {
                        this.SendMessage(this.LeaderId, message);
                    }
                });
            return true;
        }

        #region Methodes used by the state object

        internal void SendVote(string candidate, bool voteGranted)
        {
            if (voteGranted)
            {
                this.State.VotedFor = candidate;
                this.LeaderId = string.Empty;

                if (candidate == this.Id)
                {
                    return;
                }
            }

            this.SendMessage(candidate, new GrantVote(voteGranted, this.Id, this.State.CurrentTerm));
        }

        /// <summary>
        /// Changes the current status.
        /// </summary>
        /// <param name="status">Target status.</param>
        internal void SwitchTo(NodeStatus status)
        {
            this.SequencedSwitch(status);
        }

        /// <summary>
        /// Changes the current status and process the given message.
        /// </summary>
        /// <param name="status">Target status.</param>
        /// <param name="message">Message to be processed.</param>
        /// <remarks>Used this method when a message triggers a step down.</remarks>
        internal void SwitchToAndProcessMessage(NodeStatus status, object message)
        {
            this.SequencedSwitch(status);
            this.SequencedMessageReceived(message);
        }

        /// <summary>
        /// Increase the current term.
        /// </summary>
        /// <returns>The new term.</returns>
        internal long IncrementTerm()
        {
            var nextTerm = this.State.CurrentTerm + 1;
            this.State.CurrentTerm = nextTerm;
            return nextTerm;
        }

        internal void Commit(int newCommit)
        {
            if (this.lastCommit >= newCommit)
            {
                return;
            }

            for (var i = this.lastCommit + 1; i <= newCommit; i++)
            {
                this.stateMachine.Commit(this.State.LogEntries[i].Command);
                this.Logger.TraceFormat("Committed index is {0}.", i);
            }

            this.lastCommit = newCommit;
            this.Logger.DebugFormat("Commit index is now {0}.", this.lastCommit);
        }

        /// <summary>
        /// Send message to a specific node.
        /// </summary>
        /// <param name="dest">Destination node.</param>
        /// <param name="message">Message to be sent.</param>
        internal void SendMessage(string dest, object message)
        {
            this.internalMiddleware.SendMessage(dest, message);
        }

        /// <summary>
        /// Broadcast a message to all other nodes.
        /// </summary>
        /// <param name="message">Message to be broadcasted.</param>
        internal void SendToOthers(object message)
        {
            // send request to all nodes
            if (this.logger.IsTraceEnabled())
            {
                this.logger.TraceFormat("Broadcast message to all other nodes: {0}", message);
            }

            foreach (var otherNode in this.settings.OtherNodes())
            {
                this.internalMiddleware.SendMessage(otherNode, message);
            }
        }

        /// <summary>
        /// Ensure an <see cref="System.Action"/> is executed non concurrently.
        /// </summary>
        /// <param name="action">Action to sequence.</param>
        /// <remarks>Use this function to prevent race conditions, so it should be the entry point for all messages, timers and other asynchronous calls.</remarks>
        internal void Sequence(Action action)
        {
            this.sequencer.Dispatch(action);
        }

        /// <summary>
        /// Implementation of the Switch method, assuming no race conditions is possible.
        /// </summary>
        /// <param name="status">Target status.</param>
        private void SequencedSwitch(NodeStatus status)
        {
            State<T> newState;
            this.logger.DebugFormat("Switching status from {0} to {1}", this.Status, status);
            if (this.currentState != null)
            {
                this.currentState.ExitState();
            }

            switch (status)
            {
                case NodeStatus.Follower:
                    newState = new Follower<T>(this);
                    break;
                case NodeStatus.Candidate:
                    newState = new Candidate<T>(this);
                    break;
                case NodeStatus.Leader:
                    newState = new Leader<T>(this);
                    break;
                default:
                    throw new NotSupportedException("Status not supported");
            }

            this.Status = status;
            this.currentState = newState;
            this.currentState.EnterState();
        }

        #endregion

        // raft message received
        private void MessageReceived(object obj)
        {
            this.sequencer.Dispatch(() => this.SequencedMessageReceived(obj));
        }

        /// <summary>
        /// Process a received message. Basically route the message to the adequate handler.
        /// </summary>
        /// <param name="obj">Message to route.</param>
        private void SequencedMessageReceived(object obj)
        {
            if (this.currentState == null)
            {
                this.Logger.DebugFormat("Node is not active, discarding message ({0}).", obj);
                return;
            }

            this.MessagesCount++;

            var requestVote = obj as RequestVote;
            if (requestVote != null)
            {
                this.currentState.ProcessVoteRequest(requestVote);
                return;
            }

            var vote = obj as GrantVote;
            if (vote != null)
            {
                this.currentState.ProcessVote(vote);
                return;
            }

            var appendEntries = obj as AppendEntries<T>;
            if (appendEntries != null)
            {
                this.currentState.ProcessAppendEntries(appendEntries);
                return;
            }

            var appendEntriesAck = obj as AppendEntriesAck;
            if (appendEntriesAck != null)
            {
                this.currentState.ProcessAppendEntriesAck(appendEntriesAck);
                return;
            }

            this.logger.ErrorFormat("Message not recognized (Type: {0}, Message: {1})", obj.GetType(), obj);
        }

        #endregion
    }
}


text:
package functions

import (
	"net/url"
	"strings"
	"encoding/json"
)

type TasksApi struct {
	Configuration *Configuration
}

func NewTasksApi() *TasksApi {
	configuration := NewConfiguration()
	return &TasksApi{
		Configuration: configuration,
	}
}

func NewTasksApiWithBasePath(basePath string) *TasksApi {
	configuration := NewConfiguration()
	configuration.BasePath = basePath

	return &TasksApi{
		Configuration: configuration,
	}
}

/**
 * Get next task.
 * Gets the next task in the queue, ready for processing. Consumers should start processing tasks in order. No other consumer can retrieve this task.
 *
 * @return *TaskWrapper
 */
func (a TasksApi) TasksGet() (*TaskWrapper, *APIResponse, error) {

	var localVarHttpMethod = strings.ToUpper("Get")
	// create path and map variables
	localVarPath := a.Configuration.BasePath + "/tasks"

	localVarHeaderParams := make(map[string]string)
	localVarQueryParams := url.Values{}
	localVarFormParams := make(map[string]string)
	var localVarPostBody interface{}
	var localVarFileName string
	var localVarFileBytes []byte
	// add default headers if any
	for key := range a.Configuration.DefaultHeader {
		localVarHeaderParams[key] = a.Configuration.DefaultHeader[key]
	}

	// to determine the Content-Type header
	localVarHttpContentTypes := []string{ "application/json",  }

	// set Content-Type header
	localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)
	if localVarHttpContentType != "" {
		localVarHeaderParams["Content-Type"] = localVarHttpContentType
	}
	// to determine the Accept header
	localVarHttpHeaderAccepts := []string{
		"application/json",
		}

	// set Accept header
	localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)
	if localVarHttpHeaderAccept != "" {
		localVarHeaderParams["Accept"] = localVarHttpHeaderAccept
	}
	var successPayload = new(TaskWrapper)
	localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)

	var localVarURL, _ = url.Parse(localVarPath)
	localVarURL.RawQuery = localVarQueryParams.Encode()
	var localVarAPIResponse = &APIResponse{Operation: "TasksGet", Method: localVarHttpMethod, RequestURL: localVarURL.String()}
	if localVarHttpResponse != nil {
		localVarAPIResponse.Response = localVarHttpResponse.RawResponse
		localVarAPIResponse.Payload = localVarHttpResponse.Body()
	}

	if err != nil {
		return successPayload, localVarAPIResponse, err
	}
	err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload)
	return successPayload, localVarAPIResponse, err
}


text:
@interface selectAvatar ()
{
    BOOL isFullScreen;
}
@end

@implementation selectAvatar
@synthesize imageView;
@synthesize popover;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        [self addBackground:@"bg.png"];
        av = [self addImageView:self
                          image:@"avatar_ui.png"
                       position:CGPointMake(100, 32)];

    }
    return self;
}

-(void)loadCurrentPage:(int)cmd
{

    NSMutableArray *pos=[NSMutableArray array];

    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(123, 129)]];
    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(319, 129)]];
    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(516, 129)]];
    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(712, 129)]];

    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(123, 323)]];
    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(319, 323)]];
    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(516, 323)]];
    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(712, 323)]];

    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(123, 518)]];
    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(319, 518)]];
    [pos addObject:[NSValue valueWithCGPoint:CGPointMake(516, 518)]];
    //[pos addObject:[NSValue valueWithCGPoint:CGPointMake(712, 518)]];

    for (int i=0; i<[pos count]; i++) {
        CGPoint p=[[pos objectAtIndex:i] CGPointValue];

        UIButton *bt=  [self addButtonWithImageView:self
                                              image:[NSString stringWithFormat:@"avatar_%d.jpg",i+1]
                                          highlight:nil
                                           position:p
                                                  t:1000+i
                                             action:@selector(onTap:)];
    }

    [self addButton:self
              image:@"back.png"
           position:CGPointMake(30, 30)
                tag:8888
             target:self
             action:@selector(backClick:)

     ];

    [self addButton:self
              image:@"avatar_up.png"
           position:CGPointMake(726,588)
                tag:8889
             target:self
             action:@selector(chooseImage:)];

}

-(void)backClick:(UIButton*)sender
{
    [self fadeOutView:self duration:.5];
}

-(void)onTap:(UIGestureRecognizer*)sender
{

    for (int i=0; i<12; i++) {
        [self viewWithTag:1000+i].transform=CGAffineTransformMakeScale(1, 1);
    }

    [UIView animateWithDuration:.5
                     animations:^{
                         UIView *bt=[self viewWithTag:sender.view.tag];

                         [self bringSubviewToFront:bt];
                         bt.transform=CGAffineTransformMakeScale(1.2, 1.2);

                         [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d",sender.view.tag-1000+1]
                                                                   forKey:@"avatar"];

                         reg_0 *p=(reg_0*)self.superview;
                         [p updateAvatar];
                         [self fadeOutView:self duration:.5];

                     }];
}

- (IBAction)chooseImage:(id)sender {

    UIActionSheet *sheet =[[UIActionSheet alloc]initWithTitle:@"选择图片来源" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"从相册中选择",@"摄像头拍摄", nil];

    [sheet showInView:[UIApplication sharedApplication].keyWindow];

}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"butunIndex=%d",buttonIndex);
    UIViewController * viewController = [self getManager];

    switch (buttonIndex) {
        case 2:

            break;
        case 1:{
            NSLog(@"shexiang tou paishe");
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){

                UIImagePickerController *imgPicker = [UIImagePickerController new];
                imgPicker.delegate = self;
                imgPicker.allowsEditing= YES;
                imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                [viewController presentViewController:imgPicker animated:YES completion:nil];
                return;
            }
            else {

                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                    message:@"该设备没有摄像头"
                                                                   delegate:self
                                                          cancelButtonTitle:nil
                                                          otherButtonTitles:@"好", nil];
                [alertView show];

            }
        }
            break;

        case 0:{

            UIViewController * viewController = [self getManager];

            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

            // es iPad
            if ([[UIDevice currentDevice]userInterfaceIdiom] == UIUserInterfaceIdiomPad) {

                //Averiguar si está en portrait o landscape
                UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

                //PORTRAIT
                if(orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
                {

                    // [self cerrarTeclado];

                    self.popover = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
                    self.popover.delegate = self;

                    [self.popover presentPopoverFromRect:CGRectMake(600, 0, 0, 0) inView:viewController.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:NO];
                    [self.popover setPopoverContentSize:CGSizeMake(1024, 768)];

                }
                //LANDSCAPE
                if (orientation == UIInterfaceOrientationLandscapeRight || orientation == UIInterfaceOrientationLandscapeLeft)
                {

                    self.popover = [[UIPopoverController alloc] initWithContentViewController:imagePicker];
                    self.popover.delegate = self;

                    [self.popover presentPopoverFromRect:CGRectMake(600, 0, 0, 0) inView:viewController.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:NO];
                    [self.popover setPopoverContentSize:CGSizeMake(1024, 768)];

                }

            } else {
                // no es iPad
                [viewController presentViewController:imagePicker animated:YES completion:nil];
            }
        }
            break;

;

        default:

            break;
    }
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSLog(@"imageName =%@",imageName);
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录

    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];

    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    [UIApplication sharedApplication].statusBarHidden = NO;
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:@"public.image"])
    {

        UIImage *originImage = [info objectForKey:UIImagePickerControllerEditedImage];

        [self.imageView setImage:originImage];

        scaleImage = [self scaleImage:originImage toScale:0.3];

        if (UIImagePNGRepresentation(scaleImage) == nil) {

            data = UIImageJPEGRepresentation(scaleImage,1);

        } else {

            data = UIImagePNGRepresentation(scaleImage);
        }
       //将二进制数据生成UIImage
        UIImage *image = [UIImage imageWithData:data];
        [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"flag"];
        reg_0  *p=(reg_0*)self.superview;
        [p updateAvatar:image];
        [self fadeOutView:self duration:.5];

         picker.navigationBar.hidden = YES;
        [picker dismissModalViewControllerAnimated:YES];
        [popover dismissPopoverAnimated:YES];

    }

}

-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self dataCreatToCache:@".jpg" fileName:@"image"];

    return scaledImage;
}

#pragma mark 保存图片到document
-(void)dataCreatToCache:(NSData*)data fileName:(NSString*)name
{
    //或者本地路径,这边是library下
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSLibraryDirectory
                                                       , NSUserDomainMask
                                                       , YES);
    NSString *path=[paths objectAtIndex:0];
    //获取文件夹路径
    path=[path stringByAppendingPathComponent :@"image" ];
    //打开这个test文件夹,如果不存在就新建,存在就打开
    if (![[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:path
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
    }
    //将data存在image文件夹下,命名为xxx.jpg
    filePath = [NSString stringWithFormat:@"%@/%@.jpg", path ,name];

    [data writeToFile:filePath atomically:YES];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	UIViewController * viewController = [self getManager];
    [viewController dismissViewControllerAnimated:YES completion:^{}];

}

#pragma mark 从文档目录下获取Documents路径

- (NSString *)documentFolderPath
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

}

@end


text:
package chatty.gui;

import java.util.regex.Pattern;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

/**
 * A document filter that removes text based on a regular expression.
 *
 * @author tduva
 */
public class RegexDocumentFilter extends DocumentFilter {

    private final Pattern pattern;

    public RegexDocumentFilter(String regex) {
        pattern = Pattern.compile(regex);
    }

    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int off, String str, AttributeSet attr) {
        try {
            fb.insertString(off, pattern.matcher(str).replaceAll(""), attr);
        } catch (BadLocationException | NullPointerException ex) {

        }
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fb, int off, int len, String str, AttributeSet attr) {
        try {
            fb.replace(off, len, pattern.matcher(str).replaceAll(""), attr);
        } catch (BadLocationException | NullPointerException ex) {

        }
    }

}


text:
# Here are some examples of helpful functions. Feel free to
#   play around with the method calls to compute different
#   values.

# Area of a triangle

def area_of_triangle(base, height):
    return .5 * base * height

print "Triangle:", area_of_triangle(7, 4)
print

# Discriminant of the quadratic formula

def discriminant(a, b, c):
    d = b ** 2
    d -= 4 * a * c
    return d

print "Discriminant:", discriminant(1, 4, 3)
print

# Force

def force(mass, acceleration):
    return mass * acceleration

print "Force:", force(3.4, 9.8)
print

# Number of diagonals in a polygon

def num_diagonals(num_sides):
    ans = num_sides * (num_sides - 3) / 2
    return ans

print "Diagonals:", num_diagonals(7)
print

# Fat cat is Fat :)

def fat_cat(adjective):
    print adjective, "cat is", adjective

fat_cat("Fat")
fat_cat("Obvious")
print

# I love comp sci

def loves_cs(name):
    print name, "loves Computer Science!!! <3"

loves_cs("The cat")
loves_cs("The Terminator")
loves_cs("EVERYONE")


text:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.Patterns;

namespace Microsoft.AspNetCore.Routing.Matching;

public class RouteEndpointComparerTest
{
    [Fact]
    public void Compare_PrefersOrder_IfDifferent()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/", order: 1);
        var endpoint2 = CreateEndpoint("/api/foo", order: -1);

        var comparer = CreateComparer();

        // Act
        var result = comparer.Compare(endpoint1, endpoint2);

        // Assert
        Assert.Equal(1, result);
    }

    [Fact]
    public void Compare_PrefersPrecedence_IfOrderIsSame()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/api/foo", order: 1);
        var endpoint2 = CreateEndpoint("/", order: 1);

        var comparer = CreateComparer();

        // Act
        var result = comparer.Compare(endpoint1, endpoint2);

        // Assert
        Assert.Equal(1, result);
    }

    [Fact]
    public void Compare_PrefersPolicy_IfPrecedenceIsSame()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/", order: 1, new TestMetadata1());
        var endpoint2 = CreateEndpoint("/", order: 1);

        var comparer = CreateComparer(new TestMetadata1Policy());

        // Act
        var result = comparer.Compare(endpoint1, endpoint2);

        // Assert
        Assert.Equal(-1, result);
    }

    [Fact]
    public void Compare_PrefersSecondPolicy_IfFirstPolicyIsSame()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/", order: 1, new TestMetadata1());
        var endpoint2 = CreateEndpoint("/", order: 1, new TestMetadata1(), new TestMetadata2());

        var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());

        // Act
        var result = comparer.Compare(endpoint1, endpoint2);

        // Assert
        Assert.Equal(1, result);
    }

    [Fact]
    public void Compare_PrefersTemplate_IfOtherCriteriaIsSame()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/foo", order: 1, new TestMetadata1());
        var endpoint2 = CreateEndpoint("/bar", order: 1, new TestMetadata1());

        var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());

        // Act
        var result = comparer.Compare(endpoint1, endpoint2);

        // Assert
        Assert.True(result > 0);
    }

    [Fact]
    public void Compare_ReturnsZero_WhenIdentical()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/foo", order: 1, new TestMetadata1());
        var endpoint2 = CreateEndpoint("/foo", order: 1, new TestMetadata1());

        var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());

        // Act
        var result = comparer.Compare(endpoint1, endpoint2);

        // Assert
        Assert.Equal(0, result);
    }

    [Fact]
    public void Equals_NotEqual_IfOrderDifferent()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/", order: 1);
        var endpoint2 = CreateEndpoint("/api/foo", order: -1);

        var comparer = CreateComparer();

        // Act
        var result = comparer.Equals(endpoint1, endpoint2);

        // Assert
        Assert.False(result);
    }

    [Fact]
    public void Equals_NotEqual_IfPrecedenceDifferent()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/api/foo", order: 1);
        var endpoint2 = CreateEndpoint("/", order: 1);

        var comparer = CreateComparer();

        // Act
        var result = comparer.Equals(endpoint1, endpoint2);

        // Assert
        Assert.False(result);
    }

    [Fact]
    public void Equals_NotEqual_IfFirstPolicyDifferent()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/", order: 1, new TestMetadata1());
        var endpoint2 = CreateEndpoint("/", order: 1);

        var comparer = CreateComparer(new TestMetadata1Policy());

        // Act
        var result = comparer.Equals(endpoint1, endpoint2);

        // Assert
        Assert.False(result);
    }

    [Fact]
    public void Equals_NotEqual_IfSecondPolicyDifferent()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/", order: 1, new TestMetadata1());
        var endpoint2 = CreateEndpoint("/", order: 1, new TestMetadata1(), new TestMetadata2());

        var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());

        // Act
        var result = comparer.Equals(endpoint1, endpoint2);

        // Assert
        Assert.False(result);
    }

    [Fact]
    public void Equals_Equals_WhenTemplateIsDifferent()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/foo", order: 1, new TestMetadata1());
        var endpoint2 = CreateEndpoint("/bar", order: 1, new TestMetadata1());

        var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());

        // Act
        var result = comparer.Equals(endpoint1, endpoint2);

        // Assert
        Assert.True(result);
    }

    [Fact]
    public void Sort_MoreSpecific_FirstInList()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/foo", order: -1);
        var endpoint2 = CreateEndpoint("/bar/{baz}", order: -1);
        var endpoint3 = CreateEndpoint("/bar", order: 0, new TestMetadata1());
        var endpoint4 = CreateEndpoint("/foo", order: 0, new TestMetadata2());
        var endpoint5 = CreateEndpoint("/foo", order: 0);
        var endpoint6 = CreateEndpoint("/a{baz}", order: 0, new TestMetadata1(), new TestMetadata2());
        var endpoint7 = CreateEndpoint("/bar{baz}", order: 0, new TestMetadata1(), new TestMetadata2());

        // Endpoints listed in reverse of the desired order.
        var list = new List<RouteEndpoint>() { endpoint7, endpoint6, endpoint5, endpoint4, endpoint3, endpoint2, endpoint1, };

        var comparer = CreateComparer(new TestMetadata1Policy(), new TestMetadata2Policy());

        // Act
        list.Sort(comparer);

        // Assert
        Assert.Collection(
            list,
            e => Assert.Same(endpoint1, e),
            e => Assert.Same(endpoint2, e),
            e => Assert.Same(endpoint3, e),
            e => Assert.Same(endpoint4, e),
            e => Assert.Same(endpoint5, e),
            e => Assert.Same(endpoint6, e),
            e => Assert.Same(endpoint7, e));
    }

    [Fact]
    public void Compare_PatternOrder_OrdinalIgnoreCaseSort()
    {
        // Arrange
        var endpoint1 = CreateEndpoint("/I", order: 0);
        var endpoint2 = CreateEndpoint("/i", order: 0);
        var endpoint3 = CreateEndpoint("/\u0131", order: 0); // Turkish lowercase i

        var list = new List<RouteEndpoint>() { endpoint1, endpoint2, endpoint3 };

        var comparer = CreateComparer();

        // Act
        list.Sort(comparer);

        // Assert
        Assert.Collection(
            list,
            e => Assert.Same(endpoint1, e),
            e => Assert.Same(endpoint2, e),
            e => Assert.Same(endpoint3, e));
    }

    private static RouteEndpoint CreateEndpoint(string template, int order, params object[] metadata)
    {
        return new RouteEndpoint(
            TestConstants.EmptyRequestDelegate,
            RoutePatternFactory.Parse(template),
            order,
            new EndpointMetadataCollection(metadata),
            "test: " + template);
    }

    private static EndpointComparer CreateComparer(params IEndpointComparerPolicy[] policies)
    {
        return new EndpointComparer(policies);
    }

    private class TestMetadata1
    {
    }

    private class TestMetadata1Policy : IEndpointComparerPolicy
    {
        public IComparer<Endpoint> Comparer => EndpointMetadataComparer<TestMetadata1>.Default;
    }

    private class TestMetadata2
    {
    }

    private class TestMetadata2Policy : IEndpointComparerPolicy
    {
        public IComparer<Endpoint> Comparer => EndpointMetadataComparer<TestMetadata2>.Default;
    }
}


text:
<?xml version="1.0"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.commonsware.android.audio" android:versionCode="1" android:versionName="1.0">

  <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="6"/>
  <supports-screens android:largeScreens="false" android:normalScreens="true" android:smallScreens="false"/>
  <application android:icon="@drawable/cw">
    <activity android:label="AudioDemo" android:name=".AudioDemo">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
  </application>
</manifest>


text:
package com.beyondtechnicallycorrect.pong.models.velocity;

import junit.framework.Assert;

import org.junit.*;

import com.beyondtechnicallycorrect.pong.models.velocity.DirectionalVelocityInfo;
import com.beyondtechnicallycorrect.pong.models.velocity.Sanitizer;

public final class TestSanitizer {

	private static Sanitizer m_sanitizer;

	@BeforeClass
	public static void setUpClass() {
		m_sanitizer = new Sanitizer();
	}

	private void assertDirectionalVelocityInfo(
			int expectedAmountToMove,
			int expectedFramesPerMove,
			DirectionalVelocityInfo velocityInfo
		) {

		Assert.assertEquals(
				"Expected amount to move did not match with info",
				expectedAmountToMove, velocityInfo.getAmountToMove());
		Assert.assertEquals(
				"Expected frames per move did not match with info",
				expectedFramesPerMove, velocityInfo.getFramesPerMove());
	}

	@Test
	public void testSanitize_WhenOneAmountAndOneFrames_ShouldReturnSame() {
		final int AMOUNT_TO_MOVE = 1;
		final int FRAMES = 1;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);
		assertDirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenOneAmountAndTwoFrames_ShouldReturnSame() {
		final int AMOUNT_TO_MOVE = 1;
		final int FRAMES = 2;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);
		assertDirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenOneAmountAndThreeFrames_ShouldReturnSame() {
		final int AMOUNT_TO_MOVE = 1;
		final int FRAMES = 3;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);
		assertDirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenTwoAmountAndTwoFrames_ShouldReturnOneAndOne() {
		final int AMOUNT_TO_MOVE = 2;
		final int FRAMES = 2;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 1;
		final int SANITIZED_FRAMES = 1;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenThreeAmountAndTwoFrames_ShouldReturnSame() {
		final int AMOUNT_TO_MOVE = 3;
		final int FRAMES = 2;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);
		assertDirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenFourAmountAndTwoFrames_ShouldReturnTwoAndOne() {
		final int AMOUNT_TO_MOVE = 4;
		final int FRAMES = 2;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 2;
		final int SANITIZED_FRAMES = 1;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenTwoAmountAndThreeFrames_ShouldReturnSame() {
		final int AMOUNT_TO_MOVE = 2;
		final int FRAMES = 3;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);
		assertDirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenTwoAmountAndFourFrames_ShouldReturnOneAndTwo() {
		final int AMOUNT_TO_MOVE = 2;
		final int FRAMES = 4;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 1;
		final int SANITIZED_FRAME = 2;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAME, sanitized);
	}

	@Test
	public void testSanitize_WhenNegFourAmountAndTwoFrames_ShouldReturnNegTwoAndOne() {
		final int AMOUNT_TO_MOVE = -4;
		final int FRAMES = 2;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = -2;
		final int SANITIZED_FRAMES = 1;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenNegTwoAmountAndFourFrames_ShouldReturnNegOneAndTwo() {
		final int AMOUNT_TO_MOVE = -2;
		final int FRAMES = 4;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = -1;
		final int SANITIZED_FRAMES = 2;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenZeroAndOne_ShouldReturnZeroAndOne() {
		final int AMOUNT_TO_MOVE = 0;
		final int FRAMES = 1;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		assertDirectionalVelocityInfo(
				AMOUNT_TO_MOVE, FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenSixAndNine_ShouldReturnTwoAndThree() {
		final int AMOUNT_TO_MOVE = 6;
		final int FRAMES = 9;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 2;
		final int SANITIZED_FRAMES = 3;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenNineAndSix_ShouldReturnThreeAndTwo() {
		final int AMOUNT_TO_MOVE = 9;
		final int FRAMES = 6;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 3;
		final int SANITIZED_FRAMES = 2;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenNegSixAndNine_ShouldReturnNegTwoAndThree() {
		final int AMOUNT_TO_MOVE = -6;
		final int FRAMES = 9;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = -2;
		final int SANITIZED_FRAMES = 3;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenNegNineAndSix_ShouldReturnNegThreeAndTwo() {
		final int AMOUNT_TO_MOVE = -9;
		final int FRAMES = 6;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = -3;
		final int SANITIZED_FRAMES = 2;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenAtMaximumVelocityAmount_ShouldDoNormalSanitizing() {
		final int AMOUNT_TO_MOVE = 10;
		final int FRAMES = 1;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);
		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		assertDirectionalVelocityInfo(
				AMOUNT_TO_MOVE, FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenAboveMaximumVelocityAmount_ShouldFactorVelocity() {
		final int AMOUNT_TO_MOVE = 11;
		final int FRAMES = 3;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);

		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 5;
		final int SANITIZED_FRAMES = 1;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenAboveMaximumVelocityAmountAndFactoredFrameLessThanOne_ShouldSetFramesToOne() {
		final int AMOUNT_TO_MOVE = 11;
		final int FRAMES = 1;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);

		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 5;
		final int SANITIZED_FRAMES = 1;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenAboveMaximumVelocityButNegative_ShouldFactor() {
		final int AMOUNT_TO_MOVE = -11;
		final int FRAMES = 1;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);

		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = -5;
		final int SANITIZED_FRAMES = 1;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitized_WhenAtMaximumFrames_ShouldDoNormalSanitizing() {
		final int AMOUNT_TO_MOVE = 3;
		final int FRAMES = 5;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);

		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		assertDirectionalVelocityInfo(
				AMOUNT_TO_MOVE, FRAMES, sanitized);
	}

	@Test
	public void testSanitized_WhenAboveMaximumFrames_ShouldFactorVelocity() {
		final int AMOUNT_TO_MOVE = 3;
		final int FRAMES = 7;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);

		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 1;
		final int SANITIZED_FRAMES = 3;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenAboveMaximumVelocityButCanFactorBelow_ShouldFactorBelow() {
		final int AMOUNT_TO_MOVE = 14;
		final int FRAMES = 4;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);

		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 7;
		final int SANITIZED_FRAMES = 2;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

	@Test
	public void testSanitize_WhenAboveMaximumFramesButCanFactorBelow_ShouldFactorBelow() {
		final int AMOUNT_TO_MOVE = 14;
		final int FRAMES = 6;
		DirectionalVelocityInfo info =
				new DirectionalVelocityInfo(AMOUNT_TO_MOVE, FRAMES);

		DirectionalVelocityInfo sanitized = m_sanitizer.sanitize(info);

		final int SANITIZED_AMOUNT = 7;
		final int SANITIZED_FRAMES = 3;
		assertDirectionalVelocityInfo(
				SANITIZED_AMOUNT, SANITIZED_FRAMES, sanitized);
	}

}


text:
package serposcope.helpers;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author admin
 */
public class ValidatorTest {

    public ValidatorTest() {
    }

    @Test
    public void testSomeMethod() {

        assertFalse(Validator.isGenericName(null));
        assertFalse(Validator.isGenericName(" "));
        assertFalse(Validator.isGenericName("'"));
        assertFalse(Validator.isGenericName("\""));
        assertTrue(Validator.isGenericName("abc def"));
        assertTrue(Validator.isGenericName("环保部"));

    }

}


text:
@interface BaseAnimator : NSObject <DisplayLinkAnimatorDelegate>

@property(nonatomic, strong) UIView *view;

@property(nonatomic, strong) NSArray<id<DisplayLinkAnimation>> *animations;

@end


text:
using System;
using SQLite;

namespace Rosie.Node
{
	public enum CommandGenre
	{
		Basic,
		User,
		Config,
		System,
		Invalid,
	}
	public class NodeCommand
	{
		[PrimaryKey]
		public string Id { get { return $"{ClassId} - {Index}"; } set {; } }

		public int ClassId { get; set; }

		public int Index { get; set; }

		public int Instance { get; set; }

		public CommandGenre Genre { get; set; }

		public string Description { get; set; }

		public override bool Equals (object obj)
		{
			var command = obj as NodeCommand;
			if (command == null)
				return false;
			return command.Id == Id;
		}
		public override int GetHashCode ()
		{
			return Id.GetHashCode ();
		}

	}
}


text:
namespace heater
{

class TemperatureController : public IController
{
public:
  TemperatureController(util::unique_ptr<IOutput> output,
                        Sensor getMeasurement,
                        util::unique_ptr<IRegulator> regulator,
                        Setpoint getSetpoint,
                        Enabler isEnabled) :
    output(util::move(output)),
    getMeasurement(util::move(getMeasurement)),
    regulator(util::move(regulator)),
    getSetpoint(util::move(getSetpoint)),
    isEnabled(util::move(isEnabled))
  { }

  virtual ~TemperatureController() = default;

  virtual void setup() override;
  virtual void controlLoop() override;

  static util::unique_ptr<TemperatureController> getDefaultInstance();

private:
  INJECTABLE_INTERFACE(IOutput, output);
  INJECTABLE_FUNCTOR(Sensor, getMeasurement);
  INJECTABLE_INTERFACE(IRegulator, regulator);
  INJECTABLE_FUNCTOR(Setpoint, getSetpoint);
  INJECTABLE_FUNCTOR(Enabler, isEnabled);
};

} // namespace heater


text:
@interface VBRowSelfAdditionException : VBException

+ (instancetype) exceptionWithRowIndex:(NSUInteger)rowIndex;

@end


text:
<?php

namespace PersonalAccountBundle\Form;

use PersonalAccountBundle\Entity\AttendanceCollector;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class AttendanceCollectorType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('attendance_collection', CollectionType::class, ['entry_type' => AttendanceType::class,
            'label' => 'Список учеников'])
        ->add('save', SubmitType::class);
    }

    public function setDefaultOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => AttendanceCollector::class,
            'cascade_validation' => true,
        ]);
    }
}


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

namespace GuiFunctions
{

    public class BooleanOrConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            foreach (object value in values)
            {
                if ((value is bool) && (bool)value == true)
                {
                    return true;
                }
            }
            return false;
        }
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException("BooleanOrConverter is a OneWay converter.");
        }
    }
}


text:
title: "PuppetDB 3.1 » Connecting Puppet Masters to PuppetDB"
layout: default
canonical: "/puppetdb/latest/connect_puppet_master.html"
---

[puppetdb_download]: http://downloads.puppetlabs.com/puppetdb
[puppetdb_conf]: ./puppetdb_connection.html
[routes_yaml]: /puppet/latest/reference/config_file_routes.html
[exported]: /puppet/latest/reference/lang_exported.html
[install_via_module]: ./install_via_module.html
[report_processors]: /guides/reporting.html
[event]: ./api/query/v4/events.html
[report]: ./api/query/v4/reports.html
[store_report]: ./api/command/v1/commands.html#store-report-version-1
[report_format]: ./api/wire_format/report_format_v5.html
[puppetdb_server_urls]: ./puppetdb_connection.html#server_urls

> Note: To use PuppetDB, your site's puppet master(s) must be running Puppet 3.5.1 or later .

After PuppetDB is installed and running, you should configure your puppet master(s) to use it. Once connected to PuppetDB, puppet masters will do the following:

* Send every node's catalog to PuppetDB
* Send every node's facts to PuppetDB
* Query PuppetDB when compiling node catalogs that collect [exported resources][exported]

> Note: if you've [installed PuppetDB using the PuppetDB puppet module][install_via_module], then the `puppetdb::master::config` class is taking care of all of this for you.

 **Working on your puppet master server(s),** follow all of the instructions below:

## Step 1: Install Plugins

Currently, puppet masters need additional Ruby plugins in order to use PuppetDB. Unlike custom facts or functions, these cannot be loaded from a module and must be installed in Puppet's main source directory.

### On Platforms With Packages

[Enable the Puppet Labs repo](/guides/puppetlabs_package_repositories.html#open-source-repositories) and then install the `puppetdb-termini` package:

    $ sudo puppet resource package puppetdb-termini ensure=latest

### On Platforms Without Packages

If your puppet master isn't running Puppet from a supported package, you will need to install the plugins manually:

* [Download the PuppetDB source code][puppetdb_download], unzip it and navigate into the resulting directory in your terminal.
* Run `sudo cp -R puppet/lib/puppet/ /usr/lib/ruby/site_ruby/1.8/puppet`. Replace the second path with the path to your Puppet installation if you have installed it somewhere other than `/usr/lib/ruby/site_ruby`. If you are using Puppet 4 or greater, replace the second path with the path to the ruby supplied by Puppet at `/opt/puppetlabs/puppet/lib/ruby/vendor_ruby/puppet`.

## Step 2: Edit Config Files

### Locate Puppet's Config Directory

Find your puppet master's config directory by running `sudo puppet config print confdir`. It will usually be at either `/etc/puppet/` or `/etc/puppetlabs/puppet/`.

You will need to edit (or create) three files in this directory:

### 1. Edit puppetdb.conf

The [puppetdb.conf][puppetdb_conf] file will probably not exist yet. Create it, and add the PuppetDB server's URL that includes the hostname and port:

    [main]
    server_urls = https://puppetdb.example.com:8081

PuppetDB's port for secure traffic defaults to 8081 with the context root of '/'. For users that have not changed the defaults the above config (with the correct hostname) is sufficient. For more information on configuring `server_urls`, including support for multiple PuppetDB backends, see [configuring the PuppetDB server_urls][puppetdb_server_urls].

### 2. Edit puppet.conf

To enable saving facts and catalogs in PuppetDB, add the following settings to the `[master]` block of puppet.conf (or edit them if already present):

    [master]
      storeconfigs = true
      storeconfigs_backend = puppetdb

> Note: The `thin_storeconfigs` and `async_storeconfigs` settings should be absent or set to `false`. If you have previously used the puppet queue daemon (puppetqd), you should now disable it.

#### Enabling report storage

PuppetDB includes support for storing Puppet reports.  This feature can be
enabled by simply adding the `puppetdb` report processor in your `puppet.conf`
file.  If you don't already have a `reports` setting in your `puppet.conf`
file, you'll probably want to add a line like this:

    reports = store,puppetdb

This will keep Puppet's default behavior of storing the reports to disk as YAML,
while also sending the reports to PuppetDB.

You can configure how long PuppetDB stores these reports, and you can do some
very basic querying.  For more information, see:

* [The `event` query endpoint][event]
* [The `report` query endpoint][report]
* [The `store report` command][store_report]
* [The report wire format][report_format]

More information about Puppet report processors in general can be found
[here][report_processors].

### 3. Edit routes.yaml

The [routes.yaml][routes_yaml] file will probably not exist yet. The path to this Puppet configuration file can be found with the command `puppet master --configprint route_file`.

Create it if necessary, and add the following:

    ---
    master:
      facts:
        terminus: puppetdb
        cache: yaml

### Ensure proper ownership of the config files

The files created above need to be owned by the `puppet` user. Ensure that
this ownership is applied by running the following command.

    $ sudo chown -R puppet:puppet `sudo puppet config print confdir`

## Step 3: Set Security Policy

PuppetDB listens on tcp port 8081 (https). Ensure this port is open between
the Master and DB services. If the services run on the same server, no
additional configuration may be needed. If the services are on separate
servers, ensure the server and network firewalls allow the traffic flow.

PuppetDB works without modification with SELinux in enforcing mode.

## Step 4: Restart Puppet Master

Use your system's service tools to restart the puppet master service. For open source users, the command to do this will vary depending on the front-end web server being used.

> Your puppet master should now be using PuppetDB to store and retrieve catalogs, facts, and exported resources. You can test this by triggering a puppet agent run on an arbitrary node, then logging into your PuppetDB server and viewing the `/var/log/puppetlabs/puppetdb/puppetdb.log` file --- you should see calls to the "replace facts" and "replace catalog" commands:
>
>     2012-05-17 13:08:41,664 INFO  [command-proc-67] [puppetdb.command] [85beb105-5f4a-4257-a5ed-cdf0d07aa1a5] [replace facts] screech.example.com
>     2012-05-17 13:08:45,993 INFO  [command-proc-67] [puppetdb.command] [3a910863-6b33-4717-95d2-39edf92c8610] [replace catalog] screech.example.com