text:
#include <gtk/gtk.h>
#include <stdio.h>

/* This is our data identification string to store
 * data in list items
 */
const gchar *list_item_data_key="list_item_data";

/* prototypes for signal handler that we are going to connect
 * to the List widget
 */
static void  sigh_print_selection( GtkWidget *gtklist,
                                   gpointer   func_data);

static void  sigh_button_event( GtkWidget      *gtklist,
                                GdkEventButton *event,
                                GtkWidget      *frame );

/* Main function to set up the user interface */

gint main( int    argc,
           gchar *argv[] )
{
    GtkWidget *separator;
    GtkWidget *window;
    GtkWidget *vbox;
    GtkWidget *scrolled_window;
    GtkWidget *frame;
    GtkWidget *gtklist;
    GtkWidget *button;
    GtkWidget *list_item;
    GList *dlist;
    guint i;
    gchar buffer[64];

    /* Initialize GTK (and subsequently GDK) */

    gtk_init (&argc, &argv);

    /* Create a window to put all the widgets in
     * connect gtk_main_quit() to the "destroy" event of
     * the window to handle window manager close-window-events
     */
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title (GTK_WINDOW (window), "GtkList Example");
    g_signal_connect (G_OBJECT (window), "destroy",
		      G_CALLBACK (gtk_main_quit),
		      NULL);

    /* Inside the window we need a box to arrange the widgets
     * vertically */
    vbox=gtk_vbox_new (FALSE, 5);
    gtk_container_set_border_width (GTK_CONTAINER (vbox), 5);
    gtk_container_add (GTK_CONTAINER (window), vbox);
    gtk_widget_show (vbox);

    /* This is the scrolled window to put the List widget inside */
    scrolled_window = gtk_scrolled_window_new (NULL, NULL);
    gtk_widget_set_size_request (scrolled_window, 250, 150);
    gtk_container_add (GTK_CONTAINER (vbox), scrolled_window);
    gtk_widget_show (scrolled_window);

    /* Create thekList widget.
     * Connect the sigh_print_selection() signal handler
     * function to the "selection_changed" signal of the List
     * to print out the selected items each time the selection
     * has changed */
    gtklist=gtk_list_new ();
    gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (scrolled_window),
                                           gtklist);
    gtk_widget_show (gtklist);
    g_signal_connect (G_OBJECT (gtklist), "selection_changed",
                      G_CALLBACK (sigh_print_selection),
                      NULL);

    /* We create a "Prison" to put a list item in ;) */
    frame=gtk_frame_new ("Prison");
    gtk_widget_set_size_request (frame, 200, 50);
    gtk_container_set_border_width (GTK_CONTAINER (frame), 5);
    gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_OUT);
    gtk_container_add (GTK_CONTAINER (vbox), frame);
    gtk_widget_show (frame);

    /* Connect the sigh_button_event() signal handler to the List
     * which will handle the "arresting" of list items
     */
    g_signal_connect (G_OBJECT (gtklist), "button_release_event",
                      G_CALLBACK (sigh_button_event),
                      frame);

    /* Create a separator */
    separator=gtk_hseparator_new ();
    gtk_container_add (GTK_CONTAINER (vbox), separator);
    gtk_widget_show (separator);

    /* Finally create a button and connect its "clicked" signal
     * to the destruction of the window */
    button=gtk_button_new_with_label ("Close");
    gtk_container_add (GTK_CONTAINER (vbox), button);
    gtk_widget_show (button);
    g_signal_connect_swapped (G_OBJECT (button), "clicked",
                              G_CALLBACK (gtk_widget_destroy),
                              window);

    /* Now we create 5 list items, each having its own
     * label and add them to the List using gtk_container_add()
     * Also we query the text string from the label and
     * associate it with the list_item_data_key for each list item
     */
    for (i = 0; i < 5; i++) {
	GtkWidget       *label;
	gchar           *string;

	sprintf(buffer, "ListItemContainer with Label #%d", i);
	label=gtk_label_new (buffer);
	list_item=gtk_list_item_new ();
	gtk_container_add (GTK_CONTAINER (list_item), label);
	gtk_widget_show (label);
	gtk_container_add (GTK_CONTAINER (gtklist), list_item);
	gtk_widget_show (list_item);
	gtk_label_get (GTK_LABEL (label), &string);
	g_object_set_data (G_OBJECT (list_item), list_item_data_key, string);
    }
    /* Here, we are creating another 5 labels, this time
     * we use gtk_list_item_new_with_label() for the creation
     * we can't query the text string from the label because
     * we don't have the labels pointer and therefore
     * we just associate the list_item_data_key of each
     * list item with the same text string.
     * For adding of the list items we put them all into a doubly
     * linked list (GList), and then add them by a single call to
     * gtk_list_append_items().
     * Because we use g_list_prepend() to put the items into the
     * doubly linked list, their order will be descending (instead
     * of ascending when using g_list_append())
     */
    dlist = NULL;
    for (; i < 10; i++) {
	sprintf(buffer, "List Item with Label %d", i);
	list_item = gtk_list_item_new_with_label (buffer);
	dlist = g_list_prepend (dlist, list_item);
	gtk_widget_show (list_item);
	g_object_set_data (G_OBJECT (list_item),
                           list_item_data_key,
                           "ListItem with integrated Label");
    }
    gtk_list_append_items (GTK_LIST (gtklist), dlist);

    /* Finally we want to see the window, don't we? ;) */
    gtk_widget_show (window);

    /* Fire up the main event loop of gtk */
    gtk_main ();

    /* We get here after gtk_main_quit() has been called which
     * happens if the main window gets destroyed
     */
    return 0;
}

/* This is the signal handler that got connected to button
 * press/release events of the List
 */
void sigh_button_event( GtkWidget      *gtklist,
                        GdkEventButton *event,
                        GtkWidget      *frame )
{
    /* We only do something if the third (rightmost mouse button
     * was released
     */
    if (event->type == GDK_BUTTON_RELEASE &&
	event->button == 3) {
	GList           *dlist, *free_list;
	GtkWidget       *new_prisoner;

	/* Fetch the currently selected list item which
	 * will be our next prisoner ;)
	 */
	dlist = GTK_LIST (gtklist)->selection;
	if (dlist)
		new_prisoner = GTK_WIDGET (dlist->data);
	else
		new_prisoner = NULL;

	/* Look for already imprisoned list items, we
	 * will put them back into the list.
	 * Remember to free the doubly linked list that
	 * gtk_container_children() returns
	 */
	dlist = gtk_container_children (GTK_CONTAINER (frame));
	free_list = dlist;
	while (dlist) {
	    GtkWidget       *list_item;

	    list_item = dlist->data;

	    gtk_widget_reparent (list_item, gtklist);

	    dlist = dlist->next;
	}
	g_list_free (free_list);

	/* If we have a new prisoner, remove him from the
	 * List and put him into the frame "Prison".
	 * We need to unselect the item first.
	 */
	if (new_prisoner) {
	    GList   static_dlist;

	    static_dlist.data = new_prisoner;
	    static_dlist.next = NULL;
	    static_dlist.prev = NULL;

	    gtk_list_unselect_child (GTK_LIST (gtklist),
				     new_prisoner);
	    gtk_widget_reparent (new_prisoner, frame);
	}
    }
}

/* This is the signal handler that gets called if List
 * emits the "selection_changed" signal
 */
void sigh_print_selection( GtkWidget *gtklist,
                           gpointer   func_data )
{
    GList   *dlist;

    /* Fetch the doubly linked list of selected items
     * of the List, remember to treat this as read-only!
     */
    dlist = GTK_LIST (gtklist)->selection;

    /* If there are no selected items there is nothing more
     * to do than just telling the user so
     */
    if (!dlist) {
	g_print ("Selection cleared\n");
	return;
    }
    /* Ok, we got a selection and so we print it
     */
    g_print ("The selection is a ");

    /* Get the list item from the doubly linked list
     * and then query the data associated with list_item_data_key.
     * We then just print it */
    while (dlist) {
	const gchar *item_data_string;

	item_data_string = g_object_get_data (G_OBJECT (dlist->data),
	 				      list_item_data_key);
	g_print("%s ", item_data_string);

	dlist = dlist->next;
    }
    g_print ("\n");
}


text:
#
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_SEQ_REPLACE_HPP
# define BOOST_PREPROCESSOR_SEQ_REPLACE_HPP
#
# include <boost/preprocessor/arithmetic/inc.hpp>
# include <boost/preprocessor/config/config.hpp>
# include <boost/preprocessor/seq/first_n.hpp>
# include <boost/preprocessor/seq/rest_n.hpp>
#
# /* BOOST_PP_SEQ_REPLACE */
#
# if ~BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_EDG()
#    define BOOST_PP_SEQ_REPLACE(seq, i, elem) BOOST_PP_SEQ_FIRST_N(i, seq) (elem) BOOST_PP_SEQ_REST_N(BOOST_PP_INC(i), seq)
# else
#    define BOOST_PP_SEQ_REPLACE(seq, i, elem) BOOST_PP_SEQ_REPLACE_I(seq, i, elem)
#    define BOOST_PP_SEQ_REPLACE_I(seq, i, elem) BOOST_PP_SEQ_FIRST_N(i, seq) (elem) BOOST_PP_SEQ_REST_N(BOOST_PP_INC(i), seq)
# endif
#
# endif

redpajama_set_name: RedPajamaGithub


