text:
#include <cassert>

#include "structures/vroom/input/vehicle_step.h"

namespace vroom {

ForcedService::ForcedService()
  : at(std::optional<Duration>()),
    after(std::optional<Duration>()),
    before(std::optional<Duration>()) {
}

ForcedService::ForcedService(std::optional<Duration>&& at,
                             std::optional<Duration>&& after,
                             std::optional<Duration>&& before)
  : at(std::move(at)), after(std::move(after)), before(std::move(before)) {
}

VehicleStep::VehicleStep(STEP_TYPE type, ForcedService&& forced_service)
  : id(0),
    type(type),
    job_type(JOB_TYPE::SINGLE),
    forced_service(std::move(forced_service)) {
  assert(type == STEP_TYPE::START or type == STEP_TYPE::END);
}

VehicleStep::VehicleStep(STEP_TYPE type, Id id, ForcedService&& forced_service)
  : id(id),
    type(type),
    job_type(JOB_TYPE::SINGLE),
    forced_service(std::move(forced_service)) {
  assert(type == STEP_TYPE::BREAK);
}

VehicleStep::VehicleStep(JOB_TYPE job_type,
                         Id id,
                         ForcedService&& forced_service)
  : id(id),
    type(STEP_TYPE::JOB),
    job_type(job_type),
    forced_service(std::move(forced_service)) {
}

} // namespace vroom


text:
class Test {
    public void foo(Object[] array) {
        ((<warning descr="Casting 'array' to 'String[]' is redundant">String[]</warning>) array)[0] = " ";
    }

    public void bar(String[] array) {
        ((Object[]) array)[0] = new Object();
    }

    public Object obj;
    public static void setObjValueInArray(Test t, Object val) {
      t.obj = new Object[1];
      ((Object[])t.obj)[0] = val;
    }

    public static void arrayDims() {
        int[] ints = new int[] {};
        Object foo = 1;
        ints[(Integer)  foo] = 0;
        ints[(<warning descr="Casting '1' to 'Integer' is redundant">Integer</warning>)  1] = 0;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<resources>
    <!-- Example customization of dimensions originally defined in res/values/dimens.xml
         (such as screen margins) for screens with more than 820dp of available width. This
         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
    <dimen name="activity_horizontal_margin">64dp</dimen>
    <dimen name="grid_height">760dp</dimen>
    <dimen name="medium_grid_size">252dp</dimen>
    <dimen name="large_grid_size">76dp</dimen>
    <dimen name="marker_width">46dp</dimen>
</resources>


text:
CREATE INDEX index_rolename ON roles (rolename);
CREATE INDEX index_rolegroup ON roles (rolegroup);
CREATE INDEX index_tenant_id ON roles (tenant_id);

CREATE INDEX index_user_id ON accounts_roles (user_id);
CREATE INDEX index_account_id ON accounts_roles (account_id);
CREATE INDEX index_acct_role_id ON accounts_roles (role_id);

CREATE INDEX index_permission_id ON permissions_roles (permission_id);
CREATE INDEX index_perm_role_id ON permissions_roles (role_id);


text:
@interface JGAllViewController : JGBaseTableViewController

@end


text:
package org.anc.lapps.util;

import java.util.*;

/**
 * @author Keith Suderman
 */
public class LappsUtils
{
   public LappsUtils()
   {

   }

   public static String makeStringList(List<String> strings)
   {
      StringBuilder builder = new StringBuilder();
      Iterator<String> it = strings.iterator();
      if (it.hasNext())
      {
         builder.append(it.next());
      }
      while (it.hasNext())
      {
         builder.append("\n");
         builder.append(it.next());
      }
      return builder.toString();
   }

   public static String makeStringList(String[] strings)
   {
      StringBuilder builder = new StringBuilder();
      int i = 0;
      if (i < strings.length)
      {
         builder.append(strings[i]);
         ++i;
      }
      while (i < strings.length)
      {
         builder.append("\n");
         builder.append(strings[i]);
         ++i;
      }
      return builder.toString();
   }

   public static List<String> parseStringList(String input)
   {
      return Arrays.asList(input.split("\n"));
   }
}


text:
package org.apache.mahout.clustering.evaluation;

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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.mahout.clustering.classify.WeightedVectorWritable;
import org.apache.mahout.math.VectorWritable;

public class RepresentativePointsReducer
  extends Reducer<IntWritable, WeightedVectorWritable, IntWritable, VectorWritable> {

  private Map<Integer, List<VectorWritable>> representativePoints;

  @Override
  protected void cleanup(Context context) throws IOException, InterruptedException {
    for (Map.Entry<Integer, List<VectorWritable>> entry : representativePoints.entrySet()) {
      IntWritable iw = new IntWritable(entry.getKey());
      for (VectorWritable vw : entry.getValue()) {
        context.write(iw, vw);
      }
    }
    super.cleanup(context);
  }

  @Override
  protected void reduce(IntWritable key, Iterable<WeightedVectorWritable> values, Context context)
    throws IOException, InterruptedException {
    // find the most distant point
    WeightedVectorWritable mdp = null;
    for (WeightedVectorWritable dpw : values) {
      if (mdp == null || mdp.getWeight() < dpw.getWeight()) {
        mdp = new WeightedVectorWritable(dpw.getWeight(), dpw.getVector());
      }
    }
    context.write(new IntWritable(key.get()), new VectorWritable(mdp.getVector()));
  }

  @Override
  protected void setup(Context context) throws IOException, InterruptedException {
    super.setup(context);
    Configuration conf = context.getConfiguration();
    representativePoints = RepresentativePointsMapper.getRepresentativePoints(conf);
  }

  public void configure(Map<Integer, List<VectorWritable>> representativePoints) {
    this.representativePoints = representativePoints;
  }

}


text:
<com.sina.sinavideo.sdk.dlna.DLNALinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@id/dlna_zhanwei_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="@dimen/media_controller_tip_padding"
    android:visibility="gone" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/tvicon"
        android:visibility="visible" />

    <com.sina.sinavideo.sdk.dlna.DLNANameTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#b1b1b1"
        android:layout_marginTop="5dp"
        android:textSize="18sp" />
    <com.sina.sinavideo.sdk.dlna.DLNACloseButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:text="@string/dlna_switch_to_mobile"
        android:background="#3399ff"
        android:layout_marginTop="5dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:gravity="center"
        android:textSize="18sp" />

</com.sina.sinavideo.sdk.dlna.DLNALinearLayout>


text:
require 'rails/generators/mongomatic_generator'

module Mongomatic
  module Generators
    class ModelGenerator < Base
      desc "Creates a mongomatic model"
      class_option :connection,
                   :type => :string,
                   :default => "",
                   :desc => "Connection String",
                   :banner => "Mongo::Connection.new.db('test')",
                   :aliases => ['-c']

      class_option :expectations,
                   :desc => "Include Mongomatic::Expectations",
                   :default => false,
                   :aliases => ['-e'],
                   :type => :boolean

      check_class_collision

      def connection
        options[:connection]
      end

      def expectations?
        options[:expectations] == true
      end

      def create_model_file
        template "model.rb", File.join("app/models", class_path, "#{file_name}.rb")
      end

      hook_for :test_framework
    end
  end
end


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

namespace NerdAmigo.Abstractions
{
	/// <summary>
	/// Provide the current environment name for the running application
	/// For example: "development", "integration", "staging", "production"
	/// </summary>
	public interface IEnvironmentConfigurationNameResolver
	{
		string GetConfigurationName();
	}
}


text:
layout: page
title: Mueller Technologies Dinner
date: 2016-05-24
author: Catherine Garza
tags: weekly links, java
status: published
summary: Aenean finibus urna rhoncus turpis.
banner: images/banner/people.jpg
booking:
  startDate: 12/12/2019
  endDate: 12/16/2019
  ctyhocn: BNAGDHX
  groupCode: MTD
published: true
---
Curabitur tincidunt, dolor id lacinia ornare, ligula massa posuere neque, vel ornare felis velit eget eros. Suspendisse potenti. Fusce dignissim dolor risus, vel vehicula est egestas eget. Nunc ac leo sodales, facilisis elit ut, lacinia eros. Morbi accumsan dapibus dolor in egestas. Duis porta at magna id facilisis. Phasellus consequat, libero id tempor molestie, odio leo varius lectus, tempor mollis lectus eros sed enim. Donec molestie efficitur molestie. Aliquam iaculis dui sed accumsan feugiat. Nullam ut consectetur arcu. Curabitur consequat tristique condimentum. Quisque ex libero, dignissim sagittis erat sed, consectetur gravida diam.

1 Phasellus id magna a urna venenatis accumsan
1 Suspendisse sit amet magna eu lorem consectetur hendrerit at sed magna
1 Nunc nec justo porttitor, gravida neque nec, aliquet orci
1 Curabitur semper tortor sit amet venenatis fringilla
1 Integer fringilla leo et nibh ullamcorper, ac egestas orci luctus
1 Morbi elementum ante non dolor scelerisque dictum.

Nullam convallis efficitur luctus. Duis viverra nibh a elementum sodales. Donec eu tristique felis. Morbi iaculis eros vitae turpis egestas tincidunt. Nulla sapien elit, dignissim id velit nec, aliquam pulvinar ante. Ut eu posuere nunc. Mauris sodales viverra metus, in volutpat ex vehicula vitae. Praesent vulputate, quam vel euismod vulputate, lectus arcu tincidunt augue, a dignissim eros dui vitae felis. Curabitur dapibus felis non nunc porttitor, vitae pharetra urna tempor.


text:
package com.g.lazyloadlistenersample.data;

import java.util.List;

public class BooksResponse {

    private String kind;

    private int totalItems;

    private List<Book> items;

    public String getKind() {
        return kind;
    }

    public int getTotalItems() {
        return totalItems;
    }

    public List<Book> getItems() {
        return items;
    }
}


text:
    <button type="button" class="btn btn-primary" ng-click="vm.openModal()">

      Cadastrar uma ong
    </button>

          {{ong.nome}}

          {{ong.cidade}}

          {{ong.telefone}}


text:
function Force() {

  var units;
  var victor;
  var ZOCrule;
  var attackingForceId;
  var defendingForceId;
  var deleteCount;

  var retreatHexagonList;
  var eliminationTrayHexagonX;
  var eliminationTrayHexagonY;

  this.units = new Array();
  this.victor = RED_FORCE;
  this.ZOCrule = true;
  this.deleteCount = 0;

  this.retreatHexagonList = new Array();
  this.eliminationTrayHexagonX = 9;
  this.eliminationTrayHexagonY = 0;
}

function unit( unitId, unitName, unitForceId, unitHexagon, unitImage, unitStrength, unitMaxMove, unitStatus, unitReinforceZone, unitReinforceTurn ) {

  var id;
  var forceId;
 	var name;
 	var hexagon;
 	var image;
	var strength;
	var maxMove;
	var status;
	var moveAmountUsed;
	var reinforceZone;
	var reinforceTurn;
	var combatNumber;
	var combatIndex;
	var combatOdds;
	var hasContact;
	var moveCount;
	var retreatCountRequired;
	var combatResults;
	var dieRoll;
	var eliminationHexagonX;
	var eliminationHexagonY;

	this.id = unitId;
	this.name = unitName;
	this.forceId = unitForceId;
    this.hexagon = new Hexagon(unitHexagon);
    this.image = unitImage;
    this.strength = unitStrength;
    this.maxMove = unitMaxMove;
    this.status = unitStatus;
    this.moveAmountUsed = 0;
    this.reinforceZone = unitReinforceZone;
    this.reinforceTurn = unitReinforceTurn;
    this.combatNumber = 0;
    this.combatIndex = 0;
    this.combatOdds = "";
    this.hasContact = false;
	this.moveCount = 0;
    this.retreatCountRequired = 0;
    this.combatResults = NR;
}

function RetreatStep( RetreatStepStepNumber, RetreatHexagon )
{
	var stepNumber;
	var hexagon;

	this.stepNumber = RetreatStepStepNumber;
	this.hexagon = new Hexagon(RetreatHexagon.getNumber());
}

Force.prototype.addToRetreatHexagonList = function(id, retreatHexagon) {

	//alert("Force.prototype..prototype. adding: " + id + " : " + retreatHexagon.getName());
	// note: addToRetreatHexagonList() is invoked before retreat move, so
	//  the moveCount is 0 for 1st step and 1 for 2nd step

	var retreatStep = new RetreatStep( this.units[id].moveCount, retreatHexagon );

    this.retreatHexagonList.push( retreatStep );
}

Force.prototype.addUnit = function( unitName, unitForceId, unitHexagon, unitImage, unitStrength, unitMaxMove, unitStatus, unitReinforceZoneName, unitReinforceTurn ) {

    var id = this.units.length;
    this.units.push(new unit( id, unitName, unitForceId, unitHexagon, unitImage, unitStrength, unitMaxMove, unitStatus, unitReinforceZoneName, unitReinforceTurn ));
}

Force.prototype.advanceIsOnRetreatList = function(id, hexagon)
{
	var isOnList = false;

    for ( var i = 0; i < this.retreatHexagonList.length; i++ )
    {
	// note: addToRetreatHexagonList() is invoked before retreat move, so
	//  the moveCount is 0 for 1st step and 1 for 2nd step
	//  when advancing unit.moveCount will be 0 which will match 1st step retreat number

	//alert("Force.prototype..prototype. checkingt: " + id + " hexagon: " + hexagon.getName() + " with array " + this.retreatHexagonList[i].hexagon.getName());
		if ( this.retreatHexagonList[i].stepNumber == this.units[id].moveCount
			&& this.retreatHexagonList[i].hexagon.equals( hexagon ))
		{
			isOnList = true;
		}
	}

	return isOnList;
}

Force.prototype.applyCRTresults = function(combatNumber, combatResults, dieRoll)
{
    this.clearRetreatHexagonList();

    for ( var defender = 0; defender < this.units.length; defender++ )
    {
        if (this.units[defender].status == STATUS_DEFENDING && this.units[defender].combatNumber == combatNumber)
        {
            switch (combatResults)
            {
               case AR:
                    this.units[defender].status = STATUS_DEFENDED;
                    this.units[defender].retreatCountRequired = 0;
                    break;

               case AE:
                    this.units[defender].status = STATUS_DEFENDED;
                    this.units[defender].retreatCountRequired = 0;
                    break;

               case DE:
                    this.units[defender].status = STATUS_ELIMINATING;
                    this.units[defender].retreatCountRequired = 1;
                    this.addToRetreatHexagonList(defender, this.getUnitHexagon(defender));                    break;

                case DR:
                    this.units[defender].status = STATUS_CAN_RETREAT;
                    this.units[defender].retreatCountRequired = 1;
                    break;

                default:
                break;
             }
                this.units[defender].combatResults = combatResults;
                this.units[defender].dieRoll = dieRoll;
                this.units[defender].combatNumber = 0;
                this.units[defender].moveCount = 0;
        }
    }

    for ( var attacker = 0; attacker < this.units.length; attacker++ )
    {
        if (this.units[attacker].status == STATUS_ATTACKING && this.units[attacker].combatNumber == combatNumber)
        {
            switch (combatResults)
            {
                case AR:
                    this.units[attacker].status = STATUS_CAN_RETREAT;
                    this.units[attacker].retreatCountRequired = 1;
                    break;

                case AE:
                    this.units[attacker].status = STATUS_ELIMINATING;
                    this.units[attacker].retreatCountRequired = 0;
                    break;

                case DE:
                    this.units[attacker].status = STATUS_CAN_ADVANCE;
                    this.units[attacker].retreatCountRequired = 0;
                    break;

                case DR:
                    this.units[attacker].status = STATUS_CAN_ADVANCE;
                    this.units[attacker].retreatCountRequired = 0;
                    break;

                default:
                    break;
            }
            this.units[attacker].combatResults = combatResults;
            this.units[attacker].dieRoll = dieRoll;
            this.units[attacker].combatNumber = 0;
            this.units[attacker].moveCount = 0;
        }
    }
    this.removeEliminatingUnits();
}

Force.prototype.checkVictoryConditions = function()
{
    // last to occupy Marysville at 403 wins

    var hexagon = new Hexagon(403);

    for ( var id = 0; id < this.units.length; id++ )
    {
       if (this.units[id].hexagon.equals(hexagon))
        {
            this.victor = this.units[id].forceId;
        }
    }
}

Force.prototype.clearRetreatHexagonList = function() {

	this.retreatHexagonList = [];
}

Force.prototype.eliminateUnit = function(id)
{
	var hexagon = new Hexagon(this.units[id].hexpartX, this.units[id].hexpartY);
    this.deleteCount++;
	//alert("elim " + id + " at " + this.eliminationTrayHexagonX + ", " + this.eliminationTrayHexagonY);
    this.units[id].status = STATUS_ELIMINATED;
    this.units[id].hexagon.setXY(this.eliminationTrayHexagonX + ( 2 * this.deleteCount), this.eliminationTrayHexagonY);
}

Force.prototype.getAttackerStrength = function(combatNumber)
{
    var attackerStrength = 0;

    for ( var id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_ATTACKING && this.units[id].combatNumber == combatNumber)
        {
            attackerStrength += this.units[id].strength;
        }
    }

    return attackerStrength;
}

Force.prototype.getAttackerHexagonList = function(combatNumber) {

    var hexagonList = new Array();

    for (var id = 0; id < this.units.length; id++) {
        if (this.units[id].status == STATUS_ATTACKING && this.units[id].combatNumber == combatNumber) {

            hexagonList.push(this.units[id].hexagon);
        }
    }
    return hexagonList;
}

Force.prototype.getCombatHexagon = function(combatNumber)
{
    var hexagon;

    for ( var id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].combatNumber == combatNumber && this.units[id].status == STATUS_DEFENDING)
        {
            hexagon = this.units[id].hexagon;
        }
    }
    return hexagon;
}

