text:
module Game.Halma.AI.Ignorant
  ( aiMove
  ) where

import Game.Halma.Board
import Game.Halma.Rules
import Game.Halma.AI.Base

import Data.List (maximumBy)
import Data.Ord (comparing)

ignorantFixedDepth :: Int -> RuleOptions -> Team -> HalmaBoard -> Rating
ignorantFixedDepth n opts team board =
  if n <= 0 then
    rateTeam team board
  else if hasFinished board team then
    WinIn 0
  else
    beingSomewhatGreedy (rateTeam team board) $ maximum $
    map (ignorantFixedDepth (n-1) opts team . outcome board) $
    allLegalMoves opts board team

beingSomewhatGreedy :: Rating -> Rating -> Rating
beingSomewhatGreedy x y =
  case (x, y) of
    (WinIn n, _)  -> WinIn n
    (LossIn n, _) -> LossIn n
    (_, WinIn n)  -> WinIn (n+1)
    (_, LossIn n) -> LossIn (n+1)
    (Rating a, Rating b) ->
      let greedyness = 0.1
      in Rating (greedyness*a + (1-greedyness)*b)

aiMove :: RuleOptions -> HalmaBoard -> Team -> Move
aiMove opts board team =
  if null legalMoves then
    error "There is no legal move."
  else
    maximumBy (comparing $ finalRating team . outcome board) legalMoves
  where
    legalMoves = allLegalMoves opts board team
    finalRating = ignorantFixedDepth 1 opts

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Graph
{
    using System;

    using Newtonsoft.Json;

    /// <summary>
    /// The interface IContactFolderContactsCollectionPage.
    /// </summary>
    [JsonConverter(typeof(InterfaceConverter<ContactFolderContactsCollectionPage>))]
    public interface IContactFolderContactsCollectionPage : ICollectionPage<Contact>
    {
        /// <summary>
        /// Gets the next page <see cref="IContactFolderContactsCollectionRequest"/> instance.
        /// </summary>
        IContactFolderContactsCollectionRequest NextPageRequest { get; }

        /// <summary>
        /// Initializes the NextPageRequest property.
        /// </summary>
        void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString);
    }
}


text:
import logging

from Util import Pose, Position
from Util.constant import ROBOT_CENTER_TO_KICKER, BALL_RADIUS, KickForce
from Util.geometry import compare_angle
from ai.STA.Tactic.tactic import Tactic
from ai.states.game_state import GameState

class PerfectSim:

    def __init__(self, tactic_obj):
        assert not isinstance(tactic_obj, Tactic), "You must pass the class, not an instance of the class. (ex: 'GoToPosition', not 'GoToPosition()')"

        self.logger = logging.getLogger(self.__class__.__name__)
        self.tactic_obj = tactic_obj
        self.tactic = None

        self.hero_robot = None
        self.game_state = GameState()

        # Singleton are a pain in the ass, there state must be reset
        self.game_state.reset()

        # Variable for assertion
        self.last_ia_cmd = None
        self.has_charge_kick = False
        self.has_hit_ball = False

    def add_robot(self, robot_id, pose: Pose):
        self.game_state.our_team.players[robot_id].pose = pose

    def add_enemy_robot(self, robot_id, pose: Pose):
        self.game_state.enemy_team.players[robot_id].pose = pose

    def move_ball(self, position: Position):
        self.game_state.ball.position = position

    def start(self, robot_id, target: Pose):
        self.hero_robot = GameState().our_team.players[robot_id]
        self.tactic = self.tactic_obj(GameState(), self.hero_robot, target)

    def tick(self):
        if not self.tactic:
            raise RuntimeError("You must call start() to initialize the simulation")

        print("====== Executing {} ======".format(str(self.tactic.current_state.__func__)))
        ia_cmd = self.tactic.exec()

        self._apply_cmd(ia_cmd)

    def has_kick(self):
        return self.last_ia_cmd.kick_force != KickForce.NONE

    def _apply_cmd(self, ia_cmd):
        self.last_ia_cmd = ia_cmd

        if ia_cmd.target:
            print("Hero Robot moved to {}".format(ia_cmd.target))
            self.hero_robot.pose = ia_cmd.target

        if ia_cmd.kick_force != KickForce.NONE:
            if self._robot_can_hit_ball(self.hero_robot):
                print("Hero Robot has kick and hit the ball")
                self.has_hit_ball = True
            else:
                print("Hero Robot has kick, but didn't hit the ball")

        if ia_cmd.charge_kick:
            self.has_charge_kick = True

    def _robot_can_hit_ball(self, robot):
        KICK_DISTANCE_MIN = ROBOT_CENTER_TO_KICKER - BALL_RADIUS * 0.5
        KICK_DISTANCE_MAX = ROBOT_CENTER_TO_KICKER + BALL_RADIUS * 1.5
        MAX_ANGLE_FOR_KICK = 15

        ball_position = self.game_state.ball.position
        robot_to_ball = robot.pose.position - ball_position

        return KICK_DISTANCE_MIN < robot_to_ball.norm <  KICK_DISTANCE_MAX \
               and compare_angle(robot.pose.orientation, robot_to_ball.angle, abs_tol=MAX_ANGLE_FOR_KICK)


text:
package modularmachines.api;

import net.minecraft.util.math.MathHelper;

public enum IOMode {
	NONE("mm.module.io_mode.none", 0xafafaf),
	INPUT("mm.module.io_mode.input", 0x73a4f4),
	OUTPUT("mm.module.io_mode.output", 0xefad73),
	PULL("mm.module.io_mode.pull", 0xd167d3),
	PUSH("mm.module.io_mode.push", 0x6fe6ed),
	PUSH_PULL("mm.module.io_mode.push_pull", 0xd37b6b),
	DISABLED("mm.module.io_mode.disabled", 0x7a7979);

	public static final IOMode[] VALUES = values();

	private final int color;
	private final String unlocalizedName;

	IOMode(String unlocalizedName, int color) {
		this.unlocalizedName = unlocalizedName;
		this.color = color;
	}

	public static IOMode getNext(IOMode mode) {
		int ord = mode.ordinal() + 1;
		if (ord >= IOMode.values().length) {
			ord = 0;
		}
		return IOMode.values()[ord];
	}

	public static IOMode getPrevious(IOMode mode) {

		int ord = mode.ordinal() - 1;
		if (ord < 0) {
			ord = IOMode.values().length - 1;
		}
		return IOMode.values()[ord];
	}

	public static IOMode get(int index) {
		return VALUES[MathHelper.abs(index % VALUES.length)];
	}

	public boolean pulls() {
		return this == PULL || this == PUSH_PULL;
	}

	public boolean pushes() {
		return this == PUSH || this == PUSH_PULL;
	}

	public boolean canOutput() {
		return pushes() || this == NONE;
	}

	public boolean canReceiveInput() {
		return pulls() || this == NONE;
	}

	public boolean acceptsInput() {
		return this == NONE || this == INPUT;
	}

	public boolean acceptsOutput() {
		return this == NONE || this == OUTPUT;
	}

	public int getColor() {
		return color;
	}

	public String getTranslationKey() {
		return unlocalizedName;
	}
}


text:
from osc_lib.command import command
from osc_lib import utils

from openstackclient.i18n import _

def _get_columns(item):
    column_map = {
        "type": "rule_type_name",
        "drivers": "drivers",
    }
    hidden_columns = ["id", "location", "name", 'tenant_id']
    return utils.get_osc_show_columns_for_sdk_resource(
        item, column_map, hidden_columns)

class ListNetworkQosRuleType(command.Lister):
    _description = _("List QoS rule types")

    def take_action(self, parsed_args):
        client = self.app.client_manager.network
        columns = (
            'type',
        )
        column_headers = (
            'Type',
        )
        data = client.qos_rule_types()

        return (column_headers,
                (utils.get_item_properties(
                    s, columns, formatters={},
                ) for s in data))

class ShowNetworkQosRuleType(command.ShowOne):
    _description = _("Show details about supported QoS rule type")

    def get_parser(self, prog_name):
        parser = super(ShowNetworkQosRuleType, self).get_parser(prog_name)
        parser.add_argument(
            'rule_type',
            metavar="<qos-rule-type-name>",
            help=_("Name of QoS rule type")
        )
        return parser

    def take_action(self, parsed_args):
        client = self.app.client_manager.network
        obj = client.get_qos_rule_type(parsed_args.rule_type)
        display_columns, columns = _get_columns(obj)
        data = utils.get_item_properties(obj, columns)
        return display_columns, data


text:
import Ember from 'ember';

export default Ember.Controller.extend({
  actions: {
    onPostChanged() {
      this.send('postChanged');
    }
  }
});


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.medianDocs = void 0;
var medianDocs = {
  name: 'median',
  category: 'Statistics',
  syntax: ['median(a, b, c, ...)', 'median(A)'],
  description: 'Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.',
  examples: ['median(5, 2, 7)', 'median([3, -1, 5, 7])'],
  seealso: ['max', 'mean', 'min', 'prod', 'std', 'sum', 'variance', 'quantileSeq']
};
exports.medianDocs = medianDocs;


text:
<?php

namespace ContentinumComponents\Html\Table\View;

use ContentinumComponents\Html\Elements\AbstractTag;
/**
 * Display a html table cell
 *
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 */
class TableCell extends AbstractTag
{

    /**
     * display a table cell
     *
     * @return string
     */
    public function display ()
    {
        return "\n<{$this->_tag}{$this->_attribute}>{$this->_content}</{$this->_tag}>";
    }
}


text:
package com.android.spritemethodtest;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;

import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;

/**
 * A 2D rectangular mesh. Can be drawn textured or untextured.
 * This version is modified from the original Grid.java (found in
 * the SpriteText package in the APIDemos Android sample) to support hardware
 * vertex buffers.
 */
class Grid {
    private FloatBuffer mFloatVertexBuffer;
    private FloatBuffer mFloatTexCoordBuffer;
    private FloatBuffer mFloatColorBuffer;
    private IntBuffer mFixedVertexBuffer;
    private IntBuffer mFixedTexCoordBuffer;
    private IntBuffer mFixedColorBuffer;

    private CharBuffer mIndexBuffer;

    private Buffer mVertexBuffer;
    private Buffer mTexCoordBuffer;
    private Buffer mColorBuffer;
    private int mCoordinateSize;
    private int mCoordinateType;

    private int mW;
    private int mH;
    private int mIndexCount;
    private boolean mUseHardwareBuffers;
    private int mVertBufferIndex;
    private int mIndexBufferIndex;
    private int mTextureCoordBufferIndex;
    private int mColorBufferIndex;

