text:
<TITLE>Review for Smoke Signals (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Smoke Signals (1998)

reviewed by
W. Waffle

I review independent flicks and movies that deserve a second chance every week
at WWW.WAFFLEMOVIES.COM. Here is a sample:

SMOKE SIGNALS

In Smoke Signals, director Chris Erye and writer Sherman Alexie give us a
realistic and moving view of Native Americans. They drop the stereotypes and
truthfully portray Native Americans as regular people full of hopes and dreams,
facing tough decisions and coping with loss. Erye and Alexie also examine the
stereotypes and racism they face, as well as the inner struggle each faces
dealing with the world.

The movie opens with an incident that connects our two main characters for
life. In Coeur d'Alene, Idaho on Independence Day 1976, Arnold Joseph (Gary
Farmer) saved the life of Thomas (Evan Adams) as both of his parents perished
in a horrible fire. Now orphaned, Thomas is raised by his grandmother and tries
to connect with those around him through storytelling. Also rescued from the
fire is Arnold Joseph's son, Victor (Adam Beach).

Erye skillfully uses a series of flashbacks mixed with modern day action to
explain the relationship between Thomas and Victor. He shows us the friendship
shared by the two until a guilt-ridden Arnold Joseph leaves his family for
Arizona. On that day, young Thomas (Simon Baker) suggests it is young Victor's
(Cody Lightning) fault that his father has left. Victor never forgives Thomas
until his mother (Tantoo Cardinal) receives a call from Arnold Joseph's
neighbor (Irene Bedard) informing her that his father has died.

Victor wants to travel to Arizona to claim his father's remains, but cannot
afford a bus ticket. Although they have grown apart, Thomas agrees to lend him
the money, but with the condition that they go together. Thomas always had a
strong relationship with the man who saved his life, and wishes to say good-bye
with his old friend.

The resulting movie becomes one of the best buddy movies I have seen in a long
time. Unlike the classic Dean Martin/Jerry Lewis buddy pictures, this one is
driven by Alexie's sharp Tarrantino-like dialogue instead of zany situation
comedy. During the trip, we learn about the racism Victor and Thomas face as
they encounter others filled with hate.

Not only do Victor and Thomas face hate as they leave the reservation for the
first time in their lives, but they are burdened by conflicting ideas of how
they should act and portray themselves. One of the best scenes of the movie
results when Victor instructs Thomas how he should act or else, "the white man
will run all over you." Victor tells Thomas he must abandon his trademark suit
and braids for long flowing locks and a stoic appearance. Thomas transforms
himself into a warrior, but retains his nerdy demeanor, realizing that he
doesn't want to be a stereotype.

In Arizona, Thomas and Victor learn about the rehabilitated Arnold Joseph. He
gave up drinking and loved his son from afar. Arnold's neighbor, Suzy Song,
explains why he left Victor and his mother and the truth behind the most
important incident in Victor and Thomas' lives.

The picture is full of excellent performances. Gary Farmer shines as the
alcoholic and remorseful Arnold Joseph. Farmer is excellent as we slowly watch
him deteriorate and become consumed with guilt. Adam Beach is fabulous as the
emotionally withdrawn and heartbroken Victor. He fills the character full of
rage and hurt. Evan Adams should have been nominated for an Oscar for his
performance as the "Dances with Wolves"-loving, mystical, nerdy Thomas. He
creates an appealing and enduring character that you hope will reappear in
other work by Eyre and Alexie.

Why was this movie released in June of 1998?!?!?!? Unfortunately, this
excellent movie would have been better served if it were released in the fall
or winter like most Oscar contenders. That competition would have been more
appropriate than facing Saving Private Ryan, Armageddon and Something About
Mary. The movie was awarded the Audience Award and the Filmmaker's Trophy at
the 1998 Sundance Film Festival, and could have made a strong Oscar showing if
released at a better time.

Chris Eyre does an excellent job helming the first movie by Native Americans
about Native Americans. Unfortunately, the movie has some fantastic
cinematography that is lost on the small screen. Although this movie never
registered on the national radar screen, Eyre has great potential and will be
heard from as he makes more movies. Fortunately for us, this movie is available
on video, allowing us the opportunity to enjoy this hidden gem.

Smoke Signals: A-

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
import 'source-map-support/register';

import request from 'request';
import tar from 'tar';
import zlib from 'zlib';
import temp from 'temp';

// Automatically track and cleanup files at exit
temp.track();

export function getVersions(packageName) {
    return new Promise((resolve, reject) => {
        request.get({
            url: `https://api.github.com/repos/${packageName}/tags`,
            headers: {
                'User-Agent': 'request'
            }
        }, (error, resp, body) => {
            if (error) {
                return reject(error);
            }

            if (resp.statusCode !== 200) {
                return reject(new Error(packageName + ': returned ' + resp.statusCode + '\n\nbody:\n' + body));
            }

            return resolve(JSON.parse(body));
        });
    });
}

export function get(packageName, version = 'master') {
    return new Promise((resolve, reject) => {
        temp.mkdir('roc', function(err, dirPath) {
            if (err) {
                reject(err);
            }

            /* eslint-disable new-cap */
            const writeTar = tar.Extract({strip: 1, path: dirPath});
            /* eslint-enable */

            writeTar.on('finish', () => resolve(dirPath));

            request
                .get(`http://github.com/${packageName}/tarball/${version}`)
                .on('error', reject)
                .pipe(zlib.createGunzip())
                .on('error', reject)
                .pipe(writeTar)
                .on('error', reject);
        });
    });
}

redpajama_set_name: RedPajamaGithub


text:
The first method returns the first element in the collection that passes a given truth test:

```js
collect([1, 2, 3, 4]).first(item => item > 1);

// 2
```

You may also call the first method with no arguments to get the first element in the collection. If the collection is empty, null is returned:

```js
collect([1, 2, 3, 4]).first();

// 1
```