Force.prototype.getCombatInfo = function(id)
{
	return this.units[id].combatOdds;
}

Force.prototype.getDefenderStrength = function(combatNumber)
{
    var defenderStrength = 0;

    for ( var id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_DEFENDING && this.units[id].combatNumber == combatNumber)
        {
            defenderStrength += this.units[id].strength;
        }
    }

    return defenderStrength;
}

Force.prototype.getRetreatHexagonList = function() {

    var i;
    var retreatHexagonList = "advance hexagon list: ";

    for (i = 0; i < 6; i++) {

        if (retreatHexpartX[i] > 0 || retreatHexpartY[i] > 0) {
            hexagon = new hexagon(retreatHexpartX[i], retreatHexpartY[i]);
            retreatHexagonList = retreatHexagonList + " " + hexagon.getHexagonName();
        }
        //retreatHexagonList += " | " + retreatHexpartX[i] + ", " + retreatHexpartY[i];
    }

    //retreatHexagonList = retreatHexpartX[0] + ", " + retreatHexpartY[0];

    return (retreatHexagonList);
}

Force.prototype.getUnitBeingEliminatedId = function()
{
    var id;

    for ( var i = 0; i < this.units.length; i++ )
    {
        if (this.units[i].status == STATUS_ELIMINATING)
        {
            id = this.units[i].id;
        }
    }
    return id;
}

Force.prototype.getUnitCombatIndex = function(id)
{
    return this.units[id].combatIndex;
}

Force.prototype.getUnitCombatNumber = function(id)
{
    return this.units[id].combatNumber;
}

Force.prototype.getUnitForceId = function(id)
{
    return this.units[id].forceId;
}

Force.prototype.getUnitHexagon = function( id )
{

	return this.units[id].hexagon;
}

Force.prototype.getUnitInfo = function( id ) {

    var unitInfo = "";

    if (id >= 0) {
        unitInfo = this.units[id].name;
        unitInfo += " " + status_name[this.units[id].status];
        unitInfo += "
strength: " + this.units[id].strength;
        unitInfo += "
can move: " + this.units[id].maxMove;

        if (this.units[id].status == STATUS_MOVING) {
            unitInfo += "
has moved " + this.units[id].moveAmountUsed + " of " + this.units[id].maxMove;
        }
        else {
			unitInfo +="
 ";
        }

        if (this.units[id].status == STATUS_CAN_REINFORCE) {
            unitInfo += "
can reinforce on turn " + this.units[id].reinforceTurn;
        }
        else {
			unitInfo +="
 ";
        }

        if (this.units[id].status == STATUS_DEFENDING && this.unitHasAttackers(id)) {
        }
    }
	return unitInfo;
}

Force.prototype.getUnitMaximumMoveAmount = function(id)
{
    return this.units[id].maxMove;
}

Force.prototype.getUnitMoveCount = function(id)
{
    return this.units[id].moveCount;
}

Force.prototype.getUnitName = function(id)
{
	return this.units[id].name;
}

Force.prototype.getUnitReinforceTurn = function(id)
{
	return this.units[id].reinforceTurn;
}

Force.prototype.getUnitReinforceZone = function( id )
{
	return this.units[id].reinforceZone;
}

Force.prototype.getUnitRetreatCountRequired = function(id)
{
    return this.units[id].retreatCountRequired;
}

Force.prototype.getVictorId = function()
{
    return this.victor;
}

Force.prototype.hexagonIsZOC = function(id, hexagon)
{
    var isZOC = false;

    if (this.ZOCrule == true)
    {
        var los = new Los();
        los.setOrigin(hexagon);

        for ( i = 0; i < this.units.length; i++ )
        {
            los.setEndPoint(this.units[i].hexagon);
            if (los.getRange() == 1
                && this.units[i].forceId != this.units[id].forceId
                && this.units[i].status != STATUS_CAN_REINFORCE
                && this.units[i].status != STATUS_ELIMINATED
            )
            {
                isZOC = true;
                break;
            }
        }
    }
    return isZOC;
}

Force.prototype.hexagonIsOccupied = function(hexagon)
{
    var isOccupied = false;

    for ( var id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].hexagon.equals(hexagon))
        {
            isOccupied = true;
        }
    }

    return isOccupied;
}

Force.prototype.isForceEliminated = function()
{
	var isForceEliminated = false;
	var isDefendingForceEliminated = true;
	var isAttackingForceEliminated = true;

    for ( var id = 0; id < this.units.length; id++ )
    {
       if (this.units[id].forceId == this.defendingForceId && this.units[id].status != STATUS_ELIMINATED )
        {
			// found one alive, so make it false
            isDefendingForceEliminated = false;
        }
    }

    for ( var id = 0; id < this.units.length; id++ )
    {
       if (this.units[id].forceId == this.attackingForceId && this.units[id].status != STATUS_ELIMINATED )
        {
			// found one alive, so make it false
            isAttackingForceEliminated = false;
        }
    }

    if(isDefendingForceEliminated == true ||  isAttackingForceEliminated == true)
    {
		isForceEliminated = true;
    }
    return isForceEliminated;
}