    public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) {
        if (vertsAcross < 0 || vertsAcross >= 65536) {
            throw new IllegalArgumentException("vertsAcross");
        }
        if (vertsDown < 0 || vertsDown >= 65536) {
            throw new IllegalArgumentException("vertsDown");
        }
        if (vertsAcross * vertsDown >= 65536) {
            throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536");
        }

        mUseHardwareBuffers = false;

        mW = vertsAcross;
        mH = vertsDown;
        int size = vertsAcross * vertsDown;
        final int FLOAT_SIZE = 4;
        final int FIXED_SIZE = 4;
        final int CHAR_SIZE = 2;

        if (useFixedPoint) {
        	mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3)
            	.order(ByteOrder.nativeOrder()).asIntBuffer();
        	mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2)
            	.order(ByteOrder.nativeOrder()).asIntBuffer();
        	mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4)
        		.order(ByteOrder.nativeOrder()).asIntBuffer();

        	mVertexBuffer = mFixedVertexBuffer;
        	mTexCoordBuffer = mFixedTexCoordBuffer;
        	mColorBuffer = mFixedColorBuffer;
        	mCoordinateSize = FIXED_SIZE;
        	mCoordinateType = GL10.GL_FIXED;

        } else {
        	mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3)
            	.order(ByteOrder.nativeOrder()).asFloatBuffer();
        	mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2)
            	.order(ByteOrder.nativeOrder()).asFloatBuffer();
        	mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4)
        	.order(ByteOrder.nativeOrder()).asFloatBuffer();

        	mVertexBuffer = mFloatVertexBuffer;
        	mTexCoordBuffer = mFloatTexCoordBuffer;
        	mColorBuffer = mFloatColorBuffer;
        	mCoordinateSize = FLOAT_SIZE;
        	mCoordinateType = GL10.GL_FLOAT;
        }

        int quadW = mW - 1;
        int quadH = mH - 1;
        int quadCount = quadW * quadH;
        int indexCount = quadCount * 6;
        mIndexCount = indexCount;
        mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount)
            .order(ByteOrder.nativeOrder()).asCharBuffer();

        /*
         * Initialize triangle list mesh.
         *
         *     [0]-----[  1] ...
         *      |    /   |
         *      |   /    |
         *      |  /     |
         *     [w]-----[w+1] ...
         *      |       |
         *
         */

        {
            int i = 0;
            for (int y = 0; y < quadH; y++) {
                for (int x = 0; x < quadW; x++) {
                    char a = (char) (y * mW + x);
                    char b = (char) (y * mW + x + 1);
                    char c = (char) ((y + 1) * mW + x);
                    char d = (char) ((y + 1) * mW + x + 1);

                    mIndexBuffer.put(i++, a);
                    mIndexBuffer.put(i++, b);
                    mIndexBuffer.put(i++, c);

                    mIndexBuffer.put(i++, b);
                    mIndexBuffer.put(i++, c);
                    mIndexBuffer.put(i++, d);
                }
            }
        }

        mVertBufferIndex = 0;
    }

    void set(int i, int j, float x, float y, float z, float u, float v, float[] color) {
        if (i < 0 || i >= mW) {
            throw new IllegalArgumentException("i");
        }
        if (j < 0 || j >= mH) {
            throw new IllegalArgumentException("j");
        }

        final int index = mW * j + i;

        final int posIndex = index * 3;
        final int texIndex = index * 2;
        final int colorIndex = index * 4;

        if (mCoordinateType == GL10.GL_FLOAT) {
        	mFloatVertexBuffer.put(posIndex, x);
        	mFloatVertexBuffer.put(posIndex + 1, y);
        	mFloatVertexBuffer.put(posIndex + 2, z);

        	mFloatTexCoordBuffer.put(texIndex, u);
        	mFloatTexCoordBuffer.put(texIndex + 1, v);

        	if (color != null) {
        		mFloatColorBuffer.put(colorIndex, color[0]);
        		mFloatColorBuffer.put(colorIndex + 1, color[1]);
        		mFloatColorBuffer.put(colorIndex + 2, color[2]);
        		mFloatColorBuffer.put(colorIndex + 3, color[3]);
        	}
        } else {
        	mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16)));
        	mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16)));
        	mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16)));

        	mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16)));
        	mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16)));

        	if (color != null) {
        		mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16)));
        		mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16)));
        		mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16)));
        		mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16)));
        	}
        }
    }

    public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) {
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

        if (useTexture) {
            gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
            gl.glEnable(GL10.GL_TEXTURE_2D);
        } else {
            gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
            gl.glDisable(GL10.GL_TEXTURE_2D);
        }

        if (useColor) {
            gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
        } else {
            gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
        }
    }

    public void draw(GL10 gl, boolean useTexture, boolean useColor) {
        if (!mUseHardwareBuffers) {
            gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);

            if (useTexture) {
                gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
            }

            if (useColor) {
                gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer);
            }

            gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
                    GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
        } else {
            GL11 gl11 = (GL11)gl;
            // draw using hardware buffers
            gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
            gl11.glVertexPointer(3, mCoordinateType, 0, 0);

            if (useTexture) {
	            gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
	            gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
            }

            if (useColor) {
	            gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex);
	            gl11.glColorPointer(4, mCoordinateType, 0, 0);
            }

            gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
            gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount,
                    GL11.GL_UNSIGNED_SHORT, 0);

            gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
            gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);

        }
    }

    public static void endDrawing(GL10 gl) {
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    }

    public boolean usingHardwareBuffers() {
        return mUseHardwareBuffers;
    }

    /**
     * When the OpenGL ES device is lost, GL handles become invalidated.
     * In that case, we just want to "forget" the old handles (without
     * explicitly deleting them) and make new ones.
     */
    public void invalidateHardwareBuffers() {
        mVertBufferIndex = 0;
        mIndexBufferIndex = 0;
        mTextureCoordBufferIndex = 0;
        mColorBufferIndex = 0;
        mUseHardwareBuffers = false;
    }

    /**
     * Deletes the hardware buffers allocated by this object (if any).
     */
    public void releaseHardwareBuffers(GL10 gl) {
        if (mUseHardwareBuffers) {
            if (gl instanceof GL11) {
                GL11 gl11 = (GL11)gl;
                int[] buffer = new int[1];
                buffer[0] = mVertBufferIndex;
                gl11.glDeleteBuffers(1, buffer, 0);

                buffer[0] = mTextureCoordBufferIndex;
                gl11.glDeleteBuffers(1, buffer, 0);

                buffer[0] = mColorBufferIndex;
                gl11.glDeleteBuffers(1, buffer, 0);

                buffer[0] = mIndexBufferIndex;
                gl11.glDeleteBuffers(1, buffer, 0);
            }

            invalidateHardwareBuffers();
        }
    }

    /**
     * Allocates hardware buffers on the graphics card and fills them with
     * data if a buffer has not already been previously allocated.  Note that
     * this function uses the GL_OES_vertex_buffer_object extension, which is
     * not guaranteed to be supported on every device.
     * @param gl  A pointer to the OpenGL ES context.
     */
    public void generateHardwareBuffers(GL10 gl) {
        if (!mUseHardwareBuffers) {
            if (gl instanceof GL11) {
                GL11 gl11 = (GL11)gl;
                int[] buffer = new int[1];

                // Allocate and fill the vertex buffer.
                gl11.glGenBuffers(1, buffer, 0);
                mVertBufferIndex = buffer[0];
                gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
                final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize;
                gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize,
                        mVertexBuffer, GL11.GL_STATIC_DRAW);

                // Allocate and fill the texture coordinate buffer.
                gl11.glGenBuffers(1, buffer, 0);
                mTextureCoordBufferIndex = buffer[0];
                gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
                        mTextureCoordBufferIndex);
                final int texCoordSize =
                    mTexCoordBuffer.capacity() * mCoordinateSize;
                gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize,
                        mTexCoordBuffer, GL11.GL_STATIC_DRAW);

                // Allocate and fill the color buffer.
                gl11.glGenBuffers(1, buffer, 0);
                mColorBufferIndex = buffer[0];
                gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
                		mColorBufferIndex);
                final int colorSize =
                    mColorBuffer.capacity() * mCoordinateSize;
                gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize,
                		mColorBuffer, GL11.GL_STATIC_DRAW);

                // Unbind the array buffer.
                gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);

                // Allocate and fill the index buffer.
                gl11.glGenBuffers(1, buffer, 0);
                mIndexBufferIndex = buffer[0];
                gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER,
                        mIndexBufferIndex);
                // A char is 2 bytes.
                final int indexSize = mIndexBuffer.capacity() * 2;
                gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer,
                        GL11.GL_STATIC_DRAW);

                // Unbind the element array buffer.
                gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);

                mUseHardwareBuffers = true;

                assert mVertBufferIndex != 0;
                assert mTextureCoordBufferIndex != 0;
                assert mIndexBufferIndex != 0;
                assert gl11.glGetError() == 0;

            }
        }
    }

    // These functions exposed to patch Grid info into native code.
    public final int getVertexBuffer() {
    	return mVertBufferIndex;
    }

    public final int getTextureBuffer() {
    	return mTextureCoordBufferIndex;
    }

    public final int getIndexBuffer() {
    	return mIndexBufferIndex;
    }

    public final int getColorBuffer() {
    	return mColorBufferIndex;
    }

	public final int getIndexCount() {
		return mIndexCount;
	}

	public boolean getFixedPoint() {
		return (mCoordinateType == GL10.GL_FIXED);
	}

}


text:
struct InsideBuilding final : public LevelArea
{
	Vec2 offset;
	Vec3 inside_spawn, outside_spawn, xsphere_pos;
	Box2d enter_region, exit_region, region1, region2;
	float outside_rot, top, xsphere_radius, enter_y;
	Building* building;
	Int2 level_shift;

	InsideBuilding(int area_id) : LevelArea(LevelArea::Type::Building, area_id, false) {}
	void Save(GameWriter& f, bool local);
	void Load(GameReader& f, bool local);
	void Write(BitStreamWriter& f);
	bool Read(BitStreamReader& f);
};


text:
require 'helper'

