text:
package org.ensembl.healthcheck.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.ArrayUtils;
import org.ensembl.healthcheck.DatabaseRegistryEntry;

/**
 * The default implementation of {@link SqlTemplate} which provides all the
 * basic functionality that should be expected from a class which implements
 * this class. A {@link Connection} is passed into the constructor that is used
 * for all queries. Note that this should not be closed independently. You can
 * initialise with a {@link DatabaseRegistryEntry}
 *
 * @author ayates
 * @author dstaines
 */
public class ConnectionBasedSqlTemplateImpl implements SqlTemplate {

	public static final int FIRST_COLUMN_INDEX = 1;
	public static final int NO_ROW_LIMIT_CHECKS = -1;

	private final Connection connection;
	private final String uri;

	public String getUri() {
		return uri;
	}

	public ConnectionBasedSqlTemplateImpl(DatabaseRegistryEntry dbre) {
		this(dbre.getConnection());
	}

	public ConnectionBasedSqlTemplateImpl(Connection connection) {
		this.connection = connection;
		try {
			this.uri = connection.getMetaData().getURL();
		} catch (SQLException e) {
			throw new SqlUncheckedException("Could not get URL for connection");
		}
	}

	/**
   * {@inheritDoc}
   */
	public <T> List<T> mapResultSetToList(final ResultSet resultSet,
      final RowMapper<T> mapper, final int rowLimit, String sql,
      final Object[] args) throws SqlUncheckedException {
	  List<T> output = new ArrayList<T>();
	  mapResultSetToCollection(resultSet, mapper, rowLimit, sql, args, output);
	  return output;
	}

  /**
   * {@inheritDoc}
   */
  public <T> Set<T> mapResultSetToSet(final ResultSet resultSet,
      final RowMapper<T> mapper, final int rowLimit, String sql,
      final Object[] args) throws SqlUncheckedException {
    Set<T> output = new LinkedHashSet<T>();
    mapResultSetToCollection(resultSet, mapper, rowLimit, sql, args, output);
    return output;
  }