text:
A **draft proposal** of a [PlayFab CloudScript](https://api.playfab.com/docs/tutorials/landing-automation/writing-custom-cloud-script) for [Photon Realtime's Unity Memory Demo](https://doc.photonengine.com/en-us/realtime/current/tutorials/memory-demo).

Notes:

- The script is not approved (yet) by Exit Games nor PlayFab.
- The script is not battle tested (yet). Use at your own risk.
- The script contains a workaround for logging from CloudScript handlers not executed by client (adding logs to TitleData).
The recommended (new) way is to use PlayStream events or an external logging service.
- I can't recommend enough [switching to TypeScript](https://blog.playfab.com/blog/typescript2) to avoid the CloudScript madness.

Links:

- [Uploading CloudScript](https://api.playfab.com/docs/tutorials/landing-automation/using-cloud-script)
- [Photon Realtime Webhooks](https://doc.photonengine.com/en-us/realtime/current/reference/webhooks).
- [Using Photon With PlayFab](https://api.playfab.com/docs/tutorials/landing-tournaments/using-photon-with-playfab)
- [Photon Forums Discussion](http://forum.photonengine.com/discussion/9615/working-memory-demo-with-playfab)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    JBoss, Home of Professional Open Source
    Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual
    contributors by the @authors tag. See the copyright.txt in the
    distribution for a full listing of individual contributors.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<assembly xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
              http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/assembly-1.1.1.xsd">
   <id>dist</id>
   <baseDirectory>wildfly-quickstarts-${project.version}</baseDirectory>
   <formats>
      <format>zip</format>
   </formats>

   <fileSets>
      <fileSet>
         <directory>${project.basedir}/..</directory>
         <outputDirectory>/</outputDirectory>
         <excludes>
            <exclude>dist/**</exclude>
            <exclude>template/**</exclude>
            <exclude>**/target/**</exclude>
            <exclude>**/.project</exclude>
            <exclude>**/.settings/**</exclude>
            <exclude>**/.classpath</exclude>
            <exclude>**/.gitignore</exclude>
         </excludes>
      </fileSet>
   </fileSets>

</assembly>


text:
package buildcraft.api.core.render;

import net.minecraft.util.IIcon;

public interface ITextureStateManager {
	void set(IIcon icon);
}


text:
from unittest import TestCase

from pyperiods.months import MonthPeriod
from pyperiods.period import InvalidPeriodError
from pyperiods.years import YearPeriod

def _serialize(period):
    from pyperiods.restframework.serializers import PeriodSerializer
    return PeriodSerializer().to_representation(period)

def _deserialize(obj):
    from pyperiods.restframework.serializers import PeriodSerializer
    return PeriodSerializer().to_internal_value(obj)

class TestPeriodSerializer(TestCase):

    @classmethod
    def setUpClass(cls):
        from django.conf import settings
        settings.configure()

    def test_deserialize_from_object(self):
        self.assertEqual(_deserialize({'year': 2012}), YearPeriod('2012'))
        self.assertEqual(_deserialize({'year': 2012, 'month': 2}), MonthPeriod('201202'))

    def test_deserialize_from_string(self):
        self.assertEqual(_deserialize('2013'), YearPeriod('2013'))
        self.assertEqual(_deserialize('201305'), MonthPeriod('201305'))

    def test_deserialize_from_empty_inputs(self):
        from rest_framework.exceptions import ValidationError

        self.assertRaises(ValidationError, _deserialize, {})

    def test_deserialize_from_invalid_input(self):
        self.assertRaises(InvalidPeriodError, _deserialize, 'abcdef')

    def test_serialize(self):
        self.assertEqual(_serialize(YearPeriod('2012')), {'year': 2012})
        self.assertEqual(_serialize(MonthPeriod('201202')), {'year': 2012, 'month': 2})

    def test_serialize_empty(self):
        self.assertEqual(_serialize(None), None)
        self.assertRaises(ValueError, _serialize, '')
        self.assertRaises(ValueError, _serialize, 201202)


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

using System;
using System.Threading;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
    /// <summary>
    /// An adapter between editor's <see cref="IUIThreadOperationScope"/> (which supports reporting
    /// progress) and <see cref="IProgressTracker"/>.
    /// </summary>
    internal class ProgressTrackerAdapter : IProgressTracker
    {
        private readonly IUIThreadOperationScope _uiThreadOperationScope;
        private int _completedItems;
        private int _totalItems;
        private string _description;

        public ProgressTrackerAdapter(IUIThreadOperationScope uiThreadOperationScope)
        {
            Requires.NotNull(uiThreadOperationScope, nameof(uiThreadOperationScope));
            _uiThreadOperationScope = uiThreadOperationScope;
        }

        public string Description
        {
            get => _description;
            set
            {
                _description = value;
                _uiThreadOperationScope.Description = value;
            }
        }

        public int CompletedItems => _completedItems;

        public int TotalItems => _totalItems;

        public void AddItems(int count)
        {
            Interlocked.Add(ref _totalItems, count);
            ReportProgress();
        }

        public void Clear()
        {
            Interlocked.Exchange(ref _completedItems, 0);
            Interlocked.Exchange(ref _totalItems, 0);
            ReportProgress();
        }

        public void ItemCompleted()
        {
            Interlocked.Increment(ref _completedItems);
            ReportProgress();
        }

        private void ReportProgress()
            => _uiThreadOperationScope.Progress.Report(new ProgressInfo(_completedItems, _totalItems));
    }
}


text:
<?php

namespace ZephirTestCase;

use Zephir\Commands\CommandBuild;
use Zephir\Commands\CommandFullClean;

/**
 * Zephir extension builder
 */
class ZephirExtensionBuilderFactory
{
    /**
     * Factory.
     *
     * @return \ZephirTestCase\ZephirExtensionBuilder
     */
    public static function getInstance()
    {
        return new ZephirExtensionBuilder(
            new ZephirClassInfo(),
            new FileWorker(),
            new CommandBuild(),
            new CommandFullClean()
        );
    }
}


text:
if (typeof(Address) === "undefined") {
    var Address = require("../../lib/Address.js");
}
if (typeof(AddressFmt) === "undefined") {
    var AddressFmt = require("../../lib/AddressFmt.js");
}

if (typeof(ilib) === "undefined") {
    var ilib = require("../../lib/ilib.js");
}

module.exports.testaddress_SV = {
    setUp: function(callback) {
        ilib.clearCache();
        callback();
    },

    testParseAddressSVNormal: function(test) {
        test.expect(7);
        var parsedAddress = new Address("Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29, CP 1120 - MEJICANOS, SAN SALVADOR, EL SALVADOR", {locale: 'es-SV'});

        test.ok(typeof(parsedAddress) !== "undefined");
        test.equal(parsedAddress.streetAddress, "Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29");
        test.equal(parsedAddress.region, "SAN SALVADOR");
        test.equal(parsedAddress.locality, "MEJICANOS");
        test.equal(parsedAddress.postalCode, "CP 1120");
        test.equal(parsedAddress.country, "EL SALVADOR");
        test.equal(parsedAddress.countryCode, "SV");
        test.done();
    },

    testParseAddressSVNoZip: function(test) {
        test.expect(7);
        var parsedAddress = new Address("Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29, MEJICANOS, SAN SALVADOR, EL SALVADOR", {locale: 'es-SV'});

        test.ok(typeof(parsedAddress) !== "undefined");
        test.equal(parsedAddress.streetAddress, "Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29");
        test.equal(parsedAddress.region, "SAN SALVADOR");
        test.equal(parsedAddress.locality, "MEJICANOS");
        test.equal(parsedAddress.country, "EL SALVADOR");
        test.equal(parsedAddress.countryCode, "SV");
        test.ok(typeof(parsedAddress.postalCode) === "undefined");
        test.done();
    },

    testParseAddressSVManyLines: function(test) {
        test.expect(7);
        var parsedAddress = new Address("Señora Rina Isabel Peña Borja\nColonia Universitaria Norte #2\nCalle Alcaine #29\nCP 1120 - MEJICANOS\nSAN SALVADOR\nEL SALVADOR", {locale: 'es-SV'});

        test.ok(typeof(parsedAddress) !== "undefined");
        test.equal(parsedAddress.streetAddress, "Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29");
        test.equal(parsedAddress.region, "SAN SALVADOR");
        test.equal(parsedAddress.locality, "MEJICANOS");
        test.equal(parsedAddress.postalCode, "CP 1120");
        test.equal(parsedAddress.country, "EL SALVADOR");
        test.equal(parsedAddress.countryCode, "SV");
        test.done();
    },

    testParseAddressSVOneLine: function(test) {
        test.expect(7);
        var parsedAddress = new Address("Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29, CP 1120 - MEJICANOS, SAN SALVADOR, EL SALVADOR", {locale: 'es-SV'});

        test.ok(typeof(parsedAddress) !== "undefined");
        test.equal(parsedAddress.streetAddress, "Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29");
        test.equal(parsedAddress.region, "SAN SALVADOR");
        test.equal(parsedAddress.locality, "MEJICANOS");
        test.equal(parsedAddress.postalCode, "CP 1120");
        test.equal(parsedAddress.country, "EL SALVADOR");
        test.equal(parsedAddress.countryCode, "SV");
        test.done();
    },

    testParseAddressSVSuperfluousWhitespace: function(test) {
        test.expect(7);
        var parsedAddress = new Address("Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29  \n\t\n CP 1120 - MEJICANOS, SAN SALVADOR\t\n\n EL SALVADOR  \n  \t\t\t", {locale: 'es-SV'});

        test.ok(typeof(parsedAddress) !== "undefined");
        test.equal(parsedAddress.streetAddress, "Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29");
        test.equal(parsedAddress.region, "SAN SALVADOR");
        test.equal(parsedAddress.locality, "MEJICANOS");
        test.equal(parsedAddress.postalCode, "CP 1120");
        test.equal(parsedAddress.country, "EL SALVADOR");
        test.equal(parsedAddress.countryCode, "SV");
        test.done();
    },

    testParseAddressSVNoDelimiters: function(test) {
        test.expect(7);
        var parsedAddress = new Address("Señora Rina Isabel Peña Borja Colonia Universitaria Norte #2 Calle Alcaine #29 CP 1120 - MEJICANOS SAN SALVADOR EL SALVADOR", {locale: 'es-SV'});

        test.ok(typeof(parsedAddress) !== "undefined");
        test.equal(parsedAddress.streetAddress, "Señora Rina Isabel Peña Borja Colonia Universitaria Norte #2 Calle Alcaine #29");
        test.equal(parsedAddress.region, "SAN SALVADOR");
        test.equal(parsedAddress.locality, "MEJICANOS");
        test.equal(parsedAddress.postalCode, "CP 1120");
        test.equal(parsedAddress.country, "EL SALVADOR");
        test.equal(parsedAddress.countryCode, "SV");
        test.done();
    },

    testParseAddressSVSpecialChars: function(test) {
        test.expect(7);
        var parsedAddress = new Address("Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29, CP 1120 - MEJICANOS, SAN SALVADOR, EL SALVADOR", {locale: 'es-SV'});

        test.ok(typeof(parsedAddress) !== "undefined");
        test.equal(parsedAddress.streetAddress, "Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29");
        test.equal(parsedAddress.region, "SAN SALVADOR");
        test.equal(parsedAddress.locality, "MEJICANOS");
        test.equal(parsedAddress.postalCode, "CP 1120");
        test.equal(parsedAddress.country, "EL SALVADOR");
        test.equal(parsedAddress.countryCode, "SV");
        test.done();
    },

    testParseAddressSVFromUS: function(test) {
        test.expect(7);
        var parsedAddress = new Address("Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29, CP 1120 - MEJICANOS, SAN SALVADOR, EL SALVADOR", {locale: 'en-US'});

        // the country name is in English because this address is for a contact in a US database

        test.ok(typeof(parsedAddress) !== "undefined");
        test.equal(parsedAddress.streetAddress, "Señora Rina Isabel Peña Borja, Colonia Universitaria Norte #2, Calle Alcaine #29");
        test.equal(parsedAddress.region, "SAN SALVADOR");
        test.equal(parsedAddress.locality, "MEJICANOS");
        test.equal(parsedAddress.postalCode, "CP 1120");
        test.equal(parsedAddress.country, "EL SALVADOR");
        test.equal(parsedAddress.countryCode, "SV");
        test.done();
    },

    testFormatAddressSV: function(test) {
        test.expect(1);
            var parsedAddress = new Address({
            streetAddress: "Señora Rina Isabel Peña Borja\nColonia Universitaria Norte #2\nCalle Alcaine #29",
            region: "SAN SALVADOR",
            locality: "MEJICANOS",
            postalCode: "CP 1120",
            country: "EL SALVADOR",
            countryCode: "SV"
        }, {locale: 'es-SV'});

        var expected = "Señora Rina Isabel Peña Borja\nColonia Universitaria Norte #2\nCalle Alcaine #29\nCP 1120 - MEJICANOS\nSAN SALVADOR\nEL SALVADOR";
        var formatter = new AddressFmt({locale: 'es-SV'});
        test.equal(formatter.format(parsedAddress), expected);
        test.done();
    },

    testFormatAddressSVFromUS: function(test) {
        test.expect(1);
            var parsedAddress = new Address({
            streetAddress: "Señora Rina Isabel Peña Borja\nColonia Universitaria Norte #2\nCalle Alcaine #29",
            region: "SAN SALVADOR",
            locality: "MEJICANOS",
            postalCode: "CP 1120",
            country: "EL SALVADOR",
            countryCode: "SV"
        }, {locale: 'es-SV'});

        var expected = "Señora Rina Isabel Peña Borja\nColonia Universitaria Norte #2\nCalle Alcaine #29\nCP 1120 - MEJICANOS\nSAN SALVADOR\nEL SALVADOR";
        var formatter = new AddressFmt({locale: 'es-SV'});
        test.equal(formatter.format(parsedAddress), expected);
        test.done();
    }

};


text:
"""
The MIT License (MIT)

Copyright (c) 2017 LeanIX GmbH

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
"""
class Service:
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """

    def __init__(self):
        self.swaggerTypes = {
            'ID': 'str',
            'displayName': 'str',
            'parentID': 'str',
            'level': 'long',
            'release': 'str',
            'name': 'str',
            'reference': 'str',
            'alias': 'str',
            'description': 'str',
            'businessCriticalityID': 'str',
            'businessCriticalityDescription': 'str',
            'functionalSuitabilityID': 'str',
            'functionalSuitabilityDescription': 'str',
            'technicalSuitabilityID': 'str',
            'technicalSuitabilityDescription': 'str',
            'objectStatusID': 'str',
            'tags': 'list[str]',
            'fullName': 'str',
            'resourceType': 'str',
            'completion': 'str',
            'qualitySealExpiry': 'str',
            'modificationTime': 'str',
            'factSheetHasParents': 'list[FactSheetHasParent]',
            'factSheetHasChildren': 'list[FactSheetHasChild]',
            'factSheetHasDocuments': 'list[FactSheetHasDocument]',
            'factSheetHasLifecycles': 'list[FactSheetHasLifecycle]',
            'userSubscriptions': 'list[UserSubscription]',
            'factSheetHasPredecessors': 'list[FactSheetHasPredecessor]',
            'factSheetHasSuccessors': 'list[FactSheetHasSuccessor]',
            'factSheetHasRequires': 'list[FactSheetHasRequires]',
            'factSheetHasRequiredby': 'list[FactSheetHasRequiredby]',
            'serviceHasBusinessCapabilities': 'list[ServiceHasBusinessCapability]',
            'serviceHasProcesses': 'list[ServiceHasProcess]',
            'serviceHasConsumers': 'list[ServiceHasConsumer]',
            'serviceHasBusinessObjects': 'list[ServiceHasBusinessObject]',
            'serviceHasInterfaces': 'list[ServiceHasInterface]',
            'serviceHasProjects': 'list[ServiceHasProject]',
            'serviceHasResources': 'list[ServiceHasResource]',
            'factSheetHasIfaceProviders': 'list[FactSheetHasIfaceProvider]',
            'factSheetHasIfaceConsumers': 'list[FactSheetHasIfaceConsumer]'

        }
        self.ID = None # str
        self.displayName = None # str
        self.parentID = None # str
        self.level = None # long
        self.release = None # str
        self.name = None # str
        self.reference = None # str
        self.alias = None # str
        self.description = None # str
        self.businessCriticalityID = None # str
        self.businessCriticalityDescription = None # str
        self.functionalSuitabilityID = None # str
        self.functionalSuitabilityDescription = None # str
        self.technicalSuitabilityID = None # str
        self.technicalSuitabilityDescription = None # str
        self.objectStatusID = None # str
        self.tags = None # list[str]
        self.fullName = None # str
        self.resourceType = None # str
        self.completion = None # str
        self.qualitySealExpiry = None # str
        self.modificationTime = None # str
        self.factSheetHasParents = None # list[FactSheetHasParent]
        self.factSheetHasChildren = None # list[FactSheetHasChild]
        self.factSheetHasDocuments = None # list[FactSheetHasDocument]
        self.factSheetHasLifecycles = None # list[FactSheetHasLifecycle]
        self.userSubscriptions = None # list[UserSubscription]
        self.factSheetHasPredecessors = None # list[FactSheetHasPredecessor]
        self.factSheetHasSuccessors = None # list[FactSheetHasSuccessor]
        self.factSheetHasRequires = None # list[FactSheetHasRequires]
        self.factSheetHasRequiredby = None # list[FactSheetHasRequiredby]
        self.serviceHasBusinessCapabilities = None # list[ServiceHasBusinessCapability]
        self.serviceHasProcesses = None # list[ServiceHasProcess]
        self.serviceHasConsumers = None # list[ServiceHasConsumer]
        self.serviceHasBusinessObjects = None # list[ServiceHasBusinessObject]
        self.serviceHasInterfaces = None # list[ServiceHasInterface]
        self.serviceHasProjects = None # list[ServiceHasProject]
        self.serviceHasResources = None # list[ServiceHasResource]
        self.factSheetHasIfaceProviders = None # list[FactSheetHasIfaceProvider]
        self.factSheetHasIfaceConsumers = None # list[FactSheetHasIfaceConsumer]


text:
using System;
using Server.Network;
using Server.Items;

namespace Server.Items
{
	[FlipableAttribute( 0xF50, 0xF4F )]
	public class Crossbow : BaseRanged
	{
		public override int EffectID{ get{ return 0x1BFE; } }
		public override Type AmmoType{ get{ return typeof( Bolt ); } }
		public override Item Ammo{ get{ return new Bolt(); } }

		public override WeaponAbility PrimaryAbility{ get{ return WeaponAbility.ConcussionBlow; } }
		public override WeaponAbility SecondaryAbility{ get{ return WeaponAbility.MortalStrike; } }

		public override int AosStrengthReq{ get{ return 35; } }
		public override int AosMinDamage{ get{ return 18; } }
		public override int AosMaxDamage{ get{ return Core.ML ? 22 : 20; } }
		public override int AosSpeed{ get{ return 24; } }
		public override float MlSpeed{ get{ return 4.50f; } }

		public override int OldStrengthReq{ get{ return 30; } }
		public override int OldMinDamage{ get{ return 8; } }
		public override int OldMaxDamage{ get{ return 43; } }
		public override int OldSpeed{ get{ return 18; } }

		public override int DefMaxRange{ get{ return 8; } }

		public override int InitMinHits{ get{ return 31; } }
		public override int InitMaxHits{ get{ return 80; } }

		[Constructable]
		public Crossbow() : base( 0xF50 )
		{
			Weight = 7.0;
			Layer = Layer.TwoHanded;
		}

		public Crossbow( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();
		}
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Soc. mycol. Fr. 24: 5 (1908)

#### Original name
null

### Remarks
null


text:
package O2::Template::Critic::Policy::RequireQuotedAttributeValues;

use strict;
use Readonly;

use base 'O2::Template::Critic::Policy';

Readonly::Scalar my $DESC => 'Missing double or single quote around attribute value';
Readonly::Scalar my $EXPL => 'Missing double or single quote around attribute value';

#-----------------------------------------------------------------------------
sub new {
  my ($package, %config) = @_;
  my $obj = bless {}, $package;
  return $obj;
}
#-----------------------------------------------------------------------------
sub getSupportedParameters {
  return ();
}
#-----------------------------------------------------------------------------
sub getDefaultSeverity {
  return 2;
}
#-----------------------------------------------------------------------------
sub appliesTo {
  return qw( Node::AttributeValue );
}
#-----------------------------------------------------------------------------
sub violates {
  my ($obj, $element, $root) = @_;
  my $previousSibling = $element->getPreviousSibling();
  my $firstCharacter = substr($element->getValue(), 0, 1);
  if ($firstCharacter ne '"' && $firstCharacter ne "'" && $previousSibling && $previousSibling->getValue() eq '=') {
    return $obj->violation($DESC, $EXPL, $element);
  }
  return;
}
#-----------------------------------------------------------------------------
1;


text:
namespace base {

// Tests that running the bound callback invalidates the handle.
TEST(DefaultDelayedTaskHandleDelegateTest, RunTask) {
  auto delegate = std::make_unique<DefaultDelayedTaskHandleDelegate>();
  EXPECT_FALSE(delegate->IsValid());

  auto bound_callback = delegate->BindCallback(DoNothing());
  EXPECT_TRUE(delegate->IsValid());

  DelayedTaskHandle delayed_task_handle(std::move(delegate));
  EXPECT_TRUE(delayed_task_handle.IsValid());

  std::move(bound_callback).Run();
  EXPECT_FALSE(delayed_task_handle.IsValid());
}

// Tests that DefaultDelayedTaskHandleDelegate supports CancelTask().
TEST(DefaultDelayedTaskHandleDelegateTest, CancelTask) {
  auto delegate = std::make_unique<DefaultDelayedTaskHandleDelegate>();
  EXPECT_FALSE(delegate->IsValid());

  auto bound_callback = delegate->BindCallback(DoNothing());
  EXPECT_TRUE(delegate->IsValid());

  DelayedTaskHandle delayed_task_handle(std::move(delegate));
  EXPECT_TRUE(delayed_task_handle.IsValid());

  delayed_task_handle.CancelTask();
  EXPECT_FALSE(delayed_task_handle.IsValid());
  EXPECT_TRUE(bound_callback.IsCancelled());
}

// Tests that destroying the bound callback invalidates the handle.
TEST(DefaultDelayedTaskHandleDelegateTest, DestroyTask) {
  auto delegate = std::make_unique<DefaultDelayedTaskHandleDelegate>();
  EXPECT_FALSE(delegate->IsValid());

  auto bound_callback = delegate->BindCallback(DoNothing());
  EXPECT_TRUE(delegate->IsValid());

  DelayedTaskHandle delayed_task_handle(std::move(delegate));
  EXPECT_TRUE(delayed_task_handle.IsValid());

  bound_callback = OnceClosure();
  EXPECT_FALSE(delayed_task_handle.IsValid());
}

// Tests that the handle is invalid while the task is running.
TEST(DefaultDelayedTaskHandleDelegateTest, HandleInvalidInsideCallback) {
  auto delegate = std::make_unique<DefaultDelayedTaskHandleDelegate>();
  EXPECT_FALSE(delegate->IsValid());

  auto bound_callback = delegate->BindCallback(
      BindLambdaForTesting([delegate = delegate.get()]() {
        // Check that the delegate is invalid inside the callback.
        EXPECT_FALSE(delegate->IsValid());
      }));
  EXPECT_TRUE(delegate->IsValid());

  DelayedTaskHandle delayed_task_handle(std::move(delegate));
  EXPECT_TRUE(delayed_task_handle.IsValid());

  std::move(bound_callback).Run();
  EXPECT_FALSE(delayed_task_handle.IsValid());
}

}  // namespace base


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Scient. Surv. P. Rico 8(1): 147 (1926)

#### Original name
Tremella indurata Overh.

### Remarks
null


text:
import macro from 'vtk.js/Sources/macros';

const { vtkErrorMacro } = macro;

// ----------------------------------------------------------------------------
// Proxy Registration Handling
// ----------------------------------------------------------------------------

export default function addRegistrationAPI(publicAPI, model) {
  function registerProxy(proxy) {
    if (!proxy) {
      return;
    }
    model.proxyIdMapping[proxy.getProxyId()] = proxy;
    const group = proxy.getProxyGroup();
    if (!model.proxyByGroup[group]) {
      model.proxyByGroup[group] = [];
    }
    if (model.proxyByGroup[group].indexOf(proxy) === -1) {
      model.proxyByGroup[group].push(proxy);
    }
    proxy.setProxyManager(publicAPI);

    // Make sure we invoke event after the current execution path
    macro.setImmediate(() => {
      publicAPI.invokeProxyRegistrationChange({
        action: 'register',
        proxyId: proxy.getProxyId(),
        proxyName: proxy.getProxyName(),
        proxyGroup: proxy.getProxyGroup(),
        proxy,
      });
    });
  }

  // --------------------------------------------------------------------------

  function unRegisterProxy(proxyOrId) {
    const id = proxyOrId.getProxyId ? proxyOrId.getProxyId() : proxyOrId;
    const proxy = model.proxyIdMapping[id];

    // Unregister proxy in any group
    Object.keys(model.proxyByGroup).forEach((groupName) => {
      const proxyList = model.proxyByGroup[groupName];
      const index = proxyList.indexOf(proxy);
      if (index !== -1) {
        proxyList.splice(index, 1);
      }
    });

    delete model.proxyIdMapping[id];
    proxy.gcPropertyLinks('application');
    proxy.gcPropertyLinks('source');
    proxy.setProxyManager(null);
    publicAPI.invokeProxyRegistrationChange({
      action: 'unregister',
      proxyId: id,
      proxyName: proxy.getProxyName(),
      proxyGroup: proxy.getProxyGroup(),
      proxy,
    });
    return proxy;
  }

  // --------------------------------------------------------------------------

  publicAPI.setActiveSource = (source) => {
    if (model.activeSource !== source) {
      if (model.activeSourceSubscription) {
        model.activeSourceSubscription.unsubscribe();
        model.activeSourceSubscription = null;
      }
      model.activeSource = source;
      if (source) {
        model.activeSourceSubscription = source.onModified(publicAPI.modified);
      }
      publicAPI.modified();
      publicAPI.invokeActiveSourceChange(source);
    }
  };

  publicAPI.setActiveView = (view) => {
    if (model.activeView !== view) {
      if (model.activeViewSubscription) {
        model.activeViewSubscription.unsubscribe();
        model.activeViewSubscription = null;
      }
      model.activeView = view;
      if (view) {
        model.activeViewSubscription = view.onModified(publicAPI.modified);
      }
      publicAPI.modified();
      publicAPI.invokeActiveViewChange(view);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.getProxyById = (id) => model.proxyIdMapping[id];

  // --------------------------------------------------------------------------

  publicAPI.getProxyGroups = () => Object.keys(model.proxyByGroup);

  // --------------------------------------------------------------------------

  publicAPI.getProxyInGroup = (name) =>
    [].concat(model.proxyByGroup[name] || []);

  // --------------------------------------------------------------------------

  publicAPI.getSources = () => [].concat(model.proxyByGroup.Sources || []);
  publicAPI.getRepresentations = () =>
    [].concat(model.proxyByGroup.Representations || []);
  publicAPI.getViews = () => [].concat(model.proxyByGroup.Views || []);

  // --------------------------------------------------------------------------

  publicAPI.createProxy = (group, name, options) => {
    const { definitions } = model.proxyConfiguration;
    if (!definitions[group] || !definitions[group][name]) {
      return null;
    }
    const definition = definitions[group][name];
    const definitionOptions = { ...definition.options, ...options };
    const proxy = definition.class.newInstance({
      ...definitionOptions,
      proxyGroup: group,
      proxyName: name,
      proxyManager: publicAPI,
    });

    // Handle proxy property settings
    if (definition.proxyProps) {
      const proxyMap = {};
      Object.keys(definition.proxyProps).forEach((key) => {
        const newProxyDef = definition.proxyProps[key];
        proxyMap[key] = publicAPI.createProxy(
          newProxyDef.group,
          newProxyDef.name,
          newProxyDef.options
        );
      });
      proxy.set(proxyMap);
    }

    // Handle property setting
    if (definition.props) {
      proxy.set(definition.props);
    }

    registerProxy(proxy);

    if (definitionOptions.activateOnCreate) {
      proxy.activate();
    }

    return proxy;
  };

  // --------------------------------------------------------------------------

  publicAPI.getRepresentation = (source, view) => {
    const sourceToUse = source || publicAPI.getActiveSource();
    const viewToUse = view || publicAPI.getActiveView();

    // Can only get a representation for a source and a view
    if (!sourceToUse || !viewToUse || !sourceToUse.getType()) {
      return null;
    }

    const sourceId = sourceToUse.getProxyId();
    const viewId = viewToUse.getProxyId();

    let viewRepMap = model.sv2rMapping[sourceId];
    if (!viewRepMap) {
      viewRepMap = {};
      model.sv2rMapping[sourceId] = viewRepMap;
    }
    let rep = viewRepMap[viewId];
    if (!rep) {
      const viewName = viewToUse.getProxyName();
      const sourceType = sourceToUse.getType();
      const definition =
        model.proxyConfiguration.representations[viewName][sourceType];
      if (!definition) {
        vtkErrorMacro(
          `No definition for representation of ${sourceType} in view ${viewName}`
        );
        return null;
      }
      rep = publicAPI.createProxy(
        'Representations',
        definition.name,
        definition.options
      );

      model.r2svMapping[rep.getProxyId()] = { sourceId, viewId };
      viewRepMap[viewId] = rep;

      rep.setInput(sourceToUse);
      viewToUse.addRepresentation(rep);
    }
    return rep;
  };

  // --------------------------------------------------------------------------

  publicAPI.deleteProxy = (proxy) => {
    const group = proxy.getProxyGroup().toLowerCase();

    if (group === 'views') {
      proxy.getRepresentations().forEach((repProxy) => {
        publicAPI.deleteProxy(repProxy);
      });
      proxy.setContainer(null);
      unRegisterProxy(proxy);
      if (publicAPI.getActiveView() === proxy) {
        publicAPI.setActiveView(publicAPI.getViews()[0]);
      }
    } else if (group === 'representations') {
      const { sourceId, viewId } = model.r2svMapping[proxy.getProxyId()];
      const view = publicAPI.getProxyById(viewId);
      view.removeRepresentation(proxy);
      delete model.r2svMapping[proxy.getProxyId()];
      delete model.sv2rMapping[sourceId][viewId];
      unRegisterProxy(proxy);
    } else if (group === 'sources') {
      const viewToRep = model.sv2rMapping[proxy.getProxyId()];
      Object.keys(viewToRep).forEach((viewId) => {
        publicAPI.deleteProxy(viewToRep[viewId]);
      });
      unRegisterProxy(proxy);
      if (publicAPI.getActiveSource() === proxy) {
        publicAPI.setActiveSource(publicAPI.getSources()[0]);
      }
    } else {
      unRegisterProxy(proxy);
    }

    // Delete the object itself
    proxy.delete();
  };
}


text:
typedef void				( *GDI_RetVoidParamLPVOID )				( LPVOID );
typedef void				( *GDI_RetVoidParamLPVOIDDWORD )		( LPVOID, DWORD );
typedef void				( *GDI_RetVoidParamLPVOID2 )			( LPVOID, LPVOID );
typedef void				( *GDI_RetVoidParamVoidPFN )			( void );
typedef void				( *GDI_RetVoidParamLPSTR2 )				( LPSTR, LPSTR );
typedef DWORD				( *GDI_RetDWORDParamDWORDHINSTLPPFN )	( DWORD, HINSTANCE );
typedef DWORD				( *GDI_RetDWORDParamDWORD3HINSTLPPFN )	( DWORD, DWORD, DWORD, HINSTANCE );
typedef DWORD				( *GDI_RetDWORDParamDWORD4HINSTLPPFN )	( DWORD, DWORD, DWORD, DWORD, HINSTANCE );
typedef DWORD				( *GDI_RetDWORDParamDWORD4HINSTLPSTRPFN )	( DWORD, DWORD, DWORD, DWORD, HINSTANCE, LPSTR );
typedef DWORD				( *GDI_RetDWORDParamPASSDLLS )			( HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE, HINSTANCE );
typedef DWORD				( *GDI_RetDWORDParamVoidPFN )			( void );
typedef DWORD				( *GDI_RetDWORDParamDWORDPFN )			( DWORD );
typedef void				( *GDI_RetVoidParamDWORDPTRPFN )		( DWORD* );
typedef int					( *GDI_RetIntParamVoidPFN )				( void );

// DLL Function Typdefs
typedef void				( *DLL_Constructor )					( void );
typedef void				( *DLL_Destructor )						( void );
typedef void 				( *DLL_PassCore )						( LPVOID );
typedef void				( *DLL_SetErrorHandle )					( LPVOID );
typedef void				( *DLL_OptionalSecurityCode )			( int );
typedef void				( *DLL_Update )							( void );

// Image Function Typdefs
typedef void				( *IMAGE_RetVoidParamVoidPFN )      ( void );
typedef void				( *IMAGE_RetVoidParamHINSTANCEPFN ) ( HINSTANCE );

// Image Function Pointers
extern IMAGE_RetVoidParamVoidPFN			g_Image_Constructor;				// constructor
extern IMAGE_RetVoidParamVoidPFN			g_Image_Destructor;					// destructor

// Transforms Function Pointers
extern DLL_Constructor						g_Transforms_Constructor;
extern DLL_Destructor						g_Transforms_Destructor;
extern DLL_Update							g_Transforms_Update;

// Sprite Function Typdefs
typedef void				( *SPRITES_RetVoidParamVoidPFN )      ( void );
typedef void                ( *SPRITES_RetVoidParamHINSTANCE2PFN )  ( HINSTANCE, HINSTANCE );

// Sprite Function Pointers
extern SPRITES_RetVoidParamHINSTANCE2PFN	g_Sprites_Constructor;
extern SPRITES_RetVoidParamVoidPFN			g_Sprites_Destructor;
extern SPRITES_RetVoidParamVoidPFN			g_Sprites_Update;

// EXEBlock Class Defenition
class CEXEBlock
{
	public:
		CEXEBlock();
		virtual ~CEXEBlock();

		void			Clear(void);
		bool			StartInfo(LPSTR pUnpackFolderName, DWORD dwEncryptionKey);
		bool			Load(char* filename);
		bool			LoadValue(HANDLE hFile, DWORD* Value);
		bool			LoadBlock(HANDLE hFile, LPSTR* pMem, DWORD dwSize);
		bool			LoadValueArray(HANDLE hFile, DWORD** pArray, DWORD* Count);
		bool			LoadValueArrayBytes(HANDLE hFile, DWORD** pArray, DWORD* Count, DWORD dwType);
		bool			LoadValueArrayBytes(HANDLE hFile, DWORD** pArray, DWORD* Count);
		bool			LoadStringArray(HANDLE hFile, DWORD** pArray, DWORD* Count);
		bool			Save(char* filename);
		bool			SaveValue(HANDLE hFile, DWORD* Value);
		bool			SaveBlock(HANDLE hFile, LPSTR* pMem, DWORD dwSize);
		bool			SaveValueArray(HANDLE hFile, DWORD** pArray, DWORD* Count);
		bool			SaveValueArrayBytes(HANDLE hFile, DWORD** pArray, DWORD* Count);
		bool			SaveStringArray(HANDLE hFile, DWORD** pArray, DWORD* Count);
		DWORD*			CreateArray(DWORD dwCount,DWORD dwType);
		DWORD*			CreateArray(DWORD dwCount);
		bool			RecreateArray(DWORD** pArray, DWORD dwCount, DWORD NewCount);
		void			DeleteArrayContents(DWORD* pArray, DWORD dwCount);
		bool			FileExists(LPSTR pFilename);

		bool			CheckIfGotLatestDirectX ( bool bSilent );
		bool			Init(HINSTANCE hInstance, bool bResult, LPSTR* pReturnError, LPSTR pCmdLine);
		bool			InitDebug(HINSTANCE hInstance, LPVOID pDHookA, LPVOID pDHookB, LPVOID pDHookC, bool bResult, LPSTR* pReturnError, LPSTR pCmdLine, bool bMiniInit);
		bool			InitMini(LPVOID pDHookS, LPVOID pDHookJ, LPVOID pDHookR, bool bResult, LPSTR* pReturnError);
		bool			Run(bool bResult);
		bool			RunFrom(bool bResult, DWORD dwOffset);
		void			Free(void);
		void			FreeUptoDisplay(void);

	public:

		// General Flags
		bool			m_bEXEBlockPresent;

		// Executable Settings
		DWORD			m_dwInitialDisplayMode;
		DWORD			m_dwInitialDisplayWidth;
		DWORD			m_dwInitialDisplayHeight;
		DWORD			m_dwInitialDisplayDepth;
		LPSTR			m_pInitialAppName;
		LPSTR			m_pOriginalFolderName;
		LPSTR			m_pUnpackFolderName;
		LPSTR			m_pAbsoluteAppFile;
		DWORD			m_dwEncryptionKey;

		// DLL Data
		DWORD			m_dwNumberOfDLLs;
		DWORD*			m_pDLLIndexArray;
		DWORD*			m_pDLLFilenameArray;
		DWORD*			m_pDLLLoadedAlreadyArray;

		// MCB Reference Data
		DWORD			m_dwNumberOfReferences;
		DWORD*			m_pRefArray;
		DWORD*			m_pRefTypeArray;
		DWORD*			m_pRefIndexArray;

		// Runtime Error and Escape Value DWORDs
		DWORD			m_dwRuntimeErrorDWORD;
		DWORD			m_dwRuntimeErrorLineDWORD;
		DWORD			m_dwEscapeValueDWORD;

		// Runtime Error String Database
		DWORD			m_dwNumberOfRuntimeErrorStrings;
		DWORD*			m_pRuntimeErrorStringsArray;

		// Machine Code Block (MCB)
		DWORD			m_dwSizeOfMCB;
		DWORD*			m_pMachineCodeBlock;
		DWORD			m_dwStartOfMiniMC;

		// Commands Data
		DWORD			m_dwNumberOfCommands;
		DWORD*			m_pCommandDLLIdArray;
		DWORD*			m_pCommandDLLCallArray;

		// Strings Data
		DWORD			m_dwNumberOfStrings;
		DWORD*			m_pStringsArray;

		// Data Statements Data
		DWORD			m_dwNumberOfDataItems;
		LPSTR			m_pDataArray;
		DWORD*			m_pDataStringsArray;

		// Variable Space Data
		DWORD			m_dwOldVariableSpaceSize;
		DWORD			m_dwVariableSpaceSize;
		LPSTR			m_pVariableSpace;

		// Datat Statement Space Data
		DWORD			m_dwOldDataSpaceSize;
		DWORD			m_dwDataSpaceSize;
		LPSTR			m_pDataSpace;

		// Dynamic Variable Offset Array (points into VarSpace)
		DWORD			m_dwDynamicVarsQuantity;
		DWORD*			m_pDynamicVarsArray;
		DWORD*			m_pDynamicVarsArrayType;

		// New U71 - stores structure patterns
		DWORD			m_dwUsertypeStringPatternQuantity;
		LPSTR			m_pUsertypeStringPatternArray;
};


text:
'''OpenGL extension APPLE.vertex_array_range

This module customises the behaviour of the
OpenGL.raw.GL.APPLE.vertex_array_range to provide a more
Python-friendly API

Overview (from the spec)

	This extension is designed to allow very high vertex processing rates which
	are facilitated both by relieving the CPU of as much processing burden as
	possible and by allowing graphics hardware to directly access vertex data.
	Because this extension is implemented as an addition to the vertex array
	specification provided by OpenGL 1.1, applications can continue to use
	existing vertex submission logic while taking advantage of vertex array
	ranges to more efficiently process those arrays.

	The vertex array coherency model provided by OpenGL 1.1 requires that
	vertex data specified in vertex arrays be transferred from system memory
	each time Begin, DrawArrays, or DrawElements is called.  Further, OpenGL
	1.1 requires that the transfer of data be completed by the time End,
	DrawArrays, or DrawElements returns.  Both of these requirements are
	relaxed by the vertex array range extension.  Vertex data may be cached
	by the GL so there is no guarantee that changes to the vertex data will
	be reflected in following drawing commands unless it is flushed with
	FlushVertexArrayRangeAPPLE.  The reading of vertex data may be deferred
	by the GL so there is no guarantee that the GL will be finished reading
	the data until completion is forced by the use of Finish or the APPLE_fence
	extension.

	EnableClientState must be used with the VERTEX_ARRAY_RANGE_APPLE param to
	enable vertex array range.  Once this is done use of vertex array range
	requires the definition of a specific memory range for vertex data through
	VertexArrayRangeAPPLE.  It is recommended this data be page aligned (4096
	byte boundaries) and a multiple of page size in length for maximum
	efficiency in data handling and internal flushing, but this is not a
	requirement and any location and length of data can be defined as a vertex
	array.  This extension provides no memory allocators as any convenient
	memory allocator can be used.

	Once a data set is established, using VertexArrayRangeAPPLE, it can be can
	be drawn using standard OpenGL vertex array commands, as one would do
	without this extension.  Note, if any the data for any enabled array for a
	given array element index falls outside of the vertex array range, an
	undefined vertex is generated.  One should also understand removing or
	replacing all calls to vertex array range functions with no-ops or disabling
	the vertex array range by disabling the VERTEX_ARRAY_RANGE_APPLE client
	state should not change the results of an application's OpenGL drawing.

	For static data no addition coherency nor synchronization must be done and
	the client is free to draw with the specified draw as it sees fit.

	If data is dynamic, thus to be modified, FlushVertexArrayRangeAPPLE should
	be used.  The command is issued when data has been modified since the last
	call to VertexArrayRangeAPPLE or FlushVertexArrayRangeAPPLE and prior to
	drawing with such data. FlushVertexArrayRangeAPPLE only provides memory
	coherency prior to drawing (such as ensuring CPU caches are flushed or VRAM
	cached copies are updated) and does not provide any synchronization with
	previously issued drawing commands. The range flushed can be the specific
	range modified and does not have to be the entire vertex array range.
	Additionally, data maybe read immediately after a flush without need for
	further synchronization, thus overlapping areas of data maybe read, modified
	and written between two successive flushings and the data will be
	consistent.

	To synchronize data modification after drawing two methods can be used. A
	Finish command can be issued which will not return until all previously
	issued commands are complete, forcing completely synchronous operation.
	While this guarantees all drawing is complete it may not be the optimal
	solution for clients which just need to ensure drawing with the vertex array
	range or a specific range with the array is compete.  The APPLE_fence
	extension can be used when dynamic data modifications need to be
	synchronized with drawing commands. Specifically, if data is to be modified,
	a fence can be set immediately after drawing with the data.  Once it comes
	time to modify the data, the application must test (or finish) this fence to
	ensure the drawing command has completed. Failure to do this could result in
	new data being used by the previously issued drawing commands.  It should be
	noted that providing the maximum time between the drawing set fence and the
	modification test/finish fence allows the most asynchronous behavior and
	will result in the least stalling waiting for drawing completion. Techniques
	such as double buffering vertex data can be used to help further prevent
	stalls based on fence completion but are beyond the scope of this extension.

	Once an application is finished with a specific vertex array range or at
	latest prior to exit, and prior to freeing the memory associated with this
	vertex array, the client should call VertexArrayRangeAPPLE with a data
	location and length of 0 to allow the internal memory managers to complete
	any commitments for the array range.  In this case once
	VertexArrayRangeAPPLE returns it is safe to de-allocate the memory.

	An additional option is presented for vertex array ranges, the ability of
	the client to hint to OpenGL the type of access and/or use the vertex array
	memory is expected to have, by using VertexArrayParameteriAPPLE with either
	of the STORAGE_CACHED_APPLE or STORAGE_SHARED_APPLE parameter.  By default,
	all vertex array ranges are considered to be "shared".  These options allow
	the tuning of memory handling by OpenGL.  "Shared" memory is normally used
	for dynamic data that is expected to be modified and is likely mapped to AGP
	space for access by the graphics hardware and client.  "Cached" memory is
	designed to support static data and could be cached into to VRAM to provide
	the maximum access bandwidth for the vertex array.  Note, these hints can
	affect how array flushes are handled and the overhead associated with
	flushing the array, it is recommended that data be left as "shared" unless
	it really is static and there are no plans to modify it.

	To summarize the vertex array range extension provides relaxed
	synchronization rules for handling vertex array data allowing high bandwidth
	asynchronous data transfer from client memory to graphics hardware.
	Different flushing and synchronization rules are required to ensure data
	coherency when modifying data.  Lastly, memory handling hints are provided
	to allow the tunning of memory storage and access for maximum efficiency.

The official definition of this extension is available here:
http://www.opengl.org/registry/specs/APPLE/vertex_array_range.txt
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.APPLE.vertex_array_range import *
### END AUTOGENERATED SECTION


text:
from polonium.utils import is_inside, remove_redundant_children, iterfile

class UnexpectedArgumentError(RuntimeError):
    """Raise this error in patched functions after handling all expected arguments."""
    pass

class TestIsInside:
    def test_file_is_inside_of_directory(self):
        assert is_inside('/etc/passwd', '/etc')
        assert is_inside('/var/log/syslog', '/var/log')

    def test_directory_is_inside_of_directory(self):
        assert is_inside('/etc/kernel', '/etc')
        assert is_inside('/var/log/apt', '/var/log')

    def test_file_is_outside_of_directory(self):
        assert not is_inside('/etc/passwd', '/var/log')
        assert not is_inside('/var/log/syslog', '/etc')

    def test_directory_is_outside_of_directory(self):
        assert not is_inside('/etc/kernel', '/var/log')
        assert not is_inside('/var/log/apt', '/etc')

class TestRemoveRedundantChildren:
    def test_common_root(self):
        paths = [
            '/',
            '/etc',
            '/etc/kernel',
            '/etc/passwd',
            '/var',
            '/var/log',
            '/var/log/apt',
            '/var/log/syslog',
        ]
        assert remove_redundant_children(paths) == {'/'}

        paths.remove('/')
        assert remove_redundant_children(paths) == {'/etc', '/var'}

        paths.remove('/etc')
        assert remove_redundant_children(paths) == {'/etc/kernel', '/etc/passwd', '/var'}

        paths.remove('/var')
        assert remove_redundant_children(paths) == {'/etc/kernel', '/etc/passwd', '/var/log'}

        paths.remove('/var/log')
        assert remove_redundant_children(paths) == {'/etc/kernel', '/etc/passwd', '/var/log/apt', '/var/log/syslog'}

        paths.append('/')
        assert remove_redundant_children(paths) == {'/'}

    def test_common_prefix(self):
        assert remove_redundant_children(['/tmp/.env', '/tmp/.env.example']) == {'/tmp/.env', '/tmp/.env.example'}
        assert remove_redundant_children(['/tmp/.git', '/tmp/.gitignore']) == {'/tmp/.git', '/tmp/.gitignore'}

class TestIterfile:
    def test_file_path_without_exclude_paths(self):
        assert list(iterfile('/etc/passwd')) == ['/etc/passwd']
        assert list(iterfile('/tmp/.env')) == ['/tmp/.env']
        assert list(iterfile('/tmp/.env.example')) == ['/tmp/.env.example']
        assert list(iterfile('/tmp/.gitignore')) == ['/tmp/.gitignore']
        assert list(iterfile('/var/log/syslog')) == ['/var/log/syslog']

    def test_file_path_with_exclude_file_path_hit(self):
        assert list(iterfile('/etc/passwd', {'/etc/passwd'})) == []
        assert list(iterfile('/tmp/.env', {'/tmp/.env'})) == []
        assert list(iterfile('/tmp/.env.example', {'/tmp/.env.example'})) == []
        assert list(iterfile('/tmp/.gitignore', {'/tmp/.gitignore'})) == []
        assert list(iterfile('/var/log/syslog', {'/var/log/syslog'})) == []

    def test_file_path_with_exclude_file_path_miss(self):
        assert list(iterfile('/etc/passwd', {'/tmp/.env'})) == ['/etc/passwd']
        assert list(iterfile('/tmp/.env', {'/tmp/.env.example'})) == ['/tmp/.env']
        assert list(iterfile('/tmp/.env.example', {'/tmp/.gitignore'})) == ['/tmp/.env.example']
        assert list(iterfile('/tmp/.gitignore', {'/var/log/syslog'})) == ['/tmp/.gitignore']
        assert list(iterfile('/var/log/syslog', {'/etc/passwd'})) == ['/var/log/syslog']

    def test_file_path_with_exclude_directory_path_hit(self):
        assert list(iterfile('/etc/passwd', {'/'})) == []
        assert list(iterfile('/etc/passwd', {'/etc'})) == []
        assert list(iterfile('/tmp/.env', {'/'})) == []
        assert list(iterfile('/tmp/.env', {'/tmp'})) == []
        assert list(iterfile('/tmp/.env.example', {'/'})) == []
        assert list(iterfile('/tmp/.env.example', {'/tmp'})) == []
        assert list(iterfile('/tmp/.gitignore', {'/'})) == []
        assert list(iterfile('/tmp/.gitignore', {'/tmp'})) == []
        assert list(iterfile('/var/log/syslog', {'/'})) == []
        assert list(iterfile('/var/log/syslog', {'/var'})) == []
        assert list(iterfile('/var/log/syslog', {'/var/log'})) == []

    def test_file_path_with_exclude_directory_path_miss(self):
        assert list(iterfile('/etc/passwd', {'/tmp'})) == ['/etc/passwd']
        assert list(iterfile('/etc/passwd', {'/etc/kernel'})) == ['/etc/passwd']
        assert list(iterfile('/tmp/.env', {'/var'})) == ['/tmp/.env']
        assert list(iterfile('/tmp/.env', {'/tmp/.git'})) == ['/tmp/.env']
        assert list(iterfile('/tmp/.env.example', {'/var'})) == ['/tmp/.env.example']
        assert list(iterfile('/tmp/.env.example', {'/tmp/.git'})) == ['/tmp/.env.example']
        assert list(iterfile('/tmp/.gitignore', {'/var'})) == ['/tmp/.gitignore']
        assert list(iterfile('/tmp/.gitignore', {'/tmp/.git'})) == ['/tmp/.gitignore']
        assert list(iterfile('/var/log/syslog', {'/etc'})) == ['/var/log/syslog']
        assert list(iterfile('/var/log/syslog', {'/var/log/apt'})) == ['/var/log/syslog']

    def test_directory_path_without_exclude_paths(self, monkeypatch):
        def patched_walk(top, *_args, **_kwargs):
            if top == '/':
                yield '/', ['etc', 'tmp', 'var'], []
                yield '/etc', ['kernel'], ['passwd']
                yield '/etc/kernel', [], []
                yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
                yield '/tmp/.git', [], []
                yield '/var', ['log'], []
                yield '/var/log', ['apt'], ['syslog']
                yield '/var/log/apt', [], []
                return

            if top == '/etc':
                yield '/etc', ['kernel'], ['passwd']
                yield '/etc/kernel', [], []
                return

            if top == '/etc/kernel':
                yield '/etc/kernel', [], []
                return

            if top == '/tmp':
                yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
                yield '/tmp/.git', [], []
                return

            if top == '/tmp/.git':
                yield '/tmp/.git', [], []
                return

            if top == '/var':
                yield '/var', ['log'], []
                yield '/var/log', ['apt'], ['syslog']
                yield '/var/log/apt', [], []
                return

            if top == '/var/log':
                yield '/var/log', ['apt'], ['syslog']
                yield '/var/log/apt', [], []
                return

            if top == '/var/log/apt':
                yield '/var/log/apt', [], []
                return

            raise UnexpectedArgumentError('patched_walk({!r})'.format(top))

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/')) == [
            '/etc/passwd',
            '/tmp/.env',
            '/tmp/.gitignore',
            '/tmp/.env.example',
            '/var/log/syslog'
        ]
        assert list(iterfile('/etc')) == ['/etc/passwd']
        assert list(iterfile('/etc/kernel')) == []
        assert list(iterfile('/tmp')) == ['/tmp/.env', '/tmp/.gitignore', '/tmp/.env.example']
        assert list(iterfile('/tmp/.git')) == []
        assert list(iterfile('/var')) == ['/var/log/syslog']
        assert list(iterfile('/var/log')) == ['/var/log/syslog']
        assert list(iterfile('/var/log/apt')) == []

    def test_directory_path_exclude_file_path_hit(self, monkeypatch):
        def patched_walk(top, *_args, **_kwargs):
            if top == '/':
                yield '/', ['etc', 'tmp', 'var'], []
                yield '/etc', ['kernel'], ['passwd']
                yield '/etc/kernel', [], []
                yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
                yield '/tmp/.git', [], []
                yield '/var', ['log'], []
                yield '/var/log', ['apt'], ['syslog']
                yield '/var/log/apt', [], []
                return

            if top == '/etc':
                yield '/etc', ['kernel'], ['passwd']
                yield '/etc/kernel', [], []
                return

            if top == '/tmp':
                yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
                yield '/tmp/.git', [], []
                return

            if top == '/var':
                yield '/var', ['log'], []
                yield '/var/log', ['apt'], ['syslog']
                yield '/var/log/apt', [], []
                return

            if top == '/var/log':
                yield '/var/log', ['apt'], ['syslog']
                yield '/var/log/apt', [], []
                return

            raise UnexpectedArgumentError('patched_walk({!r})'.format(top))

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/', {
            '/etc/passwd',
            '/tmp/.env',
            '/tmp/.gitignore',
            '/tmp/.env.example',
            '/var/log/syslog',
        })) == []
        assert list(iterfile('/etc', {'/etc/passwd'})) == []
        assert list(iterfile('/tmp', {'/tmp/.env', '/tmp/.gitignore', '/tmp/.env.example'})) == []
        assert list(iterfile('/var', {'/var/log/syslog'})) == []
        assert list(iterfile('/var/log', {'/var/log/syslog'})) == []

    def test_directory_path_exclude_file_path_miss(self, monkeypatch):
        def patched_walk(top, *_args, **_kwargs):
            if top == '/etc':
                yield '/etc', ['kernel'], ['passwd']
                yield '/etc/kernel', [], []
                return

            if top == '/tmp':
                yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
                yield '/tmp/.git', [], []
                return

            if top == '/var':
                yield '/var', ['log'], []
                yield '/var/log', ['apt'], ['syslog']
                yield '/var/log/apt', [], []
                return

            if top == '/var/log':
                yield '/var/log', ['apt'], ['syslog']
                yield '/var/log/apt', [], []
                return

            raise UnexpectedArgumentError('patched_walk({!r})'.format(top))

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/etc', {'/tmp/.env'})) == ['/etc/passwd']
        assert list(iterfile('/tmp', {'/var/log/syslog'})) == ['/tmp/.env', '/tmp/.gitignore', '/tmp/.env.example']
        assert list(iterfile('/var', {'/etc/passwd'})) == ['/var/log/syslog']
        assert list(iterfile('/var/log', {'/etc/passwd'})) == ['/var/log/syslog']

    def test_directory_path_exclude_directory_path_hit(self, monkeypatch):
        # exclude /
        def patched_walk(*_args, **_kwargs):
            yield '/', ['etc', 'tmp', 'var'], []

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/', {'/'})) == []

        # exclude /etc
        def patched_walk(*_args, **_kwargs):
            yield '/', ['etc', 'tmp', 'var'], []
            yield '/etc', ['kernel'], ['passwd']
            yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
            yield '/tmp/.git', [], []
            yield '/var', ['log'], []
            yield '/var/log', ['apt'], ['syslog']
            yield '/var/log/apt', [], []

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/', {'/etc'})) == [
            '/tmp/.env',
            '/tmp/.gitignore',
            '/tmp/.env.example',
            '/var/log/syslog',
        ]

        # exclude /tmp
        def patched_walk(*_args, **_kwargs):
            yield '/', ['etc', 'tmp', 'var'], []
            yield '/etc', ['kernel'], ['passwd']
            yield '/etc/kernel', [], []
            yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
            yield '/var', ['log'], []
            yield '/var/log', ['apt'], ['syslog']
            yield '/var/log/apt', [], []

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/', {'/tmp'})) == [
            '/etc/passwd',
            '/var/log/syslog',
        ]

        # exclude /var
        def patched_walk(*_args, **_kwargs):
            yield '/', ['etc', 'tmp', 'var'], []
            yield '/etc', ['kernel'], ['passwd']
            yield '/etc/kernel', [], []
            yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
            yield '/tmp/.git', [], []
            yield '/var', ['log'], []

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/', {'/var'})) == [
            '/etc/passwd',
            '/tmp/.env',
            '/tmp/.gitignore',
            '/tmp/.env.example',
        ]

        # exclude /var/log
        def patched_walk(*_args, **_kwargs):
            yield '/', ['etc', 'tmp', 'var'], []
            yield '/etc', ['kernel'], ['passwd']
            yield '/etc/kernel', [], []
            yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
            yield '/tmp/.git', [], []
            yield '/var', ['log'], []
            yield '/var/log', ['apt'], ['syslog']

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/', {'/var/log'})) == [
            '/etc/passwd',
            '/tmp/.env',
            '/tmp/.gitignore',
            '/tmp/.env.example',
        ]

    def test_directory_path_exclude_directory_path_miss(self, monkeypatch):
        def patched_walk(*_args, **_kwargs):
            yield '/etc', ['kernel'], ['passwd']
            yield '/etc/kernel', [], []

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/etc', {'/tmp'})) == [
            '/etc/passwd',
        ]

        def patched_walk(*_args, **_kwargs):
            yield '/tmp', ['.git'], ['.env', '.gitignore', '.env.example']
            yield '/tmp/.git', [], []

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/tmp', {'/var'})) == [
            '/tmp/.env',
            '/tmp/.gitignore',
            '/tmp/.env.example',
        ]

        def patched_walk(*_args, **_kwargs):
            yield '/var', ['log'], []
            yield '/var/log', ['apt'], ['syslog']
            yield '/var/log/apt', [], []

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/var', {'/etc'})) == [
            '/var/log/syslog',
        ]

        def patched_walk(*_args, **_kwargs):
            yield '/var/log', ['apt'], ['syslog']
            yield '/var/log/apt', [], []

        monkeypatch.setattr('os.walk', patched_walk)

        assert list(iterfile('/var/log', {'/etc'})) == [
            '/var/log/syslog',
        ]


text:
package com.amazonaws.unmarshaller;

import com.amazonaws.http.HttpResponse;
import com.amazonaws.internal.http.JsonErrorMessageParser;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

import org.junit.Before;
import org.junit.Test;

import java.util.UUID;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class JsonErrorMessageParserTest {

    private static final JsonErrorMessageParser parser = JsonErrorMessageParser.DEFAULT_ERROR_MESSAGE_PARSER;

    private static final String MESSAGE_CONTENT = "boom";

    private HttpResponse response;

    private ObjectNode jsonNode;

    @Before
    public void setup() {
        jsonNode = JsonNodeFactory.instance.objectNode();
        response = new HttpResponse(null, null);
    }

    @Test
    public void deprecatedOverload_ParsesMessageSuccessfully() {
        jsonNode.put("message", MESSAGE_CONTENT);
        String parsed = parser.parseErrorMessage(jsonNode);
        assertEquals(MESSAGE_CONTENT, parsed);
    }

    @Test
    public void testErrorMessageAt_message() {
        jsonNode.put("message", MESSAGE_CONTENT);
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertEquals(MESSAGE_CONTENT, parsed);
    }

    @Test
    public void testErrorMessageAt_Message() {
        jsonNode.put("Message", MESSAGE_CONTENT);
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertEquals(MESSAGE_CONTENT, parsed);
    }

    @Test
    public void testErrorMessageAt_errorMessage() {
        jsonNode.put("errorMessage", MESSAGE_CONTENT);
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertEquals(MESSAGE_CONTENT, parsed);
    }

    @Test
    public void testNoErrorMessage_ReturnsNull() {
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertNull(parsed);
    }

    @Test
    public void testErrorMessageIsNumber_ReturnsNull() {
        jsonNode.put("message", 1);
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertNull(parsed);
    }

    @Test
    public void testErrorMessageIsObject_ReturnsNull() {
        jsonNode.set("message", JsonNodeFactory.instance.objectNode().put("foo", "bar"));
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertNull(parsed);
    }

    @Test
    public void testErrorMessageAtMultipleLocations_ReturnsLowerMessage() {
        jsonNode.put("message", MESSAGE_CONTENT);
        String randomStuff = UUID.randomUUID().toString();
        jsonNode.put("Message", randomStuff);
        jsonNode.put("errorMessage", randomStuff);
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertEquals(MESSAGE_CONTENT, parsed);
    }

    @Test
    public void errorMessageInHeader_ReturnsHeaderValue() {
        response.addHeader(JsonErrorMessageParser.X_AMZN_ERROR_MESSAGE, MESSAGE_CONTENT);
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertEquals(MESSAGE_CONTENT, parsed);
    }

    @Test
    public void errorMessageInHeader_ReturnsHeaderValue_CaseInsensitive() {
        response.addHeader("x-AMZN-error-message", MESSAGE_CONTENT);
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertEquals(MESSAGE_CONTENT, parsed);
    }

    @Test
    public void errorMessageInHeader_TakesPrecedenceOverMessageInBody() {
        response.addHeader(JsonErrorMessageParser.X_AMZN_ERROR_MESSAGE, MESSAGE_CONTENT);
        jsonNode.put("message", "other message in body");
        String parsed = parser.parseErrorMessage(response, jsonNode);
        assertEquals(MESSAGE_CONTENT, parsed);
    }

}


text:
FILE(GLOB CLEANDIRS "${DIR}/sandbox-*.d[0-9]*")
IF (CLEANDIRS)
  MESSAGE(STATUS "Removing ${CLEANDIRS}")
  FILE(REMOVE_RECURSE ${CLEANDIRS})
ENDIF()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Docums Mycol. 28(nos 109-110): 6 (1998)

#### Original name
Dermoloma bellerianum Bon

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>core-common</artifactId>
    <groupId>com.jtbdevelopment.core-common</groupId>
    <version>1.11-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>core-spring-web-mongo</artifactId>

  <dependencies>
    <dependency>
      <groupId>com.jtbdevelopment.core-common</groupId>
      <artifactId>core-spring-web</artifactId>
      <version>1.11-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>com.jtbdevelopment.core-common</groupId>
      <artifactId>core-spring-mongo</artifactId>
      <version>1.11-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>de.flapdoodle.embed</groupId>
      <artifactId>de.flapdoodle.embed.mongo</artifactId>
      <version>${flapdoodle.mongo.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.jtbdevelopment.core-common</groupId>
      <artifactId>core-spring-mongo</artifactId>
      <version>1.11-SNAPSHOT</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.jtbdevelopment.core-common</groupId>
      <artifactId>core-spring-web</artifactId>
      <version>1.11-SNAPSHOT</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>

  </dependencies>
</project>


text:
class CreateSpreeCustomProducts < ActiveRecord::Migration
  def change
    create_table :spree_custom_products do |t|
      t.string :name
      t.string :permalink
      t.string :description
      t.string :flavor_1_name
      t.string :flavor_2_name
      t.string :flavor_3_name
      t.integer :flavor_1_percentage
      t.integer :flavor_2_percentage
      t.integer :flavor_3_percentage
      t.string :flavor_1_sku
      t.string :flavor_2_sku
      t.string :flavor_3_sku
      t.float :sweetness
      t.float :fruity
      t.float :nutty
      t.float :vegetal
      t.float :woody
      t.float :aroma
      t.float :spicy
      t.float :floral
      t.float :strength
      t.integer :user_id
      t.boolean :public
      t.boolean :final

      t.timestamps
    end
  end
end


text:
package algorithms.search.global;

/**
 * Goal is to make an implementation of quantum annealing global
 * search, that is,
 * quantum stochastic optimization, related to subject
 * adiabatic quantum computation.
 *
 * First reading the paper "An introduction to quantum annealing"
 * by Falco and Tamascelli (2009?).
 *
 * It contains a review of simulating quantum computing,
 * quantum annealing optimization and then an improvement
 * of the later with a diffusion term.
 *
 * The paper also mentions modern variants of quantum annealing
 * and that may be what is implemented here at the end of the
 * reading.

 * might also read in detail
 *     "Quantum path minimization: An efficient method for global optimization"
 *     by Liu and Berne, 2003
 *
   "Exponential Enhancement of the Efficiency of Quantum Annealing
      by Non-Stoquastic Hamiltonians"
      by Nishimori* and Takada, 2017

    ?
    * QUBO:
    * https://github.com/alex1770/QUBO-Chimera
      Quadratic unconstrained binary optimization (QUBO) is a
      pattern matching technique, common in machine learning applications.
      QUBO is an NP hard problem.
          QUBO problems may sometimes be well-suited to algorithms aided
          by quantum annealing.[1]

    Chimera graph, a rectangularly linked grid of bipartite graphs used
    as the hardware connectivity structure in quantum annealers

 * as an exercise,
 * explore
 *     http://www.quantumplayground.net/#/home
 *
 * might impl
 * Shor:
 *    integer factorization in a quantum computer.
 *    The efficiency of Shor's algorithm is due to the efficiency of the
 *    quantum Fourier transform, and modular exponentiation by repeated
 *    squarings.
 *
 * Grovers:
 *     https://pdfs.semanticscholar.org/834b/579cde622a51a1f1459319a48452e5d9760d.pdf
 *
 * https://github.com/dwavesystems/
 *
 * looking at dwave code...
 * https://github.com/dwavesystems/dw_sa_chi/tree/master/src
 * chimera_annealer dwave_sa(fields, coupler_starts, coupler_ends, coupler_values, seed);

 */

/*
   Notes and excerpts while reading
   -------------------
 * Quantum Annealing, or Quantum Stochastic Optimization, is a
   classical randomized algorithm
 *
 *  In simulated annealing the space of admissible solutions to a given
 * optimization problem is visited by a temperature dependent random walk.
 * The cost function defines the potential energy profile of the solution
 * space and thermal fluctuations prevent the exploration from getting stuck
 * in a local minimum.
 * An opportunely scheduled temperature lowering (annealing), then, stabilizes
   the walk around a, hopefully global, minimum of the potential profile.
   The idea of using quantum, instead of thermal, jumps to explore the solution
   space of a given optimization problem was proposed
   in "A numerical implementation
   of Quantum Annealing" by Apolloni, Cesa-Bianchi, and  Falco.
   and in "Stochastic Processes" by Albeverio et al.
.  It was suggested by the behaviour of the stochastic process
   q_ν associated with the ground state (state of minimal energy) of a
   Hamiltonian of the form:
                v^2
         H_v = ---- * (2nd deriv w.r.t. x) + V(x)
                 2

 * section 3, outline
    - creating classical heuristics
    - admissible solutions to an optimization problem is
       defined by a temperature dependent random walk
       for simulated annealing
       - cost function has
           - potential energy of solution space
           - thermal fluctuations (to escape local minima)
              - specialy timed temperature lowering (annealing)
                to regulate the walk after the escape
              - QUANTUM replaces the thermal jump with tunneling
    - desribing the quantum jump:
       q_nu is associated w/ ground state of Hamiltonian
             v^2
       H_v = ---- * (2nd deriv w.r.t. x) + V(x)
              2
         -> the potential V encodes the cost function to be minimized

       Given ground state psi_nu of H_nu of a fixed nu,
       the stochastic process
       q_nu is built by "the ground state transformation",
         which is not yet defined here.

       the ground state transformation results in

       H_v = -nu * L_nu + E
                        v^2
           where L_v = ---- * (2nd deriv w.r.t. x) + b_nu
                         2

           where b_v = (1/2) * (1st deriv w.r.t. x) * ln(psi_vi(x)^2)

           as nu approaches 0, q_nu will behave like a Markov chain
              having disrete and stalbe state space.

           refs 9 and 8, emphasize that they don't reproduce the computationally
              untractable details of a quantum mechanical system,
              but instead
              simulate the ground state process of the Hamiltonian Hν as
              nu approaches 0.
              hence an efficient exploration of solution space is possible.

              the ground state estimation (psi_nu)
                 uses time evolution from the real portion of the
                 shrodinger equation
                    (exp(-t*H_nu))
              the ground state (psi_nu) is then described as
                  time approaches infinity for

                    (1/alpha_t) * exp(-t*H_nu/h) | psi_nu(0)  \ = psi_nu
                                                 |            /

                    where alpha_t = /phi_0 | psi(0) \ * exp(-t*E_0)
                                    \      |        /

               and eigenstates are phi_0(= psi_nu), phi_1,...

               and those eigenvalues E_0 < E_1 < ... E_N

            in the limit of t -> inf:
               (1/alpha_t) * exp(-t*H_nu/h) | psi_nu(0)  \
                                            |            /
               = psi_nu

               = <limit t->inf | phi_0>
                  + (1/<phi_0|psi(0)>)*exp(-t*(E_n-E_0)/hbar) | phi_n>
                  * <phi_n | psi(0)>

          the authors then use the Feyman-Kac formula to estimate
          the evolved state exp(-t*H_nu) * psi
               given init state psi
               -- x is defined as expected value of integral of
                    the potential V (==cost) along the stochastic
                    trajectories eps(tau).
                      each eps(tau) starts at x and from time 0 to t
                        makes N(t) transitions towards nearest neighbors
                        using a uniform probability.
                        N(t) is poisson process of intensity nu
                           (NLK: presumably they mean intensity is
                            proportional to nu unless they are using
                            nu as intensity instead of frequency)
                ------> ** the details of the sampling and
                            ground state (psi) estimation are in
                            Ref. 8.
                        when that is implemented,
                        given an estimate of
                        psi_nu(y) for every neighbor y of current solution x,
                        the exploration results in high probability of
                        finding the nearest-neighbour solution with
                        max estimated value of psi_nu.
                      Then the decision rule on which neighbour to accept
                      is based on tne ensemble eps(tau).

    When implemented in a working computer program,
    the procedure described above requires a variety of
    approximations.
        First of all, equation (7) reproduces the
        ground-state only in the limit t → ∞,
        corresponding to sample paths of infinite length.
        The expected value of the right hand side of (7), moreover,
        will be estimated by means of a finite size sample.
    Finally, the number of neighbours of a configuration may be too
    large to allow the estimation of ψν on the whole neighbourhood
    of a given solution. The accuracy of the approximation depends,
    for example, on the actual length νt of the sample paths,
    the number of paths n per neighbour
    and the dimension |Neigh| of the subset of the set of neighbours
    of a given solution to consider at each move.
    Some "engineering" is also in order [9]
    (see the pseudo-code of Quantum Stochastic Optimization reported here):
    for example, we can call a local optimization procedure every tloc
    quantum transitions. In addition, if the search looks to be stuck
    for in a local minimum, we can force a jump to another local minimum.

    Ref 8: "Quantum stochastic optimization" 1989 by Apolloni et al
    Reg 9: "A numerical implementation of Quantum Annealing" 1990 by
           Apolloni et al.

    Consider variants:
    Imaginary Time Quantum Monte Carlo (ITQMC)
        [26, 45, 46, 38]
    Ref 26: "Minimization of the potential energy surface of Lennard—Jones
        clusters by quantum optimization"
        by Gregor and Car 2005
    Ref 45: "Optimization using quantum mechanics: quantum annealing through
        adiabatic evolution" 2006 by Santoro and Tosatti
    Ref 46: same as 45, publ in 2008 in
        J. Phys. A: Math. Theor., 41:209801, 2008
    Ref 38: "On product, generic and random generic quantum satisfiability."
         by Laumann et al. 2009

    if pursue using mc, should look further into project
    espresso of sissa.it.
    and TurboRVB

    ?
    https://github.com/hadsed/pathintegral-qmc

    https://github.com/alex1770/QUBO-Chimera

Look for recent articles by these authors:
Inoue J-I 2005 Quantum Annealing and Related Optimization Methods ed A Das and B K Chakrabarti
(Berlin:Springer) p 171

   a quick recent review:
    https://arxiv.org/pdf/1310.1339.pdf

   ---------------
   Notes and excerpts from
      "Optimization using quantum mechanics: quantum annealing through
       adiabatic evolution"
       by Santoro and Tosatti

   ... challenging hard optimization problems,
        such as the random Ising model,
        the travelling salesman problem and
        Boolean satisfiability problems.
    The techniques used to implement quantum annealing are either
    deterministic Schrodinger's evolutions for the toy models,
    or path-integral Monte Carlo and Green's function Monte Carlo approaches,
    for the hard optimization problems.
    The crucial role played by disorder and the associated
    non-trivial Landau–Zener tunnelling phenomena is discussed and emphasized.

    The description as a toy model is because the Hilbert space of the
    problem is restricted to low N (N < 20 to 30 for spin 1/2 problems, e.g.).

    To examine the performance of different algorithms better, the authors
    look in detail at the energy structure and barriers around local minima,
    starting with simple models.

    First, one-dimensional potentials, starting from a
    double-well potential, the simplest form of barrier.
    -- compared quantum adiabatic Schrodinger ¨
       evolution, both in real and in imaginary time,
       and its classical deterministic counterpart, i.e.,
       Fokker–Planck evolution [28].
       (NOTE: Fokker-Planck evolution a.k.a. the Kolomogorv Forward eqn.
       ...time evolution of the PDE of the velocity of a particle under
       the influence of drag forces and random forces, as in Brownian motion_.
    -- also studied the performance of different stochastic
       approaches, both classical Monte Carlo and path-integral
       Monte Carlo.
    The authors found ~ equivalence of IT and RT Schrodinger annealing
    justifying practical implementations of quantum annealing based on
    imaginary-time quantum Monte Carlo schemes.

    the properties of the instantaneous spectrum of the Hamiltonian (26)
    depend on the dimensionality D of the lattice, and on the
    nearest-neighbour kinetic energy terms included
    (adjacency matrix of the quantum walker)

    PIMC:
       Berne et al. combined clever thermal and quantum annealing schemes within a
       path-integral framework to find the minimal energy configurations of
       protein models on the continuum
       (with up to N = 46 monomers) [31, 32].
          the minimal energy configurations of Lennard-Jones clusters
          of up to N = 100 atoms [33, 34].

       PIMC is summarized using 2 approaches:
         (1) disrete optimization problems, by using Ising case
         (2) continuum problems, using a particle in  potential

       simulates the equilibrium behavior of a system a finite temp T

       Edward–Anderson Ising glass in a transverse field:
           H = Hcl + Hkin = − summ_i_j (J_i_j * σ_i^2 + σ_j^2) - JMP(σ_i^x)

       this is a time-dependent Hamiltonian, and goal is to find min states
       as a function of time by turning off the transverse field (t).
       Can simulate the thermodynamics of a fixed positive T at a fixed JMP(t)
       by sampling the quantum partition function:

       The authors again quote the PIMC references above for interesting detailed
       solutions specific to their problems,
       then present a simplified model to continue exploration:
          PIMC-QA scheme whereby T is untouched during a QA simulation
          and the number of Trotter replicas P is also kept fixed,
          in order to more clearly discriminate possibly genuine quantum
          effects from thermal ones.

          PIMC-QA applied to combinatorial optimization problems:

          define a combinatorial optimization as the task of
          minimizing any given cost function that depends on
          variables w/ discrete values.
          it is straightforward to map problems over the search
          for the ground state of some Hamiltonian depending on Potts
          (or Ising) spin degrees of freedom [7, 55].

          the number of possible configurations of a very small
          32 × 32 square lattice Ising model is of order 10308,
          while the number of electrons in the universe is of
          the order 10^308

          The authors find better success for the PIMC-QA and GFMC models
          than for the CA models.
          W.R.T. 2 MC-QA models,
          the PIMC model difficulties are finite temperature T,
          possible sampling problems for the action, and difficulties with
          the Trotter break-up, so there may be alternative models that
          arise in PIMC specifically that are further improvements.
          the GFMC difficulty is that it is dependent upon
          a good guess of trial variational wavefunctions.

   ----------------
 *
 * @author nichole
 */
public class QuantumAnnealing {

    /*

    pseudocode from "An introduction to quantum annealing"
        by Falco and Tamascelli

    NOTE: still reading the variants of QA and QSO so might
    not implement following the pseudocode here.

    Looking at the pseudocode, it seems as if the success of
    finding the true global minimum depends upon the initial
    conditions, that is, the global min solution would have to be
    within a connected distance of tunelling and local minima from
    the start conditions...so the MC approach is probably better
    for some problems at exploring state space, but haven't read
    details yet...

    --------------------------------------------
    procedure 1 QA

    Input : initial condition init; control param nu;
        duration t_max; tunnel time t_drill; local opt time t_loc

    t = 0
    eps = init
    v_min = cost(eps)
    while t < t_max do
       j = 0
       repeat
          i = 0
          repeat
             eps = QuantumTransition(eps, nu, t_max)
             if cost(eps) < v_min then
                v_min = cost(c)
                i = 0; j = 0;
             else
                i = j + 1
             endif
          until i > t_loc
          epsilon = Local Optimization(eps)
          if cost(eps) < v_min then
             v_min = cost(eps)
             j = 0
          endif
       until j < t_drill
       draw a trajectory of length nu*t_max and jump there
       Local Optimization(c)

    end while

    -------------------------------
    Procedure 2 Quantum Transitions

    Input: initial condition eps; chain length nu*t; set of
        neighbors to estimate Neigh

    for all neighbour k in Neigh do
       estimate the wave function psi_nu(k)
    end for
    best = select a neighbour in Neigh w/ probability prop to psi)nu

    return best

    --------------------------------
    Procedure 3 Local Optimization

    Input: initial condition eps
       return the best solution found by any steepest descent strategy
    */

    public QuantumAnnealing() {
    }

}


text:
package lib

import (
	"fmt"
	"io"
	"os"
	"strings"

	oss "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var specChineseCat = SpecText{
	synopsisText: "将文件内容输出到标准输出",

	paramText: "object [options]",

	syntaxText: `
	ossutil cat oss://bucket/object [--payer requester] [--version-id versionId]
`,
	detailHelpText: `
    cat命令可以将oss的object内容输出到标准输出,object内容最好是文本格式

用法:
    该命令仅有一种用法:

    1) ossutil cat oss://bucket/object [--version-id versionId] [--payer requester]
       将object内容输出到标准输出
`,
	sampleText: `
    1) 将object内容输出到标准输出
       ossutil cat oss://bucket/object

    2) 将object指定版本内容输出到标准输出
       ossutil cat oss://bucket/object --version-id versionId

    3) 访问者付费模式
       ossutil cat oss://bucket/object --payer requester
`,
}

var specEnglishCat = SpecText{
	synopsisText: "Output object content to standard output",

	paramText: "object [options]",

	syntaxText: `
	ossutil cat oss://bucket/object [--payer requester] [--version-id versionId]
`,
	detailHelpText: `
	The cat command can output the object content of oss to standard output
    The object content is preferably text format

Usage:
    There is only one usage for this command:

    1) ossutil cat oss://bucket/object [--version-id versionId] [--payer requester]
       The command output object content to standard output
`,
	sampleText: `
    1) output object content to standard output
       ossutil cat oss://bucket/object

    2) output the object's specified version content to standard output
       ossutil cat oss://bucket/object --version-id versionId

    3) output object content with requester payment
       ossutil cat oss://bucket/object --payer requester
`,
}

type catOptionType struct {
	bucketName   string
	objectName   string
	encodingType string
}

type CatCommand struct {
	command       Command
	catOption     catOptionType
	commonOptions []oss.Option
}

var catCommand = CatCommand{
	command: Command{
		name:        "cat",
		nameAlias:   []string{"cat"},
		minArgc:     1,
		maxArgc:     1,
		specChinese: specChineseCat,
		specEnglish: specEnglishCat,
		group:       GroupTypeNormalCommand,
		validOptionNames: []string{
			OptionConfigFile,
			OptionEndpoint,
			OptionAccessKeyID,
			OptionAccessKeySecret,
			OptionSTSToken,
			OptionProxyHost,
			OptionProxyUser,
			OptionProxyPwd,
			OptionEncodingType,
			OptionLogLevel,
			OptionVersionId,
			OptionRequestPayer,
			OptionPassword,
			OptionMode,
			OptionECSRoleName,
			OptionTokenTimeout,
			OptionRamRoleArn,
			OptionRoleSessionName,
			OptionReadTimeout,
			OptionConnectTimeout,
			OptionSTSRegion,
			OptionSkipVerifyCert,
			OptionUserAgent,
			OptionSignVersion,
			OptionRegion,
			OptionCloudBoxID,
		},
	},
}

// function for FormatHelper interface
func (catc *CatCommand) formatHelpForWhole() string {
	return catc.command.formatHelpForWhole()
}

func (catc *CatCommand) formatIndependHelp() string {
	return catc.command.formatIndependHelp()
}

// Init simulate inheritance, and polymorphism
func (catc *CatCommand) Init(args []string, options OptionMapType) error {
	return catc.command.Init(args, options, catc)
}

// RunCommand simulate inheritance, and polymorphism
func (catc *CatCommand) RunCommand() error {
	catc.catOption.encodingType, _ = GetString(OptionEncodingType, catc.command.options)
	srcBucketUrL, err := GetCloudUrl(catc.command.args[0], catc.catOption.encodingType)
	if err != nil {
		return err
	}

	if srcBucketUrL.object == "" {
		return fmt.Errorf("object key is empty")
	}

	catc.catOption.bucketName = srcBucketUrL.bucket
	catc.catOption.objectName = srcBucketUrL.object

	// check object exist or not
	client, err := catc.command.ossClient(catc.catOption.bucketName)
	if err != nil {
		return err
	}

	bucket, err := client.Bucket(catc.catOption.bucketName)
	if err != nil {
		return err
	}

	payer, _ := GetString(OptionRequestPayer, catc.command.options)
	if payer != "" {
		if payer != strings.ToLower(string(oss.Requester)) {
			return fmt.Errorf("invalid request payer: %s, please check", payer)
		}
		catc.commonOptions = append(catc.commonOptions, oss.RequestPayer(oss.PayerType(payer)))
	}

	var options []oss.Option
	options = append(options, catc.commonOptions...)

	versionId, _ := GetString(OptionVersionId, catc.command.options)
	if len(versionId) > 0 {
		options = append(options, oss.VersionId(versionId))
	}

	body, err := bucket.GetObject(catc.catOption.objectName, options...)
	if err != nil {
		return err
	}

	defer body.Close()
	io.Copy(os.Stdout, body)
	fmt.Printf("\n")

	return err
}