describe Quaderno::Invoice do
  context 'A user with an authenticate token with invoices' do

    before(:each) do
      Quaderno::Base.configure do |config|
        config.auth_token = TEST_KEY
        config.url = TEST_URL
        config.api_version = nil
      end
    end

    it 'should get all invoices (populated db)' do
      VCR.use_cassette('all invoices') do
        invoices = Quaderno::Invoice.all
        expect(invoices.is_a? Array).to be true
        invoices.each { |invoice| expect(invoice.is_a? Quaderno::Invoice).to be true }
      end
    end

    it 'should paginate invoices' do
      VCR.use_cassette('paginated_invoices') do
        invoices = Quaderno::Invoice.all
        expect(invoices.has_more?).to be true
        second_page = invoices.next_page
        expect(second_page.map(&:id)).not_to include(invoices.map(&:id))
      end
    end

    it 'should find a invoice' do
      VCR.use_cassette('found invoice') do
        invoices = Quaderno::Invoice.all
        invoice = Quaderno::Invoice.find invoices.first.id
        expect(invoice.is_a? Quaderno::Invoice).to be true
        expect(invoice.id).to eq  invoices.first.id
      end
    end

    it 'should create a invoice' do
      VCR.use_cassette('new invoice') do
        contacts = Quaderno::Contact.all
        invoice = Quaderno::Invoice.create(contact_id: contacts[0].id ,
                                           contact_name: contacts[0].full_name,
                                           currency: 'EUR',
                                           items_attributes: [
                                             {
                                               description: 'Aircraft',
                                               quantity: '1.0',
                                               unit_price: '0.0'
                                             }
                                           ],
                                           tags: 'tnt',
                                           payment_details: '',
                                           notes: '')
        expect(invoice.is_a? Quaderno::Invoice).to be true
        expect(invoice.contact.id).to eq contacts[0].id
        expect(invoice.items[0].description).to eq 'Aircraft'

        Quaderno::Invoice.delete(invoice.id)
      end
    end

    it 'should update an invoice' do
      VCR.use_cassette('updated invoice') do
        contacts = Quaderno::Contact.all
        invoice = Quaderno::Invoice.create(contact_id: contacts[0].id ,
                                           contact_name: contacts[0].full_name,
                                           currency: 'EUR',
                                           items_attributes: [
                                             {
                                               description: 'Aircraft',
                                               quantity: '1.0',
                                               unit_price: '0.0'
                                             }
                                           ],
                                           tags: 'tnt',
                                           payment_details: '',
                                           notes: '')
        invoice = Quaderno::Invoice.update(invoice.id, payment_details: 'Show me the moneeeeeeeyy!!!!')
        expect(invoice.is_a? Quaderno::Invoice).to be true
        expect(invoice.payment_details).to eq 'Show me the moneeeeeeeyy!!!!'

        Quaderno::Invoice.delete(invoice.id)
      end
    end

    it 'should delete an invoice' do
      VCR.use_cassette('deleted invoice') do
        contacts = Quaderno::Contact.all
        invoice = Quaderno::Invoice.create(contact_id: contacts[0].id ,
                                           contact_name: contacts[0].full_name,
                                           currency: 'EUR',
                                           items_attributes: [
                                             {
                                               description: 'Aircraft',
                                               quantity: '1.0',
                                               unit_price: '0.0'
                                             }
                                           ],
                                           tags: 'tnt',
                                           payment_details: '',
                                           notes: '')
        Quaderno::Invoice.delete invoice.id
        invoices = Quaderno::Invoice.all
        expect(invoice.id).not_to eq invoices.first.id
      end
    end

    it 'should deliver an invoice' do
      VCR.use_cassette('delivered invoice') do
        invoices = Quaderno::Invoice.all
        rate_limit_before = Quaderno::Base.ping.rate_limit_info
        begin
          rate_limit_after = invoices.first.deliver
        rescue Quaderno::Exceptions::RequiredFieldsEmptyOrInvalid
          rate_limit_after = { remaining: (rate_limit_before[:remaining] - 1) }
        end

        expect(rate_limit_after[:remaining]).to eq(rate_limit_before[:remaining] - 1)
      end
    end

    it 'should add a payment' do
      VCR.use_cassette('paid invoice') do
        invoices = Quaderno::Invoice.all
        payment = invoices.first.add_payment(payment_method: 'cash', amount: 100000000)

        expect(payment.is_a? Quaderno::Payment).to be true
        expect(payment.payment_method).to eq 'cash'
        expect(payment.amount_cents).to eq 10000000000
        expect(payment.id).to eq invoices.first.payments.last.id
      end
    end

    it 'should remove a payment' do
      VCR.use_cassette('unpay an invoice') do
        invoices = Quaderno::Invoice.all
        invoices.first.add_payment(payment_method: 'cash', amount: 100000000)
        payment = invoices.first.payments.last
        array_length = invoices.first.payments.length
        invoices.first.remove_payment(payment.id) unless payment.nil?

        expect(invoices.first.payments.length).to eq(array_length.zero? ? array_length : array_length - 1)
      end
    end

    it 'should override version' do
      Quaderno::Base.api_version = OLDEST_SUPPORTED_API_VERSION

      VCR.use_cassette('create invoice on downgraded API') do
        contacts = Quaderno::Contact.all
        invoice = Quaderno::Invoice.create(contact_id: contacts[0].id ,
                                           contact_name: contacts[0].full_name,
                                           currency: 'EUR',
                                           items_attributes: [
                                             {
                                               description: 'Aircraft',
                                               quantity: '1.0',
                                               unit_price: '0.0'
                                             }
                                           ],
                                           tags: 'tnt',
                                           payment_details: '',
                                           notes: '')
        expect(invoice.total_cents.nil?).to be true
        expect(!invoice.total.nil?).to be true
        expect(invoice.is_a? Quaderno::Invoice).to be true
        expect(invoice.contact.id).to eq contacts[0].id
        expect(invoice.items[0].description).to eq('Aircraft')

        Quaderno::Invoice.delete(invoice.id)
      end
    end
  end
end


text: Specifies the build ID. The build ID is used to track which files are compiled and combined to be part of a build and later to scan those files.


text:
cls

#IsPublic IsSerial Name                                     BaseType
#-------- -------- ----                                     --------
#True     False    ScriptBlockAst                           System.Management.Automation.Language.Ast
#True     False    NamedBlockAst                            System.Management.Automation.Language.Ast
#True     False    PipelineAst                              System.Management.Automation.Language.PipelineBaseAst
#True     False    CommandExpressionAst                     System.Management.Automation.Language.CommandBaseAst
#True     False    InvokeMemberExpressionAst                System.Management.Automation.Language.MemberExpressionAst
#True     False    TypeExpressionAst                        System.Management.Automation.Language.ExpressionAst
#True     False    StringConstantExpressionAst              System.Management.Automation.Language.ConstantExpressionAst

#IsPublic IsSerial Name                        BaseType
#-------- -------- ----                        --------
#True     False    ScriptBlockAst              System.Management.Automation.Language.Ast
#True     False    NamedBlockAst               System.Management.Automation.Language.Ast
#True     False    FunctionDefinitionAst       System.Management.Automation.Language.StatementAst
#True     False    ScriptBlockAst              System.Management.Automation.Language.Ast
#True     False    NamedBlockAst               System.Management.Automation.Language.Ast
#True     False    PipelineAst                 System.Management.Automation.Language.PipelineBaseAst
#True     False    CommandExpressionAst        System.Management.Automation.Language.CommandBaseAst
#True     False    StringConstantExpressionAst System.Management.Automation.Language.ConstantExpressionAst

$src=@'
#$a=@()
#$h=@{}
#$b=1
#1..10 | % {$_}
function t {
    param($a,$b)

    $a+=1
    $a
}
#filter x {'t'}
#workflow y{'w'}
'@

$fileAST=[System.Management.Automation.Language.Parser]::ParseInput($src, [ref]$null, [ref]$null)
$fileAST.FindAll({
    param($ast)
    #1
    $ast -is [System.Management.Automation.Language.FunctionDefinitionAst]
},1) | % {
    $_.body.endblock.statements #.paramblock.parameters # parent.parent.parent #.gettype()
    #$_.extent.text
    #$_.PipelineElements.expression
} | ft -a


text:
package com.orientechnologies.orient.jdbc;

import com.orientechnologies.orient.core.OConstants;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class OrientJdbcDatabaseMetaDataTest extends OrientJdbcBaseTest {

  private DatabaseMetaData metaData;

  @Before
  public void setup() throws SQLException {
    metaData = conn.getMetaData();

  }

  @Test
  public void verifyDriverAndDatabaseVersions() throws SQLException {

    assertEquals("memory:test", metaData.getURL());
    assertEquals("admin", metaData.getUserName());
    assertEquals("OrientDB", metaData.getDatabaseProductName());
    assertEquals(OConstants.ORIENT_VERSION, metaData.getDatabaseProductVersion());
    assertEquals(2, metaData.getDatabaseMajorVersion());
    assertEquals(1, metaData.getDatabaseMinorVersion());

    assertEquals("OrientDB JDBC Driver", metaData.getDriverName());
    assertEquals("OrientDB 2.1 JDBC Driver", metaData.getDriverVersion());
    assertEquals(2, metaData.getDriverMajorVersion());
    assertEquals(1, metaData.getDriverMinorVersion());

  }

  @Test
  public void shouldRetrievePrimaryKeysMetadata() throws SQLException {

    ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, "Item");
    assertTrue(primaryKeys.next());
    assertEquals("intKey", primaryKeys.getString(4));
    assertEquals("Item.intKey", primaryKeys.getString(6));
    assertEquals(1, primaryKeys.getInt(5));

    assertTrue(primaryKeys.next());
    assertEquals("stringKey", primaryKeys.getString("COLUMN_NAME"));
    assertEquals("Item.stringKey", primaryKeys.getString("PK_NAME"));
    assertEquals(1, primaryKeys.getInt("KEY_SEQ"));

  }

  @Test
  public void shouldRetrieveTableTypes() throws SQLException {

    ResultSet tableTypes = metaData.getTableTypes();
    assertTrue(tableTypes.next());
    assertEquals("TABLE", tableTypes.getString(1));
    assertTrue(tableTypes.next());
    assertEquals("SYSTEM TABLE", tableTypes.getString(1));

    assertFalse(tableTypes.next());

  }

  @Test
  public void shouldRetrieveKeywords() throws SQLException {

    final String keywordsStr = metaData.getSQLKeywords();
    assertNotNull(keywordsStr);
    assertThat(Arrays.asList(keywordsStr.toUpperCase().split(",\\s*")), hasItem("TRAVERSE"));
  }

  @Test
  public void getFields() throws SQLException {
    ResultSet rs = conn.createStatement().executeQuery("select from OUser");

    ResultSetMetaData metaData = rs.getMetaData();

      int cc = metaData.getColumnCount();
      Set<String> colset = new HashSet<String>();
      List<Map<String, Object>> columns = new ArrayList<Map<String, Object>>(cc);
      for (int i = 1; i <= cc; i++) {
        String name = metaData.getColumnLabel(i);
        if (colset.contains(name))
          continue;
        colset.add(name);
        Map<String, Object> field = new HashMap<String, Object>();
        field.put("name", name);

        try {
          String catalog = metaData.getCatalogName(i);
          String schema = metaData.getSchemaName(i);
          String table = metaData.getTableName(i);
          ResultSet rsmc = conn.getMetaData().getColumns(catalog, schema, table, name);
          while (rsmc.next()) {
            field.put("description", rsmc.getString("REMARKS"));
            break;
          }
        } catch (SQLException se) {
          se.printStackTrace();
        }
        columns.add(field);
      }

      for (Map<String, Object> c : columns) {
        System.out.println(c);
      }
  }

  @Test
  public void shouldFetchAllTables() throws SQLException {
    ResultSet rs = this.metaData.getTables(null, null, null, null);
    int tableCount = rsSizeOf(rs);

    assertThat(tableCount, is(11));

  }

  private int rsSizeOf(ResultSet rs) throws SQLException {
    int tableCount = 0;

    while (rs.next()) {
      tableCount++;
    }
    return tableCount;
  }

  @Test
  public void shouldFillSchemaAndCatalogWithDatabaseName() throws SQLException {
    ResultSet rs = this.metaData.getTables(null, null, null, null);

    while (rs.next()) {
      assertThat(rs.getString("TABLE_SCHEM"),equalTo("test"));
      assertThat(rs.getString("TABLE_CAT"), equalTo("test"));
    }

  }

  @Test
  public void shouldGetAllTablesFilteredByAllTypes() throws SQLException {
    ResultSet rs = this.metaData.getTableTypes();
    List<String> tableTypes = new ArrayList<String>(2);
    while (rs.next()) {
      tableTypes.add(rs.getString(1));
    }
    rs = this.metaData.getTables(null, null, null, tableTypes.toArray(new String[2]));
    int tableCount = rsSizeOf(rs);
    assertThat(tableCount, is(11));
  }

  @Test
  public void getNoTablesFilteredByEmptySetOfTypes() throws SQLException {
    final ResultSet rs = this.metaData.getTables(null, null, null, new String[0]);
    int tableCount = rsSizeOf(rs);

    assertThat(tableCount,is(0));
  }

  @Test
  public void getSingleTable() throws SQLException {
    ResultSet rs = this.metaData.getTables(null, null, "ouser", null);

    assertThat(rsSizeOf(rs), is(1));
  }

  @Test
  public void shouldGetSingleColumnOfArticle() throws SQLException {
    ResultSet rs = this.metaData.getColumns(null, null, "Article", "uuid");

    assertThat(rsSizeOf(rs), is(1));
  }

  @Test
  public void shouldGetAllColumnsOfArticle() throws SQLException {
    ResultSet rs = this.metaData.getColumns(null, null, "Article", null);

    assertThat(rsSizeOf(rs),is(5));
  }

  @Test
  //FIXME this is not a test: what is the target?
  public void shouldGetAllFields() throws SQLException {
    ResultSet rsmc = conn.getMetaData().getColumns(null, null, "OUser", null);
    Set<String> fieldNames = new HashSet<String>();
    while (rsmc.next()) {
      fieldNames.add(rsmc.getString("COLUMN_NAME"));
    }

    fieldNames.removeAll(Arrays.asList("name", "password", "roles", "status"));
  }

}