	public <T> void mapResultSetToCollection(final ResultSet resultSet,
			final RowMapper<T> mapper, final int rowLimit, String sql,
			final Object[] args, final Collection<T> output) throws SqlUncheckedException {
		int position = 0;
		boolean inspectRowCount = (rowLimit > 0);

		try {
			while (resultSet.next()) {

				if (inspectRowCount && position > rowLimit) {
					String expected = Integer.toString(rowLimit);
					String actual = Integer.toString(position);
					String exceptionMessage = MessageFormat
							.format("Too many rows returned. "
									+ "Expected {0} but actual row count was {1}",
									new Object[] { expected, actual });
					String message = formatExceptionMessage(exceptionMessage,
							sql, args);
					throw new SqlUncheckedException(message);
				}

				output.add(mapper.mapRow(resultSet, position));
				position++;
			}

			if (inspectRowCount && position == 0) {
				String message = formatExceptionMessage(
						"Did not find any rows", sql, args);
				throw new SqlUncheckedException(message);
			}
		} catch (SQLException e) {
			String message = formatExceptionMessage(
					"Encountered problem whilst mapping ResultSet to Object List",
					sql, args);
			throw new SqlUncheckedException(message, e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public <T> T mapResultSetToSingleObject(ResultSet resultSet,
			RowMapper<T> mapper, String sql, Object[] args)
			throws SqlUncheckedException {
		List<T> results = mapResultSetToList(resultSet, mapper, 1, sql, args);
		return results.get(0);
	}

	/**
	 * {@inheritDoc}
	 */
	public <T> T queryForObject(final String sql, final RowMapper<T> mapper,
			final Object... args) throws SqlUncheckedException {
		return execute(sql, new ResultSetCallback<T>() {
			@Override
			public T process(ResultSet rs) throws SQLException {
				return mapResultSetToSingleObject(rs, mapper, sql, args);
			}
		}, args);
	}

	/**
	 * {@inheritDoc}
	 */
	public int execute(String sql) {
		int updatedRows = -1;
		Statement st = null;
		try {
			st = connection.createStatement();
			updatedRows = st.executeUpdate(sql);
		} catch (SQLException e) {
			createUncheckedException(sql, new Object[] {}, e);
		} finally {
			closeDbObject(st);
		}
		return updatedRows;
	}

	/**
	 * {@inheritDoc}
	 */
	public <T> T execute(String sql, ResultSetCallback<T> callback,
			Object... args) {
		T object;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = connection.prepareStatement(sql);
			bindParamsToPreparedStatement(ps, args);
			rs = ps.executeQuery();
			object = callback.process(rs);
		} catch (SQLException e) {
			throw createUncheckedException(sql, args, e);
		} finally {
			closeDbObject(rs);
			closeDbObject(ps);
		}
		return object;
	}

	/**
	 * Use this to close down {@link ResultSet} objects with null safety checks
	 */
	protected void closeDbObject(ResultSet resultSet) {
		try {
			if (resultSet != null)
				resultSet.close();
		} catch (SQLException e) {
			// ignore closing exceptions here
		}
	}

	/**
	 * Use this to close down {@link Statement} objects with null safety checks
	 */
	protected void closeDbObject(Statement st) {
		try {
			if (st != null)
				st.close();
		} catch (SQLException e) {
			// ignore closing exceptions here
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public <T> List<T> queryForList(final String sql,
			final RowMapper<T> mapper, final Object... args)
			throws SqlUncheckedException {
		return execute(sql, new ResultSetCallback<List<T>>() {
			@Override
			public List<T> process(ResultSet rs) throws SQLException {
				return mapResultSetToList(rs, mapper, NO_ROW_LIMIT_CHECKS, sql,
						args);
			}
		}, args);
	}

  /**
   * {@inheritDoc}
   */
	public <T> Set<T> queryForSet(final String sql, final RowMapper<T> mapper,
	    final Object... args) {
	  return execute(sql, new ResultSetCallback<Set<T>>() {
      @Override
      public Set<T> process(ResultSet rs) throws SQLException {
        return mapResultSetToSet(rs, mapper, NO_ROW_LIMIT_CHECKS, sql,
            args);
      }
    }, args);
	}

	/**
	 * {@inheritDoc}
	 */
	public <T> T queryForDefaultObject(final String sql, final Class<T> expected,
	    final Object... args) throws SqlUncheckedException {
		DefaultObjectRowMapper<T> mapper = new DefaultObjectRowMapper<T>(
				expected, FIRST_COLUMN_INDEX);
		return queryForObject(sql, mapper, args);
	}

	/**
	 * {@inheritDoc}
	 */
	public <T> List<T> queryForDefaultObjectList(final String sql, final Class<T> expected,
	    final Object... args) throws SqlUncheckedException {
		DefaultObjectRowMapper<T> mapper = new DefaultObjectRowMapper<T>(
				expected, FIRST_COLUMN_INDEX);
		return queryForList(sql, mapper, args);
	}

  /**
   * {@inheritDoc}
   */
  public <T> Set<T> queryForDefaultObjectSet(final String sql, final Class<T> expected,
      final Object... args) throws SqlUncheckedException {
    DefaultObjectRowMapper<T> mapper = new DefaultObjectRowMapper<T>(
        expected, FIRST_COLUMN_INDEX);
    return queryForSet(sql, mapper, args);
  }

	/**
	 * {@inheritDoc}
	 */
	public <K, T> Map<K, T> queryForMap(final String sql,
			final MapRowMapper<K, T> mapRowMapper, final Object... args)
			throws SqlUncheckedException {

		return execute(sql, new ResultSetCallback<Map<K, T>>() {
			@Override
			public Map<K, T> process(ResultSet rs) throws SQLException {
				Map<K, T> targetMap = mapRowMapper.getMap();
				int position = -1;
				while (rs.next()) {
					position++;
					K key = mapRowMapper.getKey(rs);
					if (targetMap.containsKey(key)) {
						T currentValue = targetMap.get(key);
						mapRowMapper.existingObject(currentValue, rs, position);
					} else {
						T newValue = mapRowMapper.mapRow(rs, position);
						targetMap.put(key, newValue);
					}
				}
				return targetMap;
			}
		}, args);
	}

  /**
   * {@inheritDoc}
   */
	public int update(final String sql, final Object... args) {
	  PreparedStatement ps = null;
	  try {
      ps = connection.prepareStatement(sql);
      bindParamsToPreparedStatement(ps, args);
      return ps.executeUpdate();
    } catch (SQLException e) {
      throw createUncheckedException(sql, args, e);
    } finally {
      closeDbObject(ps);
    }
	}

	// ----- EXCEPTION HANDLING

	/**
	 * Used to generically raise unchecked exceptions from sql service
	 * exceptions
	 */
	private SqlUncheckedException createUncheckedException(String sql,
			Object[] params, Throwable e) {
		String message = formatExceptionMessage(
				"Could not run statement because of SqlServiceException: "+e.getMessage(), sql,
				params);
		return new SqlUncheckedException(message, e);
	}

	// -------- COMMENTED OUT BECAUSE WE HAVE NO NEED FOR THIS YET

	// private int twoDTraceLimit = 3;
	//
	// private String formatExceptionMessage(String exceptionMessage, String
	// sql,
	// Object[][] params) {
	// List<Object> listArgs = new ArrayList<Object>();
	//
	// int loop = (params.length > twoDTraceLimit) ? twoDTraceLimit
	// : params.length;
	//
	// for (int i = 0; i < loop; i++) {
	// Object[] arg = params[i];
	// listArgs.add(Arrays.toString(arg));
	// }
	//
	// if (params.length > twoDTraceLimit) {
	// listArgs.add("More params lines than can show (" + params.length
	// + ") ...");
	// }
	//
	// Object[] args = listArgs.toArray(new Object[0]);
	// return formatExceptionMessage(exceptionMessage, sql, args);
	// }

	/**
	 * Used to generate the exception messages used through this class
	 */
	private String formatExceptionMessage(String exceptionMessage, String sql,
			Object[] args) {
		String template = "{0} URI => {1} SQL => {2} PARAMS => {3}";
		String paramsString = (ArrayUtils.isEmpty(args)) ? "NONE" : Arrays
				.toString(args);
		Object[] templateArgs = new Object[] { exceptionMessage, getUri(), sql,
				paramsString };
		String message = MessageFormat.format(template, templateArgs);
		return message;
	}

	private void bindParamsToPreparedStatement(PreparedStatement st,
			Object[] arguments) throws SQLException {
		int i = 0;
		if (arguments != null) {

			for (Object arg : arguments) {
				i++;
				if (arg == null) {
					st.setNull(i, Types.NULL);
				} else if (arg instanceof String) {
					st.setString(i, (String) arg);
				} else if (arg instanceof Integer) {
					st.setInt(i, (Integer) arg);
				} else if (arg instanceof Boolean) {
					st.setBoolean(i, (Boolean) arg);
				} else if (arg instanceof Short) {
					st.setShort(i, (Short) arg);
				} else if (arg instanceof Date) {
					st.setTimestamp(i,
							new java.sql.Timestamp(((Date) arg).getTime()));
				} else if (arg instanceof java.sql.Date) {
					st.setDate(i, new java.sql.Date(((Date) arg).getTime()));
				} else if (arg instanceof Double) {
					st.setDouble(i, (Double) arg);
				} else if (arg instanceof Long) {
					st.setLong(i, (Long) arg);
				} else if (arg instanceof BigDecimal) {
					st.setObject(i, arg);
				} else if (arg instanceof BigInteger) {
					st.setObject(i, arg);
				} else { // Object
					try {
						ByteArrayOutputStream bytesS = new ByteArrayOutputStream();
						ObjectOutputStream out = new ObjectOutputStream(bytesS);
						out.writeObject(arg);
						out.close();
						byte[] bytes = bytesS.toByteArray();
						bytesS.close();
						st.setBytes(i, bytes);
					} catch (IOException e) {
						throw new SQLException("Could not serialize object "
								+ arg + " for use in a PreparedStatement ");
					}
				}
			}
		}
	}
}


text:
package org.springframework.web.socket.server.support;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.context.Lifecycle;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.Assert;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.handler.ExceptionWebSocketHandlerDecorator;
import org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator;
import org.springframework.web.socket.server.HandshakeFailureException;
import org.springframework.web.socket.server.HandshakeHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * A {@link HttpRequestHandler} for processing WebSocket handshake requests.
 *
 * <p>This is the main class to use when configuring a server WebSocket at a specific URL.
 * It is a very thin wrapper around a {@link WebSocketHandler} and a {@link HandshakeHandler},
 * also adapting the {@link HttpServletRequest} and {@link HttpServletResponse} to
 * {@link ServerHttpRequest} and {@link ServerHttpResponse}, respectively.
 *
 * @author Rossen Stoyanchev
 * @since 4.0
 */
public class WebSocketHttpRequestHandler implements HttpRequestHandler, Lifecycle, ServletContextAware {

	private final Log logger = LogFactory.getLog(WebSocketHttpRequestHandler.class);

	private final WebSocketHandler wsHandler;

	private final HandshakeHandler handshakeHandler;

	private final List<HandshakeInterceptor> interceptors = new ArrayList<>();

	private volatile boolean running = false;

	public WebSocketHttpRequestHandler(WebSocketHandler wsHandler) {
		this(wsHandler, new DefaultHandshakeHandler());
	}

	public WebSocketHttpRequestHandler(WebSocketHandler wsHandler, HandshakeHandler handshakeHandler) {
		Assert.notNull(wsHandler, "wsHandler must not be null");
		Assert.notNull(handshakeHandler, "handshakeHandler must not be null");
		this.wsHandler = new ExceptionWebSocketHandlerDecorator(new LoggingWebSocketHandlerDecorator(wsHandler));
		this.handshakeHandler = handshakeHandler;
	}

	/**
	 * Return the WebSocketHandler.
	 */
	public WebSocketHandler getWebSocketHandler() {
		return this.wsHandler;
	}

	/**
	 * Return the HandshakeHandler.
	 */
	public HandshakeHandler getHandshakeHandler() {
		return this.handshakeHandler;
	}

	/**
	 * Configure one or more WebSocket handshake request interceptors.
	 */
	public void setHandshakeInterceptors(List<HandshakeInterceptor> interceptors) {
		this.interceptors.clear();
		if (interceptors != null) {
			this.interceptors.addAll(interceptors);
		}
	}

	/**
	 * Return the configured WebSocket handshake request interceptors.
	 */
	public List<HandshakeInterceptor> getHandshakeInterceptors() {
		return this.interceptors;
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		if (this.handshakeHandler instanceof ServletContextAware) {
			((ServletContextAware) this.handshakeHandler).setServletContext(servletContext);
		}
	}

	@Override
	public boolean isRunning() {
		return this.running;
	}

	@Override
	public void start() {
		if (!isRunning()) {
			this.running = true;
			if (this.handshakeHandler instanceof Lifecycle) {
				((Lifecycle) this.handshakeHandler).start();
			}
		}
	}

	@Override
	public void stop() {
		if (isRunning()) {
			this.running = false;
			if (this.handshakeHandler instanceof Lifecycle) {
				((Lifecycle) this.handshakeHandler).stop();
			}
		}
	}

	@Override
	public void handleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
			throws ServletException, IOException {

		ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
		ServerHttpResponse response = new ServletServerHttpResponse(servletResponse);

		HandshakeInterceptorChain chain = new HandshakeInterceptorChain(this.interceptors, this.wsHandler);
		HandshakeFailureException failure = null;

		try {
			if (logger.isDebugEnabled()) {
				logger.debug(servletRequest.getMethod() + " " + servletRequest.getRequestURI());
			}
			Map<String, Object> attributes = new HashMap<>();
			if (!chain.applyBeforeHandshake(request, response, attributes)) {
				return;
			}
			this.handshakeHandler.doHandshake(request, response, this.wsHandler, attributes);
			chain.applyAfterHandshake(request, response, null);
			response.close();
		}
		catch (HandshakeFailureException ex) {
			failure = ex;
		}
		catch (Throwable ex) {
			failure = new HandshakeFailureException("Uncaught failure for request " + request.getURI(), ex);
		}
		finally {
			if (failure != null) {
				chain.applyAfterHandshake(request, response, failure);
				throw failure;
			}
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

module.exports = exportsFn;

var util = require('util');

function exportsFn(ErrorsBase){
    ErrorsBase.inherits = inheritsFromError;
}

function inheritsFromError(constructor, parent){
    util.inherits(constructor, parent);
}


text:
require 'spec_helper'

describe AttendanceParser, ".parse_attendees" do
  let(:attendance_output) { "Sebudai,1.00,233" }

  it "should return an array of hashes" do
    att = AttendanceParser.parse_attendees(attendance_output)
    att.size.should eql(1)
    att[0].class.should eql(Hash)
  end

  it "should return duplicate members when provided" do
    output = ''
    3.times { output += attendance_output + "\n" }
    att = AttendanceParser.parse_attendees(output)

    att.size.should eql(3)
  end
end

describe AttendanceParser, ".parse_loots" do
  describe "basic parsing" do
    let(:member) { Factory(:member) }
    let(:item) { Factory(:item) }

    it "should return an array of hashes" do
      loots = AttendanceParser.parse_loots("#{member.name} - [#{item.name}]")
      loots.size.should eql(1)
      loots[0].should be_a Hash
    end

    it "should figure out price based on item stats" do
      ItemPrice.instance.expects(:price).returns(2.00)
      loots = AttendanceParser.parse_loots("#{member.name} - [#{Factory(:item_with_real_stats).name}]")
      loots[0][:price].should eql(2.00)
    end

    it "should initialize a non-existent item by ID if provided" do
      Item.expects(:find_or_initialize_by_id).with('12345').returns(item)
      AttendanceParser.parse_loots("#{member.name} - [Whatever]|12345")
    end
  end

  describe "loot attributes" do
    let(:item) { Factory(:item_with_real_stats) }

    it "should return one Hash" do
      loot = AttendanceParser.parse_loots("Member - #{item.name}")
      loot[0].should be_a Hash
    end

    it "should correctly set best_in_slot" do
      loot = AttendanceParser.parse_loots("Member (bis) - #{item.name}")
      loot[0][:best_in_slot].should be_true
    end

    it "should correctly set situational" do
      loot = AttendanceParser.parse_loots("Member (sit) - #{item.name}")
      loot[0][:situational].should be_true
    end

    it "should correctly set rot" do
      loot = AttendanceParser.parse_loots("Member (rot) - #{item.name}")
      loot[0][:rot].should be_true
    end

    it "should correctly set best_in_slot and rot at the same time" do
      loot = AttendanceParser.parse_loots("Member (bis rot) - #{item.name}")
      loot[0][:best_in_slot].should be_true
      loot[0][:rot].should be_true
    end

    it "should not have false positives for purchase types inside buyer names" do
      loot = AttendanceParser.parse_loots("Membiser - #{item.name}")
      loot[0][:best_in_slot].should be_false
    end

    it "should set member as nil if buyer is 'DE'" do
      loot = AttendanceParser.parse_loots("DE - #{item.name}")
      loot[0][:member].should be_nil
    end

    context "with multiple buyers on one line" do
      let(:loot) { AttendanceParser.parse_loots("Modrack (bis), Rosoo (sit), DE - #{item.name}") }

      it "should get the correct number of buyers" do
        loot.size.should eql(3)
      end

      it "should get the correct buyer names" do
        loot[0][:member].name.should eql('Modrack')
        loot[1][:member].name.should eql('Rosoo')
        loot[2][:member].should be_nil
      end

      it "should get the correct item types" do
        loot[0][:best_in_slot].should be_true
        loot[1][:situational].should be_true
      end
    end
  end
end


text:
package com.eaglesakura.android.margarine;

import android.content.Context;
import android.support.annotation.Keep;
import android.view.View;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * 書き込み対象のメンバ変数を構築する
 */
@Keep
public abstract class FieldResourceBinder implements FieldBinder {
    /**
     * 書き込み対象メンバ変数
     */
    final Field mField;

    /**
     * Res Id
     */
    final int mResourceId;

    /**
     * NULLを認める場合はtrue
     */
    protected boolean mNullable;

    @Keep
    public FieldResourceBinder(Context context, Field field, Class annotationClass, String identifierType) {
        mField = field;
        if (!mField.isAccessible()) {
            mField.setAccessible(true);
        }

        try {
            Annotation annotation = field.getAnnotation(annotationClass);
            try {
                mNullable = (Boolean) annotation.getClass().getMethod("nullable").invoke(annotation);
            } catch (Exception e) {
            }

            final int intResId = (Integer) annotation.getClass().getMethod("value").invoke(annotation);
            final String resName = (String) annotation.getClass().getMethod("resName").invoke(annotation);

            if (intResId != 0) {
                mResourceId = intResId;
            } else {
                mResourceId = context.getResources().getIdentifier(resName, identifierType, context.getPackageName());
                if (mResourceId == 0) {
                    throw new ResourceBindError("ResourceName Error :: " + resName);
                }
            }
        } catch (ResourceBindError e) {
            throw e;
        } catch (Exception e) {
            throw new ResourceBindError(e);
        }
    }

    /**
     * 値を書き込む
     */
    @Override
    public void apply(InjectionClass srcClass, Object src, InjectionClass dstClass, Object dst) {

        try {
            onApply(srcClass, src, dstClass, dst);
        } catch (Exception e) {
            throw new ResourceBindError(e);
        }
    }

    /**
     * 値を実際に書き込む
     */
    protected abstract void onApply(InjectionClass srcClass, Object src, InjectionClass dstClass, Object dst) throws Exception;

    @Keep
    public static class FieldBinderView extends FieldResourceBinder {
        @Keep
        public FieldBinderView(Context context, Field field, Class annotationClass) {
            super(context, field, annotationClass, "id");
            valid(View.class);
        }

        @Override
        protected void onApply(InjectionClass srcClass, Object src, InjectionClass dstClass, Object dst) throws Exception {
            mField.set(dst, lazy(srcClass, src, dstClass, dst));
        }

        public Object lazy(InjectionClass srcClass, Object src, InjectionClass dstClass, Object dst) {
            try {
                return srcClass.findView(src, mResourceId);
            } catch (Throwable e) {
                if (mNullable) {
                    // Nullを認めるため、何もしない
                    return null;
                } else {
                    throw e;
                }
            }
        }
    }

    /**
     * IDE対策のため、命名を変えておく
     */
    @Keep
    public static class FieldBinderString extends FieldResourceBinder {
        @Keep
        public FieldBinderString(Context context, Field field, Class annotationClass) {
            super(context, field, annotationClass, "string");
        }

        @Override
        protected void onApply(InjectionClass srcClass, Object src, InjectionClass dstClass, Object dst) throws Exception {
            mField.set(dst, srcClass.getStringRes(src, mResourceId));
            valid(String.class);
        }
    }

    @Keep
    public static class FieldBinderInteger extends FieldResourceBinder {
        @Keep
        public FieldBinderInteger(Context context, Field field, Class annotationClass) {
            super(context, field, annotationClass, "integer");
        }

        @Override
        protected void onApply(InjectionClass srcClass, Object src, InjectionClass dstClass, Object dst) throws Exception {
            mField.setInt(dst, srcClass.getIntRes(src, mResourceId));
            valid(int.class);
        }
    }

    @Keep
    public static class FieldBinderStringArray extends FieldResourceBinder {
        @Keep
        public FieldBinderStringArray(Context context, Field field, Class annotationClass) {
            super(context, field, annotationClass, "array");
            valid(String[].class);
        }

        @Override
        protected void onApply(InjectionClass srcClass, Object src, InjectionClass dstClass, Object dst) throws Exception {
            mField.set(dst, srcClass.getStringArrayRes(src, mResourceId));
        }
    }

    void valid(Class checkType) {
        Class<?> fieldType = mField.getType();
        if (fieldType.equals(checkType)) {
            return;
        }

        if (fieldType.asSubclass(checkType) != null) {
            return;
        }

        throw new ResourceBindError(checkType.getSimpleName() + " != " + fieldType.getSimpleName());
    }
}


text:
<!DOCTYPE html>

    <title>STPCardValidator Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset="utf-8">

          Stripe Docs

        <form role="search" action="../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

            View on GitHub

      Stripe Reference

      STPCardValidator Class Reference

            Categories

                UINavigationBar(Stripe_Theme)

            Classes

                STPAPIClient

                STPAddCardViewController

                STPAddress

                STPApplePayPaymentMethod

                STPBankAccount

                STPBankAccountParams

                STPCard

                STPCardParams

                STPCardValidator

                STPCoreScrollViewController

                STPCoreTableViewController

                STPCoreViewController

                STPCustomer

                STPCustomerDeserializer

                STPImageLibrary

                STPPaymentActivityIndicatorView

                STPPaymentCardTextField

                STPPaymentConfiguration

                STPPaymentContext

                STPPaymentMethodsViewController

                STPPaymentResult

                STPShippingAddressViewController

                STPSource

                STPSourceCardDetails

                STPSourceOwner

                STPSourceParams

                STPSourceReceiver

                STPSourceRedirect

                STPSourceSEPADebitDetails

                STPSourceVerification

                STPTheme

                STPToken

                STPUserInformation

                Stripe

            Constants

                StripeDomain

            Enums

                STPBillingAddressFields

                STPCardBrand

                STPCardFundingType

                STPCardValidationState

                STPPaymentMethodType

                STPPaymentStatus

                STPShippingStatus

                STPShippingType

                STPSourceFlow

                STPSourceRedirectStatus

                STPSourceStatus

                STPSourceType

                STPSourceUsage

                STPSourceVerificationStatus

            Protocols

                STPAddCardViewControllerDelegate

                STPBackendAPIAdapter

                STPFormEncodable

                STPPaymentCardTextFieldDelegate

                STPPaymentContextDelegate

                STPPaymentMethod

                STPPaymentMethodsViewControllerDelegate

                STPShippingAddressViewControllerDelegate

                STPSourceProtocol

            Type Definitions

                STPCustomerCompletionBlock

                STPErrorBlock

                STPShippingMethodsCompletionBlock

                STPSourceCompletionBlock

                STPTokenCompletionBlock

                STPVoidBlock

STPCardValidator

@interface STPCardValidator : NSObject

This class contains static methods to validate card numbers, expiration dates, and CVCs. For a list of test card numbers to use with this code, see https://stripe.com/docs/testing

                    +sanitizedNumericStringForString:

Returns a copy of the passed string with all non-numeric characters removed.

Declaration

Objective-C

+ (nonnull NSString *)sanitizedNumericStringForString:
    (nonnull NSString *)string;

Swift

class func sanitizedNumericString(for string: String) -> String

                        Show on GitHub

                    +stringIsNumeric:

Whether or not the target string contains only numeric characters.

Declaration

Objective-C

+ (BOOL)stringIsNumeric:(nonnull NSString *)string;

Swift

class func stringIsNumeric(_ string: String) -> Bool

                        Show on GitHub

                    +validationStateForNumber:validatingCardBrand:

Validates a card number, passed as a string. This will return STPCardValidationStateInvalid for numbers that are too short or long, contain invalid characters, do not pass Luhn validation, or (optionally) do not match a number format issued by a major card brand.

Declaration

Objective-C

+ (STPCardValidationState)validationStateForNumber:
                              (nonnull NSString *)cardNumber
                               validatingCardBrand:(BOOL)validatingCardBrand;

Swift

class func validationState(forNumber cardNumber: String, validatingCardBrand: Bool) -> STPCardValidationState

Parameters

                                cardNumber

The card number to validate. Ex.
<q>
4242424242424242</q>

                                validatingCardBrand

Whether or not to enforce that the number appears to be issued by a major card brand (or could be). For example, no issuing card network currently issues card numbers beginning with the digit 9; if an otherwise correct-length and luhn-valid card number beginning with 9 (example: 9999999999999995) were passed to this method, it would return STPCardValidationStateInvalid if this parameter were YES and STPCardValidationStateValid if this parameter were NO. If unsure, you should use YES for this value.

Return Value

STPCardValidationStateValid if the number is valid, STPCardValidationStateInvalid if the number is invalid, or STPCardValidationStateIncomplete if the number is a substring of a valid card (e.g.
<q>
4242</q>).

                        Show on GitHub

                    +brandForNumber:

The card brand for a card number or substring thereof.

Declaration

Objective-C

+ (STPCardBrand)brandForNumber:(nonnull NSString *)cardNumber;

Swift

class func brand(forNumber cardNumber: String) -> STPCardBrand

Parameters

                                cardNumber

A card number, or partial card number. For example,
<q>
4242</q>,
<q>
5555555555554444</q>, or
<q>
123</q>.

Return Value

The brand for that card number. The example parameters would return STPCardBrandVisa, STPCardBrandMasterCard, and STPCardBrandUnknown, respectively.

                        Show on GitHub

                    +lengthsForCardBrand:

The possible number lengths for cards associated with a card brand. For example, Discover card numbers contain 16 characters, while American Express cards contain 15 characters.

Declaration

Objective-C

+ (nonnull NSSet<NSNumber *> *)lengthsForCardBrand:(STPCardBrand)brand;

Swift

class func lengths(for brand: STPCardBrand) -> Set

                        Show on GitHub

                    +fragmentLengthForCardBrand:

The length of the final grouping of digits to use when formatting a card number for display. For example, Visa cards display their final 4 numbers, e.g. <q>4242</q>, while American Express cards display their final 5 digits, e.g. <q>10005</q>.

Declaration

Objective-C

+ (NSInteger)fragmentLengthForCardBrand:(STPCardBrand)brand;

Swift

class func fragmentLength(for brand: STPCardBrand) -> Int

                        Show on GitHub

                    +validationStateForExpirationMonth:

Validates an expiration month, passed as an (optionally 0-padded) string. Example valid values are <q>3</q>, <q>12</q>, and <q>08</q>. Example invalid values are <q>99</q>, <q>a</q>, and <q>00</q>. Incomplete values include <q>0</q> and <q>1</q>.

Declaration

Objective-C

+ (STPCardValidationState)validationStateForExpirationMonth:
    (nonnull NSString *)expirationMonth;

Swift

class func validationState(forExpirationMonth expirationMonth: String) -> STPCardValidationState

Parameters

                                expirationMonth

A string representing a 2-digit expiration month for a payment card.

Return Value

STPCardValidationStateValid if the month is valid, STPCardValidationStateInvalid if the month is invalid, or STPCardValidationStateIncomplete if the month is a substring of a valid month (e.g.
<q>
0</q> or
<q>
1</q>).

                        Show on GitHub

                    +validationStateForExpirationYear:inMonth:

Validates an expiration year, passed as a string representing the final 2 digits of the year. This considers the period between the current year until 2099 as valid times. An example valid year value would be <q>16</q> (assuming the current year, as determined by [NSDate date], is 2015). Will return STPCardValidationStateInvalid for a month/year combination that is earlier than the current date (i.e. @<q>15</q> and @<q>04</q> in October 2015). Example invalid year values are <q>00</q>, <q>a</q>, and <q>13</q>. Any 1-digit year string will return STPCardValidationStateIncomplete.

Declaration

Objective-C

+ (STPCardValidationState)
validationStateForExpirationYear:(nonnull NSString *)expirationYear
                         inMonth:(nonnull NSString *)expirationMonth;

Swift

class func validationState(forExpirationYear expirationYear: String, inMonth expirationMonth: String) -> STPCardValidationState

Parameters

                                expirationYear

A string representing a 2-digit expiration year for a payment card.

                                expirationMonth

A string representing a valid 2-digit expiration month for a payment card. If the month is invalid (see -validationStateForExpirationMonth), this will return STPCardValidationStateInvalid.

Return Value

STPCardValidationStateValid if the year is valid, STPCardValidationStateInvalid if the year is invalid, or STPCardValidationStateIncomplete if the year is a substring of a valid year (e.g.
<q>
1</q> or
<q>
2</q>).

                        Show on GitHub

                    +maxCVCLengthForCardBrand:

The max CVC length for a card brand (for context, American Express CVCs are 4 digits, while all others are 3).

Declaration

Objective-C

+ (NSUInteger)maxCVCLengthForCardBrand:(STPCardBrand)brand;

Swift

class func maxCVCLength(for brand: STPCardBrand) -> UInt

                        Show on GitHub

                    +validationStateForCVC:cardBrand:

Validates a card’s CVC, passed as a numeric string, for the given card brand.

Declaration

Objective-C

+ (STPCardValidationState)validationStateForCVC:(nonnull NSString *)cvc
                                      cardBrand:(STPCardBrand)brand;

Swift

class func validationState(forCVC cvc: String, cardBrand brand: STPCardBrand) -> STPCardValidationState

Parameters

                                cvc

the CVC to validate

                                brand

the card brand (can be determined from the card’s number using +brandForNumber)

Return Value

Whether the CVC represents a valid CVC for that card brand. For example, would return STPCardValidationStateValid for
<q>
123</q> and STPCardBrandVisa, STPCardValidationStateValid for
<q>
1234</q> and STPCardBrandAmericanExpress, STPCardValidationStateIncomplete for
<q>
12</q> and STPCardBrandVisa, and STPCardValidationStateInvalid for
<q>
12345</q> and any brand.

                        Show on GitHub

                    +validationStateForCard:

Validates the given card details.

Declaration

Objective-C

+ (STPCardValidationState)validationStateForCard:(nonnull STPCardParams *)card;

Swift

class func validationState(forCard card: STPCardParams) -> STPCardValidationState

Parameters

                                card

the card details to validate.

Return Value

STPCardValidationStateValid if all fields are valid, STPCardValidationStateInvalid if any field is invalid, or STPCardValidationStateIncomplete if all fields are either incomplete or valid.

                        Show on GitHub

© 2017 Stripe. All rights reserved. (Last updated: 2017-03-03)

Generated by jazzy ♪♫ v0.7.4, a Realm project.


text:
package org.activiti.engine.impl.cfg;

import org.activiti.engine.api.internal.Internal;
import org.activiti.engine.impl.interceptor.CommandContext;

/**
 */
@Internal
public interface TransactionContextFactory {

  TransactionContext openTransactionContext(CommandContext commandContext);

}


text:
"""Module which provides compatibility with older Python versions."""

__all__ = ["PY3", "int", "long", "xrange", "exec_", "callable",
           "namedtuple", "property", "defaultdict"]

import sys

# --- python 2/3 compatibility layer

PY3 = sys.version_info >= (3,)

try:
    import __builtin__
except ImportError:
    import builtins as __builtin__  # py3

if PY3:
    int = int
    long = int
    xrange = range
    exec_ = getattr(__builtin__, "exec")
    print_ = getattr(__builtin__, "print")
else:
    int = int
    long = long
    xrange = xrange

    def exec_(code, globs=None, locs=None):
        if globs is None:
            frame = _sys._getframe(1)
            globs = frame.f_globals
            if locs is None:
                locs = frame.f_locals
            del frame
        elif locs is None:
            locs = globs
        exec("""exec code in globs, locs""")

    def print_(s):
        sys.stdout.write(s + '\n')
        sys.stdout.flush()

# removed in 3.0, reintroduced in 3.2
try:
    callable = callable
except Exception:
    def callable(obj):
        for klass in type(obj).__mro__:
            if "__call__" in klass.__dict__:
                return True
        return False

# --- stdlib additions

try:
    from collections import namedtuple
except ImportError:
    from operator import itemgetter as _itemgetter
    from keyword import iskeyword as _iskeyword
    import sys as _sys

    def namedtuple(typename, field_names, verbose=False, rename=False):
        """A collections.namedtuple implementation written in Python
        to support Python versions < 2.6.

        Taken from: http://code.activestate.com/recipes/500261/
        """
        # Parse and validate the field names.  Validation serves two
        # purposes, generating informative error messages and preventing
        # template injection attacks.
        if isinstance(field_names, basestring):
             # names separated by whitespace and/or commas
            field_names = field_names.replace(',', ' ').split()
        field_names = tuple(map(str, field_names))
        if rename:
            names = list(field_names)
            seen = set()
            for i, name in enumerate(names):
                if (not min(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
                    or not name or name[0].isdigit() or name.startswith('_')
                    or name in seen):
                        names[i] = '_%d' % i
                seen.add(name)
            field_names = tuple(names)
        for name in (typename,) + field_names:
            if not min(c.isalnum() or c=='_' for c in name):
                raise ValueError('Type names and field names can only contain ' \
                                 'alphanumeric characters and underscores: %r'
                                 % name)
            if _iskeyword(name):
                raise ValueError('Type names and field names cannot be a keyword: %r' \
                                 % name)
            if name[0].isdigit():
                raise ValueError('Type names and field names cannot start with a ' \
                                 'number: %r' % name)
        seen_names = set()
        for name in field_names:
            if name.startswith('_') and not rename:
                raise ValueError('Field names cannot start with an underscore: %r'
                                 % name)
            if name in seen_names:
                raise ValueError('Encountered duplicate field name: %r' % name)
            seen_names.add(name)

        # Create and fill-in the class template
        numfields = len(field_names)
        # tuple repr without parens or quotes
        argtxt = repr(field_names).replace("'", "")[1:-1]
        reprtxt = ', '.join('%s=%%r' % name for name in field_names)
        template = '''class %(typename)s(tuple):
        '%(typename)s(%(argtxt)s)' \n
        __slots__ = () \n
        _fields = %(field_names)r \n
        def __new__(_cls, %(argtxt)s):
            return _tuple.__new__(_cls, (%(argtxt)s)) \n
        @classmethod
        def _make(cls, iterable, new=tuple.__new__, len=len):
            'Make a new %(typename)s object from a sequence or iterable'
            result = new(cls, iterable)
            if len(result) != %(numfields)d:
                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
            return result \n
        def __repr__(self):
            return '%(typename)s(%(reprtxt)s)' %% self \n
        def _asdict(self):
            'Return a new dict which maps field names to their values'
            return dict(zip(self._fields, self)) \n
        def _replace(_self, **kwds):
            'Return a new %(typename)s object replacing specified fields with new values'
            result = _self._make(map(kwds.pop, %(field_names)r, _self))
            if kwds:
                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
            return result \n
        def __getnewargs__(self):
            return tuple(self) \n\n''' % locals()
        for i, name in enumerate(field_names):
            template += '        %s = _property(_itemgetter(%d))\n' % (name, i)
        if verbose:
            sys.stdout.write(template + '\n')
            sys.stdout.flush()

        # Execute the template string in a temporary namespace
        namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
                         _property=property, _tuple=tuple)
        try:
            exec_(template, namespace)
        except SyntaxError:
            e = sys.exc_info()[1]
            raise SyntaxError(e.message + ':\n' + template)
        result = namespace[typename]

        # For pickling to work, the __module__ variable needs to be set
        # to the frame where the named tuple is created.  Bypass this
        # step in enviroments where sys._getframe is not defined (Jython
        # for example) or sys._getframe is not defined for arguments
        # greater than 0 (IronPython).
        try:
            result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
        except (AttributeError, ValueError):
            pass

        return result

# hack to support property.setter/deleter on python < 2.6
# http://docs.python.org/library/functions.html?highlight=property#property
if hasattr(property, 'setter'):
    property = property
else:
    class property(__builtin__.property):
        __metaclass__ = type

        def __init__(self, fget, *args, **kwargs):
            super(property, self).__init__(fget, *args, **kwargs)
            self.__doc__ = fget.__doc__

        def getter(self, method):
            return property(method, self.fset, self.fdel)

        def setter(self, method):
            return property(self.fget, method, self.fdel)

        def deleter(self, method):
            return property(self.fget, self.fset, method)

# py 2.5 collections.defauldict
# Taken from:
# http://code.activestate.com/recipes/523034-emulate-collectionsdefaultdict/
# credits: Jason Kirtland
try:
    from collections import defaultdict
except ImportError:
    class defaultdict(dict):

        def __init__(self, default_factory=None, *a, **kw):
            if (default_factory is not None and
                not hasattr(default_factory, '__call__')):
                raise TypeError('first argument must be callable')
            dict.__init__(self, *a, **kw)
            self.default_factory = default_factory

        def __getitem__(self, key):
            try:
                return dict.__getitem__(self, key)
            except KeyError:
                return self.__missing__(key)

        def __missing__(self, key):
            if self.default_factory is None:
                raise KeyError(key)
            self[key] = value = self.default_factory()
            return value

        def __reduce__(self):
            if self.default_factory is None:
                args = tuple()
            else:
                args = self.default_factory,
            return type(self), args, None, None, self.items()

        def copy(self):
            return self.__copy__()

        def __copy__(self):
            return type(self)(self.default_factory, self)

        def __deepcopy__(self, memo):
            import copy
            return type(self)(self.default_factory,
                              copy.deepcopy(self.items()))

        def __repr__(self):
            return 'defaultdict(%s, %s)' % (self.default_factory,
                                            dict.__repr__(self))


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

<title>BatchExecutable</title>
<meta name="date" content="2018-09-30">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

bftsmart.tom.server

Interface BatchExecutable

All Superinterfaces:

Executable

All Known Implementing Classes:

DefaultRecoverable, DurabilityCoordinator

public interface BatchExecutable
extends Executable

Executables that implement this interface will receive a batch of requests and
 deliver them to the application in a deterministic way.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

byte[][]
executeBatch(byte[][] command,
            MessageContext[] msgCtx)

Execute a batch of requests.

Methods inherited from interface bftsmart.tom.server.Executable

executeUnordered

Method Detail

executeBatch

byte[][] executeBatch(byte[][] command,
                      MessageContext[] msgCtx)

Execute a batch of requests.

Parameters:

command - The batch of requests

msgCtx - The context associated to each request

Returns:

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#include "UltimateGrid/UGCtrl.h"

class CUGEditCtrl: public CUGCtrl
{
public:
	CUGEditCtrl(void);
	~CUGEditCtrl(void);

	virtual void OnSetCell(int col,long row,CUGCell *cell);
	virtual void OnDClicked(int col,long row,RECT *rect,POINT *point,BOOL processed);
	virtual void OnCharDown(UINT *vcKey,BOOL processed);
	virtual void OnKeyUp(UINT *vcKey,BOOL processed);

	bool GetHaveChange()const { return m_bHaveChange; }
	void SetHaveChange(bool bHaveChange){ m_bHaveChange=bHaveChange; }
	virtual int OnCanSizeRow(long row) {UNREFERENCED_PARAMETER(row);return FALSE; }
	virtual int OnCanSizeTopHdg() {return FALSE; }
	//virtual int OnCanSizeSideHdg() {return TRUE; }

	void DeleteSelection();

protected:

	//void LoadDefaultWidth(CString section, CString ctrlName);
	//void SaveDefaultWidth(CString section, CString ctrlName);

	bool m_bHaveChange;
	int m_nbDay;
};


text:
test / pack / Some

Some

typealias Some = SomeCoolJvmClass

Platform and version requirements: JVM

class Some

Platform and version requirements: JS

Constructors

<init>

Some()

Functions

magic

fun magic(): Unit


text:
package com.weatherforecast.app.activity;

import net.youmi.android.AdManager;
import net.youmi.android.banner.AdSize;
import net.youmi.android.banner.AdView;
import net.youmi.android.banner.AdViewListener;

import com.example.weatherforecast.ChooseAreaActivity;
import com.example.weatherforecast.R;
import com.weatherforecast.app.service.AutoUpdateService;
import com.weatherforecast.app.util.HttpCallbackListener;
import com.weatherforecast.app.util.HttpUtil;
import com.weatherforecast.app.util.Utility;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class WeatherActivity extends Activity implements OnClickListener{
	private LinearLayout weatherInfoLayout;
	/**
	 * ÓÃÓÚÏÔʾ³ÇÊÐÃû
	 */
	private TextView cityNameText;
	/**
	 * ÓÃÓÚÏÔʾ·¢²¼Ê±¼ä
	 */
	private TextView publishText;
	/**
	 * ÓÃÓÚÏÔʾÌìÆøÃèÊöÐÅÏ¢
	 */
	private TextView weatherDespText;
	/**
	 * ÓÃÓÚÏÔʾÆøÎÂ1
	 */
	private TextView temp1Text;
	/**
	 * ÓÃÓÚÏÔʾÆøÎÂ2
	 */
	private TextView temp2Text;
	/**
	 * ÓÃÓÚÏÔʾµ±Ç°ÈÕÆÚ
	 */
	private TextView currentDateText;
	/**
	 * Çл»³ÇÊа´Å¥
	 */
	private Button switchCity;
	/**
	 * ¸üÐÂÌìÆø°´Å¥
	 */
	private Button refreshWeather;

	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.weather_layout);

		//ÓÐÃ×¹ã¸æ
		context = this;
		// ³õ'»¯½Ó¿Ú£¬Ó¦ÓÃÆô¶¯µÄʱºòµ÷ÓÃ
		// ²ÎÊý£ºappId, appSecret, µ÷ÊÔģʽ
		AdManager.getInstance(context).init("aadc57227e7b8a4b", "585c9a4bc87e7ee4");

		initView();
		String countyCode=getIntent().getStringExtra("county_code");
		if(!TextUtils.isEmpty(countyCode)){
			//ÓÐÏؼ¶´úºÅʱ¾ÍÈ¥²éѯÌìÆø
			publishText.setText("ͬ²½ÖÐ...");
			weatherInfoLayout.setVisibility(View.INVISIBLE);
			cityNameText.setVisibility(View.INVISIBLE);
			queryWeatherCode(countyCode);
		}else{
			//ûÓÐÏؼ¶´úºÅ¾ÍÏÔʾ±¾µØÌìÆø
			showWeather();
		}
		switchCity.setOnClickListener(this);
		refreshWeather.setOnClickListener(this);
		showBanner();
	}

	private void initView(){
		weatherInfoLayout=(LinearLayout) findViewById(R.id.weather_info_layout);
		cityNameText=(TextView) findViewById(R.id.city_name);
		publishText=(TextView) findViewById(R.id.publish_text);
		weatherDespText=(TextView) findViewById(R.id.weather_desp);
		temp1Text=(TextView) findViewById(R.id.temp1);
		temp2Text=(TextView) findViewById(R.id.temp2);
		currentDateText=(TextView) findViewById(R.id.current_date);
		switchCity=(Button) findViewById(R.id.switch_city);
		refreshWeather=(Button) findViewById(R.id.refresh_weather);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.switch_city:
			Intent intent=new Intent(this,ChooseAreaActivity.class);
			intent.putExtra("from_weather_activity", true);
			startActivity(intent);
			finish();
			break;
		case R.id.refresh_weather:
			publishText.setText("ͬ²½ÖÐ...");
			SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(this);
			String weatherCode=preferences.getString("weather_code", "");
			if(!TextUtils.isEmpty(weatherCode)){
				queryWeatherInfo(weatherCode);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * ²éѯÏؼ¶´úºÅËù¶ÔÓ¦µÄÌìÆø´úºÅ
	 */
	private void queryWeatherCode(String countyCode){
		String address="http://www.weather.com.cn/data/list3/city"+countyCode+".xml";
		queryFromServer(address, "countyCode");
	}

	/**
	 * ²éѯÌìÆø´úºÅËù¶ÔÓ¦µÄÌìÆø
	 */
	private void queryWeatherInfo(String countyCode){
		String address="http://www.weather.com.cn/data/cityinfo/"+countyCode+".html";
		queryFromServer(address, "weatherCode");
	}

	/**
	 * ¸ù¾Ý´«ÈëµÄµØÖ·ºÍÀàÐÍÈ¥Ïò·þÎñÆ÷²éѯÌìÆø´úºÅ»òÕßÌìÆøÐÅÏ¢
	 */
	private void queryFromServer(final String address,final String type){
		HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {

			@Override
			public void onFinish(String response) {
				if("countyCode".equals(type)){
					if(!TextUtils.isEmpty(response)){
						//´Ó·þÎñÆ÷·µ»ØµÄÊý¾ÝÖнâÎö³öÌìÆø´úºÅ
						String[] array=response.split("\\|");
						if(array!=null && array.length==2){
							String weatherCode=array[1];
							queryWeatherInfo(weatherCode);
						}
					}
				}else if("weatherCode".equals(type)){
					//´¦Àí·þÎñÆ÷·µ»ØµÄÌìÆøÐÅÏ¢
					Utility.handleWeatherResponse(WeatherActivity.this, response);
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							showWeather();
						}
					});
				}
			}

			@Override
			public void onError(final Exception e) {
				Log.e("¸üÐÂÌìÆøʧ°Ü--->", e.toString());
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						publishText.setText("ͬ²½Ê§°Ü£¡");
						Toast.makeText(WeatherActivity.this, "¸üÐÂʧ°Ü£º"+e.toString(), Toast.LENGTH_SHORT).show();
					}
				});
			}
		});
	}