[View source on GitHub](https://github.com/ecrmnn/collect.js/blob/master/src/methods/first.js)


text:
class AudioInterface: public QObject
{
	Q_OBJECT

public:
	AudioInterface(QObject *parent = 0);
	~AudioInterface();

	/// @brief Save the current settings to an XML document.
	/// @param parent The paren element to write the settings to.
	void toXML(QDomElement & parent) const;
	/// @brief Read current settings from XML document.
	/// @param parent The parent element to load the settings from.
	AudioInterface & fromXML(const QDomElement & parent);

	ParameterQString captureDevice;
	ParameterBool capturing;
	ParameterInt captureInterval;

	static QStringList inputDeviceNames();
	static QString defaultInputDeviceName();

	static QStringList ouputDeviceNames();
	static QString defaultOutputDeviceName();

signals:
	//Delivers audio levels for each channel.
	void levelData(const QVector<float> & levels, float timeus);
	//Delivers the FFT of the current audio data.
	void fftData(const QVector<float> & spectrum, int channels, float timeus);
	//Delivers beat information for the beat detection.
	void beatData(float bpm, bool isBeat);

protected slots:
	void setCaptureDevice(const QString & inputName);
	void setCaptureState(bool capturing);
	void setCaptureInterval(int interval);

	void inputDataReady();
	void inputStateChanged(QAudio::State state);

private:
	ConversionWorker * m_conversionWorker = nullptr;
	ProcessingWorker * m_processingWorker = nullptr;
	QThread m_workerThread;
	QAudioInput * m_audioInput = nullptr;
	QIODevice * m_inputDevice = nullptr;
	int m_sampleRate = 44100;
	int m_bitDepth = 16;
};


text:
package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Import;

/**
 * Indicates that the package containing the annotated class should be registered with
 * {@link AutoConfigurationPackages}.
 *
 * @author Phillip Webb
 * @since 1.3.0
 * @see AutoConfigurationPackages
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

}


text:
"""Demonstrates how to obtain short-lived credentials with identity federation."""
# [START iam_workload_identity_aws_credential]
import json
import urllib

import boto3
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest

def create_token_aws(project_number: str, pool_id: str, provider_id: str) -> None:
    # Prepare a GetCallerIdentity request.
    request = AWSRequest(
        method="POST",
        url="https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15",
        headers={
            "Host": "sts.amazonaws.com",
            "x-goog-cloud-target-resource": f"//iam.googleapis.com/projects/{project_number}/locations/global/workloadIdentityPools/{pool_id}/providers/{provider_id}"
        })

    # Set the session credentials and Sign the request.
    # get_credentials loads the required credentials as environment variables.
    # Refer:
    # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
    SigV4Auth(boto3.Session().get_credentials(), "sts", "us-east-1").add_auth(request)

    # Create token from signed request.
    token = {
        "url": request.url,
        "method": request.method,
        "headers": []
    }
    for key, value in request.headers.items():
        token["headers"].append({"key": key, "value": value})

    # The token lets workload identity federation verify the identity without revealing the AWS secret access key.
    print("Token:\n%s" % json.dumps(token, indent=2, sort_keys=True))
    print("URL encoded token:\n%s" % urllib.parse.quote(json.dumps(token)))

def main():
    # TODO(Developer): Replace the below credentials.
    # project_number: Google Project number (not the project id)
    project_number = "my-project-number"
    pool_id = "my-pool-id"
    provider_id = "my-provider-id"

    create_token_aws(project_number, pool_id, provider_id)

if __name__ == "__main__":
    main()
# [END iam_workload_identity_aws_credential]


text:
<?php

    namespace Component\Driver;

    /**
     * Description of Driver
     *
     * @author Guillaume de Lestanville <guillaume.delestanville@proximit.fr>
     */
    abstract class Driver
    {
        /**
         * Retourne la liste des schémas
         * @returns array
         */
        public function getSchemas();

        /**
         * Retourne la liste des tables d'un schéma
         */
        public function getTables($schemaname);

        /**
         * Interrogation de la base
         */
        public function query($sql);
    }


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Button</title>
  <link rel="stylesheet" href="../../../dist/css/bootstrap.min.css">

Button Bootstrap Visual Test

  <button type="button" data-loading-text="Loading for 3 seconds..." class="btn btn-primary js-loading-button">
    Loading state
  </button>

  <button type="button" class="btn btn-primary" data-toggle="button">Single toggle</button>

For checkboxes and radio buttons, ensure that keyboard behavior is functioning correctly.

Navigate to the checkboxes with the keyboard (generally, using TAB / SHIFT + TAB), and ensure that SPACE toggles the currently focused checkbox. Click on one of the checkboxes using the mouse, ensure that focus was correctly set on the actual checkbox, and that SPACE toggles the checkbox again.

      <input type="checkbox"> checkbox 1

      <input type="checkbox"> checkbox 2

      <input type="checkbox"> checkbox 3

Navigate to the radio button group with the keyboard (generally, using TAB / SHIFT + TAB). If no radio button was initially set to be selected, the first/last radio button should receive focus (depending on whether you navigated "forward" to the group with TAB or "backwards" using SHIFT + TAB). If a radio button was already selected, navigating with the keyboard should set focus to that particular radio button. Only one radio button in a group should receive focus at any given time.  Ensure that the selected radio button can be changed by using the ← and → arrow keys. Click on one of the radio buttons with the mouse,  ensure that focus was correctly set on the actual radio button, and that ← and → change the selected radio button again.

      <input type="radio" name="options" id="option1"> Radio 1

      <input type="radio" name="options" id="option2"> Radio 2

      <input type="radio" name="options" id="option3"> Radio 3


text:
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace ASC.Api.Utils
{
    public static class Binder
    {
        private static object CreateParamType(Type modelType)
        {
            var type = modelType;
            if (modelType.IsGenericType)
            {
                var genericTypeDefinition = modelType.GetGenericTypeDefinition();
                if (genericTypeDefinition == typeof(IDictionary<,>))
                    type = typeof(Dictionary<,>).MakeGenericType(modelType.GetGenericArguments());
                else if (genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>) || genericTypeDefinition == typeof(IList<>))
                    type = typeof(List<>).MakeGenericType(modelType.GetGenericArguments());
            }
            if (modelType.IsArray && modelType.HasElementType)
            {
                //Create generic list and we will convert it to aaray  later
                type = typeof(List<>).MakeGenericType(modelType.GetElementType());
            }
            return Activator.CreateInstance(type);
        }

        public static Type GetCollectionType(Type modelType)
        {
            Type type = null;
            if (modelType.IsGenericType)
            {
                var genericTypeDefinition = modelType.GetGenericTypeDefinition();
                if (typeof(IDictionary).IsAssignableFrom(genericTypeDefinition))
                    type = modelType.GetGenericArguments().Last();
                else if (typeof(IEnumerable).IsAssignableFrom(genericTypeDefinition) || typeof(ICollection).IsAssignableFrom(genericTypeDefinition) || typeof(IList).IsAssignableFrom(genericTypeDefinition))
                    type = modelType.GetGenericArguments().Last();
            }
            if (modelType.IsArray && modelType.HasElementType)
            {
                type = modelType.GetElementType();
            }
            return type;
        }

        public static object Bind(Type type, NameValueCollection collection)
        {
            return Bind(type, collection, string.Empty);
        }

        public static T Bind<T>(NameValueCollection collection)
        {
            return Bind<T>(collection, string.Empty);
        }

        public static T Bind<T>(NameValueCollection collection, string prefix)
        {
            return (T)Bind(typeof(T), collection, prefix);
        }

        public static object Bind(Type type, NameValueCollection collection, string prefix)
        {
            if (IsSimple(type))
            {
                //Just bind
                var value = GetValue(GetNameTransforms(prefix), collection, string.Empty);
                if (value != null)
                {
                    return ConvertUtils.GetConverted(value, type);
                }
            }
            var binded = CreateParamType(type);
            //Get all props
            if (IsCollection(type))
            {
                BindCollection(prefix, (IList)binded, collection);
            }
            else
            {
                binded = BindObject(type, binded, collection, prefix);
            }
            return ConvertToSourceType(binded, type);
        }

        private static object ConvertToSourceType(object binded, Type type)
        {
            if (binded != null)
            {
                if (type.IsArray && type.HasElementType && binded.GetType().IsGenericType && IsCollection(binded.GetType()))
                {
                    var genericType = binded.GetType().GetGenericArguments();
                    var arrayType = type.GetElementType();
                    if (genericType.Length == 1 && genericType[0] == arrayType)
                    {
                        IList collection = (IList)binded;
                        //Its list need to convert to array
                        Array array = Array.CreateInstance(arrayType, collection.Count);
                        collection.CopyTo(array, 0);
                        return array;
                    }
                }
            }
            return binded;
        }

        private static object BindObject(IReflect type, object binded, NameValueCollection values, string prefix)
        {
            //Get properties
            var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            var isBinded = false;
            foreach (var propertyInfo in properties)
            {
                if (IsSimple(propertyInfo.PropertyType))
                {
                    //Set from collection
                    var value = GetValue(GetName(propertyInfo), values, prefix);
                    if (value != null)
                    {
                        propertyInfo.SetValue(binded, ConvertUtils.GetConverted(value, propertyInfo), null);
                        isBinded = true;
                    }
                }
                else
                {
                    var propNames = GetName(propertyInfo);
                    PropertyInfo info = propertyInfo;
                    foreach (string propName in propNames)
                    {
                        string bindPrefix = !string.IsNullOrEmpty(prefix) ? prefix + string.Format("[{0}]", propName) : propName;
                        //find prefix in collection
                        if (IsPrefixExists(bindPrefix, values))
                        {
                            var result = Bind(info.PropertyType, values, bindPrefix);
                            if (result != null)
                            {
                                propertyInfo.SetValue(binded, result, null);
                                isBinded = true;
                                break;
                            }
                        }
                    }
                }
            }
            return isBinded ? binded : null;
        }

        private static bool IsPrefixExists(string prefix, NameValueCollection values)
        {
            return values.AllKeys.Any(x => x != null && x.StartsWith(prefix));
        }

        private static IEnumerable<string> GetName(PropertyInfo property)
        {
            return GetNameTransforms(property.Name);
        }

        private static IEnumerable<string> GetNameTransforms(string name)
        {
            return new[]
                       {
                           name,
                           StringUtils.ToCamelCase(name),
                           name.ToLower(),
                           name.ToLowerInvariant()
                       };
        }

        private static string GetValue(IEnumerable<string> names, NameValueCollection values, string prefix)
        {
            if (string.IsNullOrEmpty(prefix))
            {
                return names.Select(name => values[name]).FirstOrDefault(value => !string.IsNullOrEmpty(value));
            }

            //var regex = new Regex(@"^(\[){0,1}(" + string.Join("|", names.Select(name => Regex.Escape(name)).ToArray()) + @")(\]){0,1}");

            var keys = from key in values.AllKeys
                       where key != null && key.StartsWith(prefix)
                       let nameKey = key.Substring(prefix.Length).Trim('[', '.', ']')
                       where names.Contains(nameKey)
                       select key;

            return values[keys.SingleOrDefault() ?? string.Empty];
        }

        private static readonly ConcurrentDictionary<string, Regex> CollectionPrefixCache = new ConcurrentDictionary<string, Regex>();

        private static bool BindCollection(string prefix, IList collection, NameValueCollection values)
        {
            var isBinded = false;
            Regex parse = GetParseRegex(prefix);

            //Parse values related to collection
            const string simple = "simple";
            var keys = from key in values.AllKeys.Where(key => key != null)
                       let match = parse.Match(key)
                       group key by string.IsNullOrEmpty(match.Groups["pos"].Value) ? (match.Groups["arrleft"].Success ? string.Empty : simple) : match.Groups["pos"].Value into key
                       select key;

            foreach (var key in keys)
            {
                int index;
                bool indexed = int.TryParse(key.Key, out index);

                Type genericType = null;
                var collectionType = collection.GetType();
                if (collectionType.IsGenericType)
                {
                    genericType = collectionType.GetGenericArguments().SingleOrDefault();
                }
                else if (collectionType.IsArray && collectionType.HasElementType)
                {
                    //Create array
                    genericType = collectionType.GetElementType();
                }

                if (genericType != null)
                {
                    var newprefix = simple.Equals(key.Key) ? prefix : prefix + "[" + (indexed ? index.ToString(CultureInfo.InvariantCulture) : "") + "]";
                    if (IsSimple(genericType))
                    {
                        //Collect all and insert
                        var collectionValues = values.GetValues(newprefix);
                        if (collectionValues != null)
                        {
                            foreach (var collectionValue in collectionValues)
                            {
                                collection.Add(ConvertUtils.GetConverted(collectionValue, genericType));
                                isBinded = true;
                            }
                        }
                    }
                    else
                    {
                        var constructed = Bind(genericType, values, newprefix);
                        if (constructed != null)
                        {
                            collection.Insert(index, constructed);
                            isBinded = true;
                        }
                    }
                }
            }

            return isBinded;
        }

        private static Regex GetParseRegex(string prefix)
        {
            Regex value = null;
            if (!CollectionPrefixCache.TryGetValue(prefix, out value))
            {
                value = new Regex("(?'prefix'^" + Regex.Escape(prefix) +
                    @"(?'arrleft'\[){0,1}(?'pos'[\d]+){0,1}(?'arrright'\]){0,1})(?'suffix'.+){0,1}",
                    RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled);
                CollectionPrefixCache.TryAdd(prefix, value);
            }
            return value;
        }

        public static bool IsCollection(Type type)
        {
            return !IsSimple(type) && (type.IsArray || HasInterface(type, typeof(IEnumerable)));
        }

        public static bool HasInterface(Type type, Type interfaceType)
        {
            return type.GetInterfaces().Any(x => x == interfaceType);
        }

        private static readonly IDictionary<Type, bool> SimpleMap = new ConcurrentDictionary<Type, bool>();

        private static bool IsSimple(Type type)
        {
            bool simple;
            if (type.IsPrimitive) return true;

            if (!SimpleMap.TryGetValue(type, out simple))
            {
                var converter = TypeDescriptor.GetConverter(type);//TODO: optimize?
                simple = converter.CanConvertFrom(typeof(string));
                SimpleMap[type] = simple;
            }
            return simple;
        }

        public static long GetCollectionCount(object collection)
        {
            var collection1 = collection as ICollection;
            if (collection1 != null)
                return (collection1).Count;

            var responceType = collection.GetType();
            var lengthProperty = responceType.GetProperty("Count", BindingFlags.Public | BindingFlags.Instance) ?? responceType.GetProperty("Length", BindingFlags.Public | BindingFlags.Instance);
            if (lengthProperty != null)
            {
                return Convert.ToInt64(lengthProperty.GetValue(collection, new object[0]));
            }
            return 1;
        }
    }
}


