text:
/*
 * test_HDF5_loader.cpp
 *
 *  Created on: 14 Jul 2015
 *      Author: pqm78245
 */

#include "percival_processing.h"
#include <boost/test/unit_test.hpp>
#include <iostream>

const int TEST_FRAME_HEIGHT 	= 	32;
const int TEST_FRAME_WIDTH		=	512;
class fixture_test_percival_ADU_to_electron_correction{
	public:
		percival_frame<float> src_frame;
		percival_frame<float> output_frame;
		percival_calib_params calib;
		fixture_test_percival_ADU_to_electron_correction(){
			src_frame.set_frame_size(TEST_FRAME_HEIGHT, TEST_FRAME_WIDTH);
			output_frame.set_frame_size(TEST_FRAME_HEIGHT, TEST_FRAME_WIDTH);
		}
};

BOOST_FIXTURE_TEST_SUITE(percival_ADU_to_electron_correctionn_test, fixture_test_percival_ADU_to_electron_correction)

BOOST_AUTO_TEST_CASE ( output_frame_dimension_should_be_the_same_as_input ){
	int frame_width = 10;
	int frame_height = 5;
	src_frame.set_frame_size(frame_height, frame_width);
	calib.ADU_to_electrons_conversion.set_frame_size(frame_height, frame_width);
	BOOST_REQUIRE_NO_THROW(percival_ADU_to_electron_correction(src_frame, output_frame, calib));
	BOOST_REQUIRE_EQUAL(output_frame.width, frame_width);
	BOOST_REQUIRE_EQUAL(output_frame.height, frame_height);
}

BOOST_AUTO_TEST_CASE ( should_throw_if_calibration_data_and_input_data_dimension_mismatch ){
	int frame_width = 10;
	int frame_height = 5;
	src_frame.set_frame_size(frame_height, frame_width);
	BOOST_REQUIRE_NO_THROW(percival_ADU_to_electron_correction(src_frame, output_frame, calib));
	BOOST_REQUIRE_EQUAL(output_frame.width, frame_width);
	BOOST_REQUIRE_EQUAL(output_frame.height, frame_height);
}

BOOST_AUTO_TEST_CASE ( should_give_sensible_result ){
	src_frame.set_frame_size(TEST_FRAME_HEIGHT, TEST_FRAME_WIDTH);
	calib.ADU_to_electrons_conversion.set_frame_size(TEST_FRAME_HEIGHT, TEST_FRAME_WIDTH);
	output_frame.set_frame_size(TEST_FRAME_HEIGHT, TEST_FRAME_WIDTH);

	float test1S = 3.1;
	float test2S = 4.1;
	float test3S = 5.9;
	float test4S = 2.6;

	float test1R = 3.2;
	float test2R = 413;
	float test3R = 5.302;
	float test4R = 2.9;

	*(src_frame.data)												= test1S;
	*(src_frame.data + TEST_FRAME_HEIGHT * TEST_FRAME_WIDTH - 1)	= test2S;
	*(src_frame.data + 					 TEST_FRAME_WIDTH - 1)		= test3S;
	*(src_frame.data + TEST_FRAME_WIDTH * (TEST_FRAME_HEIGHT - 1) )	= test4S;

	*(calib.ADU_to_electrons_conversion.data)												= test1R;
	*(calib.ADU_to_electrons_conversion.data + TEST_FRAME_HEIGHT * TEST_FRAME_WIDTH - 1)	= test2R;
	*(calib.ADU_to_electrons_conversion.data + 					 TEST_FRAME_WIDTH - 1)		= test3R;
	*(calib.ADU_to_electrons_conversion.data + TEST_FRAME_WIDTH * (TEST_FRAME_HEIGHT - 1) )	= test4R;

	BOOST_REQUIRE_NO_THROW(percival_ADU_to_electron_correction(src_frame, output_frame, calib));
	//four corners
	BOOST_REQUIRE_CLOSE_FRACTION(*(output_frame.data), test1S / test1R, 0.01);												//upper left
	BOOST_REQUIRE_CLOSE_FRACTION(*(output_frame.data + TEST_FRAME_HEIGHT * TEST_FRAME_WIDTH - 1), test2S / test2R, 0.01);	//Lower right
	BOOST_REQUIRE_CLOSE_FRACTION(*(output_frame.data + 					  TEST_FRAME_WIDTH - 1), test3S / test3R, 0.01);	//upper right
	BOOST_REQUIRE_CLOSE_FRACTION(*(output_frame.data + TEST_FRAME_WIDTH  * (TEST_FRAME_HEIGHT - 1) ), test4S / test4R, 0.01);	//lower left
}

BOOST_AUTO_TEST_SUITE_END()


text:
module BalihooLpcClient
  class Api
    attr_accessor :config

    def initialize(config:)
      self.config = config
    end

    def authenticate!
      auth = Request::Authentication.new(api: self)
      auth.authenticate!
    end

    def campaigns(params: {})
      validate_params_and_fetch!(params: params, class: Request::Campaigns)
    end

    def tactics(campaign_id:, params: {})
      validate_params_and_fetch!(params: params, campaign_id: campaign_id, class: Request::Tactics)
    end

    def campaigns_with_tactics(params: {})
      validate_params_and_fetch!(params: params, class: Request::CampaignsWithTactics)
    end

    def metrics(tactic_id:, params: {})
      validate_params_and_fetch!(params: params, tactic_id: tactic_id, class: Request::Metrics)
    end

    def website_metrics(params: {})
      validate_params_and_fetch!(params: params, class: Request::WebsiteMetrics)
    end

    private

    def validate_params_and_fetch!(**args)
      validate_locations_key locations: args[:params][:locations]
      authenticated?

      fetch(**args)
    end

    def validate_locations_key(locations:)
      if config.location_key.nil? && locations.nil?
        raise ApiOptionError, 'must give params[:locations] since no location_key given'
      elsif config.location_key.nil? && !locations.is_a?(Array)
        raise ApiOptionError, 'locations must be an array'
      end
    end

    def authenticated?
      if config.client_id.nil? || config.client_api_key.nil?
        raise NotAuthenticatedError, 'must call authenticate! before any endpoint'
      end
    end

    def fetch(**args)
      klass = args.delete(:class)
      klass.new(api: self, **args).fetch
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.github.lgooddatepicker.zinternaltools;

import java.awt.Font;
import java.awt.FontMetrics;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import javax.swing.JTextField;

/**
 * CalculateMinimumTimeFieldSize, This class is used to calculate the minimum horizontal size needed
 * for text fields that hold times. (Such as the text field in the TimePicker component.)
 *
 *
The size that is returned is designed to be the smallest size that will hold the longest
 * displayable time under current TimePickerSettings, without cropping the text. The "longest time",
 * needs to take into account the following factors: The longest (in pixels) time in the current
 * display format, and the font object for valid times (including the font type and size). Note that
 * the locale information is built into the display format.
 */
public class CalculateMinimumTimeFieldSize {

  /**
   * getFormattedDateWidthInPixels, This returns the width (in pixels) of the longest formatted
   * time, using the supplied DateTimeFormatter instance and font. Note that the locale information
   * is built into the display format.
   *
   *
You may optionally add extra characters to the longestTimeString that is used in the
   * calculation, by supplying a nonzero value for the parameter numberOfExtraCharacters. This
   * parameter can also be used with a negative value to reduce the size that is returned.
   */
  public static int getFormattedTimeWidthInPixels(
      DateTimeFormatter formatForDisplayTime, Font fontValidTime, int numberOfExtraCharacters) {
    // Create the font metrics that will be used in the calculation.
    JTextField textField = new JTextField();
    FontMetrics fontMetrics = textField.getFontMetrics(fontValidTime);
    // Create the longest possible time.
    LocalTime longestTime = LocalTime.of(22, 59, 59, 999999999);
    // Generate the longest time string. Note, The locale is built into the formatter instance.
    String longestTimeString = longestTime.format(formatForDisplayTime);
    // Get the width of the longest time string (in pixels), using the supplied font metrics.
    int longestTimeWidth = fontMetrics.stringWidth(longestTimeString);
    // Add space for two characters.
    int singleNumericCharacterWidth = fontMetrics.stringWidth("8");
    longestTimeWidth += (2 * singleNumericCharacterWidth);
    // Don't return return anything less than 50 pixels by default.
    longestTimeWidth = (longestTimeWidth < 50) ? 50 : longestTimeWidth;
    // If requested, pad the result with space for any (programmer specified) extra characters.
    longestTimeWidth += (numberOfExtraCharacters * singleNumericCharacterWidth);
    // Return the width of the longest formatted time, in pixels.
    return longestTimeWidth;
  }
}


text:
FOUNDATION_EXPORT double FlagKitVersionNumber;
FOUNDATION_EXPORT const unsigned char FlagKitVersionString[];


text:
package org.apache.spark.sql.catalyst.plans.logical

import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap, Expression}
import org.apache.spark.sql.catalyst.plans.QueryPlan
import org.apache.spark.sql.catalyst.rules.RuleId
import org.apache.spark.sql.catalyst.rules.UnknownRuleId
import org.apache.spark.sql.catalyst.trees.{AlwaysProcess, CurrentOrigin, TreePatternBits}
import org.apache.spark.util.Utils

/**
 * [[AnalysisHelper]] defines some infrastructure for the query analyzer. In particular, in query
 * analysis we don't want to repeatedly re-analyze sub-plans that have previously been analyzed.
 *
 * This trait defines a flag `analyzed` that can be set to true once analysis is done on the tree.
 * This also provides a set of resolve methods that do not recurse down to sub-plans that have the
 * analyzed flag set to true.
 *
 * The analyzer rules should use the various resolve methods, in lieu of the various transform
 * methods defined in [[org.apache.spark.sql.catalyst.trees.TreeNode]] and [[QueryPlan]].
 *
 * To prevent accidental use of the transform methods, this trait also overrides the transform
 * methods to throw exceptions in test mode, if they are used in the analyzer.
 */
trait AnalysisHelper extends QueryPlan[LogicalPlan] { self: LogicalPlan =>

  private var _analyzed: Boolean = false

  /**
   * Recursively marks all nodes in this plan tree as analyzed.
   * This should only be called by
   * [[org.apache.spark.sql.catalyst.analysis.CheckAnalysis]].
   */
  private[sql] def setAnalyzed(): Unit = {
    if (!_analyzed) {
      _analyzed = true
      children.foreach(_.setAnalyzed())
    }
  }

  /**
   * Returns true if this node and its children have already been gone through analysis and
   * verification.  Note that this is only an optimization used to avoid analyzing trees that
   * have already been analyzed, and can be reset by transformations.
   */
  def analyzed: Boolean = _analyzed

  /**
   * Returns a copy of this node where `rule` has been recursively applied to the tree. When
   * `rule` does not apply to a given node, it is left unchanged. This function is similar to
   * `transform`, but skips sub-trees that have already been marked as analyzed.
   * Users should not expect a specific directionality. If a specific directionality is needed,
   * [[resolveOperatorsUp]] or [[resolveOperatorsDown]] should be used.
   *
   * @param rule the function used to transform this nodes children.
   */
  def resolveOperators(rule: PartialFunction[LogicalPlan, LogicalPlan]): LogicalPlan = {
    resolveOperatorsWithPruning(AlwaysProcess.fn, UnknownRuleId)(rule)
  }

  /**
   * Returns a copy of this node where `rule` has been recursively applied to the tree. When
   * `rule` does not apply to a given node, it is left unchanged. This function is similar to
   * `transform`, but skips sub-trees that have already been marked as analyzed.
   * Users should not expect a specific directionality. If a specific directionality is needed,
   * [[resolveOperatorsUpWithPruning]] or [[resolveOperatorsDownWithPruning]] should be used.
   *
   * @param rule   the function used to transform this nodes children.
   * @param cond   a Lambda expression to prune tree traversals. If `cond.apply` returns false
   *               on an operator T, skips processing T and its subtree; otherwise, processes
   *               T and its subtree recursively.
   * @param ruleId is a unique Id for `rule` to prune unnecessary tree traversals. When it is
   *               UnknownRuleId, no pruning happens. Otherwise, if `rule` (with id `ruleId`)
   *               has been marked as in effective on an operator T, skips processing T and its
   *               subtree. Do not pass it if the rule is not purely functional and reads a
   *               varying initial state for different invocations.
   */
  def resolveOperatorsWithPruning(cond: TreePatternBits => Boolean,
    ruleId: RuleId = UnknownRuleId)(rule: PartialFunction[LogicalPlan, LogicalPlan])
  : LogicalPlan = {
    resolveOperatorsDownWithPruning(cond, ruleId)(rule)
  }