	/**
	 * ´ÓSharePreferencesÎļþÖжÁÈ¡´æ´¢µÄÌìÆøÐÅÏ¢£¬²¢ÏÔʾµ½½çÃæÉÏ
	 */
	private void showWeather(){
		SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(this);
		cityNameText.setText(preferences.getString("city_name", ""));
		temp1Text.setText(preferences.getString("temp1", ""));
		temp2Text.setText(preferences.getString("temp2", ""));
		weatherDespText.setText(preferences.getString("weather_desp", ""));
		publishText.setText("½ñÌì"+preferences.getString("publish_time", "")+"·¢²¼");
		currentDateText.setText(preferences.getString("current_date", ""));
		weatherInfoLayout.setVisibility(View.VISIBLE);
		cityNameText.setVisibility(View.VISIBLE);
		Intent intent=new Intent(this,AutoUpdateService.class);
		startService(intent);
	}

	private void showBanner() {

		// ¹ã¸æÌõ½Ó¿Úµ÷Óã¨ÊÊÓÃÓÚÓ¦Óã©
		// ½«¹ã¸æÌõadViewÌí¼Óµ½ÐèҪչʾµÄlayout¿Ø¼þÖÐ
		// LinearLayout adLayout = (LinearLayout) findViewById(R.id.adLayout);
		// AdView adView = new AdView(context, AdSize.FIT_SCREEN);
		// adLayout.addView(adView);

		// ¹ã¸æÌõ½Ó¿Úµ÷Óã¨ÊÊÓÃÓÚÓÎÏ·£©

		// ʵÀý»¯LayoutParams(ÖØÒª)
		FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
				FrameLayout.LayoutParams.WRAP_CONTENT);
		// ÉèÖùã¸æÌõµÄÐü¸¡Î»ÖÃ
		layoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT; // ÕâÀïʾÀýΪÓÒϽÇ
		// ʵÀý»¯¹ã¸æÌõ
		AdView adView = new AdView(context, AdSize.FIT_SCREEN);
		// µ÷ÓÃActivityµÄaddContentViewº¯Êý