text:
package org.wildfly.camel.test.jibx;

import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.model.dataformat.JibxDataFormat;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.camel.test.common.jibx.PurchaseOrder;
import org.wildfly.extension.camel.CamelAware;

@CamelAware
@RunWith(Arquillian.class)
public class JibxDataFormatTest {

    @Deployment
    public static JavaArchive deployment() {
        final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "jibx-dataformat-tests");
        archive.addPackage(PurchaseOrder.class.getPackage());
        return archive;
    }

    @Test
    public void testMarshal() throws Exception {

        CamelContext camelctx = new DefaultCamelContext();
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").marshal().jibx();
            }
        });

        String expected = "<order name=\"Books\" price=\"5.3\" amount=\"1\"/>";

        camelctx.start();
        try {
            ProducerTemplate producer = camelctx.createProducerTemplate();
            String result = producer.requestBody("direct:start", new PurchaseOrder("Books", 5.3, 1), String.class);
            Assert.assertTrue(result.endsWith(expected));
        } finally {
            camelctx.stop();
        }
    }

    @Test
    public void testUnmarshal() throws Exception {

        CamelContext camelctx = new DefaultCamelContext();
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").unmarshal(new JibxDataFormat(PurchaseOrder.class));
            }
        });

        String input = "<order name=\"Books\" price=\"5.3\" amount=\"1\"/>";

        camelctx.start();
        try {
            ProducerTemplate producer = camelctx.createProducerTemplate();
            PurchaseOrder order = producer.requestBody("direct:start", input, PurchaseOrder.class);
            Assert.assertEquals("Books", order.getName());
            Assert.assertEquals(5.3, order.getPrice(), 0);
            Assert.assertEquals(1, order.getAmount());
        } finally {
            camelctx.stop();
        }
    }
}