  /**
   * Returns a copy of this node where `rule` has been recursively applied first to all of its
   * children and then itself (post-order, bottom-up). When `rule` does not apply to a given node,
   * it is left unchanged.  This function is similar to `transformUp`, but skips sub-trees that
   * have already been marked as analyzed.
   *
   * @param rule the function used to transform this nodes children.
   */
  def resolveOperatorsUp(rule: PartialFunction[LogicalPlan, LogicalPlan]): LogicalPlan = {
    resolveOperatorsUpWithPruning(AlwaysProcess.fn, UnknownRuleId)(rule)
  }

  /**
   * Returns a copy of this node where `rule` has been recursively applied first to all of its
   * children and then itself (post-order, bottom-up). When `rule` does not apply to a given node,
   * it is left unchanged.  This function is similar to `transformUp`, but skips sub-trees that
   * have already been marked as analyzed.
   *
   * @param rule   the function used to transform this nodes children.
   * @param cond   a Lambda expression to prune tree traversals. If `cond.apply` returns false
   *               on an operator T, skips processing T and its subtree; otherwise, processes
   *               T and its subtree recursively.
   * @param ruleId is a unique Id for `rule` to prune unnecessary tree traversals. When it is
   *               UnknownRuleId, no pruning happens. Otherwise, if `rule` (with id `ruleId`)
   *               has been marked as in effective on an operator T, skips processing T and its
   *               subtree. Do not pass it if the rule is not purely functional and reads a
   *               varying initial state for different invocations.
   */
  def resolveOperatorsUpWithPruning(cond: TreePatternBits => Boolean,
    ruleId: RuleId = UnknownRuleId)(rule: PartialFunction[LogicalPlan, LogicalPlan])
  : LogicalPlan = {
    if (!analyzed && cond.apply(self) && !isRuleIneffective(ruleId)) {
      AnalysisHelper.allowInvokingTransformsInAnalyzer {
        val afterRuleOnChildren = mapChildren(_.resolveOperatorsUpWithPruning(cond, ruleId)(rule))
        val afterRule = if (self fastEquals afterRuleOnChildren) {
          CurrentOrigin.withOrigin(origin) {
            rule.applyOrElse(self, identity[LogicalPlan])
          }
        } else {
          CurrentOrigin.withOrigin(origin) {
            rule.applyOrElse(afterRuleOnChildren, identity[LogicalPlan])
          }
        }
        if (self eq afterRule) {
          self.markRuleAsIneffective(ruleId)
          self
        } else {
          afterRule.copyTagsFrom(self)
          afterRule
        }
      }
    } else {
      self
    }
  }

  /** Similar to [[resolveOperatorsUp]], but does it top-down. */
  def resolveOperatorsDown(rule: PartialFunction[LogicalPlan, LogicalPlan]): LogicalPlan = {
    resolveOperatorsDownWithPruning(AlwaysProcess.fn, UnknownRuleId)(rule)
  }

  /** Similar to [[resolveOperatorsUpWithPruning]], but does it top-down. */
  def resolveOperatorsDownWithPruning(cond: TreePatternBits => Boolean,
    ruleId: RuleId = UnknownRuleId)(rule: PartialFunction[LogicalPlan, LogicalPlan])
  : LogicalPlan = {
    if (!analyzed && cond.apply(self) && !isRuleIneffective(ruleId)) {
      AnalysisHelper.allowInvokingTransformsInAnalyzer {
        val afterRule = CurrentOrigin.withOrigin(origin) {
          rule.applyOrElse(self, identity[LogicalPlan])
        }

        // Check if unchanged and then possibly return old copy to avoid gc churn.
        if (self fastEquals afterRule) {
          val rewritten_plan = mapChildren(_.resolveOperatorsDownWithPruning(cond, ruleId)(rule))
          if (self eq rewritten_plan) {
            self.markRuleAsIneffective(ruleId)
            self
          } else {
            rewritten_plan
          }
        } else {
          afterRule.mapChildren(_.resolveOperatorsDownWithPruning(cond, ruleId)(rule))
        }
      }
    } else {
      self
    }
  }

  /**
   * A variant of `transformUpWithNewOutput`, which skips touching already analyzed plan.
   */
  def resolveOperatorsUpWithNewOutput(
      rule: PartialFunction[LogicalPlan, (LogicalPlan, Seq[(Attribute, Attribute)])])
  : LogicalPlan = {
    if (!analyzed) {
      transformUpWithNewOutput(rule, skipCond = _.analyzed, canGetOutput = _.resolved)
    } else {
      self
    }
  }

  override def transformUpWithNewOutput(
      rule: PartialFunction[LogicalPlan, (LogicalPlan, Seq[(Attribute, Attribute)])],
      skipCond: LogicalPlan => Boolean,
      canGetOutput: LogicalPlan => Boolean): LogicalPlan = {
    AnalysisHelper.allowInvokingTransformsInAnalyzer {
      super.transformUpWithNewOutput(rule, skipCond, canGetOutput)
    }
  }

  override def updateOuterReferencesInSubquery(plan: LogicalPlan, attrMap: AttributeMap[Attribute])
    : LogicalPlan = {
    AnalysisHelper.allowInvokingTransformsInAnalyzer {
      super.updateOuterReferencesInSubquery(plan, attrMap)
    }
  }

  /**
   * Recursively transforms the expressions of a tree, skipping nodes that have already
   * been analyzed.
   */
  def resolveExpressions(r: PartialFunction[Expression, Expression]): LogicalPlan = {
    resolveExpressionsWithPruning(AlwaysProcess.fn, UnknownRuleId)(r)
  }

  /**
   * Recursively transforms the expressions of a tree, skipping nodes that have already
   * been analyzed.
   *
   * @param rule   the function used to transform this nodes children.
   * @param cond   a Lambda expression to prune tree traversals. If `cond.apply` returns false
   *               on a TreeNode T, skips processing T and its subtree; otherwise, processes
   *               T and its subtree recursively.
   * @param ruleId is a unique Id for `rule` to prune unnecessary tree traversals. When it is
   *               UnknownRuleId, no pruning happens. Otherwise, if `rule` (with id `ruleId`)
   *               has been marked as in effective on a TreeNode T, skips processing T and its
   *               subtree. Do not pass it if the rule is not purely functional and reads a
   *               varying initial state for different invocations.
   */
  def resolveExpressionsWithPruning(cond: TreePatternBits => Boolean,
    ruleId: RuleId = UnknownRuleId)(rule: PartialFunction[Expression, Expression]): LogicalPlan = {
    resolveOperatorsWithPruning(cond, ruleId) {
      case p => p.transformExpressionsWithPruning(cond, ruleId)(rule)
    }
  }

  protected def assertNotAnalysisRule(): Unit = {
    if (Utils.isTesting &&
        AnalysisHelper.inAnalyzer.get > 0 &&
        AnalysisHelper.resolveOperatorDepth.get == 0) {
      throw new RuntimeException("This method should not be called in the analyzer")
    }
  }

  /**
   * In analyzer, use [[resolveOperatorsDown()]] instead. If this is used in the analyzer,
   * an exception will be thrown in test mode. It is however OK to call this function within
   * the scope of a [[resolveOperatorsDown()]] call.
   * @see [[org.apache.spark.sql.catalyst.trees.TreeNode.transformDownWithPruning()]].
   */
  override def transformDownWithPruning(cond: TreePatternBits => Boolean,
    ruleId: RuleId = UnknownRuleId)(rule: PartialFunction[LogicalPlan, LogicalPlan])
  : LogicalPlan = {
    assertNotAnalysisRule()
    super.transformDownWithPruning(cond, ruleId)(rule)
  }

  /**
   * Use [[resolveOperators()]] in the analyzer.
   *
   * @see [[org.apache.spark.sql.catalyst.trees.TreeNode.transformUpWithPruning()]]
   */
  override def transformUpWithPruning(cond: TreePatternBits => Boolean,
    ruleId: RuleId = UnknownRuleId)(rule: PartialFunction[LogicalPlan, LogicalPlan])
  : LogicalPlan = {
    assertNotAnalysisRule()
    super.transformUpWithPruning(cond, ruleId)(rule)
  }

  /**
   * Use [[resolveExpressions()]] in the analyzer.
   * @see [[QueryPlan.transformAllExpressionsWithPruning()]]
   */
  override def transformAllExpressionsWithPruning(
    cond: TreePatternBits => Boolean,
    ruleId: RuleId = UnknownRuleId)(rule: PartialFunction[Expression, Expression])
  : this.type = {
    assertNotAnalysisRule()
    super.transformAllExpressionsWithPruning(cond, ruleId)(rule)
  }

  override def clone(): LogicalPlan = {
    val cloned = super.clone()
    if (analyzed) cloned.setAnalyzed()
    cloned
  }
}

object AnalysisHelper {

  /**
   * A thread local to track whether we are in a resolveOperator call (for the purpose of analysis).
   * This is an int because resolve* calls might be be nested (e.g. a rule might trigger another
   * query compilation within the rule itself), so we are tracking the depth here.
   */
  private val resolveOperatorDepth: ThreadLocal[Int] = new ThreadLocal[Int] {
    override def initialValue(): Int = 0
  }

  /**
   * A thread local to track whether we are in the analysis phase of query compilation. This is an
   * int rather than a boolean in case our analyzer recursively calls itself.
   */
  private val inAnalyzer: ThreadLocal[Int] = new ThreadLocal[Int] {
    override def initialValue(): Int = 0
  }

  def allowInvokingTransformsInAnalyzer[T](f: => T): T = {
    resolveOperatorDepth.set(resolveOperatorDepth.get + 1)
    try f finally {
      resolveOperatorDepth.set(resolveOperatorDepth.get - 1)
    }
  }

  def markInAnalyzer[T](f: => T): T = {
    inAnalyzer.set(inAnalyzer.get + 1)
    try f finally {
      inAnalyzer.set(inAnalyzer.get - 1)
    }
  }
}


text:
module.exports = function(sequelize, DataTypes) {
    var Note = sequelize.define("note", {
        note: {
            type: DataTypes.TEXT,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        }
    });

    Note.associate = function(models) {
        // We're saying that a Post should belong to an Author
        // A Post can't be created without an Author due to the foreign key constraint
        Note.belongsTo(models.note_type, {
            foreignKey: {
                allowNull: false
            }
        });
    };

    return Note;
};


text: python3 execute.py source_unity_3dball player_PPO_1A --load unity_3dball_ppo --run


text:
#pragma once

#include "geometry/grassmann.hpp"
#include "geometry/named_quantities.hpp"
#include "gmock/gmock.h"
#include "physics/dynamic_frame.hpp"
#include "physics/rigid_motion.hpp"

namespace principia {
namespace physics {
namespace internal_dynamic_frame {

template<typename InertialFrame, typename ThisFrame>
class MockDynamicFrame : public DynamicFrame<InertialFrame, ThisFrame> {
 public:
  MockDynamicFrame() {}

  MOCK_CONST_METHOD1_T(ToThisFrameAtTime,
                       RigidMotion<InertialFrame, ThisFrame>(Instant const& t));
  MOCK_CONST_METHOD1_T(FromThisFrameAtTime,
                       RigidMotion<ThisFrame, InertialFrame>(Instant const& t));

  MOCK_CONST_METHOD0(t_min, Instant());
  MOCK_CONST_METHOD0(t_max, Instant());

  MOCK_CONST_METHOD2_T(
      GeometricAcceleration,
      Vector<Acceleration, ThisFrame>(
          Instant const& t,
          DegreesOfFreedom<ThisFrame> const& degrees_of_freedom));

  using Rot = Rotation<Frenet<ThisFrame>, ThisFrame>;

  MOCK_CONST_METHOD2_T(
      FrenetFrame,
      Rot(Instant const& t,
          DegreesOfFreedom<ThisFrame> const& degrees_of_freedom));

  MOCK_CONST_METHOD1_T(
      WriteToMessage,
      void(not_null<serialization::DynamicFrame*> message));

 private:
  MOCK_CONST_METHOD2_T(
      GravitationalAcceleration,
      Vector<Acceleration, InertialFrame>(Instant const& t,
                                          Position<InertialFrame> const& q));
  MOCK_CONST_METHOD1_T(
      MotionOfThisFrame,
      AcceleratedRigidMotion<InertialFrame, ThisFrame>(Instant const& t));
};

}  // namespace internal_dynamic_frame

using internal_dynamic_frame::MockDynamicFrame;

}  // namespace physics
}  // namespace principia