		// ¼àÌý¹ã¸æÌõ½Ó¿Ú
		adView.setAdListener(new AdViewListener() {

			@Override
			public void onSwitchedAd(AdView arg0) {
				Log.i("YoumiAdDemo", "¹ã¸æÌõÇл»");
			}

			@Override
			public void onReceivedAd(AdView arg0) {
				Log.i("YoumiAdDemo", "ÇëÇó¹ã¸æ³É¹¦");

			}

			@Override
			public void onFailedToReceivedAd(AdView arg0) {
				Log.i("YoumiAdDemo", "ÇëÇó¹ã¸æʧ°Ü");
			}
		});
		((Activity) context).addContentView(adView, layoutParams);
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: xiongzai
 * Date: 15-9-21
 * Time: 下午4:26
 */
namespace app\models;

use yii\db\ActiveRecord;

class User extends ActiveRecord{

}


text:
var InternalNode = module.exports = function(order, compare) {
  this.order = order;
  this.compare = compare;
  this.isLeafNode = false;
  this.isInternalNode = true;

  this.parentNode = null;

  this.data = [];
};

InternalNode.prototype.split = function() {
  var time = Date.now();
  var m = null;
  if(this.order % 2){
    var m = (this.data.length-1)/2 - 1;
  }else{
    var m = (this.data.length-1)/2;
  }

  var tmp = new InternalNode(this.order, this.compare);
  tmp.parentNode = this.parentNode;
  for(var i=0; i<m; i++){
    tmp.data[i] = this.data.shift();
  }
  for(var i=0; i<tmp.data.length; i+=2){
    tmp.data[i].parentNode = tmp;
  }
  var key = this.data.shift();

  if(!this.parentNode){
    this.parentNode = tmp.parentNode = new InternalNode(this.order, this.compare);
  }

  return this.parentNode.insert(key, tmp, this);
};

InternalNode.prototype.insert = function(key, node1, node2) {
  if(this.data.length){
    var pos = 1;
    for(; pos < this.data.length; pos+=2){
      if(this.compare(this.data[pos], key) > 0) break;
    }

    if(pos<this.data.length) {
      pos--;
      this.data.splice(pos, 0, key);
      this.data.splice(pos, 0, node1);
    }else{
      this.data[pos-1] = node1;
      this.data.push(key);
      this.data.push(node2);
    }

    if(this.data.length > (this.order*2+1)){
      return this.split();
    }
    return null;
  }else{
    this.data[0] = node1;
    this.data[1] = key;
    this.data[2] = node2;
    return this;
  }
};


text:
#ifndef __PT_DECODER_H__
#define __PT_DECODER_H__

#include "pt_last_ip.h"
#include "pt_tnt_cache.h"

#include "intel-pt.h"

#include <stdint.h>

struct pt_decoder_function;

/* Intel(R) Processor Trace decoder flags. */
enum pt_decoder_flag {
	/* Tracing has temporarily been disabled. */
	pdf_pt_disabled		= 1 << 0,