text:
This example code contains three files:

##APIClient.php

Authors: [Magnus Johansson](/dragontoe), [Emil Andersson](/emil-nasso)

Contains functions for calling functions in the API using HTTP get or post. This relies heavily on the PHP module cURL so make sure that module is installed on your server.

##full_example.php

Author: Andreas Jönsson

An example script that allows you to make changes on a predetermined server. This makes it easy to reboot or upgrade a server for example, from a mobile web browser or from an external script. All you need is to do visit the URL of the script and fill out the password (which is defined in the script) and click on the action that you want to perform. You can also supply the action and password in the URL by appending get-variables. The implemented functions are:

* **serverlow** - Change amount of memory/cpu allocated to the server to handle low traffic.
* **serverpeak** - Change amount of memory/cpu allocated to the server to handle high (peak) traffic.
* **reboot** - Restart the server
* **details** - Get details about the server such as current hardware configuration, ip addresses and more.
* **status** - Get status information about the server such as state (running, stopped etc), cpu usage, memory usage and more.
* **memchange** - Check how much memory is used on the server and downgrade/upgrade the server as needed, automatically.
* **console** - Get all the information you need to connect to the server using VNC.

## mini_example.php

Author: Andreas Jönsson

A smaller version of full_example.php containing only the reboot-function.


text:
const { resolve } = require('path')
const fse = require('fs-extra')
const range = require('lodash.range')
const shell = require('shelljs')
const fetch = require('node-fetch')
const config = require('./config')

// download and initialize the judgers
// start !

const logDir = resolve(__dirname, 'logs')

const baseConfig = {
  apps: [
    {
      name: 'app',
      script: resolve(__dirname, `app.js`),
      'out_file': resolve(logDir, `app.out.log`),
      'error_file': resolve(logDir, `app.err.log`),
      'log_date_format': 'YYYY-MM-DD HH:mm:ss X',
      'merge_logs': true,
      'restart_delay': 500,
      env: {
        'NODE_ENV': 'production'
      }
    },
    {
      name: 'updater',
      script: resolve(__dirname, 'services', `updater.js`),
      'out_file': resolve(logDir, `updater.out.log`),
      'error_file': resolve(logDir, `updater.err.log`),
      'log_date_format': 'YYYY-MM-DD HH:mm:ss X',
      'merge_logs': true,
      env: {
        'NODE_ENV': 'production'
      }
    }
  ]
}

if (config.mail && config.mail.enable) {
  baseConfig.apps.push({
    name: 'mailer',
    script: resolve(__dirname, 'services', `mailer.js`),
    'out_file': resolve(logDir, `mailer.out.log`),
    'error_file': resolve(logDir, `mailer.err.log`),
    'log_date_format': 'YYYY-MM-DD HH:mm:ss X',
    'merge_logs': true,
    env: {
      'NODE_ENV': 'production'
    }
  })
}

async function judgeSetup () {
  let judgers = +config.judgers
  if (!(judgers >= 1 && judgers <= 10)) judgers = 1

  const judgersDir = resolve(__dirname, 'services')

  await fse.emptyDir(resolve(judgersDir, 'Judger'))

  // 下载最新版的 judger
  shell.exec(`git clone 'https://github.com/acm309/Judger' ${resolve(judgersDir, 'Judger')}`)
  shell.exec(`make -C ${resolve(judgersDir, 'Judger')}`)

  await Promise.all([
    fse.copy(resolve(judgersDir, 'Judger', 'Judge'), resolve(judgersDir, 'node-0', 'Judge')),
    fse.copy(resolve(judgersDir, 'Judger', 'config.ini'), resolve(judgersDir, 'node-0', 'config.ini'))
  ])

  await Promise.all(
    range(1, judgers)
      .map(i => fse.copy(
        resolve(judgersDir, 'node-0'),
        resolve(judgersDir, `node-${i}`)
      ))
  )

  const pm2config = baseConfig

  range(judgers).forEach(i =>
    pm2config.apps.push({
      name: `node-${i}`,
      script: resolve(judgersDir, `node-${i}/judger.js`),
      'out_file': resolve(logDir, `node-${i}-out.log`),
      'error_file': resolve(logDir, `node-${i}-err.log`),
      'log_date_format': 'YYYY-MM-DD HH:mm:ss X',
      'merge_logs': true,
      cwd: resolve(judgersDir, `node-${i}`),
      env: {
        'NODE_ENV': 'production'
      }
    })
  )

  return fse.outputJSON('pm2.config.json', pm2config, { spaces: 2, EOL: '\n' })
}

async function staticFilesSetUp () {
  const res = await fetch('https://api.github.com/repos/acm309/PutongOJ-FE/releases')
  const json = await res.json()
  const url = json[0].assets[0].browser_download_url
  shell.exec(`wget ${url} -O dist.zip`)
  shell.exec(`unzip -o dist.zip -d dist`)
  shell.exec(`cp -r dist/* public/`)
}

function main () {
  return Promise.all([
    judgeSetup(),
    staticFilesSetUp()
  ])
}

main()
  .then(() => {
    console.log('ok')
    process.exit(0)
  })
  .catch(err => {
    console.error(err)
    process.exit(-1)
  })


text:
<?php

namespace Google\AdsApi\Examples\Dfp\v201705\CreativeSetService;

require '../../../../vendor/autoload.php';

use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Dfp\DfpServices;
use Google\AdsApi\Dfp\DfpSession;
use Google\AdsApi\Dfp\DfpSessionBuilder;
use Google\AdsApi\Dfp\Util\v201705\StatementBuilder;
use Google\AdsApi\Dfp\v201705\CreativeSetService;

/**
 * This example gets all creative sets.
 *
 * <p>It is meant to be run from a command line (not as a webpage) and requires
 * that you've setup an `adsapi_php.ini` file in your home directory with your
 * API credentials and settings. See README.md for more info.
 */
class GetAllCreativeSets {

  public static function runExample(DfpServices $dfpServices,
      DfpSession $session) {
    $creativeSetService =
        $dfpServices->get($session, CreativeSetService::class);

    // Create a statement to select creative sets.
    $pageSize = StatementBuilder::SUGGESTED_PAGE_LIMIT;
    $statementBuilder = (new StatementBuilder())
        ->orderBy('id ASC')
        ->limit($pageSize);

    // Retrieve a small amount of creative sets at a time, paging
    // through until all creative sets have been retrieved.
    $totalResultSetSize = 0;
    do {
      $page = $creativeSetService->getCreativeSetsByStatement(
          $statementBuilder->toStatement());

      // Print out some information for each creative set.
      if ($page->getResults() !== null) {
        $totalResultSetSize = $page->getTotalResultSetSize();
        $i = $page->getStartIndex();
        foreach ($page->getResults() as $creativeSet) {
          printf(
              "%d) Creative set with ID %d and name '%s' was found.\n",
              $i++,
              $creativeSet->getId(),
              $creativeSet->getName()
          );
        }
      }

      $statementBuilder->increaseOffsetBy($pageSize);
    } while ($statementBuilder->getOffset() < $totalResultSetSize);

    printf("Number of results found: %d\n", $totalResultSetSize);
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new DfpSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();

    self::runExample(new DfpServices(), $session);
  }
}

GetAllCreativeSets::main();


text:
/* global define, module, require */

;(function (factory) {
  'use strict'
  if (typeof define === 'function' && define.amd) {
    // Register as an anonymous AMD module:
    define(['./load-image', './load-image-meta'], factory)
  } else if (typeof module === 'object' && module.exports) {
    factory(require('./load-image'), require('./load-image-meta'))
  } else {
    // Browser globals:
    factory(window.loadImage)
  }
})(function (loadImage) {
  'use strict'

  if (typeof fetch !== 'undefined' && typeof Request !== 'undefined') {
    loadImage.fetchBlob = function (url, callback, options) {
      if (loadImage.hasMetaOption(options)) {
        fetch(new Request(url, options))
          .then(function (response) {
            return response.blob()
          })
          .then(callback)
          .catch(function (err) {
            console.log(err) // eslint-disable-line no-console
            callback()
          })
      } else {
        callback()
      }
    }
  } else if (
    // Check for XHR2 support:
    typeof XMLHttpRequest !== 'undefined' &&
    typeof ProgressEvent !== 'undefined'
  ) {
    loadImage.fetchBlob = function (url, callback, options) {
      if (loadImage.hasMetaOption(options)) {
        // eslint-disable-next-line no-param-reassign
        options = options || {}
        var req = new XMLHttpRequest()
        req.open(options.method || 'GET', url)
        if (options.headers) {
          Object.keys(options.headers).forEach(function (key) {
            req.setRequestHeader(key, options.headers[key])
          })
        }
        req.withCredentials = options.credentials === 'include'
        req.responseType = 'blob'
        req.onload = function () {
          callback(req.response)
        }
        req.onerror = req.onabort = req.ontimeout = function (e) {
          console.log(e) // eslint-disable-line no-console
          callback()
        }
        req.send(options.body)
      } else {
        callback()
      }
    }
  }
})


text:
DIR=$(cd `dirname $0` && pwd)
source $DIR/include.sh

proj="test"

# now submit req
runurl="${APIURL}/run/script"

echo "TEST: /api/run/script GET should fail with wrong HTTP method"
$SHELL $SRC_DIR/api-expect-code.sh 405 "${runurl}" "project=" 'parameter "project" is required' && echo "OK" || exit 2

echo "TEST: /api/run/script POST should fail with no project param"
CURL_REQ_OPTS="-X POST" $SHELL $SRC_DIR/api-expect-error.sh "${runurl}" "project=" 'parameter "project" is required' && echo "OK" || exit 2

echo "TEST: /api/run/script POST should fail with no scriptFile param"
params="project=${proj}"
CURL_REQ_OPTS="-X POST" $SHELL $SRC_DIR/api-expect-error.sh "${runurl}" "${params}" 'parameter "scriptFile" is required' && echo "OK" || exit 2