Force.prototype.moreCombatToResolve = function() {

    var moreCombatToResolve = false;

    for ( id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_DEFENDING
            && this.unitHasAttackers(id)
        )
        {
            moreCombatToResolve = true;
            break;
        }
    }
    return moreCombatToResolve;
}

Force.prototype.recoverUnits = function()
{
    for ( id = 0; id < this.units.length; id++ )
    {
    switch (this.units[id].status)
        {
            case STATUS_STOPPED:
            case STATUS_DEFENDED:
            case STATUS_DEFENDING:
            case STATUS_ATTACKED:
            case STATUS_ATTACKING:
            case STATUS_RETREATED:
            case STATUS_ADVANCED:
            case STATUS_CAN_ADVANCE:

                this.units[id].status = STATUS_READY;
                this.units[id].moveAmountUsed = 0;
                break;

             default:
                break;
        }
        this.units[id].combatIndex = 0;
        this.units[id].combatNumber = 0;
        this.units[id].combatResults = NR;
    }
}

Force.prototype.removeEliminatingUnits = function()
{
    for ( var id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_ELIMINATING)
        {
           this.eliminateUnit(id);
        }
    }
}

Force.prototype.resetRemainingAdvancingUnits = function()
{
    for ( var id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_ADVANCING || this.units[id].status == STATUS_CAN_ADVANCE)
        {
            this.units[id].status = STATUS_ATTACKED;
        }
    }
}

Force.prototype.setAttackingForceId = function(forceId)
{
    if ( forceId == BLUE_FORCE )
    {
        this.attackingForceId = BLUE_FORCE;
        this.defendingForceId = RED_FORCE;
    }
    else
    {
        this.attackingForceId = RED_FORCE;
        this.defendingForceId = BLUE_FORCE;
    }
}

Force.prototype.setEliminationTrayXY = function(hexagonNumber)
{
	var hexagon = new Hexagon(hexagonNumber);
	this.eliminationTrayHexagonX = hexagon.getX();
	this.eliminationTrayHexagonY = hexagon.getY();
}

Force.prototype.setStatus = function( id,  status)
{
    var success = false;
    switch (status)
    {
        case STATUS_REINFORCING:
            if (this.units[id].forceId == this.attackingForceId && this.units[id].status == STATUS_CAN_REINFORCE)
            {
                this.units[id].status = status;
                success = true;
            }
            break;

        case STATUS_CAN_REINFORCE:
            if (this.units[id].forceId == this.attackingForceId && this.units[id].status == STATUS_REINFORCING)
            {
                this.units[id].status = status;
                success = true;
            }
            break;

        case STATUS_READY:
        case STATUS_DEFENDING:
        case STATUS_ATTACKING:
            this.units[id].status = status;
            break;

        case STATUS_MOVING:
            if (this.units[id].forceId == this.attackingForceId
                && (this.units[id].status == STATUS_READY || this.units[id].status == STATUS_REINFORCING))
            {
               this.units[id].status = status;
               this.units[id].moveCount = 0;
               this.units[id].moveAmountUsed = 0;
               success = true;
            }
            break;

        case STATUS_STOPPED:
            if (this.units[id].status == STATUS_MOVING)
            {
                this.units[id].status = status;
                success = true;
            }
            if (this.units[id].status == STATUS_ADVANCING)
            {
                this.units[id].status = STATUS_ADVANCED;
                success = true;
            }
            if (this.units[id].status == STATUS_RETREATING)
            {
                this.units[id].status = STATUS_RETREATED;
                success = true;
            }
            break;

        case STATUS_EXITED:
            if (this.units[id].status == STATUS_MOVING)
            {
                this.units[id].status = status;
                success = true;
            }
            break;

        case STATUS_RETREATING:
            if (this.units[id].status == STATUS_CAN_RETREAT)
            {
                this.units[id].status = status;
                this.units[id].moveCount = 0;
                this.units[id].moveAmountUsed = 0;
                success = true;
            }
            break;

        case STATUS_ADVANCING:
            if (this.units[id].status == STATUS_CAN_ADVANCE)
            {
                this.units[id].status = status;
                this.units[id].moveCount = 0;
                this.units[id].moveAmountUsed = 0;
                success = true;
            }
            break;

        case STATUS_ADVANCED:
            if (this.units[id].status == STATUS_ADVANCING) {
                this.units[id].status = status;
                success = true;
            }
            break;

        default:
            break;
    }
    return success;
}

Force.prototype.setupAttacker = function(id, combatNumber)
{
    this.units[id].status = STATUS_ATTACKING;
    this.units[id].combatNumber = combatNumber;
}

Force.prototype.setupDefender = function(id, combatNumber)
{
    this.units[id].status = STATUS_DEFENDING; ;
    this.units[id].combatNumber = combatNumber;
}

Force.prototype.storeCombatIndex = function(combatNumber, combatIndex)
{
    for ( var id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].combatNumber == combatNumber)
        {
            this.units[id].combatIndex = combatIndex;
        }
    }
}

Force.prototype.storeCombatOdds = function(combatNumber, combatOdds)
{
    for ( var id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].combatNumber == combatNumber)
        {
            this.units[id].combatOdds = combatOdds;
        }
    }
}

Force.prototype.undoAttackerSetup = function(id)
{
    this.units[id].status = STATUS_READY;
    this.units[id].combatNumber = 0;
    this.units[id].combatIndex = 0;
}

 Force.prototype.undoDefendersWithoutAttackers = function()
{
    for ( id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_DEFENDING && this.unitHasAttackers(id) == false)
        {
            this.units[id].status = STATUS_READY;
        }
    }
}

Force.prototype.unitCanAdvance = function(id)
{
    var Advance = false;
    if ( this.units[id].status == STATUS_CAN_ADVANCE )
    {
        Advance = true;
    }
    return Advance;
}

Force.prototype.unitCanMove = function(id) {
    var canMove = false;
    if (this.units[id].status == STATUS_READY
        && this.units[id].forceId == this.attackingForceId) {
        canMove = true;
    }
    return canMove;
}

Force.prototype.unitCanReinforce = function(id) {
    var canReinforce = false;
    if (this.units[id].status == STATUS_CAN_REINFORCE
        && this.units[id].forceId == this.attackingForceId)
    {
        canReinforce = true;
    }
    return canReinforce;
}

Force.prototype.unitCanRetreat = function(id)
{
    var canRetreat = false;
    if ( this.units[id].status == STATUS_CAN_RETREAT )
    {
        canRetreat = true;
    }
    return canRetreat;
}

Force.prototype.unitGetAttackerList = function(id)
{
    var attackerList = "";

    for ( i = 0; i < this.units.length; i++ )
    {
        if (this.units[i].forceId == this.attackingForceId
        && this.units[i].combatNumber == this.units[id].combatNumber
        )
        {
            attackerList += this.units[i].name + " ";
        }
    }
    return attackerList;
}

Force.prototype.unitHasAttackers = function(id)
{
    var hasAttackers = false;

    for ( i = 0; i < this.units.length; i++ )
    {
        if (this.units[i].forceId == this.attackingForceId
        && this.units[i].combatNumber == this.units[id].combatNumber
        )
        {
            hasAttackers = true;
            break;
        }
    }
    return hasAttackers;
}

Force.prototype.unitHasMetRetreatCountRequired = function(id)
{
    var unitHasMetRetreatCountRequired = false;

    if( this.units[id].moveCount == this.units[id].retreatCountRequired )
    {
        unitHasMetRetreatCountRequired = true;
    }

    return unitHasMetRetreatCountRequired;
}

Force.prototype.unitHasMoveAmountAvailable = function( id, moveAmount)
{
    var canMove;

    if (this.units[id].moveAmountUsed + moveAmount <= this.units[id].maxMove)
    {
        canMove = true;
    }
    else
    {
        canMove = false;
    }
    return canMove;
}

Force.prototype.unitHasNotMoved = function(id)
{
    var hasMoved;

    if (this.units[id].moveAmountUsed == 0)
    {
        hasMoved = true;
    }
    else
    {
    hasMoved = false;
    }
    return hasMoved;
}

Force.prototype.unitHasUsedMoveAmount = function(id)
{
    var maxMove;

    // moveRules amount used can be larger if can always moveRules at least one hexagon
    if (this.units[id].moveAmountUsed >= this.units[id].maxMove)
    {
        maxMove = true;
    }
    else
    {
        maxMove = false;
    }
    return maxMove;
}

Force.prototype.unitIsAttacking = function(id)
{
    var isAttacking = false;

    if (this.units[id].status == STATUS_ATTACKING)
    {
        isAttacking = true;
    }
    return isAttacking;
}

Force.prototype.unitIsDefending = function(id)
{
	var isDefending = false;

	if (this.units[id].status == STATUS_DEFENDING) {
	    isDefending = true;
	}

	return isDefending;
}

Force.prototype.unitIsEliminated = function(id)
{
    var isEliminated = false;

    if (this.units[id].status == STATUS_ELIMINATED)
    {
        isEliminated = true;
    }
    return isEliminated;
}

Force.prototype.unitIsEnemy = function(id)
{
    var isEnemy = false;

    if (this.units[id].forceId == this.defendingForceId)
    {
        isEnemy = true;
    }
    return isEnemy;
}

Force.prototype.unitIsFriendly = function(id)
{
	var isFriendly = false;

	if (this.units[id].forceId == this.attackingForceId)
	{
		isFriendly = true;
	}
	return isFriendly;
}

Force.prototype.unitIsInCombat = function(id)
{
    var inCombat = false;
    if (this.units[id].combatNumber > 0)
    {
        inCombat = true;
    }
     return inCombat;
}

Force.prototype.unitIsMoving = function(id)
{
    var isMoving = false;
    if ( this.units[id].status == STATUS_MOVING )
    {
        isMoving = true;
    }
    return isMoving;
}

Force.prototype.unitIsReinforcing = function(id)
{
    var isReinforcing;
    if (this.units[id].status == STATUS_REINFORCING)
    {
        isReinforcing = true;
    }
    else
    {
        isReinforcing = false;
    }
    return isReinforcing;
}

Force.prototype.unitIsRetreating = function(id)
{
    var isRetreating = false;
    if ( this.units[id].status == STATUS_RETREATING )
    {
        isRetreating = true;
    }
    return isRetreating;
}

Force.prototype.unitIsZOC = function(id)
{
    var isZOC = false;

    if (this.ZOCrule == true)
    {
        var los = new Los();
        los.setOrigin(this.units[id].hexagon);

        for ( i = 0; i < this.units.length; i++ )
        {
            los.setEndPoint(this.units[i].hexagon);
            if (los.getRange() == 1
                && this.units[i].forceId != this.units[id].forceId
                && this.units[i].status != STATUS_CAN_REINFORCE
                && this.units[i].status != STATUS_ELIMINATED
            )
            {
                isZOC = true;
                break;
            }
        }
    }
    return isZOC;
}

Force.prototype.unitWillUseMaxMove = function(id, moveAmount)
{
	var willStop;

    if (this.units[id].moveAmountUsed + moveAmount >= this.units[id].maxMove)
    {
		willStop = true;
	}
	else
    {
		willStop = false;
	}
	return willStop;
}

Force.prototype.unitsAreAdvancing = function()
{
    var areAdvancing = false;

    for ( id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_CAN_ADVANCE
            || this.units[id].status == STATUS_ADVANCING
        )
        {
            areAdvancing = true;
            break;
        }
    }
    return areAdvancing ;
}

Force.prototype.unitsAreBeingEliminated = function()
{
    var areBeingEliminated= false;

    for ( id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_ELIMINATING)
        {
            areBeingEliminated= true;
            break;
        }
    }
    return areBeingEliminated;
}