	/* The packet will be consumed after all events have been processed. */
	pdf_consume_packet	= 1 << 1,

	/* There had been a FUP in the last PSB+. */
	pdf_status_have_ip	= 1 << 2
};

/* Intel(R) Processor Trace event bindings.
 *
 * Events are grouped by the packet the event packet binds to.
 */
enum pt_event_binding {
	evb_psbend,
	evb_tip,
	evb_fup,

	evb_max,

	/* The maximal number of pending events - should be a power of two. */
	evb_max_pend = 8
};

struct pt_decoder {
	/* The decoder configuration. */
	struct pt_config config;

	/* The current position in the trace buffer. */
	const uint8_t *pos;

	/* The position of the last PSB packet. */
	const uint8_t *sync;

	/* The decoding function for the next packet. */
	const struct pt_decoder_function *next;

	/* The last-ip. */
	struct pt_last_ip ip;

	/* The cached tnt indicators. */
	struct pt_tnt_cache tnt;

	/* A bit-vector of decoder flags. */
	uint64_t flags;

	/* The last event. */
	struct pt_event *event;

	/* A series of pending event queues. */
	struct pt_event ev_pend[evb_max][evb_max_pend];

	/* The begin and end indices for the above event queues. */
	uint8_t ev_begin[evb_max];
	uint8_t ev_end[evb_max];