text:
import { Meteor } from 'meteor/meteor'
import { Accounts } from 'meteor/accounts-base'
import { Roles } from 'meteor/alanning:roles'
import { check } from 'meteor/check'

Meteor.methods({
  createNewUser: (options, roles) => {
    check(options, {
      email: String,
      password: String,
      profile: { name: Object, address: Object },
    })
    check(roles, [String])

    const userId = Meteor.userId()
    if (!Roles.userIsInRole(userId, ['admin'])) {
      throw new Meteor.Error('Not enough rights', 'Only admins can create new users!')
    }
    const newUserId = Accounts.createUser(options)

    // Possibly send out an enrollment email...
    // Accounts.sendEnrollmentEmail(newUserId);

    Roles.addUsersToRoles(newUserId, roles)
  },
})


text:
.. _index:

*********************************
:mod:`pyrad` -- RADIUS for Python
*********************************

:Author: Wichert Akkerman
:Version: |version|

.. module:: pyrad

Introduction
============

pyrad is an implementation of a RADIUS client as described in RFC2865.
It takes care of all the details like building RADIUS packets, sending
them and decoding responses.

Here is an example of doing a authentication request::

  import pyrad.packet
  from pyrad.client import Client
  from pyrad.dictionary import Dictionary

  srv=Client(server="radius.my.domain", secret="s3cr3t",
  	dict=Dictionary("dicts/dictionary", "dictionary.acc"))

  req=srv.CreateAuthPacket(code=pyrad.packet.AccessRequest,
  		User_Name="wichert", NAS_Identifier="localhost")
  req["User-Password"]=req.PwCrypt("password")

  reply=srv.SendPacket(req)
  if reply.code==pyrad.packet.AccessAccept:
      print "access accepted"
  else:
      print "access denied"

  print "Attributes returned by server:"
  for i in reply.keys():
      print "%s: %s" % (i, reply[i])

Requirements & Installation
===========================

pyrad requires Python 2.6 or later, or Python 3.2 or later

Installing is simple; pyrad uses the standard distutils system for installing
Python modules::

  python setup.py install

API Documentation
=================

Per-module :mod:`pyrad` API documentation.

.. toctree::
   :maxdepth: 2

   api/client
   api/dictionary
   api/host
   api/packet
   api/proxy
   api/server

Indices and tables
------------------

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
<?php
namespace Nakade\Stats\Games;

use Nakade\Stats\GameStats;
/**
 * Class SuspendedGames
 *
 * @package Nakade\Stats\Games
 */
class SuspendedGames extends GameStats
{

    /**
     * @param int $playerId
     *
     * @return int
     */
    public function getNumberOfGames($playerId)
    {

        $count=0;
        /* @var $match \Season\Entity\Match */
        foreach ($this->getMatches() as $match) {

            if (!$match->hasResult() || $match->getResult()->getResultType()->getId() != self::SUSPENDED) {
                continue;
            }

            if ($match->getBlack()->getId() == $playerId || $match->getWhite()->getId() == $playerId) {
                $count++;
            }
        }

        return $count;
    }
}


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

	<string name="hello">Hello World, ThreadDemoActivity!</string>
	<string name="app_name">ThreadDemo</string>

</resources>


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "glossEvent".
 *
 * @property integer $id
 * @property integer $event
 * @property string $name
 */
class GlossEvent extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'glossEvent';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['event'], 'integer'],
            [['name'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'event' => 'Event',
            'name' => 'Name',
        ];
    }
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
#include <string_view>
#include <vector>

#include <gmock/gmock-matchers.h>
#include <gtest/gtest.h>

#include "arrow/array.h"
#include "arrow/array/builder_binary.h"
#include "arrow/buffer.h"
#include "arrow/memory_pool.h"
#include "arrow/status.h"
#include "arrow/testing/builder.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/testing/util.h"
#include "arrow/type.h"
#include "arrow/type_traits.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/bitmap_builders.h"
#include "arrow/util/checked_cast.h"
#include "arrow/visit_data_inline.h"

namespace arrow {

using internal::checked_cast;

// ----------------------------------------------------------------------
// String / Binary tests

template <typename ArrayType>
void CheckStringArray(const ArrayType& array, const std::vector<std::string>& strings,
                      const std::vector<uint8_t>& is_valid, int repeats = 1) {
  int64_t length = array.length();
  int64_t base_length = static_cast<int64_t>(strings.size());
  ASSERT_EQ(base_length, static_cast<int64_t>(is_valid.size()));
  ASSERT_EQ(base_length * repeats, length);

  int32_t value_pos = 0;
  for (int i = 0; i < length; ++i) {
    auto j = i % base_length;
    if (is_valid[j]) {
      ASSERT_FALSE(array.IsNull(i));
      auto view = array.GetView(i);
      ASSERT_EQ(value_pos, array.value_offset(i));
      ASSERT_EQ(strings[j].size(), view.size());
      ASSERT_EQ(std::string_view(strings[j]), view);
      value_pos += static_cast<int32_t>(view.size());
    } else {
      ASSERT_TRUE(array.IsNull(i));
    }
  }
}

template <typename T>
class TestStringArray : public ::testing::Test {
 public:
  using TypeClass = T;
  using offset_type = typename TypeClass::offset_type;
  using ArrayType = typename TypeTraits<TypeClass>::ArrayType;
  using BuilderType = typename TypeTraits<TypeClass>::BuilderType;

  void SetUp() {
    chars_ = {'a', 'b', 'b', 'c', 'c', 'c'};
    offsets_ = {0, 1, 1, 1, 3, 6};
    valid_bytes_ = {1, 1, 0, 1, 1};
    expected_ = {"a", "", "", "bb", "ccc"};

    MakeArray();
  }

  void MakeArray() {
    length_ = static_cast<int64_t>(offsets_.size()) - 1;
    value_buf_ = Buffer::Wrap(chars_);
    offsets_buf_ = Buffer::Wrap(offsets_);
    ASSERT_OK_AND_ASSIGN(null_bitmap_, internal::BytesToBits(valid_bytes_));
    null_count_ = CountNulls(valid_bytes_);

    strings_ = std::make_shared<ArrayType>(length_, offsets_buf_, value_buf_,
                                           null_bitmap_, null_count_);
  }

  void TestArrayBasics() {
    ASSERT_EQ(length_, strings_->length());
    ASSERT_EQ(1, strings_->null_count());
    ASSERT_OK(strings_->ValidateFull());
    TestInitialized(*strings_);
    AssertZeroPadded(*strings_);
  }

  void TestArrayIndexOperator() {
    const auto& arr = *strings_;
    for (int64_t i = 0; i < arr.length(); ++i) {
      if (valid_bytes_[i]) {
        ASSERT_TRUE(arr[i].has_value());
        ASSERT_EQ(expected_[i], arr[i].value());
      } else {
        ASSERT_FALSE(arr[i].has_value());
      }
    }
  }

  void TestArrayCtors() {
    // ARROW-8863: ArrayData::null_count set to 0 when no validity bitmap
    // provided
    ArrayType arr(length_, offsets_buf_, value_buf_);
    ASSERT_EQ(arr.data()->null_count, 0);
  }

  void TestTotalValuesLength() {
    auto ty = TypeTraits<T>::type_singleton();
    auto arr = ArrayFromJSON(ty, R"(["a", null, "bbb", "cccc", "ddddd"])");

    offset_type values_length = arr.total_values_length();
    ASSERT_EQ(values_length, static_cast<offset_type>(13));

    offset_type sliced_values_length =
        checked_cast<const ArrayType&>(*arr.Slice(3)).total_values_length();
    ASSERT_EQ(sliced_values_length, static_cast<offset_type>(9));

    // Zero-length array is a special case
    offset_type zero_size_length =
        checked_cast<const ArrayType&>(*arr.Slice(0, 0)).total_values_length();
    ASSERT_EQ(zero_size_length, static_cast<offset_type>(0));
  }

  void TestType() {
    std::shared_ptr<DataType> type = this->strings_->type();

    if (std::is_same<TypeClass, StringType>::value) {
      ASSERT_EQ(Type::STRING, type->id());
      ASSERT_EQ(Type::STRING, this->strings_->type_id());
    } else if (std::is_same<TypeClass, LargeStringType>::value) {
      ASSERT_EQ(Type::LARGE_STRING, type->id());
      ASSERT_EQ(Type::LARGE_STRING, this->strings_->type_id());
    } else if (std::is_same<TypeClass, BinaryType>::value) {
      ASSERT_EQ(Type::BINARY, type->id());
      ASSERT_EQ(Type::BINARY, this->strings_->type_id());
    } else if (std::is_same<TypeClass, LargeBinaryType>::value) {
      ASSERT_EQ(Type::LARGE_BINARY, type->id());
      ASSERT_EQ(Type::LARGE_BINARY, this->strings_->type_id());
    } else {
      FAIL();
    }
  }

  void TestListFunctions() {
    int64_t pos = 0;
    for (size_t i = 0; i < expected_.size(); ++i) {
      ASSERT_EQ(pos, strings_->value_offset(i));
      ASSERT_EQ(expected_[i].size(), strings_->value_length(i));
      pos += expected_[i].size();
    }
  }

  void TestDestructor() {
    auto arr = std::make_shared<ArrayType>(length_, offsets_buf_, value_buf_,
                                           null_bitmap_, null_count_);
  }

  void TestGetString() {
    for (size_t i = 0; i < expected_.size(); ++i) {
      if (valid_bytes_[i] == 0) {
        ASSERT_TRUE(strings_->IsNull(i));
      } else {
        ASSERT_FALSE(strings_->IsNull(i));
        ASSERT_EQ(expected_[i], strings_->GetString(i));
      }
    }
  }

  void TestEmptyStringComparison() {
    offsets_ = {0, 0, 0, 0, 0, 0};
    offsets_buf_ = Buffer::Wrap(offsets_);
    length_ = static_cast<int64_t>(offsets_.size() - 1);

    auto strings_a = std::make_shared<ArrayType>(length_, offsets_buf_, nullptr,
                                                 null_bitmap_, null_count_);
    auto strings_b = std::make_shared<ArrayType>(length_, offsets_buf_, nullptr,
                                                 null_bitmap_, null_count_);
    ASSERT_TRUE(strings_a->Equals(strings_b));
  }

  void TestCompareNullByteSlots() {
    BuilderType builder;
    BuilderType builder2;
    BuilderType builder3;

    ASSERT_OK(builder.Append("foo"));
    ASSERT_OK(builder2.Append("foo"));
    ASSERT_OK(builder3.Append("foo"));

    ASSERT_OK(builder.Append("bar"));
    ASSERT_OK(builder2.AppendNull());

    // same length, but different
    ASSERT_OK(builder3.Append("xyz"));

    ASSERT_OK(builder.Append("baz"));
    ASSERT_OK(builder2.Append("baz"));
    ASSERT_OK(builder3.Append("baz"));

    std::shared_ptr<Array> array, array2, array3;
    FinishAndCheckPadding(&builder, &array);
    ASSERT_OK(builder2.Finish(&array2));
    ASSERT_OK(builder3.Finish(&array3));

    const auto& a1 = checked_cast<const ArrayType&>(*array);
    const auto& a2 = checked_cast<const ArrayType&>(*array2);
    const auto& a3 = checked_cast<const ArrayType&>(*array3);

    // The validity bitmaps are the same, the data is different, but the unequal
    // portion is masked out
    ArrayType equal_array(3, a1.value_offsets(), a1.value_data(), a2.null_bitmap(), 1);
    ArrayType equal_array2(3, a3.value_offsets(), a3.value_data(), a2.null_bitmap(), 1);

    ASSERT_TRUE(equal_array.Equals(equal_array2));
    ASSERT_TRUE(a2.RangeEquals(equal_array2, 0, 3, 0));

    ASSERT_TRUE(equal_array.Array::Slice(1)->Equals(equal_array2.Array::Slice(1)));
    ASSERT_TRUE(
        equal_array.Array::Slice(1)->RangeEquals(0, 2, 0, equal_array2.Array::Slice(1)));
  }

  void TestSliceGetString() {
    BuilderType builder;

    ASSERT_OK(builder.Append("a"));
    ASSERT_OK(builder.Append("b"));
    ASSERT_OK(builder.Append("c"));

    std::shared_ptr<Array> array;
    ASSERT_OK(builder.Finish(&array));
    auto s = array->Slice(1, 10);
    auto arr = std::dynamic_pointer_cast<ArrayType>(s);
    ASSERT_EQ(arr->GetString(0), "b");
  }