text:
<!DOCTYPE html>

        <title>world's simplest to do list</title>
        <link rel="stylesheet" type="text/css" href="stylesheet.css"/>

world's simplest to do list

		<form name="checkListForm">
			<input type="text" name="checkListItem" onclick="this.value='';"/>
		</form>

+


text:
package org.lwjgl.vulkan;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 * Structure specifying vertex input attribute description.
 *
 *
Valid Usage

 *
 *

 *
{@code location} must be less than {@link VkPhysicalDeviceLimits}{@code ::maxVertexInputAttributes}

 *
{@code binding} must be less than {@link VkPhysicalDeviceLimits}{@code ::maxVertexInputBindings}

 *
{@code offset} must be less than or equal to {@link VkPhysicalDeviceLimits}{@code ::maxVertexInputAttributeOffset}

 *
{@code format} must be allowed as a vertex buffer format, as specified by the {@link VK10#VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT FORMAT_FEATURE_VERTEX_BUFFER_BIT} flag in {@link VkFormatProperties}{@code ::bufferFeatures} returned by {@link VK10#vkGetPhysicalDeviceFormatProperties GetPhysicalDeviceFormatProperties}

 *

 *
 *
Valid Usage (Implicit)

 *
 *

 *
{@code format} must be a valid {@code VkFormat} value

 *

 *
 *
See Also

 *
 *
{@link VkPipelineVertexInputStateCreateInfo}

 *
 *
Member documentation

 *
 *

 *
{@code location} – the shader binding location number for this attribute.

 *
{@code binding} – the binding number which this attribute takes its data from.

 *
{@code format} – the size and type of the vertex attribute data.

 *
{@code offset} – a byte offset of this attribute relative to the start of an element in the vertex input binding.

 *

 *
 *
Layout

 *
 *
struct VkVertexInputAttributeDescription {
    uint32_t location;
    uint32_t binding;
    VkFormat format;
    uint32_t offset;
}

 */
public class VkVertexInputAttributeDescription extends Struct implements NativeResource {

	/** The struct size in bytes. */
	public static final int SIZEOF;

	public static final int ALIGNOF;

	/** The struct member offsets. */
	public static final int
		LOCATION,
		BINDING,
		FORMAT,
		OFFSET;

	static {
		Layout layout = __struct(
			__member(4),
			__member(4),
			__member(4),
			__member(4)
		);

		SIZEOF = layout.getSize();
		ALIGNOF = layout.getAlignment();

		LOCATION = layout.offsetof(0);
		BINDING = layout.offsetof(1);
		FORMAT = layout.offsetof(2);
		OFFSET = layout.offsetof(3);
	}

	VkVertexInputAttributeDescription(long address, ByteBuffer container) {
		super(address, container);
	}

	/**
	 * Creates a {@link VkVertexInputAttributeDescription} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
	 * visible to the struct instance and vice versa.
	 *
	 *
The created instance holds a strong reference to the container object.

	 */
	public VkVertexInputAttributeDescription(ByteBuffer container) {
		this(memAddress(container), checkContainer(container, SIZEOF));
	}

	@Override
	public int sizeof() { return SIZEOF; }

	/** Returns the value of the {@code location} field. */
	public int location() { return nlocation(address()); }
	/** Returns the value of the {@code binding} field. */
	public int binding() { return nbinding(address()); }
	/** Returns the value of the {@code format} field. */
	public int format() { return nformat(address()); }
	/** Returns the value of the {@code offset} field. */
	public int offset() { return noffset(address()); }

	/** Sets the specified value to the {@code location} field. */
	public VkVertexInputAttributeDescription location(int value) { nlocation(address(), value); return this; }
	/** Sets the specified value to the {@code binding} field. */
	public VkVertexInputAttributeDescription binding(int value) { nbinding(address(), value); return this; }
	/** Sets the specified value to the {@code format} field. */
	public VkVertexInputAttributeDescription format(int value) { nformat(address(), value); return this; }
	/** Sets the specified value to the {@code offset} field. */
	public VkVertexInputAttributeDescription offset(int value) { noffset(address(), value); return this; }

	/** Initializes this struct with the specified values. */
	public VkVertexInputAttributeDescription set(
		int location,
		int binding,
		int format,
		int offset
	) {
		location(location);
		binding(binding);
		format(format);
		offset(offset);

		return this;
	}

	/** Unsafe version of {@link #set(VkVertexInputAttributeDescription) set}. */
	public VkVertexInputAttributeDescription nset(long struct) {
		memCopy(struct, address(), SIZEOF);
		return this;
	}

	/**
	 * Copies the specified struct data to this struct.
	 *
	 * @param src the source struct
	 *
	 * @return this struct
	 */
	public VkVertexInputAttributeDescription set(VkVertexInputAttributeDescription src) {
		return nset(src.address());
	}

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

	/** Returns a new {@link VkVertexInputAttributeDescription} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
	public static VkVertexInputAttributeDescription malloc() {
		return create(nmemAlloc(SIZEOF));
	}

	/** Returns a new {@link VkVertexInputAttributeDescription} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
	public static VkVertexInputAttributeDescription calloc() {
		return create(nmemCalloc(1, SIZEOF));
	}

	/** Returns a new {@link VkVertexInputAttributeDescription} instance allocated with {@link BufferUtils}. */
	public static VkVertexInputAttributeDescription create() {
		return new VkVertexInputAttributeDescription(BufferUtils.createByteBuffer(SIZEOF));
	}

	/** Returns a new {@link VkVertexInputAttributeDescription} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
	public static VkVertexInputAttributeDescription create(long address) {
		return address == NULL ? null : new VkVertexInputAttributeDescription(address, null);
	}

	/**
	 * Returns a new {@link VkVertexInputAttributeDescription.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer malloc(int capacity) {
		return create(nmemAlloc(capacity * SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link VkVertexInputAttributeDescription.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer calloc(int capacity) {
		return create(nmemCalloc(capacity, SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link VkVertexInputAttributeDescription.Buffer} instance allocated with {@link BufferUtils}.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer create(int capacity) {
		return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
	}

	/**
	 * Create a {@link VkVertexInputAttributeDescription.Buffer} instance at the specified memory.
	 *
	 * @param address  the memory address
	 * @param capacity the buffer capacity
	 */
	public static Buffer create(long address, int capacity) {
		return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
	}

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

	/** Returns a new {@link VkVertexInputAttributeDescription} instance allocated on the thread-local {@link MemoryStack}. */
	public static VkVertexInputAttributeDescription mallocStack() {
		return mallocStack(stackGet());
	}

	/** Returns a new {@link VkVertexInputAttributeDescription} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
	public static VkVertexInputAttributeDescription callocStack() {
		return callocStack(stackGet());
	}

	/**
	 * Returns a new {@link VkVertexInputAttributeDescription} instance allocated on the specified {@link MemoryStack}.
	 *
	 * @param stack the stack from which to allocate
	 */
	public static VkVertexInputAttributeDescription mallocStack(MemoryStack stack) {
		return create(stack.nmalloc(ALIGNOF, SIZEOF));
	}

	/**
	 * Returns a new {@link VkVertexInputAttributeDescription} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param stack the stack from which to allocate
	 */
	public static VkVertexInputAttributeDescription callocStack(MemoryStack stack) {
		return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
	}

	/**
	 * Returns a new {@link VkVertexInputAttributeDescription.Buffer} instance allocated on the thread-local {@link MemoryStack}.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer mallocStack(int capacity) {
		return mallocStack(capacity, stackGet());
	}

	/**
	 * Returns a new {@link VkVertexInputAttributeDescription.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer callocStack(int capacity) {
		return callocStack(capacity, stackGet());
	}

	/**
	 * Returns a new {@link VkVertexInputAttributeDescription.Buffer} instance allocated on the specified {@link MemoryStack}.
	 *
	 * @param stack the stack from which to allocate
	 * @param capacity the buffer capacity
	 */
	public static Buffer mallocStack(int capacity, MemoryStack stack) {
		return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link VkVertexInputAttributeDescription.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param stack the stack from which to allocate
	 * @param capacity the buffer capacity
	 */
	public static Buffer callocStack(int capacity, MemoryStack stack) {
		return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
	}

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

	/** Unsafe version of {@link #location}. */
	public static int nlocation(long struct) { return memGetInt(struct + VkVertexInputAttributeDescription.LOCATION); }
	/** Unsafe version of {@link #binding}. */
	public static int nbinding(long struct) { return memGetInt(struct + VkVertexInputAttributeDescription.BINDING); }
	/** Unsafe version of {@link #format}. */
	public static int nformat(long struct) { return memGetInt(struct + VkVertexInputAttributeDescription.FORMAT); }
	/** Unsafe version of {@link #offset}. */
	public static int noffset(long struct) { return memGetInt(struct + VkVertexInputAttributeDescription.OFFSET); }

	/** Unsafe version of {@link #location(int) location}. */
	public static void nlocation(long struct, int value) { memPutInt(struct + VkVertexInputAttributeDescription.LOCATION, value); }
	/** Unsafe version of {@link #binding(int) binding}. */
	public static void nbinding(long struct, int value) { memPutInt(struct + VkVertexInputAttributeDescription.BINDING, value); }
	/** Unsafe version of {@link #format(int) format}. */
	public static void nformat(long struct, int value) { memPutInt(struct + VkVertexInputAttributeDescription.FORMAT, value); }
	/** Unsafe version of {@link #offset(int) offset}. */
	public static void noffset(long struct, int value) { memPutInt(struct + VkVertexInputAttributeDescription.OFFSET, value); }

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

	/** An array of {@link VkVertexInputAttributeDescription} structs. */
	public static class Buffer extends StructBuffer<VkVertexInputAttributeDescription, Buffer> implements NativeResource {

		/**
		 * Creates a new {@link VkVertexInputAttributeDescription.Buffer} instance backed by the specified container.
		 *
		 * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
		 * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
		 * by {@link VkVertexInputAttributeDescription#SIZEOF}, and its mark will be undefined.
		 *
		 *
The created buffer instance holds a strong reference to the container object.

		 */
		public Buffer(ByteBuffer container) {
			super(container, container.remaining() / SIZEOF);
		}

		Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			super(address, container, mark, pos, lim, cap);
		}

		@Override
		protected Buffer self() {
			return this;
		}

		@Override
		protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			return new Buffer(address, container, mark, pos, lim, cap);
		}

		@Override
		protected VkVertexInputAttributeDescription newInstance(long address) {
			return new VkVertexInputAttributeDescription(address, container);
		}

		@Override
		protected int sizeof() {
			return SIZEOF;
		}

		/** Returns the value of the {@code location} field. */
		public int location() { return VkVertexInputAttributeDescription.nlocation(address()); }
		/** Returns the value of the {@code binding} field. */
		public int binding() { return VkVertexInputAttributeDescription.nbinding(address()); }
		/** Returns the value of the {@code format} field. */
		public int format() { return VkVertexInputAttributeDescription.nformat(address()); }
		/** Returns the value of the {@code offset} field. */
		public int offset() { return VkVertexInputAttributeDescription.noffset(address()); }

		/** Sets the specified value to the {@code location} field. */
		public VkVertexInputAttributeDescription.Buffer location(int value) { VkVertexInputAttributeDescription.nlocation(address(), value); return this; }
		/** Sets the specified value to the {@code binding} field. */
		public VkVertexInputAttributeDescription.Buffer binding(int value) { VkVertexInputAttributeDescription.nbinding(address(), value); return this; }
		/** Sets the specified value to the {@code format} field. */
		public VkVertexInputAttributeDescription.Buffer format(int value) { VkVertexInputAttributeDescription.nformat(address(), value); return this; }
		/** Sets the specified value to the {@code offset} field. */
		public VkVertexInputAttributeDescription.Buffer offset(int value) { VkVertexInputAttributeDescription.noffset(address(), value); return this; }

	}

}