Force.prototype.unitsAreDefending = function()
{
    var areDefending = false;

    for ( id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_DEFENDING)
        {
            areDefending= true;
            break;
        }
    }
    return areDefending;
}

Force.prototype.unitsAreRetreating = function()
{
    var areRetreating = false;

    for ( id = 0; id < this.units.length; id++ )
    {
        if (this.units[id].status == STATUS_CAN_RETREAT
            || this.units[id].status == STATUS_RETREATING
        )
        {
            areRetreating = true;
            break;
        }
    }
    return areRetreating;
}

Force.prototype.updateMoveStatus = function( id,  hexagon,  moveAmount)
{
    this.units[id].hexagon = hexagon;
    this.units[id].moveCount++;
    this.units[id].moveAmountUsed = this.units[id].moveAmountUsed + moveAmount;
}


text:
// @flow

/**
 * "connection" module provide common connection utilities that are unnecessery
 * for system to work
 */

import Api, { type ApiFunctionType as _ApiFunctionType } from './Api';
import * as Socket from './Socket';

export type ApiFunctionType = _ApiFunctionType;
export { Api, Socket };


text:
ACCEPTED

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

#### Published in
Annls mycol. 18(4/6): 183 (1921)

#### Original name
Broomella munkii Speg., 1885

### Remarks
null


text:
export * from './base-form';
export * from './date';
export * from './text';
export * from './submit-button';
export * from './validation-message';
export * from './checkbox';
export * from './field-message-map';
export * from './select';
export * from './password';
export * from './utility';
export * from './textarea';
export * from './integer';
export * from './number';


text:
import React from 'react';
import { StepFunction } from 'crius-test';
import { mount } from 'enzyme';
import { RcThemeProvider } from '@ringcentral-integration/rcui';
import { ManualEntryPanel, ManualEntryPanelProps } from './ManualEntryPanel';

let wrapper;
const currentLocale = 'en-US';
const defaultTransferCountryOptions = [
  { countryId: 'CAN', countryName: 'Canada' },
  { countryId: 'FRA', countryName: 'France' },
  { countryId: 'GER', countryName: 'Germany' },
  { countryId: 'MEX', countryName: 'Mexico' },
  { countryId: 'MTQ', countryName: 'Martinique' },
  { countryId: 'USA', countryName: 'US' },
  { countryId: 'USX', countryName: 'US Extended' },
];

function setup({
  goBack = () => {},
  transferRecipientCountryId = 'USA',
  changeRecipientNumber = () => {},
  changeRecipientCountryId = () => {},
  transferRecipientNumber = '6508653454',
  allowManualInternationalTransfer = false,
}: Partial<ManualEntryPanelProps>) {
  return mount(
    <RcThemeProvider>
      <ManualEntryPanel
        currentLocale={currentLocale}
        goBack={goBack}
        transferRecipientCountryId={transferRecipientCountryId}
        changeRecipientNumber={changeRecipientNumber}
        changeRecipientCountryId={changeRecipientCountryId}
        transferCountryOptions={defaultTransferCountryOptions}
        transferRecipientNumber={transferRecipientNumber}
        allowManualInternationalTransfer={allowManualInternationalTransfer}
      />
    </RcThemeProvider>,
  );
}

interface UTCheckManualEntryRenderProps {
  internalOptions: string;
}

export const UTCheckManualEntryRender: StepFunction<UTCheckManualEntryRenderProps> = async ({
  internalOptions,
}) => {
  const wrapper = setup({});
  const dataSign = {
    'Enter number field': 'transferRecipientNumber',
    Dialpad: 'dialPad',
  };
  expect(
    wrapper.find(`[data-sign="${dataSign[internalOptions]}"]`),
  ).not.toBeUndefined();
};

export const UTManualEntryInternationalTransferForbid: StepFunction<any> = async () => {
  const transferRecipientCountryId = 'FRA';
  const allowManualInternationalTransfer = false;
  wrapper = setup({
    allowManualInternationalTransfer,
    transferRecipientCountryId,
  });
  expect(wrapper.find('PickList[data-sign="transferCountry"]')).toHaveLength(0);
};

export const UTManualEntryInternationalTransferAllowed: StepFunction<any> = async () => {
  const changeRecipientCountryId = jest.fn(() => {});
  const allowManualInternationalTransfer = true;
  const countryId = 'GER';
  wrapper = setup({
    allowManualInternationalTransfer,
    changeRecipientCountryId,
  });

  const transferCountry = wrapper
    .find('PickList[data-sign="transferCountry"]')
    .at(0);
  transferCountry.find('[role="button"]').simulate('click');
  document.body
    .querySelector<HTMLLIElement>(`li[data-value="${countryId}"]`)
    .click();
  expect(changeRecipientCountryId).toBeCalledWith(countryId);
};

export const UTManualEntryInternationalTransferRender: StepFunction<any> = async () => {
  const transferRecipientCountryId = 'FRA';
  const transferRecipientNumber = '6508653454';
  const allowManualInternationalTransfer = true;
  wrapper = setup({
    allowManualInternationalTransfer,
    transferRecipientCountryId,
    transferRecipientNumber,
  });
  const transferCountry = wrapper.find('PickList[data-sign="transferCountry"]');
  expect(transferCountry.prop('value')).toBe(transferRecipientCountryId);

  expect(transferCountry.find('[role="button"]').text()).toBe(
    defaultTransferCountryOptions.filter(
      (x) => x.countryId === transferRecipientCountryId,
    )[0].countryName,
  );

  expect(
    wrapper
      .find('RecipientsInput[data-sign="transferRecipientNumber"]')
      .prop('value'),
  ).toBe(transferRecipientNumber);
};


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Reflection.Metadata;
using Xunit;

namespace Roslyn.Test.Utilities
{
    internal static class EncValidation
    {
        internal static void VerifyModuleMvid(int generation, MetadataReader previousReader, MetadataReader currentReader)
        {
            var previousModule = previousReader.GetModuleDefinition();
            var currentModule = currentReader.GetModuleDefinition();

            Assert.Equal(previousReader.GetGuid(previousModule.Mvid), currentReader.GetGuid(currentModule.Mvid));

            Assert.Equal(generation - 1, previousModule.Generation);
            Assert.Equal(generation, currentModule.Generation);

            if (generation == 1)
            {
                Assert.True(previousModule.GenerationId.IsNil);
                Assert.True(previousModule.BaseGenerationId.IsNil);

                Assert.False(currentModule.GenerationId.IsNil);
                Assert.True(currentModule.BaseGenerationId.IsNil);
            }
            else
            {
                Assert.False(currentModule.GenerationId.IsNil);
                Assert.False(currentModule.BaseGenerationId.IsNil);

                Assert.Equal(previousReader.GetGuid(previousModule.GenerationId), currentReader.GetGuid(currentModule.BaseGenerationId));
            }

            Assert.NotEqual(default(Guid), currentReader.GetGuid(currentModule.GenerationId));
        }
    }
}


text:
module SageoneSdk
  class Client

    # Represents the countries available to select in Sage One.
    module Countries

      # @return [object] Returns all countries.
      def countries(options = {})
        get "countries", options
      end

      # @return [object] Returns the country with the given id.
      def country(id, options = {})
        get "countries/#{id}", options
      end
    end
  end
end


text:
package net.lucenews.controller;

import java.util.*;
import net.lucenews.*;
import net.lucenews.atom.*;
import net.lucenews.model.*;
import net.lucenews.model.exception.*;
import net.lucenews.view.*;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.misc.ChainedFilter;
import org.apache.lucene.search.*;
import org.w3c.dom.*;

public class FacetController extends Controller {

    public static void doGet (LuceneContext c) throws Exception {
        LuceneWebService   service  = c.getService();
        LuceneIndexManager manager  = service.getIndexManager();
        LuceneRequest      request  = c.getRequest();
        LuceneResponse     response = c.getResponse();
        LuceneIndex[]      indices  = manager.getIndices( request.getIndexNames() );
        String[]           facets   = request.getFacets();

        // Atom feed
        Feed feed = new Feed();

        // DOM Document
        org.w3c.dom.Document document = XMLController.newDocument();

        // load the readers
        IndexReader[] readers = new IndexReader[ indices.length ];
        for (int i = 0; i < indices.length; i++) {
            readers[ i ] = indices[ i ].getIndexReader();
        }
        MultiReader reader = new MultiReader( readers );

        // build the query
        Query query = null;
        if ( c.getOpenSearchQuery() != null && c.getOpenSearchQuery().getSearchTerms() != null ) {
            query = c.getQueryParser().parse( c.getOpenSearchQuery().getSearchTerms() );
        }
        else {
            query = new MatchAllDocsQuery();
        }

        // build the filter
        Filter[] filters = null;
        if ( c.getFilter() == null ) {
            filters = new Filter[]{ new QueryFilter( query ) };
        }
        else {
            filters = new Filter[]{ new QueryFilter( query ), c.getFilter() };
        }
        Filter filter = new ChainedFilter( filters, ChainedFilter.AND );

        BitSet bits = filter.bits( reader );

        // build an entry for each facet
        for (String facet : facets) {
            Entry entry = new Entry();

            entry.setTitle( facet );

            Element div = document.createElement("div");
            div.setAttribute( "xmlns", XMLController.getXHTMLNamespace() );

            Element dl = document.createElement("dl");

            TermEnum termEnumeration = reader.terms( new Term( facet, "" ) );
            while ( termEnumeration.term() != null ) {
                if ( !termEnumeration.term().field().equals( facet ) ) {
                    break;
                }

                TermDocs termDocuments = reader.termDocs( termEnumeration.term() );
                String name = termEnumeration.term().text();

                int count = 0;
                while ( termDocuments.next() ) {
                    if ( bits.get( termDocuments.doc() ) ) {
                        count++;
                    }
                }

                // only mention facets with more than one hit
                if ( count > 0 ) {
                    Element dt = document.createElement("dt");
                    dt.appendChild( document.createTextNode( name ) );
                    dl.appendChild( dt );

                    Element dd = document.createElement("dd");
                    dd.appendChild( document.createTextNode( String.valueOf( count ) ) );
                    dl.appendChild( dd );
                }

                termEnumeration.next();
            }

            div.appendChild( dl );

            entry.setContent( Content.xhtml( div ) );

            feed.addEntry( entry );
        }

        // put back the readers
        for (int i = 0; i < indices.length; i++) {
            indices[ i ].putIndexReader( readers[ i ] );
        }

        AtomView.process( c, feed );
    }

}


text:
<script type="text/javascript">

$('#deleteModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var link = button.data('link') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  // modal.find('.modal-title').text('New message to ' + recipient)
  // modal.find('.modal-body input').val(recipient)
  modal.find('#linkDeleteModal').attr('href',link)
})

$('#updateModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var id = button.data('id') // Extract info from data-* attributes
  var kode = button.data('kode') // Extract info from data-* attributes
  var persen = button.data('persen') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  // modal.find('.modal-title').text('New message to ' + recipient)
  // modal.find('.modal-body input').val(recipient)
  modal.find('#input_kode').attr('value',kode)
  modal.find('#input_id').attr('value',id)
  modal.find('#input_persen').attr('value',persen)
})

</script>


text:
Array parameters is a mechanism allowing fast updates. It can be used with commands, that don't return results, i.e. INSERT, UPDATE and DELETE.

To make it work, each query parameter must be provided as an array:

```fsharp
let insertBlog: int[] -> string[] -> string[] -> string[] -> string[] -> DateTime[] -> DbAsync<unit> =
    sql "insert into blog (blogid, name, title, description, owner, createdAt)
         values (:blogid, :name, :title, :description, :owner, :createdAt)"
```
All arrays must have the same length.

The command will be executed multiple times with array elements of subsequent indexes as parameters.

Array parameter based updates are significantly faster, than simple ones.

The extension works, when default oracle config is used:

```fsharp
let generatorConfig = Oracle.Config.createDefaultConfig createConnection
```


text:
FROM java:8
ADD sms-verification-service-0.1.0.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]


text:
"""Authentication middleware

This module provides one piece of middleware named
``authkit.authenticate.middleware`` which is used to intercept responses with
a specified status code, present a user with a means of authenticating
themselves and handle the sign in process.

Each of the authentication methods supported by the middleware is described in
detail in the main AuthKit manual. The methods include:

* HTTP Basic (``basic``)
* HTTP Digest (``digest``)
* OpenID Passurl (``openid``)
* Form and Cookie (``form``)
* Forward (``forward``)
* Redirect (``redirect``)

The authenticate middleware can be configured directly or by means of a Paste
deploy config file as used by Pylons. It can be used directly like this:

.. code-block:: Python

    from authkit.authenticate import middleware, test_app
    from paste.httpserver import serve

    import sys
    app = middleware(
        test_app,
        enable = True,
        method = 'passurl',
        cookie_secret='some_secret',
    )

    serve(app, host='0.0.0.0', port=8000)

"""

import types
import warnings
import logging
import os
import os.path

from paste.util.import_string import eval_import
from multi import MultiHandler, status_checker
from pkg_resources import iter_entry_points, load_entry_point
from paste.deploy.converters import asbool
from paste.httpexceptions import HTTPExceptionHandler

from authkit.authorize import authorize_request
from authkit.permissions import RemoteUser, no_authkit_users_in_environ, \
    AuthKitConfigError

# Main middleware base classes

class AuthKitAuthHandler(object):
    """
    The base class for all middleware responsible for handling
    authentication and setting whatever needs to be set so that the
    ``AuthKitUserSetter`` middleware can set REMOTE_USER on subsequent
    requests. ``AuthKitAuthHandler``s only get inserted into the
    middleware stack if an appropriate status code (as set in the
    ``authkit.setup.intercept`` config option) is intercepted by the
    authentication middleware.
    """
    pass

class AuthKitUserSetter(object):
    """
    The base class for all middleware responsible for attempting to set
    REMOTE_USER on each request. The class is overridden by the induvidual
    handlers.
    """
    pass

# Setting up logging

log = logging.getLogger('authkit.authenticate')

def strip_base(conf, base):
    result = {}
    for key in conf.keys():
        if key.startswith(base):
            result[key[len(base):]] = conf[key]
    return result

def swap_underscore(*confs):
    results = []
    for conf in confs:
        result = {}
        for k,v in conf.items():
            result[k.replace('.','_')] = v
        results.append(result)
    return results

def valid_password(environ, username, password):
    """
    A function which can be used with the ``basic`` and ``form`` authentication
    methods to validate a username and passowrd.

    This implementation is used by default if no other method is specified. It
    checks the for an ``authkit.users`` object present in the ``environ``
    dictionary under the ``authkit.users`` key and uses the information there
    to validate the username and password.

    In this implementation usernames are case insensitive and passwords are
    case sensitive. The function returns ``True`` if the user ``username`` has
    the password specified by ``password`` and returns ``False`` if the user
    doesn't exist or the password is incorrect.

    If you create and specify your own ``authkit.users`` object with the same
    API, this method will also work correctly with your custom solution. See
    the AuthKit manual for information on the user management api, how to
    specify a different ``authkit.users`` object (say to read user information
    from a file rather than have it specified directly) and for information on
    how to create your own ``Users`` objects.
    """
    log.debug("valid_password called. username: %s", username)
    if not environ.has_key('authkit.users'):
        raise no_authkit_users_in_environ
    users = environ['authkit.users']
    if not users.user_exists(username):
        return False
    elif users.user_has_password(username.lower(), password):
        return True
    return False

def digest_password(environ, realm, username):
    """
    This is similar to ``valid_password()`` but is used with the ``digest``
    authentication method and rather than checking a username and password and
    returning ``True`` or ``False`` it takes the realm and username as input,
    looks up the correct password and and returns a digest by calling the
    ``authkit.authenticate.digest.digest_password()`` function with the
    parameters ``realm``, ``username`` and ``password`` respectively. The
    digest returned is then compared with the one submitted by the browser.

    As with ``valid_password()`` this method is designed to work with the user
    management API so you can use it with ``authkit.users`` objects or your own
    custom ``Users`` objects. Alternatively you can specify your own function
    which can lookup the password in whichever way you prefer, perhaps from a
    database or LDAP connection.

    Only required if you intend to use HTTP digest authentication.
    """
    log.debug(
        "digest_password called. username: %s, realm: %s", username, realm
    )
    if not environ.has_key('authkit.users'):
        raise no_authkit_users_in_environ
    users = environ['authkit.users']
    if users.user_exists(username):
        password = users.user(username)['password']
        return digest.digest_password(realm, username, password)
    # After speaking to Clark Evans who wrote the origianl code, this is the
    # correct thing:
    return None

def get_authenticate_function(app, authenticate_conf, format, prefix):
    """
    Sets up the users object, adds the middleware to add the users object
    to the environ and then returns authenticate methods to check a password
    and a digest.
    """
    function = None
    users = None
    if len(authenticate_conf) < 1:
        raise AuthKitConfigError('Expected at least one authenticate key, not'
                                 ' %r'%authenticate_conf)
    if authenticate_conf.keys() == ['function']:
        function = authenticate_conf['function']
        if isinstance(function, (str, unicode)):
            function = eval_import(function)
    else:
        user_conf = strip_base(authenticate_conf, 'user.')
        if not user_conf:
            raise AuthKitConfigError('No authenticate function or users specified')
        else:
            if user_conf.has_key('encrypt'):
                enc_func = eval_import(user_conf['encrypt'])
                secret = user_conf.get('encrypt.secret','')
                def encrypt(password):
                    return enc_func(password, secret)
            else:
                encrypt = None
            user_object = 'authkit.users.UsersFromString'
            if 'type' in user_conf.keys():
                user_object = user_conf['type']
            if isinstance(user_object, (str, unicode)):
                user_object = eval_import(user_object)
            users = user_object(user_conf['data'], encrypt)
            app = AddToEnviron(app, 'authkit.users', users)
            log.debug("authkit.users added to environ")
            if format == 'basic':
                function = valid_password
                log.debug("valid_password chosen %r", function)
            elif format == 'digest':
                log.debug("digest_password chosen %r", function)
                function = digest_password
            else:
                raise Exception('Invalid format for authenticate function %r'
                                % format)
    return app, function, users

def get_template(template_conf, prefix):
    """
    Another utility method to reduce code duplication. This function parses a
    template from one of the available template options:

    ``string``
        The template as a string

    ``file``
        A file containing the template

    ``obj``
        A paste eval_import string or callable which returns a string

    authkit.form.template.string =
    authkit.form.template.file =
    authkit.form.template.obj =

    """
    template = None
    if len(template_conf) != 1:
        raise AuthKitConfigError('Expected one template entry, not %r' %
                                 (', '.join(template_conf.keys())))
    if template_conf.keys()[0] not in ['string', 'file', 'obj']:
        raise AuthKitConfigError("Template option can only be 'string', 'file'"
                                 " or 'obj'")
    if template_conf.keys()[0] == 'string':
        template = template_conf['string']
    elif template_conf.keys()[0] == 'file':
        if not os.path.exists(template_conf['file']):
            raise AuthKitConfigError('No such file %r exists. It was specified'
                                     ' by config option %r' %
                                     (template_conf['file'], prefix+'file'))
        fp = open(template_conf['file'], 'r')
        template = fp.read()
        fp.close()
        if not template:
            raise AuthKitConfigError('No data in template file %s specified by'
                                     ' config option %r' %
                                     (template_conf['file'], prefix+'file'))
    elif template_conf.keys()[0] == 'obj':
        template = eval_import(template_conf['obj'])
        if not template:
            raise AuthKitConfigError('No data in template obj %s specified by '
                                     'config option %r' %
                                     (template_conf['obj'], prefix+'obj'))
    else:
        raise AuthKitConfigError("Unknown option %r" %
                                 (prefix+template_conf.keys()[0]))
    if not template:
        raise AuthKitConfigError("The template loaded did not contain any data")
    if isinstance(template, (str, unicode)):
        def render_template():
            return template
        return render_template
    return template

#
# Main middleware creator
#

class AddToEnviron(object):
    """
    Simple middleware which adds a key to the ``environ`` dictionary.

    Used to add the ``authkit.users`` key to the environ when this is
    appropriate.
    """
    def __init__(self, app, key, object):
        self.app = app
        self.key = key
        self.object = object

    def __call__(self, environ, start_response):
        environ[self.key] = self.object
        return self.app(environ, start_response)

class AddDictToEnviron(object):
    """Simple middleware which adds the values of a dict to the environ."""
    def __init__(self, app, dct):
        self.app = app
        self.dct = dct

    def __call__(self, environ, start_response):
        environ.update(self.dct)
        return self.app(environ, start_response)

class RequireEnvironKey(object):
    def __init__(self, app, key, missing_error=None):
        self.app = app
        self.key = key
        self.missing_error = missing_error or \
            'Missing the key %(key)s from the environ. Have you setup the ' \
            'correct middleware?'

    def __call__(self, environ, start_response):
        if not environ.has_key(self.key):
            raise Exception(self.missing_error%{'key':self.key})
        return self.app(environ, start_response)

def get_methods():
    """Get a dictionary of the available method entry points."""
    available_methods = {}
    for method_handler in iter_entry_points(group='authkit.method', name=None):
        available_methods[method_handler.name] = method_handler
    return available_methods

def load_method(name, from_these=None):
    if from_these:
        return from_these[name].load()
    else:
        return load_entry_point('AuthKit','authkit.method',name)

def load_config(options, app_conf, prefix):
    merged = strip_base(app_conf, prefix)

    # Now override the auth_conf_options with the manaully specified options
    for key, value in options.items():
        if merged.has_key(key):
            warnings.warn(
                'Key %s with value %r set in the config file is being ' + \
                'replaced with value %r set in the application'%(
                    key,
                    auth_conf_options[key],
                    value
                )
            )
        merged[key.replace('_','.')] = value
    return merged