  Status ValidateFull(int64_t length, std::vector<offset_type> offsets,
                      std::string_view data, int64_t offset = 0) {
    ArrayType arr(length, Buffer::Wrap(offsets), std::make_shared<Buffer>(data),
                  /*null_bitmap=*/nullptr, /*null_count=*/0, offset);
    return arr.ValidateFull();
  }

  Status ValidateFull(const std::string& json) {
    auto ty = TypeTraits<T>::type_singleton();
    auto arr = ArrayFromJSON(ty, json);
    return arr->ValidateFull();
  }

  void TestValidateOffsets() {
    ASSERT_OK(ValidateFull(0, {0}, ""));
    ASSERT_OK(ValidateFull(1, {0, 4}, "data"));
    ASSERT_OK(ValidateFull(2, {0, 4, 4}, "data"));
    ASSERT_OK(ValidateFull(2, {0, 5, 9}, "some data"));

    // Non-zero array offset
    ASSERT_OK(ValidateFull(0, {0, 4}, "data", 1));
    ASSERT_OK(ValidateFull(1, {0, 5, 9}, "some data", 1));
    ASSERT_OK(ValidateFull(0, {0, 5, 9}, "some data", 2));

    // Not enough offsets
    ASSERT_RAISES(Invalid, ValidateFull(1, {}, ""));
    ASSERT_RAISES(Invalid, ValidateFull(1, {0}, ""));
    ASSERT_RAISES(Invalid, ValidateFull(2, {0, 4}, "data"));
    ASSERT_RAISES(Invalid, ValidateFull(1, {0, 4}, "data", 1));

    // Offset out of bounds
    ASSERT_RAISES(Invalid, ValidateFull(1, {0, 5}, "data"));
    // Negative offset
    ASSERT_RAISES(Invalid, ValidateFull(1, {-1, 0}, "data"));
    ASSERT_RAISES(Invalid, ValidateFull(1, {0, -1}, "data"));
    ASSERT_RAISES(Invalid, ValidateFull(1, {0, -1, -1}, "data", 1));
    // Offsets non-monotonic
    ASSERT_RAISES(Invalid, ValidateFull(2, {0, 5, 4}, "some data"));
  }