text:
import json
import logging
import os
import re
import sys

sys.path[0:0] = [""]

from mongo_connector import config, errors, connector
from mongo_connector.connector import get_config_options, setup_logging
from mongo_connector.doc_managers import doc_manager_simulator
from tests import unittest

from_here = lambda *paths: os.path.join(
    os.path.abspath(os.path.dirname(__file__)), *paths)

class TestConfig(unittest.TestCase):
    """Test parsing a JSON config file into a Config object."""

    def setUp(self):
        self.reset_config()

    def reset_config(self):
        self.options = get_config_options()
        self.conf = config.Config(self.options)

    def load_json(self, d, validate=True, reset_config=True):
        if reset_config:
            self.reset_config()
        # Serialize a python dictionary to json, then load it
        text = json.dumps(d)
        self.conf.load_json(text)
        if validate:
            self.load_options(reset_config=False)

    def load_options(self, d={}, reset_config=True):
        if reset_config:
            self.reset_config()
        argv = []
        for k, v in d.items():
            argv.append(str(k))
            if v is not None:
                argv.append(str(v))
        self.conf.parse_args(argv)

    def test_default(self):
        # Make sure default configuration doesn't raise any exceptions
        self.load_options()

    def test_parse_json(self):
        # Test for basic json parsing correctness
        test_config = {
            'mainAddress': 'testMainAddress',
            'oplogFile': 'testOplogFile',
            'noDump': True,
            'batchSize': 69,
            'verbosity': 3,
            'logging': {
                'type': 'file',
                'filename': 'testFilename',
                'rotationWhen': 'midnight',
                'rotationInterval': 1,
                'rotationBackups': 7,
                'host': 'testHost',
                'facility': 'testFacility'
            },
            'authentication': {
                'adminUsername': 'testAdminUsername',
                'password': 'testPassword',
                'passwordFile': 'testPasswordFile'
            },
            'fields': ['testFields1', 'testField2'],
            'namespaces': {
                'include': ['testNamespaceSet'],
                'mapping': {'testMapKey': 'testMapValue'},
                'gridfs': ['testGridfsSet']
            }
        }
        self.load_json(test_config, validate=False)

        for test_key in test_config:
            self.assertEqual(self.conf[test_key], test_config[test_key])

        # Test for partial dict updates
        test_config = {
            'logging': {
                'type': 'syslog',
                'host': 'testHost2'
            },
            'authentication': {
                'adminUsername': 'testAdminUsername2',
                'passwordFile': 'testPasswordFile2'
            },
            'namespaces': {
                'mapping': {}
            }
        }
        self.load_json(test_config, validate=False, reset_config=False)
        self.assertEqual(self.conf['logging'], {
            'type': 'syslog',
            'filename': 'testFilename',
            'rotationWhen': 'midnight',
            'rotationInterval': 1,
            'rotationBackups': 7,
            'host': 'testHost2',
            'facility': 'testFacility'
        })
        self.assertEqual(self.conf['authentication'], {
            'adminUsername': 'testAdminUsername2',
            'password': 'testPassword',
            'passwordFile': 'testPasswordFile2'
        })
        self.assertEqual(self.conf['namespaces'], {
            'include': ['testNamespaceSet'],
            'mapping': {},
            'gridfs': ['testGridfsSet']
        })

    def test_basic_options(self):
        # Test the assignment of individual options
        def test_option(arg_name, json_key, value, append_cli=True):
            self.load_options({arg_name: value if append_cli else None})
            self.assertEqual(self.conf[json_key], value)

        test_option('-m', 'mainAddress', 'testMainAddress')
        test_option('-o', 'oplogFile', 'testOplogFileShort')
        test_option('--batch-size', 'batchSize', 69)
        test_option('--continue-on-error', 'continueOnError', True,
                    append_cli=False)
        test_option('-v', 'verbosity', 3, append_cli=False)

        self.load_options({'-w': 'logFile'})
        self.assertEqual(self.conf['logging.type'], 'file')
        self.assertEqual(self.conf['logging.filename'], 'logFile')

        self.load_options({'-s': None,
                           '--syslog-host': 'testHost',
                           '--syslog-facility': 'testFacility'})
        self.assertEqual(self.conf['logging.type'], 'syslog')
        self.assertEqual(self.conf['logging.host'], 'testHost')
        self.assertEqual(self.conf['logging.facility'], 'testFacility')

        self.load_options({'-i': 'a,b,c'})
        self.assertEqual(self.conf['fields'], ['a', 'b', 'c'])

    def test_extraneous_command_line_options(self):
        self.assertRaises(errors.InvalidConfiguration,
                          self.load_options, {'-v': 3})
        # No error.
        self.load_options({'-v': None})

    def test_namespace_set(self):
        # test namespace_set and dest_namespace_set
        self.load_options({
            "-n": "source_ns_1,source_ns_2,source_ns_3",
            "-g": "dest_ns_1,dest_ns_2,dest_ns_3"
        })
        self.assertEqual(self.conf['namespaces.include'],
                         ['source_ns_1', 'source_ns_2', 'source_ns_3'])
        self.assertEqual(self.conf['namespaces.mapping'],
                         {'source_ns_1': 'dest_ns_1',
                          'source_ns_2': 'dest_ns_2',
                          'source_ns_3': 'dest_ns_3'})

    def test_namespace_set_validation(self):
        # duplicate ns_set
        args = {
            "-n": "a,a,b",
            "-g": "1,2,3"
        }
        self.assertRaises(errors.InvalidConfiguration, self.load_options, args)
        d = {
            'namespaces': {'include': ['a', 'a', 'b']}
        }
        self.assertRaises(errors.InvalidConfiguration, self.load_json, d)

        # duplicate gridfs_set
        args = {
            '--gridfs-set': 'a,a,b'
        }
        self.assertRaises(errors.InvalidConfiguration, self.load_options, args)
        d = {
            'namespaces': {'gridfs': ['a', 'a', 'b']}
        }
        self.assertRaises(errors.InvalidConfiguration, self.load_json, d)

        # duplicate dest_ns_set
        args = {
            "-n": "a,b,c",
            "--dest-namespace-set": "1,3,3"
        }
        self.assertRaises(errors.InvalidConfiguration, self.load_options, args)
        d = {
            'namespaces': {'mapping': {
                'a': 'c',
                'b': 'c'
            }}
        }
        self.assertRaises(errors.InvalidConfiguration, self.load_json, d)

        # len(ns_set) < len(dest_ns_set)
        args = {
            "--namespace-set": "a,b,c",
            "-g": "1,2,3,4"
        }
        self.assertRaises(errors.InvalidConfiguration, self.load_options, args)

        # len(ns_set) > len(dest_ns_set)
        args = {
            "--namespace-set": "a,b,c,d",
            "--dest-namespace-set": "1,2,3"
        }
        self.assertRaises(errors.InvalidConfiguration, self.load_options, args)

    def test_doc_managers_from_args(self):
        # Test basic docmanager construction from args
        args = {
            '-d': "doc_manager_simulator",
            "-t": "test_target_url",
            "-u": "id",
            "--auto-commit-interval": 10
        }
        self.load_options(args)
        self.assertEqual(len(self.conf['docManagers']), 1)

        dm = self.conf['docManagers'][0]
        self.assertTrue(isinstance(dm, doc_manager_simulator.DocManager))
        self.assertEqual(dm.url, "test_target_url")
        self.assertEqual(dm.unique_key, "id")
        self.assertEqual(dm.auto_commit_interval, 10)

        # no doc_manager but target_url
        args = {
            "-t": "1,2"
        }
        self.assertRaises(errors.InvalidConfiguration,
                          self.load_options, args)

    def test_config_validation(self):
        # can't log both to syslog and to logfile
        self.assertRaises(errors.InvalidConfiguration,
                          self.load_options, {
                              '-w': 'logFile', '-s': 'true'
                          })

        # can't specify a username without a password
        self.assertRaises(errors.InvalidConfiguration,
                          self.load_options, {
                              '-a': 'username'
                          })

        # can't specify password and password file
        self.assertRaises(errors.InvalidConfiguration,
                          self.load_options, {
                              '-a': 'username',
                              '-p': 'password',
                              '-f': 'password_file'
                          })

        # docManagers must be a list
        test_config = {
            'docManagers': "hello"
        }
        self.assertRaises(errors.InvalidConfiguration,
                          self.load_json, test_config)

        # every element of docManagers must contain a 'docManager' property
        test_config = {
            'docManagers': [
                {
                    'targetURL': 'testTargetURL'
                }
            ]
        }
        self.assertRaises(errors.InvalidConfiguration,
                          self.load_json, test_config)

        # auto commit interval can't be negative
        test_config = {
            'docManagers': [
                {
                    'docManager': 'testDocManager',
                    'autoCommitInterval': -1
                }
            ]
        }
        self.assertRaises(errors.InvalidConfiguration,
                          self.load_json, test_config)