	/* A standalone event that is reported immediately. */
	struct pt_event ev_immed;

	/* The current time stamp count. */
	uint64_t tsc;
};

/* Allocate an Intel(R) Processor Trace decoder.
 *
 * The decoder will work on the buffer defined via its base address and size.
 * The buffer shall contain raw trace data and remain valid for the lifetime of
 * the decoder.
 *
 * The decoder needs to be synchronized before it can be used.
 */
extern struct pt_decoder *pt_alloc_decoder(const struct pt_config *);

/* Free an Intel(R) Processor Trace decoder.
 *
 * The decoder object must not be used after a successful return.
 */
extern void pt_free_decoder(struct pt_decoder *);

/* Get the current decoder position.
 *
 * This is useful for reporting errors.
 *
 * Returns zero on success.
 *
 * Returns -pte_invalid if no @decoder is given.
 */
extern int pt_get_decoder_pos(struct pt_decoder *decoder, uint64_t *offset);

/* Get the position of the last synchronization point.
 *
 * This is useful when splitting a trace stream for parallel decoding.
 *
 * Returns zero on success.
 *
 * Returns -pte_invalid if no @decoder is given.
 */
extern int pt_get_decoder_sync(struct pt_decoder *decoder, uint64_t *offset);

/* Synchronize the decoder.
 *
 * Search for the next synchronization point in forward or backward direction.
 *
 * If the decoder has not been synchronized, yet, the search is started at the
 * beginning of the trace buffer in case of forward synchronization and at the
 * end of the trace buffer in case of backward synchronization.
 *
 * Returns zero on success.
 *
 * Returns -pte_invalid if no decoder is given.
 * Returns -pte_eos if no further synchronization point is found.
 * Returns -pte_bad_opc if the decoder encountered unknown packets.
 * Returns -pte_bad_packet if the decoder encountered unknown packet payloads.
 */
extern int pt_sync_forward(struct pt_decoder *);
extern int pt_sync_backward(struct pt_decoder *);

/* Start querying.
 *
 * Read ahead until the first query-relevant packet and return the current
 * query status.
 *
 * This function must be called once after synchronizing the decoder.
 *
 * On success, if the second parameter is not NULL, provides the linear address
 * of the first instruction in it, unless the address has been suppressed. In
 * this case, the address is set to zero.
 *
 * Returns a non-negative pt_status_flag bit-vector on success.
 *
 * Returns -pte_invalid if no decoder is given.
 * Returns -pte_nosync if the decoder is out of sync.
 * Returns -pte_eos if the end of the trace buffer is reached.
 * Returns -pte_bad_opc if the decoder encountered unknown packets.
 * Returns -pte_bad_packet if the decoder encountered unknown packet payloads.
 */
extern int pt_query_start(struct pt_decoder *, uint64_t *);

/* Get the next unconditional branch destination.
 *
 * On success, provides the linear destination address of the next unconditional
 * branch in the second parameter, provided it is not null, and updates the
 * decoder state accordingly.
 *
 * Returns a non-negative pt_status_flag bit-vector on success.
 *
 * Returns -pte_invalid if no decoder or no address is given.
 * Returns -pte_nosync if the decoder is out of sync.
 * Returns -pte_bad_query if no unconditional branch destination is found.
 * Returns -pte_bad_opc if the decoder encountered unknown packets.
 * Returns -pte_bad_packet if the decoder encountered unknown packet payloads.
 */
extern int pt_query_uncond_branch(struct pt_decoder *, uint64_t *);

/* Query whether the next unconditional branch has been taken.
 *
 * On success, provides 1 (taken) or 0 (not taken) in the second parameter for
 * the next conditional branch and updates the decoder state accordingly.
 *
 * Returns a non-negative pt_status_flag bit-vector on success.
 *
 * Returns -pte_invalid if no decoder or no address is given.
 * Returns -pte_nosync if the decoder is out of sync.
 * Returns -pte_bad_query if no conditional branch is found.
 * Returns -pte_bad_opc if the decoder encountered unknown packets.
 * Returns -pte_bad_packet if the decoder encountered unknown packet payloads.
 */
extern int pt_query_cond_branch(struct pt_decoder *, int *);

/* Query the next pending event.
 *
 * On success, provides the next event in the second parameter and updates the
 * decoder state accordingly.
 *
 * Returns a non-negative pt_status_flag bit-vector on success.
 *
 * Returns -pte_invalid if no decoder or no address is given.
 * Returns -pte_nosync if the decoder is out of sync.
 * Returns -pte_bad_query if no event is found.
 * Returns -pte_bad_opc if the decoder encountered unknown packets.
 * Returns -pte_bad_packet if the decoder encountered unknown packet payloads.
 */
extern int pt_query_event(struct pt_decoder *, struct pt_event *);

/* Query the current time stamp count.
 *
 * This returns the time stamp count at the decoder's current position. Since
 * the decoder is reading ahead until the next unconditional branch or event,
 * the value matches the time stamp count for that branch or event.
 *
 * The time stamp count is similar to what an rdtsc instruction would return.
 *
 * Beware that the time stamp count is no fully accurate and that it is updated
 * irregularly.
 *
 * Returns zero on success.
 *
 * Returns -pte_invalid if no @decoder is given.
 */
extern int pt_query_time(struct pt_decoder *, uint64_t *time);

static inline const uint8_t *pt_begin(const struct pt_decoder *decoder)
{
	return decoder->config.begin;
}

static inline const uint8_t *pt_end(const struct pt_decoder *decoder)
{
	return decoder->config.end;
}

static inline int pt_check_bounds(const struct pt_decoder *decoder, int size)
{
	const uint8_t *begin, *end;

	if (size < 0)
		return -pte_internal;

	begin = decoder->pos;
	end = pt_end(decoder);

	if (end < begin)
		return -pte_internal;

	begin += size;
	if (end < begin)
		return -pte_eos;

	return 0;
}

/* Initialize the decoder.
 *
 * Returns zero on success, a negative error code otherwise.
 */
extern int pt_decoder_init(struct pt_decoder *, const struct pt_config *);

/* Finalize the decoder. */
extern void pt_decoder_fini(struct pt_decoder *);

/* Check if decoding the next decoder function will result in an event.
 *
 * Returns 1 if it will result in an event.
 * Returns 0 if it will not result in an event.
 * Returns -pte_invalid if @decoder is NULL.
 */
extern int pt_will_event(const struct pt_decoder *decoder);

/* Reset the decoder state.
 *
 * This resets the cache fields of the decoder state. It does not modify
 * buffer-related fields.
 */
extern void pt_reset(struct pt_decoder *);

/* Get a standalone event.
 *
 * Returns a pointer to the decoder's standalone event struct.
 */
extern struct pt_event *pt_standalone_event(struct pt_decoder *);

/* Enqueue an event.
 *
 * Adds a new event to the event queue for binding @evb.
 *
 * Returns a pointer to the queued event on success.
 * Returns NULL if the queue is full.
 */
extern struct pt_event *pt_enqueue_event(struct pt_decoder *,
					 enum pt_event_binding evb);

/* Dequeue an event.
 *
 * Removes the first event from the queue for binding @evb and returns a pointer
 * to it. The pointer is valid until the next dequeue operation.
 *
 * Returns a pointer to the dequeued event on success.
 * Returns NULL if the queue is empty.
 */
extern struct pt_event *pt_dequeue_event(struct pt_decoder *,
					 enum pt_event_binding evb);

/* Clear an event queue.
 *
 * Removes all events from the event queue for binding @evb.
 */
extern void pt_discard_events(struct pt_decoder *,
			      enum pt_event_binding evb);

/* Check whether events are pending.
 *
 * Returns non-zero if there is at least one event in the event queue
 * for binding @evb.
 * Returns 0 if the event queue for binging @evb is empty.
 * Returns a negative error code otherwise.
 */
extern int pt_event_pending(const struct pt_decoder *,
			    enum pt_event_binding evb);

/* Search for an event of a specific type.
 *
 * Returns a pointer to an event of type @type in the event queue for
 * binding @evb. If there is more than one event of type @type, it is
 * undefined to which of these events the returned pointer points.
 */
extern struct pt_event *pt_find_event(struct pt_decoder *,
				      enum pt_event_type type,
				      enum pt_event_binding evb);

#endif /* __PT_DECODER_H__ */


text:
package de.hpi.bpmn2_0.factory;

import org.oryxeditor.server.diagram.Shape;

import de.hpi.bpmn2_0.annotations.StencilId;
import de.hpi.bpmn2_0.exceptions.BpmnConverterException;
import de.hpi.bpmn2_0.model.BaseElement;
import de.hpi.bpmn2_0.model.data_object.ITSystem;
import de.hpi.bpmn2_0.model.diagram.ITSystemShape;

/**
 * @author Philipp Giese
 * @author Sven Wagner-Boysen
 *
 */
@StencilId("ITSystem")
public class ITSystemFactory extends AbstractBpmnFactory {