  void TestValidateData() {
    // Valid UTF8
    ASSERT_OK(ValidateFull(R"(["Voix", "ambiguë", "d'un", "cœur"])"));
    ASSERT_OK(ValidateFull(R"(["いろはにほへと", "ちりぬるを", "わかよたれそ"])"));
    ASSERT_OK(ValidateFull(R"(["😀", "😄"])"));
    ASSERT_OK(ValidateFull(1, {0, 4}, "\xf4\x8f\xbf\xbf"));  // \U0010ffff

    // Invalid UTF8
    auto ty = TypeTraits<T>::type_singleton();
    auto st1 = ValidateFull(3, {0, 4, 6, 9}, "abc \xff def");
    // Hypothetical \U00110000
    auto st2 = ValidateFull(1, {0, 4}, "\xf4\x90\x80\x80");
    // Single UTF8 character straddles two entries
    auto st3 = ValidateFull(2, {0, 1, 2}, "\xc3\xa9");
    if (T::is_utf8) {
      ASSERT_RAISES(Invalid, st1);
      ASSERT_RAISES(Invalid, st2);
      ASSERT_RAISES(Invalid, st3);
    } else {
      ASSERT_OK(st1);
      ASSERT_OK(st2);
      ASSERT_OK(st3);
    }
  }

 protected:
  std::vector<offset_type> offsets_;
  std::vector<char> chars_;
  std::vector<uint8_t> valid_bytes_;

  std::vector<std::string> expected_;

  std::shared_ptr<Buffer> value_buf_;
  std::shared_ptr<Buffer> offsets_buf_;
  std::shared_ptr<Buffer> null_bitmap_;

  int64_t null_count_;
  int64_t length_;

  std::shared_ptr<ArrayType> strings_;
};

TYPED_TEST_SUITE(TestStringArray, BaseBinaryArrowTypes);

TYPED_TEST(TestStringArray, TestArrayBasics) { this->TestArrayBasics(); }

TYPED_TEST(TestStringArray, TestArrayIndexOperator) { this->TestArrayIndexOperator(); }

TYPED_TEST(TestStringArray, TestArrayCtors) { this->TestArrayCtors(); }

TYPED_TEST(TestStringArray, TestType) { this->TestType(); }

TYPED_TEST(TestStringArray, TestListFunctions) { this->TestListFunctions(); }

TYPED_TEST(TestStringArray, TestDestructor) { this->TestDestructor(); }

TYPED_TEST(TestStringArray, TestGetString) { this->TestGetString(); }

TYPED_TEST(TestStringArray, TestEmptyStringComparison) {
  this->TestEmptyStringComparison();
}

TYPED_TEST(TestStringArray, CompareNullByteSlots) { this->TestCompareNullByteSlots(); }

TYPED_TEST(TestStringArray, TestSliceGetString) { this->TestSliceGetString(); }

TYPED_TEST(TestStringArray, TestValidateOffsets) { this->TestValidateOffsets(); }

TYPED_TEST(TestStringArray, TestValidateData) { this->TestValidateData(); }

template <typename T>
class TestUTF8Array : public ::testing::Test {
 public:
  using TypeClass = T;
  using offset_type = typename TypeClass::offset_type;
  using ArrayType = typename TypeTraits<TypeClass>::ArrayType;

  Status ValidateUTF8(int64_t length, std::vector<offset_type> offsets,
                      std::string_view data, int64_t offset = 0) {
    ArrayType arr(length, Buffer::Wrap(offsets), std::make_shared<Buffer>(data),
                  /*null_bitmap=*/nullptr, /*null_count=*/0, offset);
    return arr.ValidateUTF8();
  }

  Status ValidateUTF8(const std::string& json) {
    auto ty = TypeTraits<T>::type_singleton();
    auto arr = ArrayFromJSON(ty, json);
    return checked_cast<const ArrayType&>(*arr).ValidateUTF8();
  }

  void TestValidateUTF8() {
    ASSERT_OK(ValidateUTF8(R"(["Voix", "ambiguë", "d'un", "cœur"])"));
    ASSERT_OK(ValidateUTF8(1, {0, 4}, "\xf4\x8f\xbf\xbf"));  // \U0010ffff

    ASSERT_RAISES(Invalid, ValidateUTF8(1, {0, 1}, "\xf4"));

    // More tests in TestValidateData() above
    // (ValidateFull() calls ValidateUTF8() internally)
  }
};

TYPED_TEST_SUITE(TestUTF8Array, StringArrowTypes);

TYPED_TEST(TestUTF8Array, TestValidateUTF8) { this->TestValidateUTF8(); }

// ----------------------------------------------------------------------
// String builder tests

template <typename T>
class TestStringBuilder : public ::testing::Test {
 public:
  using TypeClass = T;
  using offset_type = typename TypeClass::offset_type;
  using ArrayType = typename TypeTraits<TypeClass>::ArrayType;
  using BuilderType = typename TypeTraits<TypeClass>::BuilderType;

  void SetUp() { builder_.reset(new BuilderType(pool_)); }

  void Done() {
    std::shared_ptr<Array> out;
    FinishAndCheckPadding(builder_.get(), &out);

    result_ = std::dynamic_pointer_cast<ArrayType>(out);
    ASSERT_OK(result_->ValidateFull());
  }

  void TestScalarAppend() {
    std::vector<std::string> strings = {"", "bb", "a", "", "ccc"};
    std::vector<uint8_t> is_valid = {1, 1, 1, 0, 1};

    int N = static_cast<int>(strings.size());
    int reps = 10;

    for (int j = 0; j < reps; ++j) {
      for (int i = 0; i < N; ++i) {
        if (!is_valid[i]) {
          ASSERT_OK(builder_->AppendNull());
        } else {
          ASSERT_OK(builder_->Append(strings[i]));
        }
      }
    }
    Done();

    ASSERT_EQ(reps * N, result_->length());
    ASSERT_EQ(reps, result_->null_count());
    ASSERT_EQ(reps * 6, result_->value_data()->size());

    CheckStringArray(*result_, strings, is_valid, reps);
  }

  void TestScalarAppendUnsafe() {
    std::vector<std::string> strings = {"", "bb", "a", "", "ccc"};
    std::vector<uint8_t> is_valid = {1, 1, 1, 0, 1};

    int N = static_cast<int>(strings.size());
    int reps = 13;
    int64_t total_length = 0;
    for (const auto& s : strings) {
      total_length += static_cast<int64_t>(s.size());
    }

    ASSERT_OK(builder_->Reserve(N * reps));
    ASSERT_OK(builder_->ReserveData(total_length * reps));

    for (int j = 0; j < reps; ++j) {
      for (int i = 0; i < N; ++i) {
        if (!is_valid[i]) {
          builder_->UnsafeAppendNull();
        } else {
          builder_->UnsafeAppend(strings[i]);
        }
      }
    }
    ASSERT_EQ(builder_->value_data_length(), total_length * reps);
    Done();

    ASSERT_OK(result_->ValidateFull());
    ASSERT_EQ(reps * N, result_->length());
    ASSERT_EQ(reps, result_->null_count());
    ASSERT_EQ(reps * total_length, result_->value_data()->size());

    CheckStringArray(*result_, strings, is_valid, reps);
  }

  void TestExtendCurrent() {
    std::vector<std::string> strings = {"", "bbbb", "aaaaa", "", "ccc"};
    std::vector<uint8_t> is_valid = {1, 1, 1, 0, 1};

    int N = static_cast<int>(strings.size());
    int reps = 10;

    for (int j = 0; j < reps; ++j) {
      for (int i = 0; i < N; ++i) {
        if (!is_valid[i]) {
          ASSERT_OK(builder_->AppendNull());
        } else if (strings[i].length() > 3) {
          ASSERT_OK(builder_->Append(strings[i].substr(0, 3)));
          ASSERT_OK(builder_->ExtendCurrent(strings[i].substr(3)));
        } else {
          ASSERT_OK(builder_->Append(strings[i]));
        }
      }
    }
    Done();

    ASSERT_EQ(reps * N, result_->length());
    ASSERT_EQ(reps, result_->null_count());
    ASSERT_EQ(reps * 12, result_->value_data()->size());

    CheckStringArray(*result_, strings, is_valid, reps);
  }

  void TestExtendCurrentUnsafe() {
    std::vector<std::string> strings = {"", "bbbb", "aaaaa", "", "ccc"};
    std::vector<uint8_t> is_valid = {1, 1, 1, 0, 1};

    int N = static_cast<int>(strings.size());
    int reps = 13;
    int64_t total_length = 0;
    for (const auto& s : strings) {
      total_length += static_cast<int64_t>(s.size());
    }

    ASSERT_OK(builder_->Reserve(N * reps));
    ASSERT_OK(builder_->ReserveData(total_length * reps));

    for (int j = 0; j < reps; ++j) {
      for (int i = 0; i < N; ++i) {
        if (!is_valid[i]) {
          builder_->UnsafeAppendNull();
        } else if (strings[i].length() > 3) {
          builder_->UnsafeAppend(strings[i].substr(0, 3));
          builder_->UnsafeExtendCurrent(strings[i].substr(3));
        } else {
          builder_->UnsafeAppend(strings[i]);
        }
      }
    }
    ASSERT_EQ(builder_->value_data_length(), total_length * reps);
    Done();

    ASSERT_EQ(reps * N, result_->length());
    ASSERT_EQ(reps, result_->null_count());
    ASSERT_EQ(reps * 12, result_->value_data()->size());

    CheckStringArray(*result_, strings, is_valid, reps);
  }

  void TestVectorAppend() {
    std::vector<std::string> strings = {"", "bb", "a", "", "ccc"};
    std::vector<uint8_t> valid_bytes = {1, 1, 1, 0, 1};

    int N = static_cast<int>(strings.size());
    int reps = 1000;

    for (int j = 0; j < reps; ++j) {
      ASSERT_OK(builder_->AppendValues(strings, valid_bytes.data()));
    }
    Done();

    ASSERT_EQ(reps * N, result_->length());
    ASSERT_EQ(reps, result_->null_count());
    ASSERT_EQ(reps * 6, result_->value_data()->size());

    CheckStringArray(*result_, strings, valid_bytes, reps);
  }

  void TestAppendCStringsWithValidBytes() {
    const char* strings[] = {nullptr, "aaa", nullptr, "ignored", ""};
    std::vector<uint8_t> valid_bytes = {1, 1, 1, 0, 1};

    int N = static_cast<int>(sizeof(strings) / sizeof(strings[0]));
    int reps = 1000;

    for (int j = 0; j < reps; ++j) {
      ASSERT_OK(builder_->AppendValues(strings, N, valid_bytes.data()));
    }
    Done();

    ASSERT_EQ(reps * N, result_->length());
    ASSERT_EQ(reps * 3, result_->null_count());
    ASSERT_EQ(reps * 3, result_->value_data()->size());

    CheckStringArray(*result_, {"", "aaa", "", "", ""}, {0, 1, 0, 0, 1}, reps);
  }

  void TestAppendCStringsWithoutValidBytes() {
    const char* strings[] = {"", "bb", "a", nullptr, "ccc"};

    int N = static_cast<int>(sizeof(strings) / sizeof(strings[0]));
    int reps = 1000;

    for (int j = 0; j < reps; ++j) {
      ASSERT_OK(builder_->AppendValues(strings, N));
    }
    Done();

    ASSERT_EQ(reps * N, result_->length());
    ASSERT_EQ(reps, result_->null_count());
    ASSERT_EQ(reps * 6, result_->value_data()->size());

    CheckStringArray(*result_, {"", "bb", "a", "", "ccc"}, {1, 1, 1, 0, 1}, reps);
  }

  void TestCapacityReserve() {
    std::vector<std::string> strings = {"aaaaa", "bbbbbbbbbb", "ccccccccccccccc",
                                        "dddddddddd"};
    int N = static_cast<int>(strings.size());
    int reps = 15;
    int64_t length = 0;
    int64_t capacity = 1000;
    int64_t expected_capacity = bit_util::RoundUpToMultipleOf64(capacity);

    ASSERT_OK(builder_->ReserveData(capacity));

    ASSERT_EQ(length, builder_->value_data_length());
    ASSERT_EQ(expected_capacity, builder_->value_data_capacity());

    for (int j = 0; j < reps; ++j) {
      for (int i = 0; i < N; ++i) {
        ASSERT_OK(builder_->Append(strings[i]));
        length += static_cast<int64_t>(strings[i].size());

        ASSERT_EQ(length, builder_->value_data_length());
        ASSERT_EQ(expected_capacity, builder_->value_data_capacity());
      }
    }

    int extra_capacity = 500;
    expected_capacity = bit_util::RoundUpToMultipleOf64(length + extra_capacity);

    ASSERT_OK(builder_->ReserveData(extra_capacity));

    ASSERT_EQ(length, builder_->value_data_length());
    int64_t actual_capacity = builder_->value_data_capacity();
    ASSERT_GE(actual_capacity, expected_capacity);
    ASSERT_EQ(actual_capacity & 63, 0);

    Done();

    ASSERT_EQ(reps * N, result_->length());
    ASSERT_EQ(0, result_->null_count());
    ASSERT_EQ(reps * 40, result_->value_data()->size());
  }

  void TestOverflowCheck() {
    auto max_size = builder_->memory_limit();

    ASSERT_OK(builder_->ValidateOverflow(1));
    ASSERT_OK(builder_->ValidateOverflow(max_size));
    ASSERT_RAISES(CapacityError, builder_->ValidateOverflow(max_size + 1));

    ASSERT_OK(builder_->Append("bb"));
    ASSERT_OK(builder_->ValidateOverflow(max_size - 2));
    ASSERT_RAISES(CapacityError, builder_->ValidateOverflow(max_size - 1));

    ASSERT_OK(builder_->AppendNull());
    ASSERT_OK(builder_->ValidateOverflow(max_size - 2));
    ASSERT_RAISES(CapacityError, builder_->ValidateOverflow(max_size - 1));

    ASSERT_OK(builder_->Append("ccc"));
    ASSERT_OK(builder_->ValidateOverflow(max_size - 5));
    ASSERT_RAISES(CapacityError, builder_->ValidateOverflow(max_size - 4));
  }

  void TestZeroLength() {
    // All buffers are null
    Done();
    ASSERT_EQ(result_->length(), 0);
    ASSERT_EQ(result_->null_count(), 0);
  }

 protected:
  MemoryPool* pool_ = default_memory_pool();
  std::unique_ptr<BuilderType> builder_;
  std::shared_ptr<ArrayType> result_;
};

TYPED_TEST_SUITE(TestStringBuilder, BaseBinaryArrowTypes);

TYPED_TEST(TestStringBuilder, TestScalarAppend) { this->TestScalarAppend(); }

TYPED_TEST(TestStringBuilder, TestScalarAppendUnsafe) { this->TestScalarAppendUnsafe(); }

TYPED_TEST(TestStringBuilder, TestExtendCurrent) { this->TestExtendCurrent(); }

TYPED_TEST(TestStringBuilder, TestExtendCurrentUnsafe) {
  this->TestExtendCurrentUnsafe();
}

TYPED_TEST(TestStringBuilder, TestVectorAppend) { this->TestVectorAppend(); }

TYPED_TEST(TestStringBuilder, TestAppendCStringsWithValidBytes) {
  this->TestAppendCStringsWithValidBytes();
}

TYPED_TEST(TestStringBuilder, TestAppendCStringsWithoutValidBytes) {
  this->TestAppendCStringsWithoutValidBytes();
}

TYPED_TEST(TestStringBuilder, TestCapacityReserve) { this->TestCapacityReserve(); }

TYPED_TEST(TestStringBuilder, TestZeroLength) { this->TestZeroLength(); }

TYPED_TEST(TestStringBuilder, TestOverflowCheck) { this->TestOverflowCheck(); }

// ----------------------------------------------------------------------
// ChunkedBinaryBuilder tests

class TestChunkedBinaryBuilder : public ::testing::Test {
 public:
  void SetUp() {}

  void Init(int32_t chunksize) {
    builder_.reset(new internal::ChunkedBinaryBuilder(chunksize));
  }

  void Init(int32_t chunksize, int32_t chunklength) {
    builder_.reset(new internal::ChunkedBinaryBuilder(chunksize, chunklength));
  }

 protected:
  std::unique_ptr<internal::ChunkedBinaryBuilder> builder_;
};

TEST_F(TestChunkedBinaryBuilder, BasicOperation) {
  const int32_t chunksize = 1000;
  Init(chunksize);

  const int elem_size = 10;
  uint8_t buf[elem_size];

  BinaryBuilder unchunked_builder;

  const int iterations = 1000;
  for (int i = 0; i < iterations; ++i) {
    random_bytes(elem_size, i, buf);

    ASSERT_OK(unchunked_builder.Append(buf, elem_size));
    ASSERT_OK(builder_->Append(buf, elem_size));
  }

  std::shared_ptr<Array> unchunked;
  ASSERT_OK(unchunked_builder.Finish(&unchunked));

  ArrayVector chunks;
  ASSERT_OK(builder_->Finish(&chunks));

  // This assumes that everything is evenly divisible
  ArrayVector expected_chunks;
  const int elems_per_chunk = chunksize / elem_size;
  for (int i = 0; i < iterations / elems_per_chunk; ++i) {
    expected_chunks.emplace_back(unchunked->Slice(i * elems_per_chunk, elems_per_chunk));
  }

  ASSERT_EQ(expected_chunks.size(), chunks.size());
  for (size_t i = 0; i < chunks.size(); ++i) {
    AssertArraysEqual(*expected_chunks[i], *chunks[i]);
  }
}

TEST_F(TestChunkedBinaryBuilder, Reserve) {
  // ARROW-6060
  const int32_t chunksize = 1000;
  Init(chunksize);
  ASSERT_OK(builder_->Reserve(chunksize / 2));
  auto bytes_after_first_reserve = default_memory_pool()->bytes_allocated();
  for (int i = 0; i < 8; ++i) {
    ASSERT_OK(builder_->Reserve(chunksize / 2));
  }
  // no new memory will be allocated since capacity was sufficient for the loop's
  // Reserve() calls
  ASSERT_EQ(default_memory_pool()->bytes_allocated(), bytes_after_first_reserve);
}

TEST_F(TestChunkedBinaryBuilder, NoData) {
  Init(1000);

  ArrayVector chunks;
  ASSERT_OK(builder_->Finish(&chunks));

  ASSERT_EQ(1, chunks.size());
  ASSERT_EQ(0, chunks[0]->length());
}

TEST_F(TestChunkedBinaryBuilder, LargeElements) {
  Init(100);

  const int bufsize = 101;
  uint8_t buf[bufsize];

  const int iterations = 100;
  for (int i = 0; i < iterations; ++i) {
    random_bytes(bufsize, i, buf);
    ASSERT_OK(builder_->Append(buf, bufsize));
  }

  ArrayVector chunks;
  ASSERT_OK(builder_->Finish(&chunks));
  ASSERT_EQ(iterations, static_cast<int>(chunks.size()));

  int64_t total_data_size = 0;
  for (auto chunk : chunks) {
    ASSERT_EQ(1, chunk->length());
    total_data_size +=
        static_cast<int64_t>(static_cast<const BinaryArray&>(*chunk).GetView(0).size());
  }
  ASSERT_EQ(iterations * bufsize, total_data_size);
}

TEST_F(TestChunkedBinaryBuilder, LargeElementCount) {
  int32_t max_chunk_length = 100;
  Init(100, max_chunk_length);

  auto length = max_chunk_length + 1;

  // ChunkedBinaryBuilder can reserve memory for more than its configured maximum
  // (per chunk) element count
  ASSERT_OK(builder_->Reserve(length));

  for (int64_t i = 0; i < 2 * length; ++i) {
    // Appending more elements than have been reserved memory simply overflows to the next
    // chunk
    ASSERT_OK(builder_->Append(""));
  }

  ArrayVector chunks;
  ASSERT_OK(builder_->Finish(&chunks));

  // should have two chunks full of empty strings and another with two more empty strings
  ASSERT_EQ(chunks.size(), 3);
  ASSERT_EQ(chunks[0]->length(), max_chunk_length);
  ASSERT_EQ(chunks[1]->length(), max_chunk_length);
  ASSERT_EQ(chunks[2]->length(), 2);
  for (auto&& boxed_chunk : chunks) {
    const auto& chunk = checked_cast<const BinaryArray&>(*boxed_chunk);
    ASSERT_EQ(chunk.value_offset(0), chunk.value_offset(chunk.length()));
  }
}

TEST(TestChunkedStringBuilder, BasicOperation) {
  const int chunksize = 100;
  internal::ChunkedStringBuilder builder(chunksize);

  std::string value = "0123456789";

  const int iterations = 100;
  for (int i = 0; i < iterations; ++i) {
    ASSERT_OK(builder.Append(value));
  }

  ArrayVector chunks;
  ASSERT_OK(builder.Finish(&chunks));

  ASSERT_EQ(10, chunks.size());

  // Type is correct
  for (auto chunk : chunks) {
    ASSERT_TRUE(chunk->type()->Equals(utf8()));
  }
}

// ----------------------------------------------------------------------
// ArraySpanVisitor<binary-like> tests

struct BinaryAppender {
  Status VisitNull() {
    data.emplace_back("(null)");
    return Status::OK();
  }

  Status VisitValue(std::string_view v) {
    data.push_back(v);
    return Status::OK();
  }

  std::vector<std::string_view> data;
};

template <typename T>
class TestBaseBinaryDataVisitor : public ::testing::Test {
 public:
  using TypeClass = T;

  void SetUp() override { type_ = TypeTraits<TypeClass>::type_singleton(); }

  void TestBasics() {
    auto array = ArrayFromJSON(type_, R"(["foo", null, "bar"])");
    BinaryAppender appender;
    ArraySpanVisitor<TypeClass> visitor;
    ASSERT_OK(visitor.Visit(*array->data(), &appender));
    ASSERT_THAT(appender.data, ::testing::ElementsAreArray({"foo", "(null)", "bar"}));
    ARROW_UNUSED(visitor);  // Workaround weird MSVC warning
  }

  void TestSliced() {
    auto array = ArrayFromJSON(type_, R"(["ab", null, "cd", "ef"])")->Slice(1, 2);
    BinaryAppender appender;
    ArraySpanVisitor<TypeClass> visitor;
    ASSERT_OK(visitor.Visit(*array->data(), &appender));
    ASSERT_THAT(appender.data, ::testing::ElementsAreArray({"(null)", "cd"}));
    ARROW_UNUSED(visitor);  // Workaround weird MSVC warning
  }

 protected:
  std::shared_ptr<DataType> type_;
};

TYPED_TEST_SUITE(TestBaseBinaryDataVisitor, BaseBinaryArrowTypes);

TYPED_TEST(TestBaseBinaryDataVisitor, Basics) { this->TestBasics(); }

TYPED_TEST(TestBaseBinaryDataVisitor, Sliced) { this->TestSliced(); }

}  // namespace arrow


text:
<!--
Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
for details. All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
-->
<link rel="import" href="../../packages/experimental_boot/b.html">


text:
/* $NetBSD: ppcstart.c,v 1.2 1999/12/30 21:09:56 is Exp $ */

/*-
 * Copyright (c) 1999 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Ignatios Souvatzis.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by the NetBSD
 *        Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Startit for Phase5 PPC boards.
 */

#include <sys/types.h>
#include "libstubs.h"

#include "kickstart68.c"

void
startit(kp, ksize, entry, fmem, fmemsz, cmemsz,
	    boothowto, esym, cpuid, eclock, amiga_flags, I_flag,
	    bootpartoff, history)

	u_long kp, ksize, entry, fmem, fmemsz, cmemsz,
		boothowto, esym, cpuid, eclock, amiga_flags, I_flag,
		bootpartoff, history;
{
	int i;

#define ONESEC
/* #define ONESEC for (i=0; i<1000000; i++) */

	ONESEC *(volatile u_int16_t *)0xdff180 = 0x0f0;
	*(volatile u_int8_t *)0xf60000 = 0x10;
	ONESEC *(volatile u_int16_t *)0xdff180 = 0xf80;

	memcpy((caddr_t)0xfff00100, kickstart, kicksize);
	*(volatile u_int32_t *)0xfff000f4 = fmem;
	*(volatile u_int32_t *)0xfff000f8 = kp;
	*(volatile u_int32_t *)0xfff000fc = ksize;
	ONESEC *(volatile u_int16_t *)0xdff180 = 0xf00;
	*(volatile u_int8_t *)0xf60000 = 0x90;
	*(volatile u_int8_t *)0xf60000 = 0x08;
	/* NOTREACHED */
	while (1) {
		*(volatile u_int16_t *)0xdff180 = 0x0f0;
		*(volatile u_int16_t *)0xdff180 = 0x00f;
	}
}


text:
package com.edu.fireeyes.fragments;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.edu.fireeyes.R;

/**
 * 查勘任务fragment
 *
 * @author MBENBEN
 *
 */
public class QueryFragment extends Fragment {
	private RadioGroup rGroup;
	private FragmentManager fm;
	private FragmentTransaction trans;
	private ImageView ivHelp;

	private ArrayList<Integer> ivList = new ArrayList<Integer>();
	private int screenWidth, screenHight;
	private int index = 0;
	private PopupWindow popupwindow;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_query, null);

		DisplayMetrics metrics = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);
		screenWidth = metrics.widthPixels;
		screenHight = metrics.heightPixels;

		initViews(view);

		initDatas();

		registerListener();

		return view;
	}