class TestConnectorConfig(unittest.TestCase):
    """Test creating a Connector from a Config."""

    # Configuration where every option is set to a non-default value.
    set_everything_config = {
        "mainAddress": "localhost:12345",
        "oplogFile": from_here("lib", "dummy.timestamp"),
        "noDump": True,
        "batchSize": 3,
        "verbosity": 1,
        "continueOnError": True,
        "timezoneAware": True,

        "logging": {
            "type": "file",
            "filename": from_here("lib", "dummy-connector.log"),
            "rotationWhen": "H",
            "rotationInterval": 3,
            "rotationBackups": 10
        },

        "authentication": {
            "adminUsername": "elmo",
            "passwordFile": from_here("lib", "dummy.pwd")
        },

        "ssl": {
            "sslCertfile": "certfile.pem",
            "sslKeyfile": "certfile.key",
            "sslCACerts": "ca.pem",
            "sslCertificatePolicy": "required"
        },

        "fields": ["field1", "field2", "field3"],

        "namespaces": {
            "include": ["db.source1", "db.source2"],
            "mapping": {
                "db.source1": "db.dest1",
                "db.source2": "db.dest2"
            },
            "gridfs": ["db.fs"]
        },

        "docManagers": [
            {
                "docManager": "doc_manager_simulator",
                "targetURL": "localhost:12345",
                "bulkSize": 500,
                "uniqueKey": "id",
                "autoCommitInterval": 10,
                "args": {"key": "value"}
            }
        ]
    }

    # Argv that sets all possible options to a different value from the
    # config JSON above. Some options cannot be reset, since they conflict
    # with the JSON config and will cause an Exception to be raised.
    # Conflicted options are already tested in the TestConfig TestCase.
    set_everything_differently_argv = [
        '-m', 'localhost:1000',
        '-o', from_here('lib', 'bar.timestamp'),
        '--batch-size', '100',
        '--verbose',
        '--logfile-when', 'D',
        '--logfile-interval', '5',
        '--logfile-backups', '10',
        '--fields', 'fieldA,fieldB',
        '--gridfs-set', 'db.gridfs',
        '--unique-key', 'customer_id',
        '--auto-commit-interval', '100',
        '--continue-on-error',
        '-t', 'localhost:54321',
        '-d', 'doc_manager_simulator',
        '-n', 'foo.bar,fiz.biz',
        '-g', 'foo2.bar2,fiz2.biz2',
        '--ssl-certfile', 'certfile2.pem',
        '--ssl-ca-certs', 'ca2.pem',
        '--ssl-certificate-policy', 'optional'
    ]

    # Set of files to keep in the 'lib' directory after each run.
    # The Connector and OplogThread create their own files in this directory
    # that should be cleaned out between tests.
    files_to_keep = set(('dummy.pwd',))

    def setUp(self):
        self.config = config.Config(get_config_options())
        # Remove all logging Handlers, since tests may create Handlers.
        logger = logging.getLogger()
        for handler in logger.handlers:
            logger.removeHandler(handler)

    def tearDown(self):
        for filename in os.listdir(from_here('lib')):
            if filename not in self.files_to_keep:
                try:
                    os.remove(from_here('lib', filename))
                except OSError:
                    pass  # File may no longer exist.

    def assertConnectorState(self):
        """Assert that a Connector is constructed from a Config properly."""
        mc = connector.Connector.from_config(self.config)

        # Test Connector options.
        self.assertEqual(mc.address, self.config['mainAddress'])
        self.assertIsInstance(mc.doc_managers[0],
                              doc_manager_simulator.DocManager)

        pwfile = self.config['authentication.passwordFile']
        if pwfile:
            with open(pwfile, 'r') as fd:
                test_password = re.sub(r'\s', '', fd.read())
                self.assertEqual(mc.auth_key, test_password)

        self.assertEqual(mc.auth_username,
                         self.config['authentication.adminUsername'])
        self.assertEqual(mc.oplog_checkpoint, self.config['oplogFile'])
        self.assertEqual(mc.tz_aware, self.config['timezoneAware'])
        self.assertEqual(mc.ssl_kwargs.get('ssl_certfile'),
                         self.config['ssl.sslCertfile'])
        self.assertEqual(mc.ssl_kwargs.get('ssl_ca_certs'),
                         self.config['ssl.sslCACerts'])
        self.assertEqual(mc.ssl_kwargs.get('ssl_keyfile'),
                         self.config['ssl.sslKeyfile'])
        self.assertEqual(mc.ssl_kwargs.get('ssl_cert_reqs'),
                         self.config['ssl.sslCertificatePolicy'])
        command_helper = mc.doc_managers[0].command_helper
        self.assertEqual(command_helper.namespace_set,
                         self.config['namespaces.include'])
        self.assertEqual(command_helper.dest_mapping,
                         self.config['namespaces.mapping'])

        # Test Logger options.
        log_levels = [
            logging.ERROR,
            logging.WARNING,
            logging.INFO,
            logging.DEBUG
        ]
        test_logger = setup_logging(self.config)
        self.assertEqual(
            log_levels[self.config['verbosity']],
            test_logger.level)
        test_handlers = [
            h for h in test_logger.handlers
            if isinstance(h, logging.handlers.TimedRotatingFileHandler)]
        self.assertEqual(len(test_handlers), 1)
        test_handler = test_handlers[0]
        expected_handler = logging.handlers.TimedRotatingFileHandler(
            'test-dummy.log',
            when=self.config['logging.rotationWhen'],
            interval=self.config['logging.rotationInterval'],
            backupCount=self.config['logging.rotationBackups'])
        self.assertEqual(test_handler.when, expected_handler.when)
        self.assertEqual(test_handler.backupCount,
                         expected_handler.backupCount)
        self.assertEqual(test_handler.interval, expected_handler.interval)

        # Test keyword arguments passed to OplogThread.
        ot_kwargs = mc.kwargs
        self.assertEqual(ot_kwargs['ns_set'], self.config['namespaces.include'])
        self.assertEqual(ot_kwargs['collection_dump'],
                         not self.config['noDump'])
        self.assertEqual(ot_kwargs['gridfs_set'],
                         self.config['namespaces.gridfs'])
        self.assertEqual(ot_kwargs['continue_on_error'],
                         self.config['continueOnError'])
        self.assertEqual(ot_kwargs['fields'], self.config['fields'])
        self.assertEqual(ot_kwargs['batch_size'], self.config['batchSize'])

        # Test DocManager options.
        for dm, dm_expected in zip(mc.doc_managers, self.config['docManagers']):
            self.assertEqual(dm.kwargs, dm_expected.kwargs)
            self.assertEqual(dm.auto_commit_interval,
                             dm_expected.auto_commit_interval)
            self.assertEqual(dm.url, dm_expected.url)
            self.assertEqual(dm.chunk_size, dm_expected.chunk_size)

    def test_connector_config_file_options(self):
        # Test Config with only a configuration file.
        self.config.load_json(
            json.dumps(self.set_everything_config))
        self.config.parse_args(argv=[])
        self.assertConnectorState()

    def test_connector_with_argv(self):
        # Test Config with arguments given on the command-line.
        self.config.parse_args(self.set_everything_differently_argv)
        self.assertConnectorState()

    def test_override_config_with_argv(self):
        # Override some options in the config file with given command-line
        # options.
        self.config.load_json(
            json.dumps(TestConnectorConfig.set_everything_config))
        self.config.parse_args(self.set_everything_differently_argv)
        self.assertConnectorState()