	/* (non-Javadoc)
	 * @see de.hpi.bpmn2_0.factory.AbstractBpmnFactory#createBpmnElement(org.oryxeditor.server.diagram.Shape, de.hpi.bpmn2_0.factory.BPMNElement)
	 */
	@Override
	public BPMNElement createBpmnElement(Shape shape, BPMNElement parent)
			throws BpmnConverterException {
		ITSystemShape itSystemShape = (ITSystemShape) this.createDiagramElement(shape);
		ITSystem itSystem = (ITSystem) this.createProcessElement(shape);

		itSystemShape.setITSystemRef(itSystem);

		return new BPMNElement(itSystemShape, itSystem, shape.getResourceId());
	}

	/* (non-Javadoc)
	 * @see de.hpi.bpmn2_0.factory.AbstractBpmnFactory#createDiagramElement(org.oryxeditor.server.diagram.Shape)
	 */
	@Override
	protected Object createDiagramElement(Shape shape) {
		ITSystemShape itSystemShape = new ITSystemShape();

		this.setVisualAttributes(itSystemShape, shape);

		return itSystemShape;
	}

	/* (non-Javadoc)
	 * @see de.hpi.bpmn2_0.factory.AbstractBpmnFactory#createProcessElement(org.oryxeditor.server.diagram.Shape)
	 */
	@Override
	protected BaseElement createProcessElement(Shape shape)
			throws BpmnConverterException {
		ITSystem system = new ITSystem();
		this.setCommonAttributes(system, shape);

		system.setName(shape.getProperty("name"));
		system.setId(shape.getResourceId());

		return system;
	}

}


text:
package com.facebook.buck.python;

import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.shell.ShellStep;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.zip.Unzip;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class PexStep extends ShellStep {
  private static final String SRC_ZIP = ".src.zip";

  private final ProjectFilesystem filesystem;

  // The PEX builder environment variables.
  private final ImmutableMap<String, String> environment;

  // The PEX builder command prefix.
  private final ImmutableList<String> commandPrefix;

  // The path to the executable to create.
  private final Path destination;

  // The main module that begins execution in the PEX.
  private final String entry;

  // The map of modules to sources to package into the PEX.
  private final ImmutableMap<Path, Path> modules;

  // The map of resources to include in the PEX.
  private final ImmutableMap<Path, Path> resources;
  private final Path pythonPath;
  private final Path tempDir;

  // The map of native libraries to include in the PEX.
  private final ImmutableMap<Path, Path> nativeLibraries;

  // The list of prebuilt python libraries to add to the PEX.
  private final ImmutableSet<Path> prebuiltLibraries;

  private final boolean zipSafe;

  public PexStep(
      ProjectFilesystem filesystem,
      ImmutableMap<String, String> environment,
      ImmutableList<String> commandPrefix,
      Path pythonPath,
      Path tempDir,
      Path destination,
      String entry,
      ImmutableMap<Path, Path> modules,
      ImmutableMap<Path, Path> resources,
      ImmutableMap<Path, Path> nativeLibraries,
      ImmutableSet<Path> prebuiltLibraries,
      boolean zipSafe) {
    super(filesystem.getRootPath());

    this.filesystem = filesystem;
    this.environment = environment;
    this.commandPrefix = commandPrefix;
    this.pythonPath = pythonPath;
    this.tempDir = tempDir;
    this.destination = destination;
    this.entry = entry;
    this.modules = modules;
    this.resources = resources;
    this.nativeLibraries = nativeLibraries;
    this.prebuiltLibraries = prebuiltLibraries;
    this.zipSafe = zipSafe;
  }

  @Override
  public String getShortName() {
    return "pex";
  }

  /** Return the manifest as a JSON blob to write to the pex processes stdin.
   * <p>
   * We use stdin rather than passing as an argument to the processes since
   * manifest files can occasionally get extremely large, and surpass exec/shell
   * limits on arguments.
   */
  @Override
  protected Optional<String> getStdin(ExecutionContext context) {
    // Convert the map of paths to a map of strings before converting to JSON.
    ImmutableMap<Path, Path> resolvedModules;
    try {
      resolvedModules = getExpandedSourcePaths(modules);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    ImmutableMap.Builder<String, String> modulesBuilder = ImmutableMap.builder();
    for (ImmutableMap.Entry<Path, Path> ent : resolvedModules.entrySet()) {
      modulesBuilder.put(ent.getKey().toString(), ent.getValue().toString());
    }
    ImmutableMap.Builder<String, String> resourcesBuilder = ImmutableMap.builder();
    for (ImmutableMap.Entry<Path, Path> ent : resources.entrySet()) {
      resourcesBuilder.put(ent.getKey().toString(), ent.getValue().toString());
    }
    ImmutableMap.Builder<String, String> nativeLibrariesBuilder = ImmutableMap.builder();
    for (ImmutableMap.Entry<Path, Path> ent : nativeLibraries.entrySet()) {
      nativeLibrariesBuilder.put(ent.getKey().toString(), ent.getValue().toString());
    }
    ImmutableList.Builder<String> prebuiltLibrariesBuilder = ImmutableList.builder();
    for (Path req : prebuiltLibraries) {
      prebuiltLibrariesBuilder.add(req.toString());
    }
    try {
      return Optional.of(
          context.getObjectMapper().writeValueAsString(
              ImmutableMap.of(
                  "modules", modulesBuilder.build(),
                  "resources", resourcesBuilder.build(),
                  "nativeLibraries", nativeLibrariesBuilder.build(),
                  "prebuiltLibraries", prebuiltLibrariesBuilder.build())));
    } catch (IOException e) {
      throw Throwables.propagate(e);
    }
  }

  @Override
  protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
    ImmutableList.Builder<String> builder = ImmutableList.builder();
    builder.addAll(commandPrefix);
    builder.add("--python");
    builder.add(pythonPath.toString());
    builder.add("--entry-point");
    builder.add(entry);

    if (!zipSafe) {
      builder.add("--no-zip-safe");
    }

    builder.add(destination.toString());
    return builder.build();
  }

  @Override
  public ImmutableMap<String, String> getEnvironmentVariables(ExecutionContext context) {
    return environment;
  }

  private ImmutableMap<Path, Path> getExpandedSourcePaths(ImmutableMap<Path, Path> paths)
      throws IOException {
    ImmutableMap.Builder<Path, Path> sources = ImmutableMap.builder();

    for (ImmutableMap.Entry<Path, Path> ent : paths.entrySet()) {
      if (ent.getValue().toString().endsWith(SRC_ZIP)) {
        Path destinationDirectory = filesystem.resolve(
            tempDir.resolve(ent.getKey()));
        Files.createDirectories(destinationDirectory);

        ImmutableList<Path> zipPaths = Unzip.extractZipFile(
            filesystem.resolve(ent.getValue()),
            destinationDirectory,
            Unzip.ExistingFileMode.OVERWRITE);
        for (Path path : zipPaths) {
          Path modulePath = destinationDirectory.relativize(path);
          sources.put(modulePath, path);
        }
      } else {
        sources.put(ent.getKey(), ent.getValue());
      }
    }

    return sources.build();
  }

  @VisibleForTesting
  protected ImmutableList<String> getCommandPrefix() {
    return commandPrefix;
  }

}


text:
package core.controller.internals;

import java.awt.Color;
import java.awt.Point;

import core.ipc.repeatClient.repeatPeerClient.api.RepeatsClientApi;

public class RemoteRepeatsMouseCore extends AbstractMouseCoreImplementation {