def middleware(app, app_conf=None, global_conf=None, prefix='authkit.',
               handle_httpexception=True, middleware=None, **options):
    """
    This function sets up the AuthKit authenticate middleware and its use and
    options are described in detail in the AuthKit manual.

    The function takes the following arguments and returns a WSGI application
    wrapped in the appropriate AuthKit authentication middleware based on the
    options specified:

    ``app``
        The WSGI application the authenticate middleware should wrap

    ``app_conf``
        A paste deploy ``app_conf`` dictionary to be used to setup the
        middleware

    ``global_conf``
         A paste deploy ``global_conf`` dictionary

    ``prefix``
        The prefix which all authkit related options in the config file will
        have prefixed to their names. This defaults to ``authkit.`` and
        shouldn't normally need overriding.

    ``middleware``
        A make_middleware function which should be called directly instead of
        loading and calling a function based on the method name. If this is
        set then ``authkit.setup.methof`` should not be set.

    ``**options``
        Any AuthKit options which are setup directly in Python code. If
        specified, these options will override any options specifed in a config
        file.

    All option names specified in the config file will have their prefix
    removed and any ``.`` characters replaced by ``_`` before the options
    specified by ``options`` are merged in. This means that the the option
    ``authkit.cookie.name`` specified in a config file sets the same options as
    ``cookie_name`` specified directly as an option.
    """
    if handle_httpexception:
        app = HTTPExceptionHandler(app)

    # Configure the config files

    if global_conf is None:
        global_conf = {}
    if app_conf is None:
        app_conf = {}
    if not isinstance(app_conf, dict):
        raise AuthKitConfigError(
            "Expected app_conf to be paste deploy app_conf dictionary "
            "from not %r" % app_conf
        )

    # Merge config file and options
    available_methods = get_methods()

    all_conf = load_config(options, app_conf, prefix)
    if middleware is not None and all_conf.has_key('setup.method'):
        raise AuthKitConfigError(
            'You cannot specify a middleware function '
            'and an authkit.setup.method'
        )
    if not middleware and not all_conf.has_key('setup.method'):
        raise AuthKitConfigError('No authkit.setup.method was specified')

    # Check to see if middleware is disabled
    if asbool(all_conf.get('setup.enable', True)) == False:
        warnings.warn("AuthKit middleware has been turned off by the config "
                      "option authkit.setup.enable")
        return app

    # Status Checking/Changing Middleware
    intercept = [str(x).strip() for x in \
                 all_conf.get('setup.intercept','401').split(',')]
    if not '401' in intercept:
        warnings.warn(
            "AuthKit is configured via the authkit.setup.intercept option not "
            "to intercept 401 responses so the authentication middleware will "
            "not be triggered even if a 401 Unauthenticated response is "
            "returned.")

    if middleware:
        prefix_ = prefix
        app = middleware(
            app,
            auth_conf=all_conf,
            app_conf=app_conf,
            global_conf=global_conf,
            prefix=prefix_,
        )
    else:
        methods = [method.strip() for method in all_conf['setup.method'].split(',')]
        log.debug("Trying to load the following methods: %r", methods)
        for method in methods:
            if method in ['setup','config']:
                raise AuthKitConfigError("The name %s is reserved cannot be used "
                                         "as a method name" % method)
            if not available_methods.has_key(method):
                raise AuthKitConfigError(
                    'The authkit method %r is not available. The available methods '
                    'are %s and %s'%(
                        all_conf['setup.method'],
                        ', '.join(available_methods.keys()[:-1]),
                        available_methods.keys()[-1],
                    )
                )
            prefix_ = prefix+method+'.'
            auth_conf = strip_base(all_conf, method+'.')

            app = available_methods[method].load()(
                app,
                auth_conf=auth_conf,
                app_conf=app_conf,
                global_conf=global_conf,
                prefix=prefix_,
            )
    app = AddDictToEnviron(
        app,
        {
            'authkit.config':strip_base(all_conf, 'config.'),
            'authkit.intercept':intercept,
            'authkit.authenticate': True,
        }
    )
    return app

def sample_app(environ, start_response):
    """
    A sample WSGI application that returns a 401 status code when the path
    ``/private`` is entered, triggering the authenticate middleware to
    prompt the user to sign in.

    If used with the authenticate middleware's form method, the path
    ``/signout`` will display a signed out message if
    ``authkit.cookie.signout = /signout`` is specified in the config file.

    If used with the authenticate middleware's forward method, the path
    ``/signin`` should be used to display the sign in form.

    The path ``/`` always displays the environment.
    """
    if environ['PATH_INFO']=='/private':
        authorize_request(environ, RemoteUser())
    if environ['PATH_INFO'] == '/signout':
        start_response('200 OK', [('Content-type', 'text/plain; charset=UTF-8')])
        if environ.has_key('REMOTE_USER'):
            return ["Signed Out"]
        else:
            return ["Not signed in"]
    elif environ['PATH_INFO'] == '/signin':
        start_response('200 OK', [('Content-type', 'text/plain; charset=UTF-8')])
        return ["Your application would display a \nsign in form here."]
    else:
        start_response('200 OK', [('Content-type', 'text/plain; charset=UTF-8')])
    result = ['You Have Access To This Page.\n\nHere is the environment...\n\n']
    for k,v in environ.items():
        result.append('%s: %s\n'%(k,v))
    return result


text:
package migrations

import (
	"xorm.io/xorm"
)

func addHTTPMethodToWebhook(x *xorm.Engine) error {
	type Webhook struct {
		HTTPMethod string `xorm:"http_method DEFAULT 'POST'"`
	}

	return x.Sync2(new(Webhook))
}


text:
#ifndef ART_COMPILER_DEX_QUICK_MIR_TO_LIR_INL_H_
#define ART_COMPILER_DEX_QUICK_MIR_TO_LIR_INL_H_

#include "mir_to_lir.h"

#include "dex/compiler_internals.h"

namespace art {

/* Mark a temp register as dead.  Does not affect allocation state. */
inline void Mir2Lir::ClobberBody(RegisterInfo* p) {
  if (p->is_temp) {
    DCHECK(!(p->live && p->dirty))  << "Live & dirty temp in clobber";
    p->live = false;
    p->s_reg = INVALID_SREG;
    p->def_start = NULL;
    p->def_end = NULL;
    if (p->pair) {
      p->pair = false;
      Clobber(p->partner);
    }
  }
}

inline LIR* Mir2Lir::RawLIR(int dalvik_offset, int opcode, int op0,
                            int op1, int op2, int op3, int op4, LIR* target) {
  LIR* insn = static_cast<LIR*>(arena_->Alloc(sizeof(LIR), ArenaAllocator::kAllocLIR));
  insn->dalvik_offset = dalvik_offset;
  insn->opcode = opcode;
  insn->operands[0] = op0;
  insn->operands[1] = op1;
  insn->operands[2] = op2;
  insn->operands[3] = op3;
  insn->operands[4] = op4;
  insn->target = target;
  SetupResourceMasks(insn);
  if ((opcode == kPseudoTargetLabel) || (opcode == kPseudoSafepointPC) ||
      (opcode == kPseudoExportedPC)) {
    // Always make labels scheduling barriers
    insn->use_mask = insn->def_mask = ENCODE_ALL;
  }
  return insn;
}

/*
 * The following are building blocks to construct low-level IRs with 0 - 4
 * operands.
 */
inline LIR* Mir2Lir::NewLIR0(int opcode) {
  DCHECK(is_pseudo_opcode(opcode) || (GetTargetInstFlags(opcode) & NO_OPERAND))
      << GetTargetInstName(opcode) << " " << opcode << " "
      << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
      << current_dalvik_offset_;
  LIR* insn = RawLIR(current_dalvik_offset_, opcode);
  AppendLIR(insn);
  return insn;
}

inline LIR* Mir2Lir::NewLIR1(int opcode, int dest) {
  DCHECK(is_pseudo_opcode(opcode) || (GetTargetInstFlags(opcode) & IS_UNARY_OP))
      << GetTargetInstName(opcode) << " " << opcode << " "
      << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
      << current_dalvik_offset_;
  LIR* insn = RawLIR(current_dalvik_offset_, opcode, dest);
  AppendLIR(insn);
  return insn;
}

inline LIR* Mir2Lir::NewLIR2(int opcode, int dest, int src1) {
  DCHECK(is_pseudo_opcode(opcode) || (GetTargetInstFlags(opcode) & IS_BINARY_OP))
      << GetTargetInstName(opcode) << " " << opcode << " "
      << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
      << current_dalvik_offset_;
  LIR* insn = RawLIR(current_dalvik_offset_, opcode, dest, src1);
  AppendLIR(insn);
  return insn;
}

inline LIR* Mir2Lir::NewLIR3(int opcode, int dest, int src1, int src2) {
  DCHECK(is_pseudo_opcode(opcode) || (GetTargetInstFlags(opcode) & IS_TERTIARY_OP))
      << GetTargetInstName(opcode) << " " << opcode << " "
      << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
      << current_dalvik_offset_;
  LIR* insn = RawLIR(current_dalvik_offset_, opcode, dest, src1, src2);
  AppendLIR(insn);
  return insn;
}

inline LIR* Mir2Lir::NewLIR4(int opcode, int dest, int src1, int src2, int info) {
  DCHECK(is_pseudo_opcode(opcode) || (GetTargetInstFlags(opcode) & IS_QUAD_OP))
      << GetTargetInstName(opcode) << " " << opcode << " "
      << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
      << current_dalvik_offset_;
  LIR* insn = RawLIR(current_dalvik_offset_, opcode, dest, src1, src2, info);
  AppendLIR(insn);
  return insn;
}

inline LIR* Mir2Lir::NewLIR5(int opcode, int dest, int src1, int src2, int info1,
                             int info2) {
  DCHECK(is_pseudo_opcode(opcode) || (GetTargetInstFlags(opcode) & IS_QUIN_OP))
      << GetTargetInstName(opcode) << " " << opcode << " "
      << PrettyMethod(cu_->method_idx, *cu_->dex_file) << " "
      << current_dalvik_offset_;
  LIR* insn = RawLIR(current_dalvik_offset_, opcode, dest, src1, src2, info1, info2);
  AppendLIR(insn);
  return insn;
}

/*
 * Mark the corresponding bit(s).
 */
inline void Mir2Lir::SetupRegMask(uint64_t* mask, int reg) {
  *mask |= GetRegMaskCommon(reg);
}

/*
 * Set up the proper fields in the resource mask
 */
inline void Mir2Lir::SetupResourceMasks(LIR* lir) {
  int opcode = lir->opcode;

  if (opcode <= 0) {
    lir->use_mask = lir->def_mask = 0;
    return;
  }

  uint64_t flags = GetTargetInstFlags(opcode);

  if (flags & NEEDS_FIXUP) {
    lir->flags.pcRelFixup = true;
  }

  /* Get the starting size of the instruction's template */
  lir->flags.size = GetInsnSize(lir);

  /* Set up the mask for resources that are updated */
  if (flags & (IS_LOAD | IS_STORE)) {
    /* Default to heap - will catch specialized classes later */
    SetMemRefType(lir, flags & IS_LOAD, kHeapRef);
  }

  /*
   * Conservatively assume the branch here will call out a function that in
   * turn will trash everything.
   */
  if (flags & IS_BRANCH) {
    lir->def_mask = lir->use_mask = ENCODE_ALL;
    return;
  }

  if (flags & REG_DEF0) {
    SetupRegMask(&lir->def_mask, lir->operands[0]);
  }

  if (flags & REG_DEF1) {
    SetupRegMask(&lir->def_mask, lir->operands[1]);
  }

  if (flags & SETS_CCODES) {
    lir->def_mask |= ENCODE_CCODE;
  }

  if (flags & (REG_USE0 | REG_USE1 | REG_USE2 | REG_USE3)) {
    int i;

    for (i = 0; i < 4; i++) {
      if (flags & (1 << (kRegUse0 + i))) {
        SetupRegMask(&lir->use_mask, lir->operands[i]);
      }
    }
  }

  if (flags & USES_CCODES) {
    lir->use_mask |= ENCODE_CCODE;
  }

  // Handle target-specific actions
  SetupTargetResourceMasks(lir);
}

}  // namespace art

#endif  // ART_COMPILER_DEX_QUICK_MIR_TO_LIR_INL_H_


text:
package com.guardtime.ksi.service.client.http;

import java.net.URL;