if __name__ == '__main__':
    unittest.main()


text:
const async = require('async');
const types = require('check-types');
const debug = require('debug')('Server');
const util = require('util');

const routes = [];

function replaceParams(path) {
  'use strict';
  if (!types.string(path))
    return path;
  if (path.indexOf(':') < 0)
    return '^' + path.split('\/').join('\\/') + '$';
  var string = '^';
  const arr = path.split('\/');
  for (var item in arr) {
    if (!arr.hasOwnProperty(item))
      continue;
    var str = arr[item];
    if (str === '' || str.length !== 0)
      string += '\\/';
    if (str.startsWith(':')) {
      str = '\\/[0-9]+';
    }
    string += str;
  }
  string += '$';
  string = string.split('\\/\\/').join('\\/');
  return string;
}

module.exports = function(router) {
  'use strict';
  if (types.object(router.stack))
    return router;
  async.forEach(router.stack, function(stackItem, _callback) {
    const route = stackItem.route;
    const path = replaceParams(route.path.toLowerCase());
    const method = route.stack[0].method.toUpperCase();
    routes.push({
      path: path,
      method: method
    });
    debug(util.format('Method: %s; RegEx: %s', method, path));
    _callback();
  });
  return router;
};


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * $Id: CastExpr.java,v 1.2.4.1 2005/09/12 10:06:35 pvedula Exp $
 */

package com.sun.org.apache.xalan.internal.xsltc.compiler;

import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.IF_ICMPNE;
import com.sun.org.apache.bcel.internal.generic.INVOKEINTERFACE;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.SIPUSH;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.BooleanType;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MultiHashtable;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.NodeType;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ResultTreeType;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError;
import com.sun.org.apache.xml.internal.dtm.Axis;

/**
 * @author Jacek Ambroziak
 * @author Santiago Pericas-Geertsen
 * @author Morten Jorgensen
 * @author Erwin Bolwidt <ejb@klomp.org>
 */