echo "TEST: /api/run/script POST should fail with empty scriptFile content"
touch $DIR/test.tmp
docurl -F scriptFile=@$DIR/test.tmp ${runurl}?${params} > $DIR/curl.out
if [ 0 != $? ] ; then
    errorMsg "FAIL: failed query request"
    exit 2
fi

$SHELL $SRC_DIR/api-test-error.sh $DIR/curl.out "Input script file was empty" && echo "OK" || exit 2
rm $DIR/test.tmp

OUTF=/tmp/script.out
SCRIPTF=/tmp/script.tmp
####
#  echo a script into a temp file
####
cat <<END > $SCRIPTF
#!/bin/bash
echo hello
echo @node.name@ > $OUTF
END

#remove script.out if it exists

[ -f $OUTF ] && rm $OUTF

echo "TEST: /api/run/script should succeed and return execution id"
# make api request
docurl -F scriptFile=@$SCRIPTF ${runurl}?${params} > $DIR/curl.out
if [ 0 != $? ] ; then
    errorMsg "FAIL: failed query request"
    exit 2
fi

$SHELL $SRC_DIR/api-test-success.sh $DIR/curl.out || exit 2

execid=$($XMLSTARLET sel -T -t -v "/result/execution/@id" -n $DIR/curl.out)
if [ "" == "${execid}" ] ; then
    errorMsg "FAIL: expected execution id in result: ${execid}"
    exit 2
fi

##wait for script to execute...
api_waitfor_execution $execid || fail "Waiting for $execid to finish"
$SHELL $SRC_DIR/api-expect-exec-success.sh $execid || exit 2

if [ ! -f $OUTF ] ; then
    errorMsg "FAIL: Expected script to execute and create script.out file"
    exit 2
else
    cat $OUTF
    rm $OUTF
fi

echo "OK"

rm $DIR/curl.out
rm $SCRIPTF


text:
package com.hello2morrow.sonargraph.integration.access.model.internal;

import com.hello2morrow.sonargraph.integration.access.model.IWildcardPattern;

abstract class AbstractWildcardPatternImpl extends NamedElementImpl implements IWildcardPattern
{
    private static final long serialVersionUID = 1L;
    private final int numberOfMatches;

    public AbstractWildcardPatternImpl(final String fqName, final String kind, final String presentationKind, final String name,
            final String presentationName, final int numberOfMatches)
    {
        super(kind, presentationKind, name, presentationName, fqName, null);
        this.numberOfMatches = numberOfMatches;
    }

    @Override
    public String getPattern()
    {
        return getName();
    }

    @Override
    public int getNumberOfMatches()
    {
        return numberOfMatches;
    }
}


text:
module ActiverecordRedshiftAdapter
  # the current version of this gem
  VERSION = "0.9.15"
end


text:
package Paws::DMS::DeleteReplicationInstanceResponse;
  use Moose;
  has ReplicationInstance => (is => 'ro', isa => 'Paws::DMS::ReplicationInstance');

  has _request_id => (is => 'ro', isa => 'Str');

### main pod documentation begin ###

=head1 NAME

Paws::DMS::DeleteReplicationInstanceResponse

=head1 ATTRIBUTES

=head2 ReplicationInstance => L<Paws::DMS::ReplicationInstance>

The replication instance that was deleted.

=head2 _request_id => Str

=cut

1;


text:
package org.grassroot.android.fragments;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;

import org.grassroot.android.R;
import org.grassroot.android.activities.AddMembersActivity;
import org.grassroot.android.activities.GroupMembersActivity;
import org.grassroot.android.activities.HomeScreenActivity;
import org.grassroot.android.activities.RemoveMembersActivity;
import org.grassroot.android.interfaces.GroupConstants;
import org.grassroot.android.models.Group;
import org.grassroot.android.utils.Constant;
import org.grassroot.android.utils.IntentUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class GroupQuickMemberModalFragment extends android.support.v4.app.DialogFragment {

    private static final String TAG = GroupQuickMemberModalFragment.class.getSimpleName();

    @BindView(R.id.ic_home_add_member_active)
    ImageView icAddMemberIcon;
    @BindView(R.id.ic_home_view_members_active)
    ImageView icViewMemberIcon;
    @BindView(R.id.ic_remove_members_active)
    ImageView icRemoveMembersIcon;

    private Unbinder unbinder;

    private Group group;
    private String groupUid;
    private String groupName;
    private int groupPosition;

    private boolean addMemberPermitted, viewMembersPermitted, removeMembersPermitted;

    // would rather use good practice and not have empty constructor, but Android is Android
    public GroupQuickMemberModalFragment() { }

    @Override
    public void onStart() {
        super.onStart();
        getDialog().getWindow().setWindowAnimations(R.style.animation_fast_flyinout);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.modal_group_members_quick, container, false);
        unbinder = ButterKnife.bind(this, view);
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0));
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle b = getArguments();
        if (b == null) {
            throw new UnsupportedOperationException("Error! Null arguments passed to modal");
        }

        Log.d(TAG, "inside quickGroupMemberBundle, passed bundle = " + b.toString());
        group = b.getParcelable(GroupConstants.OBJECT_FIELD);
        groupPosition = b.getInt(Constant.INDEX_FIELD);

        if (group == null) {
            throw new UnsupportedOperationException("Error! Fragment called without group object");
        }

        groupUid = group.getGroupUid();
        groupName = group.getGroupName();

        addMemberPermitted = group.canAddMembers();
        viewMembersPermitted = group.canViewMembers();
        removeMembersPermitted = group.canDeleteMembers();

        int addIcon = addMemberPermitted ? R.drawable.ic_add_circle_active_24dp : R.drawable.ic_add_circle_inactive_24dp;
        int viewIcon = viewMembersPermitted ? R.drawable.ic_list_icon_active_24dp : R.drawable.ic_list_icon_inactive_24dp;
        int removeIcon = removeMembersPermitted ? R.drawable.ic_remove_circle_active_24dp : R.drawable.ic_remove_circle_inactive_24dp;

        icAddMemberIcon.setImageResource(addIcon);
        icViewMemberIcon.setImageResource(viewIcon);
        icRemoveMembersIcon.setImageResource(removeIcon);
    }

    @OnClick(R.id.ic_home_add_member_active)
    public void gmAddMemberIconListener() {
        if (addMemberPermitted) {
            Intent addMember = IntentUtils.constructIntent(getActivity(), AddMembersActivity.class, groupUid, groupName);
            addMember.putExtra(Constant.INDEX_FIELD, groupPosition);
            // note: inefficiency here in routing back via activity, but getParentFragment is throwing a null error...
            getActivity().startActivity(addMember);
            getDialog().dismiss();
        } else {
            getDialog().dismiss();
        }
    }

    @OnClick(R.id.ic_home_view_members_active)
    public  void gmViewMembersIconListener() {
        if (viewMembersPermitted) {
            Intent viewMembers = IntentUtils.constructIntent(getActivity(), GroupMembersActivity.class, group);
            viewMembers.putExtra(Constant.PARENT_TAG_FIELD, HomeScreenActivity.class.getCanonicalName());
            startActivity(viewMembers);
            getDialog().dismiss();
        } else {
            getDialog().dismiss();
        }
    }

    @OnClick(R.id.ic_remove_members_active)
    public void gmRemoveMembersIconListener() {
        if (removeMembersPermitted) {
            Intent removeMembers = IntentUtils.constructIntent(getActivity(), RemoveMembersActivity.class, groupUid, groupName);
            removeMembers.putExtra(Constant.INDEX_FIELD, groupPosition);
            getActivity().startActivity(removeMembers);
            getDialog().dismiss();
        } else {
            getDialog().dismiss();

        }
    }

}


text:
require 'fileutils'

module FileHelpers
  #
  # Directory Paths
  #

  def default_input_directory
    File.join root_directory, 'docs'
  end

  def default_output_directory
    File.join root_directory, 'public'
  end

  def tmp_directory
    File.join root_directory, 'tmp'
  end

  #
  # Directory Operations
  #

  def copy_directory(source, destination)
    FileUtils.rm_rf   destination
    FileUtils.mkdir_p File.dirname(destination)
    FileUtils.cp_r    source, destination
  end

  def move_directory(source, destination)
    FileUtils.rm_rf   destination
    FileUtils.mkdir_p File.dirname(destination)
    FileUtils.mv      source, destination
  end

  def empty_tmp_directory
    FileUtils.rm_rf tmp_directory
  end

  def empty_output_directory
    FileUtils.rm_rf @output_directory
  end

  #
  # File Operations
  #

  def each_file(directory)
    directory_glob = Dir.glob(File.join(directory, '**', '*'))

    directory_glob.sort.each do |entry|
      yield(entry) unless File.directory?(entry) or entry !~ /md|html/
    end
  end

  private

  def root_directory
    File.expand_path(File.join(File.dirname(__FILE__), '..'))
  end
end


text:
package pass.web.view;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pass.core.model.VerificationCode;
import pass.core.service.AccountService;
import pass.core.service.VerificationService;
import pass.web.common.Container;
import pass.web.common.WebConfig;
import pass.web.common.WebUtil;

@WebServlet ("/reset_password.do")
public class ResetPassword extends HttpServlet
{

    private final static Logger LOGGER = Logger.getLogger(ResetPassword.class.getName());

    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException
    {
        VerificationService vServ = new VerificationService(Container.getInstance().getMailer());
        VerificationCode vc = vServ.getVerificationCode(request.getParameter("code"));
        AccountService accServ = new AccountService(vServ);
        boolean success = accServ.resetPassword(vc, request.getParameter("password"));
        if (success) {
            Map<String, Object> data = new HashMap<>();
            data.put("title", "Password changed successfully");
            data.put("message",
                     "You can now sign in using your new password. "
                     + "Proceed to sign in page.");
            WebUtil.renderTemplate(request, response, "public/message.ftl", data);
        }
        else {
            LOGGER.log(Level.WARNING,
                       "Failed to reset password for {0}",
                       vc.toString());
        }
    }
}


text:
from network import Network
from participant import Participant, CSV_Participant
from battery import Battery, Central_Battery
from tariffs import Tariffs
import util
from results import Results
import energy_sim
import financial_sim

# Required 3rd party libraries
import datetime
import pandas as pd
import numpy as np
import pprint
import csv
import os

#  ==================
# PROGRAM STARTS HERE
#  ==================

# Directories where input and output data lives.
output_dir = 'byron_output'
data_dir ='data'

# Create a network - this stores information on the electricity network we want to model.
mynetwork = Network('Byron')

# Load the participants from a csv
mynetwork.add_participants_from_csv(data_dir,"participant_meta_data.csv")

# Create a central battery.
battery_capacity = 0.001
central_battery = Central_Battery(cap_kWh=battery_capacity, cap_kW=battery_capacity, cycle_eff=0.99, ui_battery_discharge_windows_path=os.path.join(data_dir,"ui_battery_discharge_window_eg.csv"))
# Add the battery to the network.
mynetwork.add_central_battery(central_battery)