	private RepeatsClientApi api;

	public RemoteRepeatsMouseCore(RepeatsClientApi api) {
		this.api = api;
	}

	@Override
	public Point getPosition() {
		return api.mouse().getPosition();
	}

	@Override
	public Color getColor(int x, int y) {
		return api.mouse().getColor(x, y);
	}

	@Override
	public Color getColor() {
		return api.mouse().getColor();
	}

	@Override
	public void hold(int mask, int duration) throws InterruptedException {
		api.mouse().hold(mask, duration);
	}

	@Override
	public void hold(int mask, int x, int y, int duration) throws InterruptedException {
		api.mouse().hold(mask, x, y, duration);
	}

	@Override
	public void press(int mask) {
		api.mouse().press(mask);
	}

	@Override
	public void release(int mask) {
		api.mouse().release(mask);
	}

	@Override
	public void move(int newX, int newY) {
		api.mouse().move(newX, newY);
	}

	@Override
	public void drag(int sourceX, int sourceY, int destX, int destY) {
		api.mouse().drag(sourceX, sourceY, destX, destY);
	}

	@Override
	public void moveBy(int amountX, int amountY) {
		api.mouse().moveBy(amountX, amountY);
	}

	@Override
	public void dragBy(int amountX, int amountY) {
		api.mouse().dragBy(amountX, amountY);
	}

}


text:
#include <math.h>

#include <algorithm>

#include BOSS_WEBRTC_U_logging__rtc_event_log__events__rtc_event_audio_network_adaptation_h //original-code:"logging/rtc_event_log/events/rtc_event_audio_network_adaptation.h"
#include BOSS_WEBRTC_U_logging__rtc_event_log__rtc_event_log_h //original-code:"logging/rtc_event_log/rtc_event_log.h"
#include "modules/audio_coding/audio_network_adaptor/event_log_writer.h"
#include BOSS_WEBRTC_U_rtc_base__ptr_util_h //original-code:"rtc_base/ptr_util.h"

namespace webrtc {

EventLogWriter::EventLogWriter(RtcEventLog* event_log,
                               int min_bitrate_change_bps,
                               float min_bitrate_change_fraction,
                               float min_packet_loss_change_fraction)
    : event_log_(event_log),
      min_bitrate_change_bps_(min_bitrate_change_bps),
      min_bitrate_change_fraction_(min_bitrate_change_fraction),
      min_packet_loss_change_fraction_(min_packet_loss_change_fraction) {
  RTC_DCHECK(event_log_);
}

EventLogWriter::~EventLogWriter() = default;

void EventLogWriter::MaybeLogEncoderConfig(
    const AudioEncoderRuntimeConfig& config) {
  if (last_logged_config_.num_channels != config.num_channels)
    return LogEncoderConfig(config);
  if (last_logged_config_.enable_dtx != config.enable_dtx)
    return LogEncoderConfig(config);
  if (last_logged_config_.enable_fec != config.enable_fec)
    return LogEncoderConfig(config);
  if (last_logged_config_.frame_length_ms != config.frame_length_ms)
    return LogEncoderConfig(config);
  if ((!last_logged_config_.bitrate_bps && config.bitrate_bps) ||
      (last_logged_config_.bitrate_bps && config.bitrate_bps &&
       std::abs(*last_logged_config_.bitrate_bps - *config.bitrate_bps) >=
           std::min(static_cast<int>(*last_logged_config_.bitrate_bps *
                                     min_bitrate_change_fraction_),
                    min_bitrate_change_bps_))) {
    return LogEncoderConfig(config);
  }
  if ((!last_logged_config_.uplink_packet_loss_fraction &&
       config.uplink_packet_loss_fraction) ||
      (last_logged_config_.uplink_packet_loss_fraction &&
       config.uplink_packet_loss_fraction &&
       fabs(*last_logged_config_.uplink_packet_loss_fraction -
            *config.uplink_packet_loss_fraction) >=
           min_packet_loss_change_fraction_ *
               *last_logged_config_.uplink_packet_loss_fraction)) {
    return LogEncoderConfig(config);
  }
}

void EventLogWriter::LogEncoderConfig(const AudioEncoderRuntimeConfig& config) {
  auto config_copy = rtc::MakeUnique<AudioEncoderRuntimeConfig>(config);
  event_log_->Log(
      rtc::MakeUnique<RtcEventAudioNetworkAdaptation>(std::move(config_copy)));
  last_logged_config_ = config;
}

}  // namespace webrtc