import static com.guardtime.ksi.util.Util.notNull;
import static com.guardtime.ksi.util.Util.toUrl;

/**
 * Configures HTTP service settings: URL and connection parameters of the KSI service. The connection parameters include HTTP connection settings like timeouts and proxy configuration.
 */
public class HttpSettings {

    private URL url;
    private HTTPConnectionParameters parameters = new HTTPConnectionParameters();

    /**
     * Creates HTTP service settings with provided parameters.
     *
     * @param url
     *         URL of KSI service
     */
    public HttpSettings(String url) {
        this(url,  null);
    }

    /**
     * Creates HTTP service settings with provided parameters.
     *
     * @param url
     *         URL of KSI service
     * @param parameters
     *         connection parameters.
     */
    public HttpSettings(String url, HTTPConnectionParameters parameters) {
        notNull(url, "KSI service URL");
        this.url = toUrl(url);
        if (parameters != null) {
            this.parameters = parameters;
        }
    }

    /**
     * @return URL of the KSI service.
     */
    public URL getUrl() {
        return url;
    }

    /**
     * @return Proxy URL.
     */
    public URL getProxyUrl() {
        return parameters.getProxyUrl();
    }

    /**
     * @return Proxy user.
     */
    public String getProxyUser() {
        return parameters.getProxyUser();
    }

    /**
     * @return Proxy password.
     */
    public String getProxyPassword() {
        return parameters.getProxyPassword();
    }

    /**
     * @return Connection timeout.
     */
    public int getConnectionTimeout() {
        return parameters.getConnectionTimeout();
    }

    /**
     * @return Read timeout.
     */
    public int getReadTimeout() {
        return parameters.getReadTimeout();
    }

    /**
     * @return Connection parameters.
     */
    public HTTPConnectionParameters getParameters() {
        return parameters;
    }

}


text:
created: 2015-08-25 15:52:16.451349
description: The individual starts in a prone position on the ground with the arms
  straight out in front of the body.
groups: [Core]
muscles: [Lower Back, Erector Spinae]
template: exercise.html
title: Hyperextension
variants: [Thumbs Up, Swimmer, Superman, Pillow Humper]
---
The individual starts in a prone position on the ground with the arms straight out in front of the body. The arms, legs and upper chest are lifted off the ground, and then slowly lowered back to the ground. This exercise is also known as "Supermans".

The Thumbs-Up variant starts in the same position, but the individual forms two fists with the thumbs pointed straight up, then lifts the head, shoulders and chest off the ground as high as possible.

The Swimmers variation raises and lowers the opposite leg and arm and alternates sides.

The Pillow Humpers variant places a towel under the hips and the feet under a stationary object like a low bed or couch. The hands are placed behind the head and the torso is raised off the ground as far as possible.

## Resources