	private void registerListener() {

		rGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.query_rbtn_wait_submit:
					fm = getChildFragmentManager();
					trans = fm.beginTransaction();
					trans.replace(R.id.query_framelayout,
							new WaitSubmitTaskFragment());
					trans.commit();
					break;
				case R.id.query_rbtn_wait_query:
					fm = getChildFragmentManager();
					trans = fm.beginTransaction();
					trans.replace(R.id.query_framelayout,
							new WaitQueryTaskFragment());
					trans.commit();
					break;
				case R.id.query_rbtn_wait_requery:
					fm = getChildFragmentManager();
					trans = fm.beginTransaction();
					trans.replace(R.id.query_framelayout,
							new RequeryTaskFragment());
					trans.commit();
					break;

				default:
					break;
				}
			}
		});

		ivHelp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				View view = View.inflate(getActivity(),
						R.layout.help_popupwindow, null);
				final ImageView ivIcon = (ImageView) view
						.findViewById(R.id.help_iv);
				ImageView ivDelete = (ImageView) view
						.findViewById(R.id.help_delete);
				popupwindow = new PopupWindow(view, screenWidth, screenHight);
				popupwindow.setFocusable(true);
				ivIcon.setImageResource(ivList.get(index));

				ivIcon.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (ivList.size() - 1 > index) {
							index++;
							ivIcon.setImageResource(ivList.get(index));
						} else {
							popupwindow.dismiss();
							index = 0;
						}

					}
				});
				popupwindow.showAtLocation(v, Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
				ivDelete.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						popupwindow.dismiss();
					}
				});
			}

		});

	}

	private void initDatas() {
		ivList.add(R.drawable.query1);
		ivList.add(R.drawable.query2);
		ivList.add(R.drawable.query3);

		fm = getChildFragmentManager();
		trans = fm.beginTransaction();
		trans.replace(R.id.query_framelayout, new WaitSubmitTaskFragment());
		trans.commit();

	}

	private void initViews(View view) {
		rGroup = (RadioGroup) view.findViewById(R.id.query_rgroup_task);
		ivHelp = (ImageView) view.findViewById(R.id.query_main_help);
	}
}


text:
"""
This file contains a minimal set of tests for compliance with the extension
array interface test suite, and should contain no other tests.
The test suite for the full functionality of the array is located in
`pandas/tests/arrays/`.

The tests in this file are inherited from the BaseExtensionTests, and only
minimal tweaks should be applied to get the tests passing (by overwriting a
parent method).

Additional tests should either be added to one of the BaseExtensionTests
classes (if they are relevant for the extension interface for all dtypes), or
be added to the array-specific tests in `pandas/tests/arrays/`.

"""
import numpy as np
import pytest

from pandas._libs import iNaT

from pandas.core.dtypes.dtypes import PeriodDtype

import pandas as pd
from pandas.core.arrays import PeriodArray
from pandas.tests.extension import base

@pytest.fixture(params=["D", "2D"])
def dtype(request):
    return PeriodDtype(freq=request.param)

@pytest.fixture
def data(dtype):
    return PeriodArray(np.arange(1970, 2070), freq=dtype.freq)

@pytest.fixture
def data_for_twos(dtype):
    return PeriodArray(np.ones(100) * 2, freq=dtype.freq)

@pytest.fixture
def data_for_sorting(dtype):
    return PeriodArray([2018, 2019, 2017], freq=dtype.freq)

@pytest.fixture
def data_missing(dtype):
    return PeriodArray([iNaT, 2017], freq=dtype.freq)

@pytest.fixture
def data_missing_for_sorting(dtype):
    return PeriodArray([2018, iNaT, 2017], freq=dtype.freq)

@pytest.fixture
def data_for_grouping(dtype):
    B = 2018
    NA = iNaT
    A = 2017
    C = 2019
    return PeriodArray([B, B, NA, NA, A, A, B, C], freq=dtype.freq)

@pytest.fixture
def na_value():
    return pd.NaT

class BasePeriodTests:
    pass

class TestPeriodDtype(BasePeriodTests, base.BaseDtypeTests):
    pass

class TestConstructors(BasePeriodTests, base.BaseConstructorsTests):
    pass

class TestGetitem(BasePeriodTests, base.BaseGetitemTests):
    pass

class TestIndex(base.BaseIndexTests):
    pass

class TestMethods(BasePeriodTests, base.BaseMethodsTests):
    def test_combine_add(self, data_repeated):
        # Period + Period is not defined.
        pass

class TestInterface(BasePeriodTests, base.BaseInterfaceTests):

    pass

class TestArithmeticOps(BasePeriodTests, base.BaseArithmeticOpsTests):
    implements = {"__sub__", "__rsub__"}

    def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
        # frame & scalar
        if all_arithmetic_operators in self.implements:
            df = pd.DataFrame({"A": data})
            self.check_opname(df, all_arithmetic_operators, data[0], exc=None)
        else:
            # ... but not the rest.
            super().test_arith_frame_with_scalar(data, all_arithmetic_operators)

    def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
        # we implement substitution...
        if all_arithmetic_operators in self.implements:
            s = pd.Series(data)
            self.check_opname(s, all_arithmetic_operators, s.iloc[0], exc=None)
        else:
            # ... but not the rest.
            super().test_arith_series_with_scalar(data, all_arithmetic_operators)

    def test_arith_series_with_array(self, data, all_arithmetic_operators):
        if all_arithmetic_operators in self.implements:
            s = pd.Series(data)
            self.check_opname(s, all_arithmetic_operators, s.iloc[0], exc=None)
        else:
            # ... but not the rest.
            super().test_arith_series_with_scalar(data, all_arithmetic_operators)

    def _check_divmod_op(self, s, op, other, exc=NotImplementedError):
        super()._check_divmod_op(s, op, other, exc=TypeError)

    def test_add_series_with_extension_array(self, data):
        # we don't implement + for Period
        s = pd.Series(data)
        msg = (
            r"unsupported operand type\(s\) for \+: "
            r"\'PeriodArray\' and \'PeriodArray\'"
        )
        with pytest.raises(TypeError, match=msg):
            s + data

    @pytest.mark.parametrize("box", [pd.Series, pd.DataFrame])
    def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box):
        # Override to use __sub__ instead of __add__
        other = pd.Series(data)
        if box is pd.DataFrame:
            other = other.to_frame()

        result = data.__sub__(other)
        assert result is NotImplemented

class TestCasting(BasePeriodTests, base.BaseCastingTests):
    pass

class TestComparisonOps(BasePeriodTests, base.BaseComparisonOpsTests):
    pass

class TestMissing(BasePeriodTests, base.BaseMissingTests):
    pass

class TestReshaping(BasePeriodTests, base.BaseReshapingTests):
    pass

class TestSetitem(BasePeriodTests, base.BaseSetitemTests):
    pass

class TestGroupby(BasePeriodTests, base.BaseGroupbyTests):
    pass

class TestPrinting(BasePeriodTests, base.BasePrintingTests):
    pass

class TestParsing(BasePeriodTests, base.BaseParsingTests):
    @pytest.mark.parametrize("engine", ["c", "python"])
    def test_EA_types(self, engine, data):
        super().test_EA_types(engine, data)

class Test2DCompat(BasePeriodTests, base.NDArrayBacked2DTests):
    pass


text:
#include "audio_disk_resource.h"
#include "audio.h"
#include <portable_io.h>
#include "ogg_vorbis_decoder.h"

void AudioDiskResource::loadImpl (void)
{
    // head radio. because your head NEEDS IT.

    // why using OGRE anyways? I'm just following CollisionMesh.c++'s example and doing so here
    // [DC] we are still using ogre's IO code, that understands putting files in zips etc.
    Ogre::DataStreamPtr file;
    try {
        file = Ogre::ResourceGroupManager::getSingleton().openResource(name.substr(1),"GRIT");
    } catch (Ogre::Exception &e) {
        GRIT_EXCEPT(e.getDescription());
    }

    uint32_t fourcc = 0;
    file->read(&fourcc, sizeof(fourcc));

    if (fourcc == 0x46464952) // RIFF
    {
        file->seek(0);
        loadWAV(file);
    }
    else if (fourcc == 0x5367674F) // OggS
    {
        file->seek(0);
        loadOGG(file);
    }
    else
    {
        GRIT_EXCEPT("Unknown audio file format in " + name);
    }

}

struct chunk_header
{
    uint32_t fourcc;
    uint32_t size;
};

struct riff_header
{
    chunk_header chunk;
    uint32_t format;
};

struct wave_format
{
    uint16_t format_tag;
    uint16_t channels;
    uint32_t samples;
    uint32_t bytesPerSec;
    uint16_t blockAlign;
    uint16_t bitsPerSample;
    uint16_t size;
};