# Create a 'tariffs' object that stores information and logic about different tariffs.
my_tariffs = Tariffs('Test',os.path.join(data_dir,"retail_tariffs.csv"),os.path.join(data_dir,"duos.csv"),os.path.join(data_dir,"tuos.csv"), os.path.join(data_dir,"nuos.csv"), os.path.join(data_dir,"ui_tariffs_eg.csv"))

# Define the start and end times of the simulation.
start = datetime.datetime(year=2017,month=2,day=26,hour=4)
end =  datetime.datetime(year=2017,month=2,day=26,hour=23) #this is an end time very near the start, good for testing code because we don't do many calculations.
# end =  datetime.datetime(year=2017,month=4,day=30,hour=23) #this is the total end time for all the data in the byron model

# Generate a list of time periods in half hour increments, on which to run the simulation. These must be included in the input time series.
time_periods = util.generate_dates_in_range(start, end, 30)
# Create a results object to store the results of the simulations
results = Results(time_periods, [p.get_id() for p in mynetwork.get_participants()])
# Perform energy simulations and store the results in our results object.
energy_sim.simulate(time_periods, mynetwork, my_tariffs, results)
# Perform financial calculations based on the energy sim and store the results in our results object.
financial_sim.simulate(time_periods, mynetwork, my_tariffs, results)
# Print to CSV files
results.to_csv(output_dir, info_tag=battery_capacity)


text:
import awacs
import awacs.aws
import awacs.sns
import awacs.sqs

from troposphere import GetAtt, Ref, Template
from troposphere.iam import LoginProfile, Policy, User

t = Template()

t.add_resource(
    User(
        "myuser",
        Path="/",
        LoginProfile=LoginProfile(Password="myP@ssW0rd"),
        Policies=[
            Policy(
                PolicyName="giveaccesstoqueueonly",
                PolicyDocument=awacs.aws.PolicyDocument(
                    Statement=[
                        awacs.aws.Statement(
                            Effect=awacs.aws.Allow,
                            Action=[awacs.aws.Action("sqs", "*")],
                            Resource=[GetAtt("myqueue", "Arn")],
                        ),
                        awacs.aws.Statement(
                            Effect=awacs.aws.Deny,
                            Action=[awacs.aws.Action("sqs", "*")],
                            NotResource=[GetAtt("myqueue", "Arn")],
                        ),
                    ],
                ),
            ),
            Policy(
                PolicyName="giveaccesstotopiconly",
                PolicyDocument=awacs.aws.PolicyDocument(
                    Statement=[
                        awacs.aws.Statement(
                            Effect=awacs.aws.Allow,
                            Action=[awacs.aws.Action("sns", "*")],
                            Resource=[Ref("mytopic")],
                        ),
                        awacs.aws.Statement(
                            Effect=awacs.aws.Deny,
                            Action=[awacs.aws.Action("sns", "*")],
                            NotResource=[Ref("mytopic")],
                        ),
                    ],
                ),
            ),
        ],
    )
)

print(t.to_json())


text:
package com.github.visgeek.utils.collections.test.testcase.ienumerable.ienumerable;

import org.junit.Test;

import com.github.visgeek.utils.collections.Enumerable;
import com.github.visgeek.utils.collections.IEnumerable;
import com.github.visgeek.utils.functions.Action0;
import com.github.visgeek.utils.testing.Assert2;

public class AsStream {
	@Test
	public void case01() {
		IEnumerable<Integer> source = ()->Enumerable.of(1, 2, 3).iterator();
		Action0 action = () -> ((IEnumerable<Integer>) () -> source.asStream().iterator()).any();
		Assert2.assertExceptionNotThrown(action);
	}
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[Serializable]
public class FloatRange {

    public float min;
    public float max;
    public float size {
        get {
            return max - min;
        }
    }

    public FloatRange(float _min, float _max) {
        min = _min;
        max = _max;
    }

    public float Random {
        get { return UnityEngine.Random.Range(min, max); }
    }

    public float MapTo(float input, float min, float max) {
        return MyMath.Map(input, min, max, this.min, this.max);
    }