final class CastExpr extends Expression {
    private final Expression _left;

    /**
     * Legal conversions between internal types.
     */
    private static final MultiHashtable<Type, Type> InternalTypeMap = new MultiHashtable<>();

    static {
        // Possible type conversions between internal types
        InternalTypeMap.put(Type.Boolean, Type.Boolean);
        InternalTypeMap.put(Type.Boolean, Type.Real);
        InternalTypeMap.put(Type.Boolean, Type.String);
        InternalTypeMap.put(Type.Boolean, Type.Reference);
        InternalTypeMap.put(Type.Boolean, Type.Object);

        InternalTypeMap.put(Type.Real, Type.Real);
        InternalTypeMap.put(Type.Real, Type.Int);
        InternalTypeMap.put(Type.Real, Type.Boolean);
        InternalTypeMap.put(Type.Real, Type.String);
        InternalTypeMap.put(Type.Real, Type.Reference);
        InternalTypeMap.put(Type.Real, Type.Object);

        InternalTypeMap.put(Type.Int, Type.Int);
        InternalTypeMap.put(Type.Int, Type.Real);
        InternalTypeMap.put(Type.Int, Type.Boolean);
        InternalTypeMap.put(Type.Int, Type.String);
        InternalTypeMap.put(Type.Int, Type.Reference);
        InternalTypeMap.put(Type.Int, Type.Object);

        InternalTypeMap.put(Type.String, Type.String);
        InternalTypeMap.put(Type.String, Type.Boolean);
        InternalTypeMap.put(Type.String, Type.Real);
        InternalTypeMap.put(Type.String, Type.Reference);
        InternalTypeMap.put(Type.String, Type.Object);

        InternalTypeMap.put(Type.NodeSet, Type.NodeSet);
        InternalTypeMap.put(Type.NodeSet, Type.Boolean);
        InternalTypeMap.put(Type.NodeSet, Type.Real);
        InternalTypeMap.put(Type.NodeSet, Type.String);
        InternalTypeMap.put(Type.NodeSet, Type.Node);
        InternalTypeMap.put(Type.NodeSet, Type.Reference);
        InternalTypeMap.put(Type.NodeSet, Type.Object);

        InternalTypeMap.put(Type.Node, Type.Node);
        InternalTypeMap.put(Type.Node, Type.Boolean);
        InternalTypeMap.put(Type.Node, Type.Real);
        InternalTypeMap.put(Type.Node, Type.String);
        InternalTypeMap.put(Type.Node, Type.NodeSet);
        InternalTypeMap.put(Type.Node, Type.Reference);
        InternalTypeMap.put(Type.Node, Type.Object);

        InternalTypeMap.put(Type.ResultTree, Type.ResultTree);
        InternalTypeMap.put(Type.ResultTree, Type.Boolean);
        InternalTypeMap.put(Type.ResultTree, Type.Real);
        InternalTypeMap.put(Type.ResultTree, Type.String);
        InternalTypeMap.put(Type.ResultTree, Type.NodeSet);
        InternalTypeMap.put(Type.ResultTree, Type.Reference);
        InternalTypeMap.put(Type.ResultTree, Type.Object);

        InternalTypeMap.put(Type.Reference, Type.Reference);
        InternalTypeMap.put(Type.Reference, Type.Boolean);
        InternalTypeMap.put(Type.Reference, Type.Int);
        InternalTypeMap.put(Type.Reference, Type.Real);
        InternalTypeMap.put(Type.Reference, Type.String);
        InternalTypeMap.put(Type.Reference, Type.Node);
        InternalTypeMap.put(Type.Reference, Type.NodeSet);
        InternalTypeMap.put(Type.Reference, Type.ResultTree);
        InternalTypeMap.put(Type.Reference, Type.Object);

        InternalTypeMap.put(Type.Object, Type.String);

        InternalTypeMap.put(Type.Void, Type.String);

        InternalTypeMap.makeUnmodifiable();
    }

    private boolean _typeTest = false;

    /**
     * Construct a cast expression and check that the conversion is
     * valid by calling typeCheck().
     */
    public CastExpr(Expression left, Type type) throws TypeCheckError {
        _left = left;
        _type = type;           // use inherited field

        if ((_left instanceof Step) && (_type == Type.Boolean)) {
            Step step = (Step)_left;
            if ((step.getAxis() == Axis.SELF) && (step.getNodeType() != -1))
                _typeTest = true;
        }

        // check if conversion is valid
        setParser(left.getParser());
        setParent(left.getParent());
        left.setParent(this);
        typeCheck(left.getParser().getSymbolTable());
    }

    public Expression getExpr() {
        return _left;
    }

    /**
     * Returns true if this expressions contains a call to position(). This is
     * needed for context changes in node steps containing multiple predicates.
     */
    public boolean hasPositionCall() {
        return(_left.hasPositionCall());
    }

    public boolean hasLastCall() {
        return(_left.hasLastCall());
    }

    public String toString() {
        return "cast(" + _left + ", " + _type + ")";
    }

    /**
     * Type checking a cast expression amounts to verifying that the
     * type conversion is legal. Cast expressions are created during
     * type checking, but typeCheck() is usually not called on them.
     * As a result, this method is called from the constructor.
     */
    public Type typeCheck(SymbolTable stable) throws TypeCheckError {
        Type tleft = _left.getType();
        if (tleft == null) {
            tleft = _left.typeCheck(stable);
        }
        if (tleft instanceof NodeType) {
            tleft = Type.Node;  // multiple instances
        }
        else if (tleft instanceof ResultTreeType) {
            tleft = Type.ResultTree; // multiple instances
        }
        if (InternalTypeMap.maps(tleft, _type) != null) {
            return _type;
        }
        // throw new TypeCheckError(this);
        throw new TypeCheckError(new ErrorMsg(
            ErrorMsg.DATA_CONVERSION_ERR, tleft.toString(), _type.toString()));
    }

    public void translateDesynthesized(ClassGenerator classGen,
                                       MethodGenerator methodGen) {
        FlowList fl;
        final Type ltype = _left.getType();

        // This is a special case for the self:: axis. Instead of letting
        // the Step object create and iterator that we cast back to a single
        // node, we simply ask the DOM for the node type.
        if (_typeTest) {
            final ConstantPoolGen cpg = classGen.getConstantPool();
            final InstructionList il = methodGen.getInstructionList();

            final int idx = cpg.addInterfaceMethodref(DOM_INTF,
                                                      "getExpandedTypeID",
                                                      "(I)I");
            il.append(new SIPUSH((short)((Step)_left).getNodeType()));
            il.append(methodGen.loadDOM());
            il.append(methodGen.loadContextNode());
            il.append(new INVOKEINTERFACE(idx, 2));
            _falseList.add(il.append(new IF_ICMPNE(null)));
        }
        else {

            _left.translate(classGen, methodGen);
            if (_type != ltype) {
                _left.startIterator(classGen, methodGen);
                if (_type instanceof BooleanType) {
                    fl = ltype.translateToDesynthesized(classGen, methodGen,
                                                        _type);
                    if (fl != null) {
                        _falseList.append(fl);
                    }
                }
                else {
                    ltype.translateTo(classGen, methodGen, _type);
                }
            }
        }
    }

    public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
        final Type ltype = _left.getType();
        _left.translate(classGen, methodGen);
        if (_type.identicalTo(ltype) == false) {
            _left.startIterator(classGen, methodGen);
            ltype.translateTo(classGen, methodGen, _type);
        }
    }
}