void AudioDiskResource::loadWAV(Ogre::DataStreamPtr &file)
{
    riff_header header;
    file->read(&header, sizeof(header));

    if (header.format != 0x45564157) // WAVE
    {
        GRIT_EXCEPT(name + " is not a WAVE file.");
    }

    // FIXME: possibly use more advanced chunk reading?
    chunk_header fmtHeader;
    file->read(&fmtHeader, sizeof(fmtHeader));

    if (fmtHeader.fourcc != 0x20746d66)
    {
        GRIT_EXCEPT("First chunk in " + name + " wasn't 'fmt'.");
    }

    // save the fmt position so we can seek from it later on
    size_t fmtStart = file->tell();

    // read the format header
    wave_format fmt;
    file->read(&fmt, sizeof(fmt));

    if (fmt.format_tag != 1) // PCM
    {
        GRIT_EXCEPT(name + " isn't PCM (only PCM is supported right now)");
    }

    if (fmt.channels > 2)
    {
        GRIT_EXCEPT(name + " has more than two channels.");
    }

    if (fmt.bitsPerSample != 8 && fmt.bitsPerSample != 16)
    {
        GRIT_EXCEPT(name + " isn't 8 or 16 bits per sample.");
    }

    // seek to the data start
    file->seek(fmtStart + fmtHeader.size);

    // read the data and the data header
    chunk_header dataHeader;
    file->read(&dataHeader, sizeof(dataHeader));

    if (dataHeader.fourcc != 0x61746164)
    {
        GRIT_EXCEPT("Second chunk in " + name + " wasn't 'data'.");
    }

    if (fmt.channels == 0) {
        GRIT_EXCEPT("Wave file has zero channels: \""+name+"\"");
    }

    if (fmt.channels > 2) {
        GRIT_EXCEPT("Wave file has too many channels: \""+name+"\"");
    }

    size_t bytes_per_sample = fmt.bitsPerSample/8;
    size_t samples = dataHeader.size / fmt.channels / bytes_per_sample;

    uint8_t* data = new uint8_t[dataHeader.size];
    file->read(data, dataHeader.size);

    // generate an AL buffer

    alBufferLeft = 0;
    alBufferRight = 0;
    alBuffer = 0;

    ALenum mono_format = (fmt.bitsPerSample == 8) ? AL_FORMAT_MONO8 : AL_FORMAT_MONO16;
    ALenum stereo_format = (fmt.bitsPerSample == 8) ? AL_FORMAT_STEREO8 : AL_FORMAT_STEREO16;

    if (fmt.channels == 1) {
        stereo = false;
        alGenBuffers(1, &alBufferLeft);
        alBufferData(alBufferLeft, mono_format, data, dataHeader.size, fmt.samples);
    } else {
        stereo = true;
        alGenBuffers(1, &alBuffer);
        alBufferData(alBuffer, stereo_format, data, dataHeader.size, fmt.samples);
        uint8_t* data1 = new uint8_t[dataHeader.size / 2];
        for (size_t i=0 ; i<samples ; ++i) memcpy(&data1[i*bytes_per_sample], &data[2*i*bytes_per_sample], bytes_per_sample);
        alGenBuffers(1, &alBufferLeft);
        alBufferData(alBufferLeft, mono_format, data1, dataHeader.size/2, fmt.samples);
        for (size_t i=0 ; i<samples ; ++i) memcpy(&data1[i*bytes_per_sample], &data[(2*i+1)*bytes_per_sample], bytes_per_sample);
        alGenBuffers(1, &alBufferRight);
        alBufferData(alBufferRight, mono_format, data1, dataHeader.size/2, fmt.samples);
        delete[] data1;
    }

    // free the data (as memory is in the AL buffer now)
    delete[] data;

    // close the stream
    file->close();
}

void AudioDiskResource::loadOGG(Ogre::DataStreamPtr &file)
{
    alBufferLeft = 0;
    alBufferRight = 0;
    alBuffer = 0;

    OggVorbisDecoder decoder(name, file);

    const int size = 4096;
    char buffer[size];

    std::vector<char> data;

    while (true) {
        int bytes_read = decoder.read(buffer, size);
        if(bytes_read == 0) break;
        data.insert(data.end(), buffer, buffer+bytes_read);
    }

    //these doesn't mean to be changed, the OggVorbisDecoder is now decoding 2 bytes samples only, and this are left here just for readability
    const int bytes_per_sample = 2;
    const ALenum mono_format = AL_FORMAT_MONO16;
    const ALenum stereo_format = AL_FORMAT_STEREO16;

    if (decoder.stereo()) { //stereo
        stereo = true;
        alGenBuffers(1, &alBuffer);
        alBufferData(alBuffer, stereo_format, &data[0], data.size(), decoder.rate());
        char *data1 = new char[data.size() / 2];
        size_t samples = data.size() / 2 / bytes_per_sample;
        for (size_t i=0 ; i < samples; ++i)
            memcpy(&data1[i*bytes_per_sample], &data[2*i*bytes_per_sample], bytes_per_sample);
        alGenBuffers(1, &alBufferLeft);
        alBufferData(alBufferLeft, mono_format, data1, data.size()/2, decoder.rate());
        for (size_t i=0 ; i < samples; ++i)
            memcpy(&data1[i*bytes_per_sample], &data[(2*i+1)*bytes_per_sample], bytes_per_sample);
        alGenBuffers(1, &alBufferRight);
        alBufferData(alBufferRight, mono_format, data1, data.size()/2, decoder.rate());
        delete[] data1;
    } else { //mono
        stereo = false;
        alGenBuffers(1, &alBufferLeft);
        alBufferData(alBufferLeft, mono_format, &data[0], data.size(), decoder.rate());
    }

    file->close();
}

void AudioDiskResource::unloadImpl (void)
{
    if (alBuffer != 0) alDeleteBuffers(1, &alBuffer);
    if (alBufferLeft != 0) alDeleteBuffers(1, &alBufferLeft);
    if (alBufferRight != 0) alDeleteBuffers(1, &alBufferRight);
}


text:
import React from 'react';
import ReactDom from 'react-dom';
import { Router, Route } from 'react-router';

import AppContainer from './components/AppContainer.jsx'

import NewEventUI from './components/NewEventUI.jsx'
import NewUserUI from './components/NewUserUI.jsx'
import UserScheduleUI from './components/UserScheduleUI.jsx'
import Home from './components/Home.jsx'
//import About from './components/About.jsx'
{/*About Page Links*/
}
//<Route path="/about" component={About}>
//</Route>

//<Route path="/event/new" component={NewEventUI}>
//</Route>
ReactDom.render((
  <Router>
    <Route path="/" component={Home}>
      {/*New Event UI Links*/}

    </Route>
    <Route path="event/new" component={NewEventUI}>
    </Route>
    <Route path="user/new" component={NewUserUI}>
    </Route>
    <Route path="user/:id/schedule" component={UserScheduleUI}>
    </Route>

  </Router>
), document.getElementById('main'))


text:
<?php

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper;

function sc_configure($instance)
{
    $instance->configure();
}

class BarClass extends BazClass
{
    protected $baz;
    public $foo = 'foo';

    public function setBaz(BazClass $baz)
    {
        $this->baz = $baz;
    }

    public function getBaz()
    {
        return $this->baz;
    }
}

class BazClass
{
    protected $foo;

    public function setFoo(Foo $foo)
    {
        $this->foo = $foo;
    }

    public function configure($instance)
    {
        $instance->configure();
    }

    public static function getInstance()
    {
        return new self();
    }

    public static function configureStatic($instance)
    {
        $instance->configure();
    }

    public static function configureStatic1()
    {
    }
}

class BarUserClass
{
    public $bar;

    public function __construct(BarClass $bar)
    {
        $this->bar = $bar;
    }
}

class MethodCallClass
{
    public $simple;
    public $complex;
    private $callPassed = false;

    public function callMe()
    {
        $this->callPassed = is_scalar($this->simple) && is_object($this->complex);
    }

    public function callPassed()
    {
        return $this->callPassed;
    }
}

class DummyProxyDumper implements ProxyDumper
{
    public function isProxyCandidate(Definition $definition)
    {
        return $definition->isLazy();
    }

    public function getProxyFactoryCode(Definition $definition, $id)
    {
        return "        // lazy factory\n\n";
    }

    public function getProxyCode(Definition $definition)
    {
        return "// proxy code\n";
    }
}


text:
package com.kronos.router.utils;

// Copy from galaxy sdk ${com.alibaba.android.galaxy.utils.ClassUtils}

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import dalvik.system.DexFile;

/**
 * Scanner, find out class with any conditions, copy from google source code.
 *
 * @author 正纬 Contact me.
 * @version 1.0
 * @since 16/6/27 下午10:58
 */
public class ClassUtils {
    private static final String EXTRACTED_NAME_EXT = ".classes";
    private static final String EXTRACTED_SUFFIX = ".zip";

    private static final String SECONDARY_FOLDER_NAME = "code_cache" + File.separator + "secondary-dexes";

    private static final String PREFS_FILE = "multidex.version";
    private static final String KEY_DEX_NUMBER = "dex.number";

    private static final int VM_WITH_MULTIDEX_VERSION_MAJOR = 2;
    private static final int VM_WITH_MULTIDEX_VERSION_MINOR = 1;

    private static SharedPreferences getMultiDexPreferences(Context context) {
        return context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE);
    }

    /**
     * 通过指定包名,扫描包下面包含的所有的ClassName
     *
     * @param context     U know
     * @param packageName 包名
     * @return 所有class的集合
     */
    public static List<String> getFileNameByPackageName(Context context, String packageName) throws PackageManager.NameNotFoundException, IOException {
        List<String> classNames = new ArrayList<>();
        for (String path : getSourcePaths(context)) {
            DexFile dexfile = null;
            try {
                if (path.endsWith(EXTRACTED_SUFFIX)) {
                    //NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache"
                    dexfile = DexFile.loadDex(path, path + ".tmp", 0);
                } else {
                    dexfile = new DexFile(path);
                }
                Enumeration<String> dexEntries = dexfile.entries();
                while (dexEntries.hasMoreElements()) {
                    String className = dexEntries.nextElement();
                    if (className.contains(packageName)) {
                        classNames.add(className);
                    }
                }
            } catch (Throwable ignore) {
                Log.e("ARouter", "Scan map file in dex files made error.", ignore);
            } finally {
                if (null != dexfile) {
                    try {
                        dexfile.close();
                    } catch (Throwable ignore) {
                    }
                }
            }
        }

        Log.d("ARouter", "Filter " + classNames.size() + " classes by packageName <" + packageName + ">");
        return classNames;
    }

    /**
     * get all the dex path
     *
     * @param context the application context
     * @return all the dex path
     * @throws PackageManager.NameNotFoundException
     * @throws IOException
     */
    public static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException {
        ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
        File sourceApk = new File(applicationInfo.sourceDir);

        List<String> sourcePaths = new ArrayList<>();
        sourcePaths.add(applicationInfo.sourceDir); //add the default apk path

        //the prefix of extracted file, ie: test.classes
        String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;

//        如果VM已经支持了MultiDex,就不要去Secondary Folder加载 Classesx.zip了,那里已经么有了
//        通过是否存在sp中的multidex.version是不准确的,因为从低版本升级上来的用户,是包含这个sp配置的
        if (!isVMMultidexCapable()) {
            //the total dex numbers
            int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);
            File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);

            for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {
                //for each dex file, ie: test.classes2.zip, test.classes3.zip...
                String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;
                File extractedFile = new File(dexDir, fileName);
                if (extractedFile.isFile()) {
                    sourcePaths.add(extractedFile.getAbsolutePath());
                    //we ignore the verify zip part
                } else {
                    throw new IOException("Missing extracted secondary dex file '" + extractedFile.getPath() + "'");
                }
            }
        }
        sourcePaths.addAll(tryLoadInstantRunDexFile(applicationInfo));

        return sourcePaths;
    }

    /**
     * Get instant run dex path, used to catch the branch usingApkSplits=false.
     */
    private static List<String> tryLoadInstantRunDexFile(ApplicationInfo applicationInfo) {
        List<String> instantRunSourcePaths = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && null != applicationInfo.splitSourceDirs) {
            // add the splite apk, normally for InstantRun, and newest version.
            instantRunSourcePaths.addAll(Arrays.asList(applicationInfo.splitSourceDirs));
            Log.d("ARouter", "Found InstantRun support");
        } else {
            try {
                // This man is reflection from Google instant run sdk, he will tell me where the dex files go.
                Class pathsByInstantRun = Class.forName("com.android.tools.fd.runtime.Paths");
                Method getDexFileDirectory = pathsByInstantRun.getMethod("getDexFileDirectory", String.class);
                String instantRunDexPath = (String) getDexFileDirectory.invoke(null, applicationInfo.packageName);

                File instantRunFilePath = new File(instantRunDexPath);
                if (instantRunFilePath.exists() && instantRunFilePath.isDirectory()) {
                    File[] dexFile = instantRunFilePath.listFiles();
                    for (File file : dexFile) {
                        if (null != file && file.exists() && file.isFile() && file.getName().endsWith(".dex")) {
                            instantRunSourcePaths.add(file.getAbsolutePath());
                        }
                    }
                    Log.d("ARouter", "Found InstantRun support");
                }

            } catch (Exception e) {
                Log.e("ARouter", "InstantRun support error, " + e.getMessage());
            }
        }

        return instantRunSourcePaths;
    }

    /**
     * Identifies if the current VM has a native support for multidex, meaning there is no need for
     * additional installation by this library.
     *
     * @return true if the VM handles multidex
     */
    private static boolean isVMMultidexCapable() {
        boolean isMultidexCapable = false;
        String vmName = null;

        try {
            if (isYunOS()) {    // YunOS需要特殊判断
                vmName = "'YunOS'";
                isMultidexCapable = Integer.valueOf(System.getProperty("ro.build.version.sdk")) >= 21;
            } else {    // 非YunOS原生Android
                vmName = "'Android'";
                String versionString = System.getProperty("java.vm.version");
                if (versionString != null) {
                    Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+)?").matcher(versionString);
                    if (matcher.matches()) {
                        try {
                            int major = Integer.parseInt(matcher.group(1));
                            int minor = Integer.parseInt(matcher.group(2));
                            isMultidexCapable = (major > VM_WITH_MULTIDEX_VERSION_MAJOR)
                                    || ((major == VM_WITH_MULTIDEX_VERSION_MAJOR)
                                    && (minor >= VM_WITH_MULTIDEX_VERSION_MINOR));
                        } catch (NumberFormatException ignore) {
                            // let isMultidexCapable be false
                        }
                    }
                }
            }
        } catch (Exception ignore) {

        }

        Log.i("galaxy", "VM with name " + vmName + (isMultidexCapable ? " has multidex support" : " does not have multidex support"));
        return isMultidexCapable;
    }

    /**
     * 判断系统是否为YunOS系统
     */
    private static boolean isYunOS() {
        try {
            String version = System.getProperty("ro.yunos.version");
            String vmName = System.getProperty("java.vm.name");
            return (vmName != null && vmName.toLowerCase().contains("lemur"))
                    || (version != null && version.trim().length() > 0);
        } catch (Exception ignore) {
            return false;
        }
    }
}