    public float Clamp(float value) {
        return Mathf.Clamp(value, min, max);
    }
}


text:
/****************************************************************************
 * libc/stdio/lib_setvbuf.c
 *
 *   Copyright (C) 2017 Gregory Nutt. All rights reserved.
 *   Author: Alan Carvalho de Assis <acassis@gmail.com>
 *           Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT will THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#include <sys/types.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#include <tinyara/fs/fs.h>

#include "lib_internal.h"

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: setvbuf
 *
 * Description:
 *   The setvbuf() function may be used after the stream pointed to by
 *   stream is associated with an open file but before any other operation
 *   (other than an unsuccessful call to setvbuf()) is performed on the
 *   stream. The argument type determines how stream will be buffered, as
 *   follows:
 *
 *   _IOFBF - Will cause input/output to be fully buffered.
 *   _IOLBF - Will cause input/output to be line buffered.
 *   _IONBF - Will cause input/output to be unbuffered.
 *
 * If buf is not a null pointer, the array it points to may be used instead
 * of a buffer allocated by setvbuf() and the argument size specifies the size
 * of the array; otherwise, size may determine the size of a buffer allocated
 * by the setvbuf() function. The contents of the array at any time are
 * unspecified.
 *
 * Input Parameters:
 *   stream - the stream to flush
 *   buffer - the user allocate buffer. If NULL, will allocates a buffer of
 *            specified size
 *   mode   - specifies a mode for file buffering
 *   size   - size of buffer
 *
 * Returned Value:
 *   Upon successful completion, setvbuf() will return 0. Otherwise, it will
 *   return a non-zero value if an invalid value is given for type or if the
 *   request cannot be honored, [CX] and may set errno to indicate the error
 *
 ****************************************************************************/

#if CONFIG_STDIO_BUFFER_SIZE > 0
int setvbuf(FAR FILE *stream, FAR char *buffer, int mode, size_t size)
{
	FAR unsigned char *newbuf;
	uint8_t flags;
	int errcode;

	/* Verify arguments */
	/* Make sure that a valid mode was provided */

	if (mode != _IOFBF && mode != _IOLBF && mode != _IONBF) {
		errcode = EINVAL;
		goto errout;
	}

	/* If a buffer pointer is provided, then it must have a non-zero size */

	if (buffer != NULL && size == 0) {
		errcode = EINVAL;
		goto errout;
	}

	/* My assumption is that if size is zero for modes {_IOFBF, _IOLBF} the
	 * caller is only attempting to change the buffering mode.  In this case,
	 * the existing buffer should be re-used (if there is one).  If there is no
	 * existing buffer, then I suppose we should allocate one of the default
	 * size?
	 */

	if ((mode == _IOFBF || mode == _IOLBF) && size == 0 && stream->fs_bufstart == NULL) {
		size = BUFSSIZ;
	}

	/* A non-zero size (or a non-NULL buffer) with mode = _IONBF makes no
	 * sense but is, apparently, permissible. We simply force the buffer to
	 * NULL and size to zero in this case without complaining.
	 */

	else if (mode == _IONBF) {
		buffer = NULL;
		size = 0;
	}

	/* Make sure that we have exclusive access to the stream */

	lib_take_semaphore(stream);

	/* setvbuf() may only be called AFTER the file has been opened and BEFORE
	 * any operations have been performed on the string.
	 */

	/* Return EBADF if the file is not open */

	if (stream->fs_fd < 0) {
		errcode = EBADF;
		goto errout_with_semaphore;
	}

	/* Return EBUSY if operations have already been performed on the buffer.
	 * Here we really only verify that there is no valid data in the existing
	 * buffer.
	 *
	 * REVIST:  There could be race conditions here, could there not?
	 */

	if (stream->fs_bufpos != stream->fs_bufstart) {
		errcode = EBUSY;
		goto errout_with_semaphore;
	}

	/* Initialize by clearing related flags.  We try to avoid any permanent
	 * changes to the stream structure until we know that we will be
	 * successful.
	 */

	flags = stream->fs_flags & ~(__FS_FLAG_LBF | __FS_FLAG_UBF);

	/* Allocate a new buffer if one is needed or reuse the existing buffer it
	 * is appropriate to do so.
	 */

	switch (mode) {
	case _IOLBF:
		flags |= __FS_FLAG_LBF;

		/* Fall through */

	case _IOFBF:
		/* Use the existing buffer if size == 0 */

		if (size > 0) {
			/* A new buffer is needed.  Did the caller provide the buffer
			 * memory?
			 */

			if (buffer != NULL) {
				newbuf = (FAR unsigned char *)buffer;

				/* Indicate that we have an I/O buffer managed by the caller of
				 * setvbuf.
				 */

				flags |= __FS_FLAG_UBF;
			} else {
				newbuf = (FAR unsigned char *)lib_malloc(size);
				if (newbuf == NULL) {
					errcode = ENOMEM;
					goto errout_with_semaphore;
				}
			}
		} else {
			/* Re-use the existing buffer and retain some existing flags.
			 * This supports changing the buffering mode without changing
			 * the buffer.
			 */

			DEBUGASSERT(stream->fs_bufstart != NULL);
			flags |= stream->fs_flags & __FS_FLAG_UBF;
			goto reuse_buffer;
		}

		break;

	case _IONBF:
		/* No buffer needed... We must be performing unbuffered I/O */

		newbuf = NULL;
		break;

	default:
		PANIC();
	}

	/* Do not release the previous buffer if it was allocated by the user
	 * on a previous call to setvbuf().
	 */

	if (stream->fs_bufstart != NULL && (stream->fs_flags & __FS_FLAG_UBF) == 0) {
		lib_free(stream->fs_bufstart);
	}

	/* Set the new buffer information */

	stream->fs_bufstart = newbuf;
	stream->fs_bufpos = newbuf;
	stream->fs_bufread = newbuf;
	stream->fs_bufend = newbuf + size;

	/* Update the stream flags and return success */

reuse_buffer:

	stream->fs_flags = flags;
	lib_give_semaphore(stream);
	return OK;

errout_with_semaphore:
	lib_give_semaphore(stream);

errout:
	set_errno(errcode);
	return ERROR;
}
#endif


text:
{-# LANGUAGE DeriveFunctor #-}
-- | Our extended FCode monad.

-- We add a mapping from names to CmmExpr, to support local variable names in
-- the concrete C-- code.  The unique supply of the underlying FCode monad
-- is used to grab a new unique for each local variable.

-- In C--, a local variable can be declared anywhere within a proc,
-- and it scopes from the beginning of the proc to the end.  Hence, we have
-- to collect declarations as we parse the proc, and feed the environment
-- back in circularly (to avoid a two-pass algorithm).

module GHC.StgToCmm.ExtCode (
        CmmParse, unEC,
        Named(..), Env,

        loopDecls,
        getEnv,

        withName,
        getName,

        newLocal,
        newLabel,
        newBlockId,
        newFunctionName,
        newImport,
        lookupLabel,
        lookupName,

        code,
        emit, emitLabel, emitAssign, emitStore,
        getCode, getCodeR, getCodeScoped,
        emitOutOfLine,
        withUpdFrameOff, getUpdFrameOff
)

where

import GhcPrelude

import qualified GHC.StgToCmm.Monad as F
import GHC.StgToCmm.Monad (FCode, newUnique)

import GHC.Cmm
import GHC.Cmm.CLabel
import GHC.Cmm.Graph

import GHC.Cmm.BlockId
import DynFlags
import FastString
import Module
import UniqFM
import Unique
import UniqSupply

import Control.Monad (ap)

-- | The environment contains variable definitions or blockids.
data Named
        = VarN CmmExpr          -- ^ Holds CmmLit(CmmLabel ..) which gives the label type,
                                --      eg, RtsLabel, ForeignLabel, CmmLabel etc.

        | FunN   UnitId      -- ^ A function name from this package
        | LabelN BlockId                -- ^ A blockid of some code or data.

-- | An environment of named things.
type Env        = UniqFM Named

-- | Local declarations that are in scope during code generation.
type Decls      = [(FastString,Named)]

-- | Does a computation in the FCode monad, with a current environment
--      and a list of local declarations. Returns the resulting list of declarations.
newtype CmmParse a
        = EC { unEC :: String -> Env -> Decls -> FCode (Decls, a) }
    deriving (Functor)

type ExtCode = CmmParse ()

returnExtFC :: a -> CmmParse a
returnExtFC a   = EC $ \_ _ s -> return (s, a)

thenExtFC :: CmmParse a -> (a -> CmmParse b) -> CmmParse b
thenExtFC (EC m) k = EC $ \c e s -> do (s',r) <- m c e s; unEC (k r) c e s'

instance Applicative CmmParse where
      pure = returnExtFC
      (<*>) = ap

instance Monad CmmParse where
  (>>=) = thenExtFC

instance MonadUnique CmmParse where
  getUniqueSupplyM = code getUniqueSupplyM
  getUniqueM = EC $ \_ _ decls -> do
    u <- getUniqueM
    return (decls, u)

instance HasDynFlags CmmParse where
    getDynFlags = EC (\_ _ d -> do dflags <- getDynFlags
                                   return (d, dflags))

-- | Takes the variable declarations and imports from the monad
--      and makes an environment, which is looped back into the computation.
--      In this way, we can have embedded declarations that scope over the whole
--      procedure, and imports that scope over the entire module.
--      Discards the local declaration contained within decl'
--
loopDecls :: CmmParse a -> CmmParse a
loopDecls (EC fcode) =
      EC $ \c e globalDecls -> do
        (_, a) <- F.fixC $ \ ~(decls, _) ->
          fcode c (addListToUFM e decls) globalDecls
        return (globalDecls, a)

-- | Get the current environment from the monad.
getEnv :: CmmParse Env
getEnv  = EC $ \_ e s -> return (s, e)

-- | Get the current context name from the monad
getName :: CmmParse String
getName  = EC $ \c _ s -> return (s, c)

-- | Set context name for a sub-parse
withName :: String -> CmmParse a -> CmmParse a
withName c' (EC fcode) = EC $ \_ e s -> fcode c' e s

addDecl :: FastString -> Named -> ExtCode
addDecl name named = EC $ \_ _ s -> return ((name, named) : s, ())

-- | Add a new variable to the list of local declarations.
--      The CmmExpr says where the value is stored.
addVarDecl :: FastString -> CmmExpr -> ExtCode
addVarDecl var expr = addDecl var (VarN expr)

-- | Add a new label to the list of local declarations.
addLabel :: FastString -> BlockId -> ExtCode
addLabel name block_id = addDecl name (LabelN block_id)

-- | Create a fresh local variable of a given type.
newLocal
        :: CmmType              -- ^ data type
        -> FastString           -- ^ name of variable
        -> CmmParse LocalReg    -- ^ register holding the value

newLocal ty name = do
   u <- code newUnique
   let reg = LocalReg u ty
   addVarDecl name (CmmReg (CmmLocal reg))
   return reg

-- | Allocate a fresh label.
newLabel :: FastString -> CmmParse BlockId
newLabel name = do
   u <- code newUnique
   addLabel name (mkBlockId u)
   return (mkBlockId u)

-- | Add add a local function to the environment.
newFunctionName
        :: FastString   -- ^ name of the function
        -> UnitId    -- ^ package of the current module
        -> ExtCode

newFunctionName name pkg = addDecl name (FunN pkg)

-- | Add an imported foreign label to the list of local declarations.
--      If this is done at the start of the module the declaration will scope
--      over the whole module.
newImport
        :: (FastString, CLabel)
        -> CmmParse ()

newImport (name, cmmLabel)
   = addVarDecl name (CmmLit (CmmLabel cmmLabel))

-- | Lookup the BlockId bound to the label with this name.
--      If one hasn't been bound yet, create a fresh one based on the
--      Unique of the name.
lookupLabel :: FastString -> CmmParse BlockId
lookupLabel name = do
  env <- getEnv
  return $
     case lookupUFM env name of
        Just (LabelN l) -> l
        _other          -> mkBlockId (newTagUnique (getUnique name) 'L')

-- | Lookup the location of a named variable.
--      Unknown names are treated as if they had been 'import'ed from the runtime system.
--      This saves us a lot of bother in the RTS sources, at the expense of
--      deferring some errors to link time.
lookupName :: FastString -> CmmParse CmmExpr
lookupName name = do
  env    <- getEnv
  return $
     case lookupUFM env name of
        Just (VarN e)   -> e
        Just (FunN pkg) -> CmmLit (CmmLabel (mkCmmCodeLabel pkg          name))
        _other          -> CmmLit (CmmLabel (mkCmmCodeLabel rtsUnitId name))

-- | Lift an FCode computation into the CmmParse monad
code :: FCode a -> CmmParse a
code fc = EC $ \_ _ s -> do
                r <- fc
                return (s, r)

emit :: CmmAGraph -> CmmParse ()
emit = code . F.emit

emitLabel :: BlockId -> CmmParse ()
emitLabel = code . F.emitLabel

emitAssign :: CmmReg  -> CmmExpr -> CmmParse ()
emitAssign l r = code (F.emitAssign l r)

emitStore :: CmmExpr  -> CmmExpr -> CmmParse ()
emitStore l r = code (F.emitStore l r)

getCode :: CmmParse a -> CmmParse CmmAGraph
getCode (EC ec) = EC $ \c e s -> do
  ((s',_), gr) <- F.getCodeR (ec c e s)
  return (s', gr)

getCodeR :: CmmParse a -> CmmParse (a, CmmAGraph)
getCodeR (EC ec) = EC $ \c e s -> do
  ((s', r), gr) <- F.getCodeR (ec c e s)
  return (s', (r,gr))

getCodeScoped :: CmmParse a -> CmmParse (a, CmmAGraphScoped)
getCodeScoped (EC ec) = EC $ \c e s -> do
  ((s', r), gr) <- F.getCodeScoped (ec c e s)
  return (s', (r,gr))

emitOutOfLine :: BlockId -> CmmAGraphScoped -> CmmParse ()
emitOutOfLine l g = code (F.emitOutOfLine l g)

withUpdFrameOff :: UpdFrameOffset -> CmmParse () -> CmmParse ()
withUpdFrameOff size inner
  = EC $ \c e s -> F.withUpdFrameOff size $ (unEC inner) c e s

getUpdFrameOff :: CmmParse UpdFrameOffset
getUpdFrameOff = code $ F.getUpdFrameOff


text:
// Created by Ron 'Maxwolf' McDowell (ron.mcdowell@gmail.com)
// Timestamp 01/03/2016@1:50 AM

using System;
using System.Text;

namespace OregonTrail
{
    /// <summary>
    ///     Tabulates results about the hunting session after it ends, depending on the performance of the player and how many
    ///     animals they killed, if any will be calculated in weight. Players can only ever take 100 pounds of meat back to
    ///     the vehicle so this discourages mass killing.
    /// </summary>
    [ParentWindow(typeof (Travel))]
    public sealed class HuntingResult : InputForm<TravelInfo>
    {
        /// <summary>
        ///     References the total weight of all the animals the player killed so we only have to reference it once.
        /// </summary>
        private int _finalKillWeight;

        /// <summary>
        ///     Holds all of the data for our final hunting result before rendering out to player.
        /// </summary>
        private StringBuilder _huntScore;

        /// <summary>
        ///     Initializes a new instance of the <see cref="InputForm{T}" /> class.
        ///     This constructor will be used by the other one
        /// </summary>
        /// <param name="window">The window.</param>
        public HuntingResult(IWindow window) : base(window)
        {
            _huntScore = new StringBuilder();
        }

        public override object MenuCommands
        {
            get { return new[] {"Ok"}; }
        }

        /// <summary>
        ///     Fired after the state has been completely attached to the simulation letting the state know it can browse the user
        ///     data and other properties below it.
        /// </summary>
        public override void OnFormPostCreate()
        {
            base.OnFormPostCreate();

            // After hunting we roll the dice on the party and player and skip a day.
            UserData.Game.TakeTurn(false);
        }

        /// <summary>
        ///     Fired when dialog prompt is attached to active game Windows and would like to have a string returned.
        /// </summary>
        /// <returns>
        ///     The dialog prompt text.<see cref="string" />.
        /// </returns>
        protected override string OnDialogPrompt()
        {
            // Clear previous hunting score information.
            _huntScore.Clear();

            // Calculate total weight of all animals killed by player during hunt.
            var killWeight = UserData.Hunt.KillWeight;

            // Depending on kill weight we change response and message.
            if (killWeight <= 0)
            {
                _huntScore.AppendLine($"You were unable to shoot any food.{Environment.NewLine}");
            }
            else if (killWeight > 0)
            {
                // Message to let the player know they killed prey.
                _huntScore.AppendLine(
                    $"From the animals you shot, you got {killWeight.ToString("N0")} pounds of meat.");

                // Adds the killing weight since it is safe at this point.
                _finalKillWeight = killWeight;

                // Player can only take MAXFOOD amount from hunt regardless of total weight.
                if (killWeight <= HuntManager.MaxFood)
                    return _huntScore.ToString();

                // Forces the weight of the kill to become
                _finalKillWeight = HuntManager.MaxFood;

                // Player killed to many animals.
                _huntScore.Append(
                    $" However, you were only able to carry {_finalKillWeight.ToString("N0")} pounds back to the wagon.");
            }

            // Return the hunting result to text renderer.
            return _huntScore.ToString();
        }

        /// <summary>
        ///     Fired when the dialog receives favorable input and determines a response based on this. From this method it is
        ///     common to attach another state, or remove the current state based on the response.
        /// </summary>
        /// <param name="reponse">The response the dialog parsed from simulation input buffer.</param>
        protected override void OnDialogResponse(DialogResponse reponse)
        {
            // Transfers the total finalized kill weight we calculated to vehicle inventory as food in pounds.
            if (_finalKillWeight > 0)
                UserData.Game.Vehicle.Inventory[Entities.Food].AddQuantity(_finalKillWeight);

            // Destroys all hunting related data now that we are done with it.
            UserData.DestroyHunt();

            // Returns to the travel menu so the player can continue down the trail.
            ClearForm();
        }
    }
}


text:
#include "mtom_callback.h"
#include <axiom.h>
#include <stdio.h>
#include <axis2_op_ctx.h>
#include <axiom_soap_envelope.h>
#include <axiom_soap_body.h>
#include <axis2_const.h>
#include <axutil_param.h>

axiom_node_t *build_response(
    const axutil_env_t *env,
    axiom_data_handler_t *data_handler);

axis2_status_t process_attachments(
    axis2_msg_ctx_t *msg_ctx,
    const axutil_env_t * env,
    void *user_param,
    axis2_char_t *callback_name);

axiom_node_t*
axis2_mtom_callback_mtom(
    const axutil_env_t * env,
    axiom_node_t * node,
    axis2_msg_ctx_t *msg_ctx)
{
    axiom_node_t *attachment_node = NULL;
    axiom_node_t *binary_node = NULL;
    axiom_node_t *ret_node = NULL;
    axis2_status_t status = AXIS2_FAILURE;
    void *user_param = NULL;
    axutil_param_t *callback_name_param = NULL;
    axis2_char_t *callback_name = NULL;

    AXIS2_ENV_CHECK(env, NULL);

    /* Expected request format is :-
     * <ns1:mtomSample xmlns:ns1="http://ws.apache.org/axis2/c/samples">
     <ns1:attachment>
     <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" href="cid:1.dd5183d4-d58a-1da1-2578-001125b4c063@apache.org"></xop:Include>
     </ns1:attachment>
     </ns1:mtomSample>
     */
    if (!node)                  /* 'mtomSample' node */
    {
        AXIS2_ERROR_SET(env->error, AXIS2_ERROR_SVC_SKEL_INPUT_OM_NODE_NULL,
                        AXIS2_FAILURE);
        printf("Echo client ERROR: input parameter NULL\n");
        return NULL;
    }

    attachment_node = axiom_node_get_first_child(node, env);
    if (!attachment_node)        /* 'text' node */
    {
        AXIS2_ERROR_SET(env->error,
                        AXIS2_ERROR_SVC_SKEL_INVALID_XML_FORMAT_IN_REQUEST,
                        AXIS2_FAILURE);
        printf("Echo client ERROR: invalid XML in request\n");
        return NULL;
    }

    /* This is the paramter specified in the services.xml
     * or in axis2.xml
     */

    callback_name_param = axis2_msg_ctx_get_parameter (msg_ctx, env,
        AXIS2_MTOM_CACHING_CALLBACK);

    if(callback_name_param)
    {
        callback_name = (axis2_char_t *) axutil_param_get_value (callback_name_param, env);
    }

    /* This will process the attachment data in the stream */

    status = process_attachments(msg_ctx, env, user_param, callback_name);
    if(status == AXIS2_FAILURE)
    {
        return NULL;
    }

    binary_node = axiom_node_get_first_child(attachment_node, env);
    if (binary_node)
    {
        axiom_data_handler_t *data_handler = NULL;
        axiom_text_t *bin_text = NULL;
        axis2_char_t *attachment_id = NULL;
        axiom_data_handler_t *data_handler_res = NULL;
        axis2_char_t *location = NULL;

        bin_text = (axiom_text_t *)axiom_node_get_data_element(binary_node, env);
        if(bin_text)
        {
            data_handler = axiom_text_get_data_handler(bin_text, env);
            if(!data_handler)
            {
                return NULL;
            }
        }

        attachment_id = axiom_data_handler_get_mime_id(data_handler, env);

        if(!attachment_id)
        {
            return NULL;
        }

        /* This is the case where the attachment resides in memory */

        if (!axiom_data_handler_get_cached(data_handler, env))
        {
           /* axis2_byte_t *input_buff = NULL;
            axis2_byte_t *buff = NULL;
            int buff_len = 0;*/

            axiom_data_handler_set_file_name(data_handler, env, attachment_id);
            axiom_data_handler_write_to(data_handler, env);
            location = attachment_id;
        }

        else
        {
            axiom_data_handler_type_t data_handler_type;
            data_handler_type = axiom_data_handler_get_data_handler_type(data_handler, env);

            if(data_handler_type == AXIOM_DATA_HANDLER_TYPE_CALLBACK)
            {
                /* The service implementer should be aware of how to deal with the attachment
                 * Becasue it was stored using the callback he provided. */

                  /*axis2_char_t command[1000];

                  sprintf(command, "rm -f /opt/tmp/%s", attachment_id);
                  system(command);*/

                /*location = attachment_id;*/
                  /*location = "/home/manjula/axis2/mtom/resources/song.MP3"; */

                    location = "/opt/manjula-mtom.MPG";
            }
            else if(data_handler_type == AXIOM_DATA_HANDLER_TYPE_FILE)
            {
                axis2_char_t *file_name = NULL;

                file_name = axiom_data_handler_get_file_name(data_handler, env);
                if(file_name)
                {
                    location = axutil_strdup(env, file_name);
                }
            }
        }

        /* The samples sends back an attachment to the client. Hence we are creating the
         * response data_handler as a type CALLBACK. So the sender callback should be
         * specified either in the services.xml or in the axis2.xml.
         */

        data_handler_res = axiom_data_handler_create(env, NULL, NULL);
        axiom_data_handler_set_data_handler_type(data_handler_res, env, AXIOM_DATA_HANDLER_TYPE_CALLBACK);
        axiom_data_handler_set_user_param(data_handler_res, env, (void *)location);

        axis2_msg_ctx_set_doing_mtom (msg_ctx, env, AXIS2_TRUE);
        ret_node = build_response(env, data_handler_res);
    }
    else
    {
        AXIS2_ERROR_SET(env->error,
                        AXIS2_ERROR_SVC_SKEL_INVALID_XML_FORMAT_IN_REQUEST,
                        AXIS2_FAILURE);
        printf("Echo client ERROR: invalid XML in request\n");
        return NULL;
    }

    return ret_node;
}

/* Builds the response content */

axiom_node_t *build_response(
    const axutil_env_t *env,
    axiom_data_handler_t *data_handler)
{
    axiom_node_t *mtom_om_node = NULL;
    axiom_element_t *mtom_om_ele = NULL;
    axiom_node_t *text_node = NULL;
    axiom_namespace_t *ns1 = NULL;

    ns1 =
        axiom_namespace_create(env, "http://ws.apache.org/axis2/c/samples",
                               "ns1");
    mtom_om_ele =
        axiom_element_create(env, NULL, "response", ns1, &mtom_om_node);

    axiom_text_create_with_data_handler(env, mtom_om_node, data_handler,
        &text_node);

    return mtom_om_node;
}

axis2_status_t process_attachments(
    axis2_msg_ctx_t *msg_ctx,
    const axutil_env_t * env,
    void *user_param,
    axis2_char_t *callback_name)
{
    axis2_op_ctx_t *op_ctx = NULL;
    axis2_msg_ctx_t *in_msg_ctx = NULL;
    axiom_soap_envelope_t *soap_envelope = NULL;
    axiom_soap_body_t *soap_body = NULL;

    op_ctx = axis2_msg_ctx_get_op_ctx(msg_ctx, env);
    if(op_ctx)
    {
        in_msg_ctx = axis2_op_ctx_get_msg_ctx(op_ctx, env, AXIS2_WSDL_MESSAGE_LABEL_IN);
        if(in_msg_ctx)
        {
            soap_envelope = axis2_msg_ctx_get_soap_envelope(in_msg_ctx, env);
            if(soap_envelope)
            {
                soap_body = axiom_soap_envelope_get_body(soap_envelope, env);
                if(soap_body)
                {
                    return axiom_soap_body_process_attachments(soap_body, env, user_param, callback_name);
                }
                else
                {
                    return AXIS2_FAILURE;
                }
            }
            else
            {
                return AXIS2_FAILURE;
            }
        }
        else
        {
            return AXIS2_FAILURE;
        }
    }
    else
    {
        return AXIS2_FAILURE;
    }
}


text:
layout: post
title: "Curabitur Tortor"
date: 2014-05-09 15:15:20
categories:
  - sit amet
  - sed lacinia
---
Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.

Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna.


text:
sudo yum install openstack-neutron.noarch-2014.1.5 -y
sudo yum install openstack-neutron-bigswitch.noarch-2014.1.5 -y
sudo yum install openstack-neutron-brocade.noarch-2014.1.5 -y
sudo yum install openstack-neutron-cisco.noarch-2014.1.5 -y
sudo yum install openstack-neutron-hyperv.noarch-2014.1.5 -y
sudo yum install openstack-neutron-linuxbridge.noarch-2014.1.5 -y
sudo yum install openstack-neutron-mellanox.noarch-2014.1.5 -y
sudo yum install openstack-neutron-metaplugin.noarch-2014.1.5 -y
sudo yum install openstack-neutron-metering-agent.noarch-2014.1.5 -y
sudo yum install openstack-neutron-midonet.noarch-2014.1.5 -y
sudo yum install openstack-neutron-ml2.noarch-2014.1.5 -y
sudo yum install openstack-neutron-nec.noarch-2014.1.5 -y
sudo yum install openstack-neutron-nicira.noarch-2013.2.4 -y
sudo yum install openstack-neutron-openvswitch.noarch-2014.1.5 -y
sudo yum install openstack-neutron-plumgrid.noarch-2014.1.5 -y
sudo yum install openstack-neutron-ryu.noarch-2014.1.5 -y
sudo yum install openstack-neutron-vpn-agent.noarch-2014.1.5 -y
sudo yum install python-neutron.noarch-2014.1.5 -y


text:
**1. History of the project**

In the first version  it was planned to be with 3 fixed  task categories HTML, CSS and JavaScript,  had only 2 functionalities to create and delete tasks .

Second version(Current), it was no more focused on three  exact categories. The user  had the chance to create as many as he wants categories. For every element there was custom animation for creating or deleting. In this version everything  was static and the information was not saved on server.
Also when creating category there are few options to personalize the category:

* Add title
* Add title color
* Add category background
* Add  screen position - there are three screen positions(left, middle, right), this works only on devices with larger screens.

When Category is created  users can remove it or choose to create task.

* There are 3 tasks counters-  total tasks counts, tasks to finish, finished tasks.

Task options:

* Checked - for when its ready;
* Edit - separate box is created to edit the task;
* Remove - removing the task for the selected category

**2. Current version updates.**

 The functionality is the same, but preparations for non-static version alreay started. Now for every category is created new object Category, which is saved in array-  categories.

 22.1.2017 - Default buttons were changed with icons, added  navigation and about section, small changes on the  tasks design.

**3. Stuff to add.**

 Add more options like making task important, change font-size type...
 To add drag and drop functionality, to find host when everything can be saved to user profile;


text:
package org.apereo.cas.authentication.principal.provision;

import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.authentication.principal.PrincipalProvisioner;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.BooleanUtils;
import org.pac4j.core.client.BaseClient;
import org.pac4j.core.profile.UserProfile;

/**
 * This is {@link ScimDelegatedClientUserProfileProvisioner}.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@RequiredArgsConstructor
@Slf4j
public class ScimDelegatedClientUserProfileProvisioner extends BaseDelegatedClientUserProfileProvisioner {
    private final PrincipalProvisioner provisioner;

    @Override
    public void execute(final Principal principal, final UserProfile profile,
                        final BaseClient client, final Credential credential) {
        val result = provisioner.provision(principal, credential);
        LOGGER.info("Provisioned principal [{}] from external identity provider [{}]: [{}]",
            principal.getId(), profile.getClientName(),
            BooleanUtils.toString(result, "success", "failure"));
    }
}