* [Wikipedia: Bodyweight exercise](https://en.wikipedia.org/wiki/Bodyweight_exercise)


text:
#ifndef IMOBILEBACKUP2_H
#define IMOBILEBACKUP2_H

#ifdef __cplusplus
extern "C" {
#endif

#include <libimobiledevice/libimobiledevice.h>
#include <libimobiledevice/lockdown.h>

#define MOBILEBACKUP2_SERVICE_NAME "com.apple.mobilebackup2"

/** Error Codes */
typedef enum {
	MOBILEBACKUP2_E_SUCCESS           =  0,
	MOBILEBACKUP2_E_INVALID_ARG       = -1,
	MOBILEBACKUP2_E_PLIST_ERROR       = -2,
	MOBILEBACKUP2_E_MUX_ERROR         = -3,
	MOBILEBACKUP2_E_SSL_ERROR         = -4,
	MOBILEBACKUP2_E_RECEIVE_TIMEOUT   = -5,
	MOBILEBACKUP2_E_BAD_VERSION       = -6,
	MOBILEBACKUP2_E_REPLY_NOT_OK      = -7,
	MOBILEBACKUP2_E_NO_COMMON_VERSION = -8,
	MOBILEBACKUP2_E_UNKNOWN_ERROR     = -256
} mobilebackup2_error_t;

typedef struct mobilebackup2_client_private mobilebackup2_client_private;
typedef mobilebackup2_client_private *mobilebackup2_client_t; /**< The client handle. */

/**
 * Connects to the mobilebackup2 service on the specified device.
 *
 * @param device The device to connect to.
 * @param service The service descriptor returned by lockdownd_start_service.
 * @param client Pointer that will be set to a newly allocated
 *     mobilebackup2_client_t upon successful return.
 *
 * @return MOBILEBACKUP2_E_SUCCESS on success, MOBILEBACKUP2_E_INVALID ARG
 *     if one or more parameter is invalid, or MOBILEBACKUP2_E_BAD_VERSION
 *     if the mobilebackup2 version on the device is newer.
 */
mobilebackup2_error_t mobilebackup2_client_new(idevice_t device, lockdownd_service_descriptor_t service, mobilebackup2_client_t * client);

/**
 * Starts a new mobilebackup2 service on the specified device and connects to it.
 *
 * @param device The device to connect to.
 * @param client Pointer that will point to a newly allocated
 *     mobilebackup2_client_t upon successful return. Must be freed using
 *     mobilebackup2_client_free() after use.
 * @param label The label to use for communication. Usually the program name.
 *  Pass NULL to disable sending the label in requests to lockdownd.
 *
 * @return MOBILEBACKUP2_E_SUCCESS on success, or an MOBILEBACKUP2_E_* error
 *     code otherwise.
 */
mobilebackup2_error_t mobilebackup2_client_start_service(idevice_t device, mobilebackup2_client_t* client, const char* label);

/**
 * Disconnects a mobilebackup2 client from the device and frees up the
 * mobilebackup2 client data.
 *
 * @param client The mobilebackup2 client to disconnect and free.
 *
 * @return MOBILEBACKUP2_E_SUCCESS on success, or MOBILEBACKUP2_E_INVALID_ARG
 *     if client is NULL.
 */
mobilebackup2_error_t mobilebackup2_client_free(mobilebackup2_client_t client);

/**
 * Sends a backup message plist.
 *
 * @param client The connected MobileBackup client to use.
 * @param message The message to send. This will be inserted into the request
 *     plist as value for MessageName. If this parameter is NULL,
 *     the plist passed in the options parameter will be sent directly.
 * @param options Additional options as PLIST_DICT to add to the request.
 *     The MessageName key with the value passed in the message parameter
 *     will be inserted into this plist before sending it. This parameter
 *     can be NULL if message is not NULL.
 */
mobilebackup2_error_t mobilebackup2_send_message(mobilebackup2_client_t client, const char *message, plist_t options);

/**
 * Receives a DL* message plist from the device.
 * This function is a wrapper around device_link_service_receive_message.
 *
 * @param client The connected MobileBackup client to use.
 * @param msg_plist Pointer to a plist that will be set to the contents of the
 *    message plist upon successful return.
 * @param dlmessage A pointer that will be set to a newly allocated char*
 *     containing the DL* string from the given plist. It is up to the caller
 *     to free the allocated memory. If this parameter is NULL
 *     it will be ignored.
 *
 * @return MOBILEBACKUP2_E_SUCCESS if a DL* message was received,
 *    MOBILEBACKUP2_E_INVALID_ARG if client or message is invalid,
 *    MOBILEBACKUP2_E_PLIST_ERROR if the received plist is invalid
 *    or is not a DL* message plist, or MOBILEBACKUP2_E_MUX_ERROR if
 *    receiving from the device failed.
 */
mobilebackup2_error_t mobilebackup2_receive_message(mobilebackup2_client_t client, plist_t *msg_plist, char **dlmessage);

/**
 * Send binary data to the device.
 *
 * @note This function returns MOBILEBACKUP2_E_SUCCESS even if less than the
 *     requested length has been sent. The fourth parameter is required and
 *     must be checked to ensure if the whole data has been sent.
 *
 * @param client The MobileBackup client to send to.
 * @param data Pointer to the data to send
 * @param length Number of bytes to send
 * @param bytes Number of bytes actually sent
 *
 * @return MOBILEBACKUP2_E_SUCCESS if any data was successfully sent,
 *     MOBILEBACKUP2_E_INVALID_ARG if one of the parameters is invalid,
 *     or MOBILEBACKUP2_E_MUX_ERROR if sending of the data failed.
 */
mobilebackup2_error_t mobilebackup2_send_raw(mobilebackup2_client_t client, const char *data, uint32_t length, uint32_t *bytes);

/**
 * Receive binary from the device.
 *
 * @note This function returns MOBILEBACKUP2_E_SUCCESS even if no data
 *     has been received (unless a communication error occurred).
 *     The fourth parameter is required and must be checked to know how
 *     many bytes were actually received.
 *
 * @param client The MobileBackup client to receive from.
 * @param data Pointer to a buffer that will be filled with the received data.
 * @param length Number of bytes to receive. The data buffer needs to be large
 *     enough to store this amount of data.
 * @paran bytes Number of bytes actually received.
 *
 * @return MOBILEBACKUP2_E_SUCCESS if any or no data was received,
 *     MOBILEBACKUP2_E_INVALID_ARG if one of the parameters is invalid,
 *     or MOBILEBACKUP2_E_MUX_ERROR if receiving the data failed.
 */
mobilebackup2_error_t mobilebackup2_receive_raw(mobilebackup2_client_t client, char *data, uint32_t length, uint32_t *bytes);

/**
 * Performs the mobilebackup2 protocol version exchange.
 *
 * @param client The MobileBackup client to use.
 * @param local_versions An array of supported versions to send to the remote.
 * @param count The number of items in local_versions.
 * @param remote_version Holds the protocol version of the remote on success.
 *
 * @return MOBILEBACKUP2_E_SUCCESS on success, or a MOBILEBACKUP2_E_* error
 *     code otherwise.
 */
mobilebackup2_error_t mobilebackup2_version_exchange(mobilebackup2_client_t client, double local_versions[], char count, double *remote_version);

/**
 * Send a request to the connected mobilebackup2 service.
 *
 * @param client
 * @param request The request to send to the backup service.
 *     Currently, this is one of "Backup", "Restore", "Info", or "List".
 * @param target_identifier UDID of the target device.
 * @param source_identifier UDID of backup data?
 * @param options Additional options in a plist of type PLIST_DICT.
 *
 * @return MOBILEBACKUP2_E_SUCCESS if the request was successfully sent,
 *     or a MOBILEBACKUP2_E_* error value otherwise.
 */
mobilebackup2_error_t mobilebackup2_send_request(mobilebackup2_client_t client, const char *request, const char *target_identifier, const char *source_identifier, plist_t options);

/**
 * Sends a DLMessageStatusResponse to the device.
 *
 * @param client The MobileBackup client to use.
 * @param status_code The status code to send.
 * @param status1 A status message to send. Can be NULL if not required.
 * @param status2 An additional status plist to attach to the response.
 *     Can be NULL if not required.
 *
 * @return MOBILEBACKUP2_E_SUCCESS on success, MOBILEBACKUP2_E_INVALID_ARG
 *     if client is invalid, or another MOBILEBACKUP2_E_* otherwise.
 */
mobilebackup2_error_t mobilebackup2_send_status_response(mobilebackup2_client_t client, int status_code, const char *status1, plist_t status2);

#ifdef __cplusplus
}
#endif

#endif


text:
#ifndef QPROCESS_H
#define QPROCESS_H

#include <QtCore/qiodevice.h>
#include <QtCore/qstringlist.h>
#include <QtCore/qshareddata.h>

QT_BEGIN_NAMESPACE

#ifndef QT_NO_PROCESS

#if !defined(Q_OS_WIN) || defined(Q_QDOC)
typedef qint64 Q_PID;
#else
QT_END_NAMESPACE
typedef struct _PROCESS_INFORMATION *Q_PID;
QT_BEGIN_NAMESPACE
#endif

class QProcessPrivate;
class QProcessEnvironmentPrivate;

class Q_CORE_EXPORT QProcessEnvironment
{
public:
    QProcessEnvironment();
    QProcessEnvironment(const QProcessEnvironment &other);
    ~QProcessEnvironment();
    QProcessEnvironment &operator=(const QProcessEnvironment &other);

    inline void swap(QProcessEnvironment &other) { qSwap(d, other.d); }

    bool operator==(const QProcessEnvironment &other) const;
    inline bool operator!=(const QProcessEnvironment &other) const
    { return !(*this == other); }

    bool isEmpty() const;
    void clear();

    bool contains(const QString &name) const;
    void insert(const QString &name, const QString &value);
    void remove(const QString &name);
    QString value(const QString &name, const QString &defaultValue = QString()) const;

    QStringList toStringList() const;

    QStringList keys() const;

    void insert(const QProcessEnvironment &e);

    static QProcessEnvironment systemEnvironment();

private:
    friend class QProcessPrivate;
    friend class QProcessEnvironmentPrivate;
    QSharedDataPointer<QProcessEnvironmentPrivate> d;
};

Q_DECLARE_SHARED(QProcessEnvironment)

class Q_CORE_EXPORT QProcess : public QIODevice
{
    Q_OBJECT
public:
    enum ProcessError {
        FailedToStart, //### file not found, resource error
        Crashed,
        Timedout,
        ReadError,
        WriteError,
        UnknownError
    };
    enum ProcessState {
        NotRunning,
        Starting,
        Running
    };
    enum ProcessChannel {
        StandardOutput,
        StandardError
    };
    enum ProcessChannelMode {
        SeparateChannels,
        MergedChannels,
        ForwardedChannels,
        ForwardedOutputChannel,
        ForwardedErrorChannel
    };
    enum InputChannelMode {
        ManagedInputChannel,
        ForwardedInputChannel
    };
    enum ExitStatus {
        NormalExit,
        CrashExit
    };

    explicit QProcess(QObject *parent = 0);
    virtual ~QProcess();

    void start(const QString &program, const QStringList &arguments, OpenMode mode = ReadWrite);
    void start(const QString &command, OpenMode mode = ReadWrite);
    void start(OpenMode mode = ReadWrite);
    bool open(OpenMode mode = ReadWrite) Q_DECL_OVERRIDE;

    QString program() const;
    void setProgram(const QString &program);

    QStringList arguments() const;
    void setArguments(const QStringList & arguments);

    ProcessChannelMode readChannelMode() const;
    void setReadChannelMode(ProcessChannelMode mode);
    ProcessChannelMode processChannelMode() const;
    void setProcessChannelMode(ProcessChannelMode mode);
    InputChannelMode inputChannelMode() const;
    void setInputChannelMode(InputChannelMode mode);

    ProcessChannel readChannel() const;
    void setReadChannel(ProcessChannel channel);

    void closeReadChannel(ProcessChannel channel);
    void closeWriteChannel();

    void setStandardInputFile(const QString &fileName);
    void setStandardOutputFile(const QString &fileName, OpenMode mode = Truncate);
    void setStandardErrorFile(const QString &fileName, OpenMode mode = Truncate);
    void setStandardOutputProcess(QProcess *destination);

#if defined(Q_OS_WIN)
    QString nativeArguments() const;
    void setNativeArguments(const QString &arguments);
#endif

    QString workingDirectory() const;
    void setWorkingDirectory(const QString &dir);

    void setEnvironment(const QStringList &environment);
    QStringList environment() const;
    void setProcessEnvironment(const QProcessEnvironment &environment);
    QProcessEnvironment processEnvironment() const;

    QProcess::ProcessError error() const;
    QProcess::ProcessState state() const;

    // #### Qt 5: Q_PID is a pointer on Windows and a value on Unix
    Q_PID pid() const;
    qint64 processId() const;

    bool waitForStarted(int msecs = 30000);
    bool waitForReadyRead(int msecs = 30000);
    bool waitForBytesWritten(int msecs = 30000);
    bool waitForFinished(int msecs = 30000);

    QByteArray readAllStandardOutput();
    QByteArray readAllStandardError();

    int exitCode() const;
    QProcess::ExitStatus exitStatus() const;

    // QIODevice
    qint64 bytesAvailable() const;
    qint64 bytesToWrite() const;
    bool isSequential() const;
    bool canReadLine() const;
    void close();
    bool atEnd() const;

    static int execute(const QString &program, const QStringList &arguments);
    static int execute(const QString &command);

    static bool startDetached(const QString &program, const QStringList &arguments,
                              const QString &workingDirectory
#if defined(Q_QDOC)
                              = QString()
#endif
                              , qint64 *pid = 0);
#if !defined(Q_QDOC)
    static bool startDetached(const QString &program, const QStringList &arguments); // ### Qt6: merge overloads
#endif
    static bool startDetached(const QString &command);

    static QStringList systemEnvironment();

    static QString nullDevice();

public Q_SLOTS:
    void terminate();
    void kill();

Q_SIGNALS:
    void started(
#if !defined(Q_QDOC)
        QPrivateSignal
#endif
    );
    void finished(int exitCode); // ### Qt 6: merge the two signals with a default value
    void finished(int exitCode, QProcess::ExitStatus exitStatus);
    void error(QProcess::ProcessError error);
    void stateChanged(QProcess::ProcessState state
#if !defined(Q_QDOC)
        , QPrivateSignal
#endif
    );

    void readyReadStandardOutput(
#if !defined(Q_QDOC)
        QPrivateSignal
#endif
    );
    void readyReadStandardError(
#if !defined(Q_QDOC)
        QPrivateSignal
#endif
    );

protected:
    void setProcessState(ProcessState state);

    virtual void setupChildProcess();

    // QIODevice
    qint64 readData(char *data, qint64 maxlen);
    qint64 writeData(const char *data, qint64 len);

private:
    Q_DECLARE_PRIVATE(QProcess)
    Q_DISABLE_COPY(QProcess)

    Q_PRIVATE_SLOT(d_func(), bool _q_canReadStandardOutput())
    Q_PRIVATE_SLOT(d_func(), bool _q_canReadStandardError())
    Q_PRIVATE_SLOT(d_func(), bool _q_canWrite())
    Q_PRIVATE_SLOT(d_func(), bool _q_startupNotification())
    Q_PRIVATE_SLOT(d_func(), bool _q_processDied())
    Q_PRIVATE_SLOT(d_func(), void _q_notified())
    friend class QProcessManager;
};

#endif // QT_NO_PROCESS

QT_END_NAMESPACE

#endif // QPROCESS_H


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Tales of life and data.">
  <meta name="author" content="Tyler Edelman">
  <meta name="keywords" content="Tales of life and data.">
  <link rel="canonical" href="/categories/tech.html">
  <title>{ Data Driven } | tech</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

  <link href="/css/grayscale.css" rel="stylesheet">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
  <link href="//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
  <link href="//fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/rrssb.css" />

    <link rel="shortcut icon" type="image/x-icon" href="/img/favicon.ico">

  <meta name="apple-mobile-web-app-capable" content="yes">
  <link rel="apple-touch-icon" sizes="36x36" href="/img/web-app/icon-36p.png">
  <link rel="apple-touch-icon" sizes="48x48" href="/img/web-app/icon-48p.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/img/web-app/icon-72p.png">
  <link rel="apple-touch-icon" sizes="96x96" href="/img/web-app/icon-96p.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/img/web-app/icon-144p.png">
  <link rel="apple-touch-icon" sizes="192x192" href="/img/web-app/icon-192p.png">

  <link rel="manifest" href="/manifest.json">

<meta name="theme-color" content="#000000">

<meta name="msapplication-navbutton-color" content="#000000">

<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

      </button>

            { Data Driven }

                 About

                 Blog

                 Timeline

                 Contact

Category: tech

  27 Jun 2015
  .

      tech

  .

    Welcome to { Personal } Jekyll Theme!

  Comments

  25 Jun 2015
  .

      tech

  .

    Initial setup

  Comments

  24 Jun 2015
  .

      tech

  .

    Modifying the Header

  Comments

  22 Jun 2015
  .

      tech

  .

    Web app mode

  Comments

  20 Jun 2015
  .

      tech

  .

    Setting up the Blog

  Comments

  19 Jun 2015
  .

      tech

  .

    Writing posts

  Comments

  12 Jun 2015
  .

      tech

  .

    Adding a life event in the Timeline

  Comments

  11 Jun 2015
  .

      tech

  .

    Modifying the social buttons

  Comments

  10 Jun 2015
  .

      tech

  .

    Modifying the Contact

  Comments

Copyright © Tyler Edelman 2016


text:
namespace TBag.BloomFilters
{
    /// <summary>
    /// Interface for creating compressed arrays
    /// </summary>
    public interface ICompressedArrayFactory
    {
        /// <summary>
        /// Create a new compressed array
        /// </summary>
        /// <typeparam name="T">Array element type</typeparam>
        /// <returns></returns>
        ICompressedArray<T> Create<T>()
            where T : struct;
    }
}


text:
class SpreadsheetsController < InheritedResources::Base

  def create
    create! do |success, failure|
      success.html { redirect_to @spreadsheet }
      failure.html { render }
    end
  end

  def generate_arps
    @spreadsheet = Spreadsheet.find(params[:id])
    @spreadsheet.arps.each do |arp|
      mass_line = arp.find_mass_line_for_arp
      if !mass_line.nil?
        arp.populate_info_from_mass_line
        arp.complete = true
        arp.save
        next
      end

      idea = arp.find_mockbot_idea_for_arp
      if !idea.nil?
        arp.populate_info_from_mockbot(idea)
        arp.complete = true
        arp.save
        next
      end
    end

    redirect_to @spreadsheet, notice: "ARP data has been generated for every ARP that possibly could"

  end

  def images_to_rename
    @spreadsheet = Spreadsheet.find(params[:id])
    respond_to do |format|
      format.html
      format.csv { send_data @spreadsheet.csv_download, filename: "arps_to_generate_batch_#{@spreadsheet.batch_id}.csv" }
    end
  end

  def download
    @spreadsheet = Spreadsheet.find(params[:id])
    respond_to do |format|
      format.csv { send_data @spreadsheet.csv_download, filename: "arps_to_generate_batch_#{@spreadsheet.batch_id}.csv" }
    end
  end

  def missing_arps
    @spreadsheet = Spreadsheet.find(params[:id])
    respond_to do |format|
      format.html
    end
  end

  private

  def spreadsheet_params
    params.require(:spreadsheet).permit(:file, :batch_id)
  end

end


text:
```scratch
when green flag clicked
set [total 1 v] to [0]
set [total 2 v] to [0]
set [index v] to [1]
repeat (6)
  ask (join (join [Enter digit ] (index)) [ of the product code:]) and wait
  change [index v] by (1)
  change [total 1 v] by (answer)
  ask (join (join [Enter digit ] (index)) [ of the product code:]) and wait
  change [index v] by (1)
  change [total 2 v] by (answer)
end
ask (join (join [Enter digit ] (index)) [ of the product code:]) and wait
change [total 1 v] by (answer)
set [total v] to ((total 1) + ((total 2) * (3)))
say (join [Total: ] (total))
```