text:
require 'yaml'
require 'shellwords'
require_relative '../services/services_helper'

module Kontena::Cli::Stacks
  class ServiceGenerator
    include Kontena::Cli::Services::ServicesHelper

    attr_reader :service_config

    def initialize(service_config)
      @service_config = service_config
    end

    ##
    # @return [Hash]
    def generate
      parse_data(service_config)
    end

    private

    ##
    # @param [Hash] options
    # @return [Hash]
    def parse_data(options)
      data = {}
      data['instances'] = options['instances']
      data['image'] = parse_image(options['image'])
      data['env'] = options['environment'] || options['env']
      data['links'] = parse_links(options['links'] || [])
      data['external_links'] = parse_links(options['external_links'] || [])
      data['ports'] = parse_stringified_ports(options['ports'] || [])
      data['memory'] = parse_memory(options['mem_limit'].to_s) if options['mem_limit']
      data['memory_swap'] = parse_memory(options['memswap_limit'].to_s) if options['memswap_limit']
      data['shm_size'] = parse_memory(options['shm_size'].to_s) if options['shm_size']
      data['cpus'] = options['cpus'] if options['cpus']
      data['cpu_shares'] = options['cpu_shares'] if options['cpu_shares']
      data['volumes'] = options['volumes'] || []
      data['volumes_from'] = options['volumes_from'] || []
      data['cmd'] = Shellwords.split(options['command']) if options['command']
      data['affinity'] = options['affinity'] || []
      data['user'] = options['user'] if options['user']
      data['stateful'] = options['stateful'] == true
      data['privileged'] = options['privileged'] unless options['privileged'].nil?
      data['cap_add'] = options['cap_add'] if options['cap_add']
      data['cap_drop'] = options['cap_drop'] if options['cap_drop']
      data['net'] = options['net'] if options['net']
      data['pid'] = options['pid'] if options['pid']
      data['log_driver'] = options['log_driver'] if options['log_driver']
      data['log_opts'] = options['log_opt'] if options['log_opt'] && !options['log_opt'].empty?
      deploy_opts = options['deploy'] || {}
      data['strategy'] = deploy_opts['strategy'] if deploy_opts['strategy']
      deploy = {
        'wait_for_port' => deploy_opts['wait_for_port'],
        'min_health' => deploy_opts['min_health']
      }
      if deploy_opts.has_key?('interval')
        deploy['interval'] = parse_relative_time(deploy_opts['interval'])
      else
        deploy['interval'] = nil
      end
      data['deploy_opts'] = deploy
      data['hooks'] = options['hooks'] || {}
      data['secrets'] = options['secrets'] if options['secrets']
      data['certificates'] = options['certificates'] if options['certificates']
      data['build'] = parse_build_options(options) if options['build']
      data['health_check'] = parse_health_check(options)
      data['stop_signal'] = options['stop_signal'] if options['stop_signal']
      data['stop_grace_period'] = options['stop_grace_period'] if options['stop_grace_period']
      data['read_only'] = options['read_only'] || false
      data['entrypoint'] = options['entrypoint'] if options['entrypoint']
      data
    end

    # @param [Array<String>] port_options
    # @return [Array<Hash>]
    def parse_stringified_ports(port_options)
      parse_ports(port_options).map {|p|
        {
          'ip' => p[:ip],
          'container_port' => p[:container_port],
          'node_port' => p[:node_port],
          'protocol' => p[:protocol]
        }
      }
    end

    # @param [Array<String>] link_options
    # @return [Array<Hash>]
    def parse_links(link_options)
      link_options.map{|l|
        if l.kind_of?(String)
          service_name, alias_name = l.split(':')
        elsif l.kind_of?(Hash)
          service_name = l['name']
          alias_name = l['alias']
        else
          raise TypeError, "Invalid link type #{l.class.name}, expecting String or Hash"
        end
        if service_name.nil?
          raise ArgumentError.new("Invalid link value #{l}")
        end
        alias_name = service_name if alias_name.nil?
        {
            'name' => service_name,
            'alias' => alias_name
        }
      }
    end

    # @param [Hash] options
    # @return [Hash]
    def parse_build_options(options)
      build = {}
      build['context'] = options['build'] if options['build']
      build['dockerfile'] = options['dockerfile'] if options['dockerfile']
      build
    end

    # @param [Hash] options
    # @return [Hash]
    def parse_health_check(options)
      health_check = {}
      %w(port protocol uri timeout interval initial_delay).each do |k|
        health_check[k] = options.dig('health_check', k)
      end
      health_check
    end
  end
end


text:
@class UMTextView;
@class UMRadialView;
@interface UMChatToolBar : UIToolbar

@property (strong, nonatomic) UMTextView *inputTextView;

@property (strong, nonatomic) UIButton *rightButton;
@property (strong, nonatomic) UIButton *leftButton;
@property (strong, nonatomic) UIButton *recordButton;
@property (strong, nonatomic) UIButton *plusButton;
@property (nonatomic) BOOL textValid;

@property (nonatomic) BOOL isAudioEnabled;
@property (nonatomic) BOOL isAudioInput;

@property (strong, nonatomic) NSString *audioPath;
@property (strong, nonatomic) NSMutableDictionary *contactInfo;

@property (nonatomic) BOOL isEditMode;

- (NSString *)textContent;
//- (void)showRecordInfo;

- (void)cleanInputText;
@end


text:
package cat.calidos.morfeu.model.metadata.injection;

import java.net.URI;

import javax.annotation.Nullable;
import javax.inject.Named;

import dagger.BindsInstance;
import dagger.Component;

import com.sun.xml.xsom.XSAnnotation;

import cat.calidos.morfeu.model.Metadata;

/** This component is used to fetch the metadata for a cell model, needs the annotation as well as the location in the
* 	cell model hierarchy.
* 	@author daniel giribet
*///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Component(modules={ModelMetadataModule.class})
public interface ModelMetadataComponent {

Metadata value();

@Component.Builder
interface Builder {

	@BindsInstance Builder from(@Nullable XSAnnotation annotation);
	@BindsInstance Builder withParentURI(@Nullable @Named("ParentURI") URI parentURI);

	ModelMetadataComponent build();

}

}


text:
source ~/.bash_profile

data=$1
month_time=$2
hive_table1=$3
hive_table2=$4
echo $data
echo $hive_table1
echo $hive_table2
hdfs dfs -rm -r -f -skipTrash /dataOffline/$hive_table2/ds=$data
spark-sql --driver-class-path /data/tmp/zhanshulin/jar/mysql-connector-java-commercial-5.1.40-bin.jar --name 分类标准化 --driver-memory 8g --executor-memory 8G --executor-cores 4 --num-executors 3 --conf "spark.default.parallelism=100" --master yarn --queue q_gmv --master yarn -e"
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nostrict;
set mapred.job.queue.name=q_gmv;

use default;
set hive.map.aggr=true;
set hive.groupby.skewindata=true;
set hive.exec.parallel=true;
set mapred.reduce.tasks=10;
select '删除临时表 ';

drop table article_level_num_month;
drop table tmp_leve_1_avg_1;
drop table tmp_leve_2_avg_1;
drop table tmp_leve_1_avg_11;
drop table tmp_leve_2_avg_11;
drop table tmp_leve_1_num_1;
drop table tmp_leve_2_num_1;
drop table tmp_leve_1_num_11;
drop table tmp_leve_2_num_11;
DROP TABLE  tmp_article_level_num_month;
drop TABLE  article_level_num_month;

select '统计最近30天原创和优惠的分类访问次数';
select '临时表 tmp_article_level_num_month';
create table tmp_article_level_num_month as select device_id ,user_id ,article_channel_name ,level_type ,level_id ,level_num ,article_channel_id from JFH_article_level_num where ds between '$month_time' and '$data' ;
select '临时表 article_level_num_month';
create table article_level_num_month as select device_id ,user_id ,article_channel_name ,level_type ,level_id ,sum(level_num) as level_num ,article_channel_id from tmp_article_level_num_month group by device_id ,user_id ,article_channel_name ,level_type ,level_id ,article_channel_id;

select '临时表 tmp_leve_1_avg_1';
create table tmp_leve_1_avg_1 as select device_id,user_id,article_channel_id,stddev(level_num) as stddev,avg(level_num) as avg from article_level_num_month where level_type = 1 and article_channel_id = 1 group by device_id,user_id,article_channel_id;
select '临时表 tmp_leve_2_avg_1';
create table tmp_leve_2_avg_1 as select device_id,user_id,article_channel_id,stddev(level_num) as stddev,avg(level_num) as avg from article_level_num_month where level_type = 2 and article_channel_id = 1 group by device_id,user_id,article_channel_id;

select '临时表 tmp_leve_1_num_1';
create table tmp_leve_1_num_1 as select t1.device_id,t1.user_id,t2.article_channel_name,t2.level_type,t2.level_id,t2.level_num,t1.article_channel_id,t1.stddev,t1.avg from tmp_leve_1_avg_1 t1 join article_level_num_month t2 on t1.device_id=t2.device_id and t1.user_id=t2.user_id and t1.article_channel_id=t2.article_channel_id where t2.level_type = 1 and t1.device_id <> '';
select '临时表 tmp_leve_2_num_1';
create table tmp_leve_2_num_1 as select t1.device_id,t1.user_id,t2.article_channel_name,t2.level_type,t2.level_id,t2.level_num,t1.article_channel_id,t1.stddev,t1.avg from tmp_leve_2_avg_1 t1 join article_level_num_month t2 on t1.device_id=t2.device_id and t1.user_id=t2.user_id and t1.article_channel_id=t2.article_channel_id where t2.level_type = 2 and t1.device_id <> '';

select '插入优惠 1 级分类标准化';
insert into table $hive_table2 partition(ds='$data') select device_id,user_id,article_channel_name,level_type,level_id,level_num,(case level_standar when 'NaN' then 0 else level_standar end) as level_standar,article_channel_id from (select device_id,user_id,article_channel_name,level_type,level_id,level_num,round((level_num-avg) / stddev , 4) as level_standar , article_channel_id from tmp_leve_1_num_1 group by device_id,user_id,article_channel_name,level_type,level_id,level_num,avg,stddev,article_channel_id) t ;
select '插入优惠 2 级分类标准化';
insert into table $hive_table2 partition(ds='$data') select device_id,user_id,article_channel_name,level_type,level_id,level_num,(case level_standar when 'NaN' then 0 else level_standar end) as level_standar,article_channel_id from (select device_id,user_id,article_channel_name,level_type,level_id,level_num,round((level_num-avg) / stddev , 4) as level_standar , article_channel_id from tmp_leve_2_num_1 group by device_id,user_id,article_channel_name,level_type,level_id,level_num,avg,stddev,article_channel_id) t ;

exit;
"


text:
package schema;

public class S6000007
    extends Schematic
{

    public S6000007(){
        super("S6000007","SPARTAN","S6_PVCU_3B_BGA","degrees","12","sprintf","%5.4f","Photovolatic Control Unit (PVCU) - Solar Array - 3B - Beta Gimble Assembly (BGA) Position (degrees)","Photovolatic Control Unit (PVCU) - Solar Array - 3B - Beta Gimble Assembly (BGA) Position (degrees) 0 degrees points inboard");
    }

    public Object parse(String string){
        try {
            return new Float(string);
        }
        catch (NumberFormatException exc){
            return string;
        }
    }

}