text:
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// Composite Swagger for Recovery Services Backup Client
    /// </summary>
    public partial interface IRecoveryServicesBackupClient : System.IDisposable
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        System.Uri BaseUri { get; set; }

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; }

        /// <summary>
        /// Credentials needed for the client to connect to Azure.
        /// </summary>
        Microsoft.Rest.ServiceClientCredentials Credentials { get; }

        /// <summary>
        /// The subscription Id.
        /// </summary>
        string SubscriptionId { get; set; }

        /// <summary>
        /// Gets or sets the preferred language for the response.
        /// </summary>
        string AcceptLanguage { get; set; }

        /// <summary>
        /// Gets or sets the retry timeout in seconds for Long Running
        /// Operations. Default value is 30.
        /// </summary>
        int? LongRunningOperationRetryTimeout { get; set; }

        /// <summary>
        /// When set to true a unique x-ms-client-request-id value is
        /// generated and included in each request. Default is true.
        /// </summary>
        bool? GenerateClientRequestId { get; set; }

        /// <summary>
        /// Gets the IItemLevelRecoveryConnectionsOperations.
        /// </summary>
        IItemLevelRecoveryConnectionsOperations ItemLevelRecoveryConnections { get; }

        /// <summary>
        /// Gets the IRestoresOperations.
        /// </summary>
        IRestoresOperations Restores { get; }

        /// <summary>
        /// Gets the IProtectionPolicyOperationStatusesOperations.
        /// </summary>
        IProtectionPolicyOperationStatusesOperations ProtectionPolicyOperationStatuses { get; }

        /// <summary>
        /// Gets the IProtectionPolicyOperationResultsOperations.
        /// </summary>
        IProtectionPolicyOperationResultsOperations ProtectionPolicyOperationResults { get; }

        /// <summary>
        /// Gets the IProtectionPoliciesOperations.
        /// </summary>
        IProtectionPoliciesOperations ProtectionPolicies { get; }

        /// <summary>
        /// Gets the IProtectionContainerOperationResultsOperations.
        /// </summary>
        IProtectionContainerOperationResultsOperations ProtectionContainerOperationResults { get; }

        /// <summary>
        /// Gets the IProtectionContainerRefreshOperationResultsOperations.
        /// </summary>
        IProtectionContainerRefreshOperationResultsOperations ProtectionContainerRefreshOperationResults { get; }

        /// <summary>
        /// Gets the IProtectionContainersOperations.
        /// </summary>
        IProtectionContainersOperations ProtectionContainers { get; }

        /// <summary>
        /// Gets the IRecoveryPointsOperations.
        /// </summary>
        IRecoveryPointsOperations RecoveryPoints { get; }

        /// <summary>
        /// Gets the IBackupsOperations.
        /// </summary>
        IBackupsOperations Backups { get; }

        /// <summary>
        /// Gets the IProtectedItemOperationStatusesOperations.
        /// </summary>
        IProtectedItemOperationStatusesOperations ProtectedItemOperationStatuses { get; }

        /// <summary>
        /// Gets the IProtectedItemOperationResultsOperations.
        /// </summary>
        IProtectedItemOperationResultsOperations ProtectedItemOperationResults { get; }

        /// <summary>
        /// Gets the IProtectedItemsOperations.
        /// </summary>
        IProtectedItemsOperations ProtectedItems { get; }

        /// <summary>
        /// Gets the IProtectableItemsOperations.
        /// </summary>
        IProtectableItemsOperations ProtectableItems { get; }

        /// <summary>
        /// Gets the IExportJobsOperationResultsOperations.
        /// </summary>
        IExportJobsOperationResultsOperations ExportJobsOperationResults { get; }

        /// <summary>
        /// Gets the IJobOperationResultsOperations.
        /// </summary>
        IJobOperationResultsOperations JobOperationResults { get; }

        /// <summary>
        /// Gets the IJobsOperations.
        /// </summary>
        IJobsOperations Jobs { get; }

        /// <summary>
        /// Gets the IJobCancellationsOperations.
        /// </summary>
        IJobCancellationsOperations JobCancellations { get; }

        /// <summary>
        /// Gets the IJobDetailsOperations.
        /// </summary>
        IJobDetailsOperations JobDetails { get; }

        /// <summary>
        /// Gets the IBackupOperationStatusesOperations.
        /// </summary>
        IBackupOperationStatusesOperations BackupOperationStatuses { get; }

        /// <summary>
        /// Gets the IBackupOperationResultsOperations.
        /// </summary>
        IBackupOperationResultsOperations BackupOperationResults { get; }

        /// <summary>
        /// Gets the IBackupEnginesOperations.
        /// </summary>
        IBackupEnginesOperations BackupEngines { get; }

    }
}


text:
import {
    AffectationBaseItem
}
from './affectationbase';
//
class EtudAffectation extends AffectationBaseItem {
    constructor(oMap) {
        super(oMap);
        if ((oMap !== undefined) && (oMap !== null)) {
            if (oMap.etudiantid !== undefined) {
                this.etudiantid = oMap.etudiantid;
            }
        }
    }
    get type() {
        return 'etudaffectation';
    }
    //
    get etudiantid() {
        return (this._etudid !== undefined) ? this._etudid : null;
    }
    set etudiantid(s) {
        this._etudid = ((s !== undefined) && (s !== null) && (s.toString().trim().length > 0)) ? s : null;
    }
    get has_etudiantid() {
        return (this.etudiantid !== null);
    }
    get is_storeable() {
        return (super.is_storeable && this.has_etudiantid);
    }
    to_insert_map(oMap) {
        super.to_insert_map(oMap);
        if (this.has_etudiantid) {
            oMap.etudiantid = this.etudiantid;
        }
    } // to_insert_map
    get collection_name() {
        return 'etudaffectations';
    }
} // class EtudAffectation

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in De Wildeman, Fl. Bas- et Moyen-Congo 3(1): 14 (1909)

#### Original name
Physalospora clerodendri Syd.

### Remarks
null


text:
'''
Creates module name for an elm file.
'''

import json
import os.path
import re

def file_exists(path, filename):
    file_path = os.path.join(path, filename)
    return os.path.isfile(file_path)

def get_package_file(path):
    if file_exists(path, 'elm.json'):
        return os.path.join(path, 'elm.json')
    if file_exists(path, 'elm-package.json'):
        return os.path.join(path, 'elm-package.json')
    raise FileNotFoundError('Could not find elm.json or elm-package.json files.')

def get_source_directory_paths(project_root):
    filename = get_package_file(project_root)
    with open(filename) as elm_package_json:
        data = json.load(elm_package_json)
        return data['source-directories']

def has_package_file(path):
    return file_exists(path, 'elm.json') or file_exists(path, 'elm-package.json')

def walk_dir_until(start, test):
    current = start
    while (current != '/'):
        if test(current):
            return current
        else:
            current = os.path.dirname(current)

def find_project_root(module_path):
    return walk_dir_until(module_path, has_package_file)

def remove_elm_extension(file_path):
    if file_path.endswith('.elm'):
        return file_path[:-4]
    else:
        return file_path

def convert_path_to_dot_separated(string):
    slashless = re.sub(r'/', '.', string)
    leading_dotless = re.sub(r'^\.', '', slashless)
    return leading_dotless

def strip_source_directory(module_path, root_path, source_dirs):
    for source_dir in source_dirs:
        abs_source_dir = os.path.join(root_path, source_dir)
        index = module_path.find(abs_source_dir)
        if index == 0:
            length = len(abs_source_dir)
            return module_path[length:]
    # If this fails, just return the filename.
    return os.path.basename(module_path)

def build_orphan_module_name(module_path):
    filename = os.path.basename(module_path)
    return remove_elm_extension(filename)

def build_project_module_name(project_root, module_path):
    source_dirs = get_source_directory_paths(project_root)
    module_path_from_source = strip_source_directory(module_path, project_root, source_dirs)
    module_path_without_extension = remove_elm_extension(module_path_from_source)
    return convert_path_to_dot_separated(module_path_without_extension)

def convert_path_to_module_name(module_path):
    project_root = find_project_root(module_path)

    # If not in a project, fallback to using filename.
    if project_root == None:
        return build_orphan_module_name(module_path)

    return build_project_module_name(project_root, module_path)


text:
from shellbot import Command

class Next(Command):
    """
    Displays the next item to do

    >>>command = Next(store=store)
    >>>shell.load_command(command)

    """

    keyword = u'next'
    information_message = u'Display next item to do'

    def execute(self, bot, arguments=None, **kwargs):
        """
        Displays the next item to do
        """
        if self.engine.factory is None:
            raise AttributeError(u'Todo factory has not been initialised')

        item = self.engine.factory.read()
        if item is not None:
            bot.say(u"Coming next: {}".format(item))
        else:
            bot.say(u"Nothing to do yet.")


text:
@interface TLNetTypeTableViewController : UITableViewController

@end


text:
namespace android.util
{
	[global::MonoJavaBridge.JavaClass()]
	public partial class Base64 : java.lang.Object
	{
		internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
		protected Base64(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
		{
		}
		private static global::MonoJavaBridge.MethodId _m0;
		public static byte[] decode(java.lang.String arg0, int arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.util.Base64._m0.native == global::System.IntPtr.Zero)
				global::android.util.Base64._m0 = @__env.GetStaticMethodIDNoThrow(global::android.util.Base64.staticClass, "decode", "(Ljava/lang/String;I)[B");
			return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.util.Base64.staticClass, global::android.util.Base64._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as byte[];
		}
		private static global::MonoJavaBridge.MethodId _m1;
		public static byte[] decode(byte[] arg0, int arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.util.Base64._m1.native == global::System.IntPtr.Zero)
				global::android.util.Base64._m1 = @__env.GetStaticMethodIDNoThrow(global::android.util.Base64.staticClass, "decode", "([BI)[B");
			return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.util.Base64.staticClass, global::android.util.Base64._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as byte[];
		}
		private static global::MonoJavaBridge.MethodId _m2;
		public static byte[] decode(byte[] arg0, int arg1, int arg2, int arg3)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.util.Base64._m2.native == global::System.IntPtr.Zero)
				global::android.util.Base64._m2 = @__env.GetStaticMethodIDNoThrow(global::android.util.Base64.staticClass, "decode", "([BIII)[B");
			return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.util.Base64.staticClass, global::android.util.Base64._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as byte[];
		}
		private static global::MonoJavaBridge.MethodId _m3;
		public static byte[] encode(byte[] arg0, int arg1, int arg2, int arg3)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.util.Base64._m3.native == global::System.IntPtr.Zero)
				global::android.util.Base64._m3 = @__env.GetStaticMethodIDNoThrow(global::android.util.Base64.staticClass, "encode", "([BIII)[B");
			return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.util.Base64.staticClass, global::android.util.Base64._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as byte[];
		}
		private static global::MonoJavaBridge.MethodId _m4;
		public static byte[] encode(byte[] arg0, int arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.util.Base64._m4.native == global::System.IntPtr.Zero)
				global::android.util.Base64._m4 = @__env.GetStaticMethodIDNoThrow(global::android.util.Base64.staticClass, "encode", "([BI)[B");
			return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.util.Base64.staticClass, global::android.util.Base64._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as byte[];
		}
		private static global::MonoJavaBridge.MethodId _m5;
		public static global::java.lang.String encodeToString(byte[] arg0, int arg1)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.util.Base64._m5.native == global::System.IntPtr.Zero)
				global::android.util.Base64._m5 = @__env.GetStaticMethodIDNoThrow(global::android.util.Base64.staticClass, "encodeToString", "([BI)Ljava/lang/String;");
			return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.util.Base64.staticClass, global::android.util.Base64._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
		}
		private static global::MonoJavaBridge.MethodId _m6;
		public static global::java.lang.String encodeToString(byte[] arg0, int arg1, int arg2, int arg3)
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			if (global::android.util.Base64._m6.native == global::System.IntPtr.Zero)
				global::android.util.Base64._m6 = @__env.GetStaticMethodIDNoThrow(global::android.util.Base64.staticClass, "encodeToString", "([BIII)Ljava/lang/String;");
			return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(android.util.Base64.staticClass, global::android.util.Base64._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as java.lang.String;
		}
		public static int DEFAULT
		{
			get
			{
				return 0;
			}
		}
		public static int NO_PADDING
		{
			get
			{
				return 1;
			}
		}
		public static int NO_WRAP
		{
			get
			{
				return 2;
			}
		}
		public static int CRLF
		{
			get
			{
				return 4;
			}
		}
		public static int URL_SAFE
		{
			get
			{
				return 8;
			}
		}
		public static int NO_CLOSE
		{
			get
			{
				return 16;
			}
		}
		static Base64()
		{
			global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
			global::android.util.Base64.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/util/Base64"));
		}
	}
}


text:
{% extends "dashboard/base.html" %}
{% load babel %}
{% load dashboard %}
{% load i18n %}
{% load i18n_address_tags %}
{% load materializecss %}
{% load static %}
{% load status %}

{% block title %}
  {% trans "Fulfill" context "Dashboard order fulfillment" %} {{ order }} - {% trans "Orders" context "Dashboard orders list" %} - {{ block.super }}
{% endblock %}

{% block body_class %}body-orders{% endblock %}

{% block menu_orders_class %}active{% endblock %}

{% block header_menu %}
  {% url "dashboard:orders" as url %}
  {% include "dashboard/includes/_back_link.html" with url=url %}
{% endblock %}

{% block breadcrumbs %}

        {% trans "Orders" context "Dashboard orders list" %}

        <svg data-src="{% static "dashboard/images/arrow-left.svg" %}" fill="#fff" width="20px" height="20px" />

        {{ order }}

        {% trans "Fulfill" context "Dashboard order fulfillment" %}

{% endblock %}

{% block content %}

    <form role="form" class="card" method="post" novalidate>
    {% csrf_token %}
    {{ formset.management_form }}

              {% trans "Fulfill order" context "Fulfill order title" %}

                  {% trans "Item" context "Modal remove order line table header" %}

                  {% trans "Quantity" context "Modal remove order line table header" %}

              {% for line in unfulfilled_lines %}

                    {% if line.variant %}
                      {{ line.product_name }}
                    {% else %}
                      {{ line.product_name }}
                    {% endif %}

                      {% blocktrans trimmed with sku=line.product_sku context "Order table text" %}
                        SKU: {{ sku }}
                      {% endblocktrans %}

                    {% get_formset_form formset forloop.counter0 as line_form %}

                      <input id="{{ line_form.order_line.auto_id }}"
                             type="hidden"
                             name="{{ line_form.order_line.html_name }}"
                             required="{{ line_form.order_line.field.required }}"
                             value="{{ line_form.order_line.value }}">
                      <input id="{{ line_form.quantity.auto_id }}"
                             max="{{ line.quantity_unfulfilled }}"
                             min="0"
                             name="{{ line_form.quantity.html_name }}"
                             required="{{ line_form.quantity.field.required }}"
                             type="number"
                             value="{{ line_form.quantity.value }}">
                      {% blocktrans trimmed with quantity_unfulfilled=line.quantity_unfulfilled context "Fulfill order table quantity unfulfilled" %}
                        of {{ quantity_unfulfilled }}
                      {% endblocktrans %}

                      {% for error in line_form.quantity.errors %}

{{ error }}

                      {% endfor %}
                      {% for error in formset.non_form_errors %}

{{ error }}

                      {% endfor %}
                      {% if line_form.quantity.help_text %}

                          {{ line_form.quantity.field.help_text|safe }}

                      {% endif %}

              {% endfor %}

          {{ form.tracking_number|materializecss }}
          {% if form.send_mail %}
            {{ form.send_mail|materializecss }}
          {% endif %}

            {% trans "Cancel" context "Dashboard cancel action" %}

          <button type="submit" class="btn waves-effect">
            {% trans "Fulfill" context "Dashboard update action" %}
          </button>

    </form>

{% endblock %}


text:
package io.norberg.automatter.test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import com.google.common.collect.ImmutableList;
import io.norberg.automatter.AutoMatter;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.Test;

public class GenericsTest {

  @AutoMatter
  interface GenericFoobar<T1, T2 extends Collection<? extends T1>> {

    T1 field1();

    T2 field2();
  }

  @Test
  public void test_T1_Number_T2_ListOfInteger() {
    final Number value1 = 17;
    final List<Integer> value2 = ImmutableList.of(1, 2, 3);

    final GenericFoobarBuilder<Number, List<Integer>> builder = new GenericFoobarBuilder<>();

    builder.field1(value1);
    builder.field2(value2);

    // Verify builder getters
    final Number builderField1 = builder.field1();
    final Object builderField1b = builder.field1();
    final List<Integer> builderField2 = builder.field2();
    final List<? extends Number> builderField2b = builder.field2();
    assertThat(builderField1, is(value1));
    assertThat(builderField1b, Matchers.<Object>is(value1));
    assertThat(builderField2, is(value2));
    assertThat(builderField2b, Matchers.<List<? extends Number>>is(value2));

    // Verify value getters
    final GenericFoobar<Number, List<Integer>> foobar = builder.build();
    final Number field1 = foobar.field1();
    final Object field1b = foobar.field1();
    final List<? extends Integer> field2 = foobar.field2();
    final List<? extends Number> field2b = foobar.field2();
    assertThat(field1, is(value1));
    assertThat(field1b, is(value1));
    assertThat(field2, Matchers.<List<? extends Integer>>is(value2));
    assertThat(field2b, Matchers.<List<? extends Number>>is(value2));

    // Verify copy constructors
    final GenericFoobarBuilder<Number, List<Integer>> copied1 = GenericFoobarBuilder.from(builder);
    final GenericFoobarBuilder<Number, List<Integer>> copied2 = GenericFoobarBuilder.from(foobar);
    final GenericFoobarBuilder<Number, List<? extends Number>> copied3 =
        GenericFoobarBuilder.<Number, List<? extends Number>>from(builder);
    final GenericFoobarBuilder<Number, List<? extends Number>> copied4 =
        GenericFoobarBuilder.<Number, List<? extends Number>>from(foobar);
    final GenericFoobarBuilder<Object, List<? extends Serializable>> copied5 =
        GenericFoobarBuilder.<Object, List<? extends Serializable>>from(builder);
    final GenericFoobarBuilder<Object, List<? extends Serializable>> copied6 =
        GenericFoobarBuilder.<Object, List<? extends Serializable>>from(foobar);
  }

  @Test
  public void test_T1_Number_T2_ListOfIntegerSubclass() throws Exception {
    final Number value1 = 17;
    final List<? extends Integer> value2 = ImmutableList.of(1, 2, 3);

    final GenericFoobarBuilder<Number, List<? extends Integer>> builder =
        new GenericFoobarBuilder<>();

    builder.field1(value1);
    builder.field2(value2);

    // Verify builder getters
    final Number builderField1 = builder.field1();
    final Object builderField1b = builder.field1();
    final List<? extends Integer> builderField2 = builder.field2();
    final List<? extends Number> builderField2b = builder.field2();
    assertThat(builderField1, is(value1));
    assertThat(builderField1b, Matchers.<Object>is(value1));
    assertThat(builderField2, Matchers.<List<? extends Integer>>is(value2));
    assertThat(builderField2b, Matchers.<List<? extends Number>>is(value2));

    // Verify value getters
    final GenericFoobar<Number, List<? extends Integer>> foobar = builder.build();
    final Number field1 = foobar.field1();
    final Object field1b = foobar.field1();
    final List<? extends Integer> field2 = foobar.field2();
    final List<? extends Number> field2b = foobar.field2();
    assertThat(field1, is(value1));
    assertThat(field1b, is((Object) value1));
    assertThat(field2, Matchers.<List<? extends Integer>>is(value2));
    assertThat(field2b, Matchers.<List<? extends Number>>is(value2));

    // Verify that assigning a concretely typed list works
    final List<Integer> value2b = ImmutableList.of(5, 6, 7);
    builder.field2(value2b);
    assertThat(builder.field2(), Matchers.<List<? extends Integer>>is(value2b));
    assertThat(builder.build().field2(), Matchers.<List<? extends Integer>>is(value2b));

    // Verify copy constructors
    final GenericFoobarBuilder<Number, List<? extends Integer>> copied1 =
        GenericFoobarBuilder.from(builder);
    final GenericFoobarBuilder<Number, List<? extends Integer>> copied2 =
        GenericFoobarBuilder.from(foobar);
    final GenericFoobarBuilder<Number, List<? extends Number>> copied3 =
        GenericFoobarBuilder.<Number, List<? extends Number>>from(builder);
    final GenericFoobarBuilder<Number, List<? extends Number>> copied4 =
        GenericFoobarBuilder.<Number, List<? extends Number>>from(foobar);
    final GenericFoobarBuilder<Object, List<? extends Serializable>> copied5 =
        GenericFoobarBuilder.<Object, List<? extends Serializable>>from(builder);
    final GenericFoobarBuilder<Object, List<? extends Serializable>> copied6 =
        GenericFoobarBuilder.<Object, List<? extends Serializable>>from(foobar);
  }

  @Test
  public void test_T1_Number_T2_ListOfNumber() throws Exception {
    final Number value1 = 17;
    final List<Number> value2 = ImmutableList.<Number>of(1, 2, 3);

    final GenericFoobarBuilder<Number, List<Number>> builder = new GenericFoobarBuilder<>();

    builder.field1(value1);
    builder.field2(value2);

    // Verify builder getters
    final Number builderField1 = builder.field1();
    final Object builderField1b = builder.field1();
    final List<Number> builderField2 = builder.field2();
    final List<? extends Serializable> builderField2b = builder.field2();
    assertThat(builderField1, is(value1));
    assertThat(builderField1b, Matchers.<Object>is(value1));
    assertThat(builderField2, is(value2));
    assertThat(builderField2b, Matchers.<List<? extends Serializable>>is(value2));

    // Verify value getters
    final GenericFoobar<Number, List<Number>> foobar = builder.build();
    final Number field1 = foobar.field1();
    final Object field1b = foobar.field1();
    final List<Number> field2 = foobar.field2();
    final List<? extends Serializable> field2b = foobar.field2();
    assertThat(field1, is(value1));
    assertThat(field1b, is((Object) value1));
    assertThat(field2, is(value2));
    assertThat(field2b, Matchers.<List<? extends Serializable>>is(value2));

    // Verify copy constructors
    final GenericFoobarBuilder<Number, List<Number>> copied1 = GenericFoobarBuilder.from(builder);
    final GenericFoobarBuilder<Number, List<Number>> copied2 = GenericFoobarBuilder.from(foobar);
    final GenericFoobarBuilder<Number, List<? extends Number>> copied3 =
        GenericFoobarBuilder.<Number, List<? extends Number>>from(builder);
    final GenericFoobarBuilder<Number, List<? extends Number>> copied4 =
        GenericFoobarBuilder.<Number, List<? extends Number>>from(foobar);
    final GenericFoobarBuilder<Object, List<? extends Serializable>> copied5 =
        GenericFoobarBuilder.<Object, List<? extends Serializable>>from(builder);
    final GenericFoobarBuilder<Object, List<? extends Serializable>> copied6 =
        GenericFoobarBuilder.<Object, List<? extends Serializable>>from(foobar);
  }

  @Test
  public void test_T1_Number_T2_ListOfNumberSubclass() throws Exception {
    final Number value1 = 17;
    final List<? extends Number> value2 = ImmutableList.<Number>of(1, 2, 3);

    final GenericFoobarBuilder<Number, List<? extends Number>> builder =
        new GenericFoobarBuilder<>();

    builder.field1(value1);
    builder.field2(value2);

    // Verify builder getters
    final Number builderField1 = builder.field1();
    final Object builderField1b = builder.field1();
    final List<? extends Number> builderField2 = builder.field2();
    final List<? extends Serializable> builderField2b = builder.field2();
    assertThat(builderField1, is(value1));
    assertThat(builderField1b, is(value1));
    assertThat(builderField2, Matchers.<List<? extends Number>>is((value2)));
    assertThat(builderField2b, Matchers.<List<? extends Serializable>>is((value2)));

    // Verify value getters
    final GenericFoobar<Number, List<? extends Number>> foobar = builder.build();
    final Number field1 = foobar.field1();
    final Object field1b = foobar.field1();
    final List<? extends Number> field2 = foobar.field2();
    final List<? extends Serializable> field2b = foobar.field2();
    assertThat(field1, is(value1));
    assertThat(field1b, is(value1));
    assertThat(field2, Matchers.<List<? extends Number>>is(value2));
    assertThat(field2b, Matchers.<List<? extends Serializable>>is(value2));

    // Verify that assigning a list of a more specific type works
    final List<Integer> value2b = ImmutableList.of(5, 6, 7);
    builder.field2(value2b);
    assertThat(builder.field2(), Matchers.<List<? extends Number>>is(value2b));
    assertThat(builder.build().field2(), Matchers.<List<? extends Number>>is(value2b));

    // Verify copy constructors
    final GenericFoobarBuilder<Number, List<? extends Number>> copied1 =
        GenericFoobarBuilder.from(builder);
    final GenericFoobarBuilder<Number, List<? extends Number>> copied2 =
        GenericFoobarBuilder.from(foobar);
    final GenericFoobarBuilder<Object, List<? extends Serializable>> copied3 =
        GenericFoobarBuilder.<Object, List<? extends Serializable>>from(builder);
    final GenericFoobarBuilder<Object, List<? extends Serializable>> copied4 =
        GenericFoobarBuilder.<Object, List<? extends Serializable>>from(foobar);
    final GenericFoobarBuilder<Object, List<?>> copied5 =
        GenericFoobarBuilder.<Object, List<?>>from(builder);
    final GenericFoobarBuilder<Object, List<?>> copied6 =
        GenericFoobarBuilder.<Object, List<?>>from(foobar);
  }
}


text:
namespace TeamBuilder.Clients.Models.Account
{
    using System;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;

    using TeamBuilder.Clients.Common.Validation.Attributes;
    using TeamBuilder.Data.Models;

    public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [StringLength(30, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
        [RegularExpression("^([a-zA-Z0-9][_]?)*[a-zA-Z0-9]$", ErrorMessage = "Username may contain only letters, digits and \"_\" (can't appear in the beginning/end).")]
        public string Username { get; set; }

        [DisplayName("First Name")]
        public string FirstName { get; set; }

        [DisplayName("Last Name")]
        public string LastName { get; set; }

        [DisplayName("Birth Date")]
        [DataType(DataType.Date)]
        [DateRange(MinValue = "01/01/1900", MaxValue = "12/31/9999", ErrorMessage = "Date must be after {0}.")]
        public DateTime? BirthDate { get; set; }

        public Gender Gender { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }
}


text:
(function(){

  module.exports = {
    uniforms: {
      t0: { type: 't', value: null },
      t1: { type: 't', value: null }
    },
    vertexShader: require('../copy/copy.vertex.glsl'),
    fragmentShader: require('./add.fragment.glsl')
  };

})();


text:
//
//   Copyright 2015 Blu Age Corporation - Plano, Texas
//
//   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.
using System.Data;

namespace Summer.Batch.Data.Parameter
{
    /// <summary>
    /// Class providing and extension to facilitate adding parameters to command.
    /// </summary>
    public static class ParameterExtension
    {
        /// <summary>
        /// Adds a new parameter to a command
        /// </summary>
        /// <param name="command">the command to add a parameter to</param>
        /// <param name="name">the name of the parameter to add</param>
        /// <param name="value">(optional) the value of the parameter</param>
        public static void AddParameter(this IDbCommand command, string name, object value = null)
        {
            var parameter = command.CreateParameter();
            parameter.ParameterName = name;
            if (value != null)
            {
                parameter.Value = value;
            }
            command.Parameters.Add(parameter);
        }
    }
}


text:
import ts from 'typescript';

// **IMPORTANT** Changing the PLACEHOLDER_BLANK_LINE_COMMENT constant below is a
// breaking change and should probably never happen. This unique comment is
// documented in multiple locations, and users may have written tools that
// depend on it.

/**
 * The content of the comments generated by the preserveBlankLines transformer.
 *
 * Contains a fixed random string that is meaningless and serves only to make
 * the chance of collisions negligible.
 */
export const BLANK_LINE_PLACEHOLDER_COMMENT = `__BLANK_LINE_PLACEHOLDER_G1JVXUEBNCL6YN5NFE13MD1PT3H9OIHB__`;

/**
 * A regular expression that matches the comments generated by the
 * preserveBlankLines transformer, including the leading "//" and preceding
 * indentation.
 */
export const BLANK_LINE_PLACEHOLDER_COMMENT_REGEXP = new RegExp(
  `\\s*//${BLANK_LINE_PLACEHOLDER_COMMENT}`,
  'g'
);

/**
 * TypeScript transformer that replaces blank lines in the original source with
 * a unique comment, allowing original line formatting to be preserved after
 * transform using a simple search-and-replace.
 *
 * For example, given:
 *
 *   import 'foo';
 *
 *   class Foo {
 *     foo() {}
 *
 *     bar() {}
 *   }
 *
 * Produces:
 *
 *   import 'foo';
 *   //__BLANK_LINE_PLACEHOLDER_G1JVXUEBNCL6YN5NFE13MD1PT3H9OIHB__
 *   class Foo {
 *     foo() {}
 *     //__BLANK_LINE_PLACEHOLDER_G1JVXUEBNCL6YN5NFE13MD1PT3H9OIHB__
 *     bar() {}
 *   }
 *
 * These placeholder comments can be replaced with newlines after transform with
 * the `BLANK_LINE_PLACEHOLDER_COMMENT_REGEXP` regexp, or with any equivalent
 * search-and-replace operation for the comment style shown above.
 */
export function preserveBlankLinesTransformer(): ts.TransformerFactory<ts.SourceFile> {
  return (context) => {
    return (file) => {
      const sourceFileText = file.getFullText();
      if (!sourceFileText) {
        return file;
      }
      // SourceFile > SyntaxList > first child
      const firstChild = file.getChildAt(0).getChildAt(0);
      const transformer = new PreserveBlankLinesTransformer(
        sourceFileText,
        firstChild
      );
      const visit = (node: ts.Node): ts.VisitResult<ts.Node> => {
        transformer.addComments(node);
        return ts.visitEachChild(node, visit, context);
      };
      return ts.visitNode(file, visit);
    };
  };
}

const BLANK_LINE = Symbol();

/**
 * We create one of these per file.
 */
class PreserveBlankLinesTransformer {
  private readonly _sourceFileText: string;
  private readonly _firstChild: ts.Node;
  private readonly _handledTriviaRanges = new Set<string>();
  private readonly _deletedTriviaRanges = new Set<string>();

  constructor(sourceFileText: string, firstChild: ts.Node) {
    this._sourceFileText = sourceFileText;
    this._firstChild = firstChild;
  }

  addComments(node: ts.Node): void {
    if (ts.isSourceFile(node)) {
      // Source files get the same trivia as the first child, but it is not
      // possible to remove existing trivia nor add synthetic comments to a
      // source file (it has no effect). Skip it so that we handle leading
      // trivia from the first child instead.
      return;
    }

    // The same trivia range can be associated with multiple AST nodes. For
    // example, `let x=0` is represented as VariableStatement >
    // VariableDeclarationList, where both have the same trivia range. We must
    // only handle each trivia range once, otherwise we'll emit duplicate
    // comments.
    const triviaRangeKey = `${node.getFullStart()}:${node.getStart()}`;
    if (this._handledTriviaRanges.has(triviaRangeKey)) {
      // If we delete a trivia range from one node, but not the other, the
      // trivia will still be emitted. So, we must delete the range from every
      // node it is associated with.
      if (this._deletedTriviaRanges.has(triviaRangeKey)) {
        deleteTriviaRange(node);
      }
      return;
    }
    this._handledTriviaRanges.add(triviaRangeKey);

    // Multiple leading comments can be associated with a node, and there can be
    // blank lines before or after any of them.
    const newComments: Array<ts.CommentRange | typeof BLANK_LINE> = [];
    const existingComments =
      ts.getLeadingCommentRanges(this._sourceFileText, node.getFullStart()) ??
      [];
    let anyBlankLinesToAdd = false;
    let anyExistingCommentsToResynthesize = false;

    // Each of the existing comments.
    let previousRegionEnd = node.getFullStart();
    for (const comment of existingComments) {
      if (node !== this._firstChild) {
        const leadingWhitespace = this._sourceFileText.slice(
          previousRegionEnd,
          comment.pos
        );
        for (let i = 0; i < countBlankLines(leadingWhitespace); i++) {
          newComments.push(BLANK_LINE);
          anyBlankLinesToAdd = true;
        }
        newComments.push(comment);
        anyExistingCommentsToResynthesize = true;
      }
      // If this is the first child node, we are restricted in what we can do,
      // because the source file node has the same trivia as the first child,
      // and there is no way to prevent it from being emitted (the
      // `deleteTrivaRange` trick doesn't work). This means we can't preserve
      // blank lines before or between leading comments at start of the file --
      // but we can at least preserve blank lines after those leading comments.
      previousRegionEnd = comment.end;
    }

    // The remaining trivia after the last existing comment (or the entire
    // trivia if there weren't any existing comments).
    if (previousRegionEnd < node.getStart()) {
      const postCommentText = this._sourceFileText.slice(
        previousRegionEnd,
        node.getStart()
      );
      for (let i = 0; i < countBlankLines(postCommentText); i++) {
        newComments.push(BLANK_LINE);
        anyBlankLinesToAdd = true;
      }
    }

    if (!anyBlankLinesToAdd) {
      return;
    }

    // The TypeScript APIs around manipulating comments are a bit crude.
    // Original source comments are represented differently to "synthetic"
    // comments (ones created during a transform). We don't have the ability to
    // insert a comment before or between existing source comments, so we
    // instead delete all of the source trivia, and then reconstruct all of the
    // original comments + new blank line comments as synthetic comments.
    if (anyExistingCommentsToResynthesize) {
      deleteTriviaRange(node);
      this._deletedTriviaRanges.add(triviaRangeKey);
    }

    for (const comment of newComments) {
      if (comment === BLANK_LINE) {
        ts.addSyntheticLeadingComment(
          node,
          ts.SyntaxKind.SingleLineCommentTrivia,
          BLANK_LINE_PLACEHOLDER_COMMENT,
          /* trailing newline */ true
        );
      } else {
        const commentText = this._sourceFileText.slice(
          comment.pos + 2, // trim the leading "//" or "/*"
          comment.kind === ts.SyntaxKind.MultiLineCommentTrivia
            ? comment.end - 2 // trim the trailing "*/"
            : comment.end
        );
        ts.addSyntheticLeadingComment(
          node,
          comment.kind,
          commentText,
          comment.hasTrailingNewLine
        );
      }
    }
  }
}

const countBlankLines = (str: string) => {
  let newLines = 0;
  for (const char of str) {
    if (char === '\n') {
      newLines++;
    }
  }
  return Math.max(0, newLines - 1);
};

/**
 * A trick for removing original source trivia from the AST.
 */
const deleteTriviaRange = (node: ts.Node) =>
  ts.setTextRange(node, {pos: node.getStart(), end: node.getEnd()});


text:
<ion-view hide-back-button="true">
	<ion-nav-title>
		{{navTitle}}
	</ion-nav-title>
	</ion-nav-bar>
	<ion-content class="ahjo-bg has-header">
		<ion-list>

						Rajaus: {{filterData.filterSelect}}

					<select name='filterSelect' id='filterSelect' ng-model="filterData.filterSelect">
						<option ng-repeat="f in filterData.filterOpts" value="{{f.id}}">{{f.name}}</option>
					</select>

				<ion-item ng-repeat="i in meetings" class="item-text-wrap ahjoitem">

						{{i.date}} | {{i.policymaker_name}}

				</ion-item>
			</div
		</ion-list>
	</ion-content>
</ion-view>


text:
'use strict';
goog.provide('framework.referencerenderer.rrDefs');

goog.scope(function() {

var rrDefs = framework.referencerenderer.rrDefs;

/**
 * @enum
 */
rrDefs.FaceType = {
    FACETYPE_FRONT: 0,
    FACETYPE_BACK: 1
};

/**
 * @enum
 */
rrDefs.IndexType = {
    INDEXTYPE_UINT8: 0,
    INDEXTYPE_UINT16: 1,
    INDEXTYPE_UINT32: 2
};

/**
 * @enum
 */
rrDefs.ProvokingVertex = {
    PROVOKINGVERTEX_FIRST: 1,
    PROVOKINGVERTEX_LAST: 2 // \note valid value, "last vertex", not last of enum
};

/**
 * @interface
 */
rrDefs.Sampler = function() {};

/**
 * @param {Array<number>} pos
 * @param {number=} lod
 * @return {Array<number>}
 */
rrDefs.Sampler.prototype.sample = function(pos, lod) {};

/**
 * @param {Array<Array<number>>} packetTexcoords 4 coordinates
 * @param {number} lodBias
 * @return {Array<Array<number>>} 4 vec4 samples
 */
rrDefs.Sampler.prototype.sample4 = function(packetTexcoords, lodBias) {};

});


text:
require 'spec_helper'
require 'tmpdir'

describe Chef::Provider::Directory do
  let(:tmp_dir) { Dir.mktmpdir }
  let(:new_resource) { Chef::Resource::Directory.new(tmp_dir) }
  let(:node) { Chef::Node.new }
  let(:events) { Chef::EventDispatch::Dispatcher.new }
  let(:run_context) { Chef::RunContext.new(node, {}, events) }
  let(:directory) { Chef::Provider::Directory.new(new_resource, run_context) }

  describe "#load_current_resource" do
    describe "scanning file security metadata"
    describe "on unix", unix_only: true do
      describe "when the directory exists" do
        let(:dir_stat) { File::Stat.new(tmp_dir) }
        let(:expected_uid) { dir_stat.uid }
        let(:expected_gid) { dir_stat.gid }
        let(:expected_mode) { "0%o" % ( dir_stat.mode & 007777 ) }
        let(:expected_pwnam) { Etc.getpwuid(expected_uid).name }
        let(:expected_grnam) { Etc.getgrgid(expected_gid).name }

        it "describes the access mode as a String of octal integers" do
          directory.load_current_resource
          expect(directory.current_resource.mode).to eq(expected_mode)
        end

        it "when the new_resource.owner is numeric, describes the owner as a numeric uid" do
          new_resource.owner(500)
          directory.load_current_resource
          expect(directory.current_resource.owner).to eql(expected_uid)
        end

        it "when the new_resource.group is numeric, describes the group as a numeric gid" do
          new_resource.group(500)
          directory.load_current_resource
          expect(directory.current_resource.group).to eql(expected_gid)
        end

        it "when the new_resource.owner is a string, describes the owner as a string" do
          new_resource.owner("foo")
          directory.load_current_resource
          expect(directory.current_resource.owner).to eql(expected_pwnam)
        end

        it "when the new_resource.group is a string, describes the group as a string" do
          new_resource.group("bar")
          directory.load_current_resource
          expect(directory.current_resource.group).to eql(expected_grnam)
        end
      end
    end

    describe "on windows", windows_only: true do
      describe "when the directory exists" do
        it "the mode is always nil" do
          directory.load_current_resource
          expect(directory.current_resource.mode).to be nil
        end

        it "the owner is always nil" do
          directory.load_current_resource
          expect(directory.current_resource.owner).to be nil
        end

        it "the group is always nil" do
          directory.load_current_resource
          expect(directory.current_resource.group).to be nil
        end

        it "rights are always nil (incorrectly)" do
          directory.load_current_resource
          expect(directory.current_resource.rights).to be nil
        end

        it "inherits is always nil (incorrectly)" do
          directory.load_current_resource
          expect(directory.current_resource.inherits).to be nil
        end
      end
    end

    describe "when the directory does not exist" do
      before do
        FileUtils.rmdir tmp_dir
      end

      it "sets the mode, group and owner to nil" do
        directory.load_current_resource
        expect(directory.current_resource.mode).to eq(nil)
        expect(directory.current_resource.group).to eq(nil)
        expect(directory.current_resource.owner).to eq(nil)
      end
    end

  end

  describe "#define_resource_requirements" do
    describe "on unix", unix_only: true do
      it "raises an exception if the user does not exist" do
        new_resource.owner("arglebargle_iv")
        expect(Etc).to receive(:getpwnam).with("arglebargle_iv").and_raise(ArgumentError)
        directory.action = :create
        directory.load_current_resource
        expect(directory.access_controls).to receive(:define_resource_requirements).and_call_original
        directory.define_resource_requirements
        expect { directory.process_resource_requirements }.to raise_error(ArgumentError)
      end

      it "raises an exception if the group does not exist" do
        new_resource.group("arglebargle_iv")
        expect(Etc).to receive(:getgrnam).with("arglebargle_iv").and_raise(ArgumentError)
        directory.action = :create
        directory.load_current_resource
        expect(directory.access_controls).to receive(:define_resource_requirements).and_call_original
        directory.define_resource_requirements
        expect { directory.process_resource_requirements }.to raise_error(ArgumentError)
      end
    end
  end

  describe "#run_action(:create)" do
    describe "when the directory exists" do
      it "does not create the directory" do
        expect(Dir).not_to receive(:mkdir).with(new_resource.path)
        directory.run_action(:create)
      end

      it "should not set the resource as updated" do
        directory.run_action(:create)
        expect(new_resource).not_to be_updated
      end
    end

    describe "when the directory does not exist" do
      before do
        FileUtils.rmdir tmp_dir
      end

      it "creates the directory" do
        directory.run_action(:create)
        expect(File.exist?(tmp_dir)).to be true
      end

      it "sets the new resource as updated" do
        directory.run_action(:create)
        expect(new_resource).to be_updated
      end
    end

    describe "when the parent directory does not exist" do
      before do
        new_resource.path "#{tmp_dir}/foobar"
        FileUtils.rmdir tmp_dir
      end

      it "raises an exception when recursive is false" do
        new_resource.recursive false
        expect { directory.run_action(:create) }.to raise_error(Chef::Exceptions::EnclosingDirectoryDoesNotExist)
      end

      it "creates the directories when recursive is true" do
        new_resource.recursive true
        directory.run_action(:create)
        expect(new_resource).to be_updated
        expect(File.exist?("#{tmp_dir}/foobar")).to be true
      end

      it "raises an exception when the parent directory is a file and recursive is true" do
        FileUtils.touch tmp_dir
        new_resource.recursive true
        expect { directory.run_action(:create) }.to raise_error
      end

      it "raises the right exception when the parent directory is a file and recursive is true" do
        pending "this seems to return the wrong error"  # FIXME
        FileUtils.touch tmp_dir
        new_resource.recursive true
        expect { directory.run_action(:create) }.to raise_error(Chef::Exceptions::EnclosingDirectoryDoesNotExist)
      end
    end
  end

  describe "#run_action(:create)" do
    describe "when the directory exists" do
      it "deletes the directory" do
        directory.run_action(:delete)
        expect(File.exist?(tmp_dir)).to be false
      end

      it "sets the new resource as updated" do
        directory.run_action(:delete)
        expect(new_resource).to be_updated
      end
    end

    describe "when the directory does not exist" do
      before do
        FileUtils.rmdir tmp_dir
      end

      it "does not delete the directory" do
        expect(Dir).not_to receive(:delete).with(new_resource.path)
        directory.run_action(:delete)
      end

      it "sets the new resource as updated" do
        directory.run_action(:delete)
        expect(new_resource).not_to be_updated
      end
    end

    describe "when the directory is not writable" do
      before do
        allow(Chef::FileAccessControl).to receive(:writable?).and_return(false)
      end

      it "cannot delete it and raises an exception" do
        expect {  directory.run_action(:delete) }.to raise_error(RuntimeError)
      end
    end

    describe "when the target directory is a file" do
      before do
        FileUtils.rmdir tmp_dir
        FileUtils.touch tmp_dir
      end

      it "cannot delete it and raises an exception" do
        expect {  directory.run_action(:delete) }.to raise_error(RuntimeError)
      end
    end
  end
end


text:
/*************************************************************************/
/*  audio_stream_player_3d.h                                             */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* 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.                */
/*************************************************************************/

#ifndef AUDIO_STREAM_PLAYER_3D_H
#define AUDIO_STREAM_PLAYER_3D_H

#include "scene/3d/spatial.h"
#include "scene/3d/spatial_velocity_tracker.h"
#include "servers/audio/audio_filter_sw.h"
#include "servers/audio/audio_stream.h"
#include "servers/audio_server.h"

class Camera;
class AudioStreamPlayer3D : public Spatial {

	GDCLASS(AudioStreamPlayer3D, Spatial)
public:
	enum AttenuationModel {
		ATTENUATION_INVERSE_DISTANCE,
		ATTENUATION_INVERSE_SQUARE_DISTANCE,
		ATTENUATION_LOGARITHMIC,
	};

	enum OutOfRangeMode {
		OUT_OF_RANGE_MIX,
		OUT_OF_RANGE_PAUSE,
	};

	enum DopplerTracking {
		DOPPLER_TRACKING_DISABLED,
		DOPPLER_TRACKING_IDLE_STEP,
		DOPPLER_TRACKING_PHYSICS_STEP
	};

private:
	enum {
		MAX_OUTPUTS = 8,
		MAX_INTERSECT_AREAS = 32

	};

	struct Output {

		AudioFilterSW filter;
		AudioFilterSW::Processor filter_process[6];
		AudioFrame vol[4];
		float filter_gain;
		float pitch_scale;
		int bus_index;
		int reverb_bus_index;
		AudioFrame reverb_vol[4];
		Viewport *viewport; //pointer only used for reference to previous mix

		Output() {
			filter_gain = 0;
			viewport = NULL;
			reverb_bus_index = -1;
			bus_index = -1;
		}
	};

	Output outputs[MAX_OUTPUTS];
	volatile int output_count;
	volatile bool output_ready;

	//these are used by audio thread to have a reference of previous volumes (for ramping volume and avoiding clicks)
	Output prev_outputs[MAX_OUTPUTS];
	int prev_output_count;

	Ref<AudioStreamPlayback> stream_playback;
	Ref<AudioStream> stream;
	Vector<AudioFrame> mix_buffer;

	volatile float setseek;
	volatile bool active;
	volatile float setplay;

	AttenuationModel attenuation_model;
	float unit_db;
	float unit_size;
	float max_db;
	float pitch_scale;
	bool autoplay;
	bool stream_paused;
	bool stream_paused_fade_in;
	bool stream_paused_fade_out;
	StringName bus;

	void _mix_audio();
	static void _mix_audios(void *self) { reinterpret_cast<AudioStreamPlayer3D *>(self)->_mix_audio(); }

	void _set_playing(bool p_enable);
	bool _is_active() const;

	void _bus_layout_changed();

	uint32_t area_mask;

	bool emission_angle_enabled;
	float emission_angle;
	float emission_angle_filter_attenuation_db;
	float attenuation_filter_cutoff_hz;
	float attenuation_filter_db;

	float max_distance;

	Ref<SpatialVelocityTracker> velocity_tracker;

	DopplerTracking doppler_tracking;

	OutOfRangeMode out_of_range_mode;

	float _get_attenuation_db(float p_distance) const;

protected:
	void _validate_property(PropertyInfo &property) const;
	void _notification(int p_what);
	static void _bind_methods();

public:
	void set_stream(Ref<AudioStream> p_stream);
	Ref<AudioStream> get_stream() const;

	void set_unit_db(float p_volume);
	float get_unit_db() const;

	void set_unit_size(float p_volume);
	float get_unit_size() const;

	void set_max_db(float p_boost);
	float get_max_db() const;

	void set_pitch_scale(float p_pitch_scale);
	float get_pitch_scale() const;

	void play(float p_from_pos = 0.0);
	void seek(float p_seconds);
	void stop();
	bool is_playing() const;
	float get_playback_position();

	void set_bus(const StringName &p_bus);
	StringName get_bus() const;

	void set_autoplay(bool p_enable);
	bool is_autoplay_enabled();

	void set_max_distance(float p_metres);
	float get_max_distance() const;

	void set_area_mask(uint32_t p_mask);
	uint32_t get_area_mask() const;

	void set_emission_angle_enabled(bool p_enable);
	bool is_emission_angle_enabled() const;

	void set_emission_angle(float p_angle);
	float get_emission_angle() const;

	void set_emission_angle_filter_attenuation_db(float p_angle_attenuation_db);
	float get_emission_angle_filter_attenuation_db() const;

	void set_attenuation_filter_cutoff_hz(float p_hz);
	float get_attenuation_filter_cutoff_hz() const;

	void set_attenuation_filter_db(float p_db);
	float get_attenuation_filter_db() const;

	void set_attenuation_model(AttenuationModel p_model);
	AttenuationModel get_attenuation_model() const;

	void set_out_of_range_mode(OutOfRangeMode p_mode);
	OutOfRangeMode get_out_of_range_mode() const;

	void set_doppler_tracking(DopplerTracking p_tracking);
	DopplerTracking get_doppler_tracking() const;

	void set_stream_paused(bool p_pause);
	bool get_stream_paused() const;

	AudioStreamPlayer3D();
	~AudioStreamPlayer3D();
};

VARIANT_ENUM_CAST(AudioStreamPlayer3D::AttenuationModel)
VARIANT_ENUM_CAST(AudioStreamPlayer3D::OutOfRangeMode)
VARIANT_ENUM_CAST(AudioStreamPlayer3D::DopplerTracking)
#endif // AUDIO_STREAM_PLAYER_3D_H


text:
class CefTranslatorTestHandlerCToCpp
    : public CefCToCpp<CefTranslatorTestHandlerCToCpp, CefTranslatorTestHandler,
        cef_translator_test_handler_t> {
 public:
  CefTranslatorTestHandlerCToCpp();

  // CefTranslatorTestHandler methods.
  int GetValue() override;
};

#endif  // BUILDING_CEF_SHARED
#endif  // CEF_LIBCEF_DLL_CTOCPP_TEST_TRANSLATOR_TEST_HANDLER_CTOCPP_H_


text:
package com.vsked.auth.service;

import com.vsked.auth.entity.User;

public interface UserService {
    void save(User user);

    User findByUsername(String username);
}


text:
from setuptools import setup

with open('parxiv.py') as f:
    for line in f:
        if line.startswith('__version__'):
            version = eval(line.split('=')[-1])

long_description = open('README.md').read()

setup(name='parxiv',
      license='MIT',
      version=version,
      description='Generate a clean directory for uploading to Arxiv (clean-latex-to-arxiv).',
      long_description=long_description,
      author='Luke Olson',
      author_email='luke.olson@gmail.com',
      url='https://github.com/lukeolson/parxiv',
      py_modules=['parxiv'],
      install_requires=['ply'],
      entry_points={'console_scripts': ['parxiv = parxiv:main']},
      classifiers=['Environment :: Console',
                   'License :: OSI Approved :: MIT License',
                   'Programming Language :: Python',
                   'Programming Language :: Python :: 2',
                   'Programming Language :: Python :: 3',
                   'Topic :: Utilities'])


text:
phenotype('"Auxotrophies, carbon and"').
phenotype('Carbohydrate and lipid biosynthesis defects').
phenotype('Cell cycle defects').
phenotype('Cell morphology and organelle mutants').
phenotype('Conditional phenotypes').
phenotype('Mating and sporulation defects').
phenotype('Nucleic acid metabolism defects').
phenotype('Sensitivity to aminoacid analogs and other drugs').
phenotype('Sensitivity to antibiotics').
phenotype('Sensitivity to immunosuppressants').
phenotype('Stress response defects').


text:
package org.zstack.core.salt;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.DirectoryWalker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.MessageSafe;
import org.zstack.header.AbstractService;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.message.Message;
import org.zstack.utils.DebugUtils;
import org.zstack.utils.IptablesUtils;
import org.zstack.utils.ShellUtils;
import org.zstack.utils.Utils;
import org.zstack.utils.data.StringTemplate;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.path.PathUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 */
public class SaltFacadeImpl extends AbstractService implements SaltFacade {
    private static final CLogger logger = Utils.getLogger(SaltFacadeImpl.class);

    @Autowired
    private CloudBus bus;

    private int masterMaxOpenFiles = 1024;
    private int masterWorkerThreads = 10;
    private String masterFileRoots = "/srv/salt";

    private String saltBootstrapScriptPath;
    private String saltMinionConfPath;
    private Map<String, Boolean> moduleChanges = new HashMap<String, Boolean>();

    @Override
    @MessageSafe
    public void handleMessage(Message msg) {
        bus.dealWithUnknownMessage(msg);
    }

    @Override
    public String getId() {
        return bus.makeLocalServiceId(SaltConstant.SERVICE_ID);
    }

    private boolean deployFile(File src, File dst) throws IOException {
        if (dst.exists() && PathUtil.compareFileByMd5(src, dst)) {
            logger.debug(String.format("MD5 of src file[%s] and dst file[%s] are the same, no need to deploy", src.getAbsolutePath(), dst.getAbsolutePath()));
            return false;
        }

        FileUtils.copyFile(src, dst);
        logger.debug(String.format("deployed src file[%s] to dst file[%s]", src.getAbsolutePath(), dst.getAbsolutePath()));
        return true;
    }

    private File rewriteMasterConfFile() throws IOException {
        File masterConfTmpt = PathUtil.findFileOnClassPath(PathUtil.join("salt", SaltConstant.MASTER_CONF_NAME), true);

        Map<String, String> map = new HashMap<String, String>();
        map.put("maxOpenFiles", String.valueOf(masterMaxOpenFiles));
        map.put("workerThreads", String.valueOf(masterWorkerThreads));

        String srcConf = FileUtils.readFileToString(masterConfTmpt);
        String conf = StringTemplate.subsititute(srcConf, map);
        File masterConf = File.createTempFile("zstack-salt", "master");
        FileUtils.write(masterConf, conf);

        return masterConf;
    }

    private void prepareSaltMaster() throws IOException {
        File srcMasterConf = rewriteMasterConfFile();
        try {
            IptablesUtils.insertRuleToFilterTable("-A INPUT -p tcp -m state --state NEW -m tcp --dport 4505 -j ACCEPT");
            IptablesUtils.insertRuleToFilterTable("-A INPUT -p tcp -m state --state NEW -m tcp --dport 4506 -j ACCEPT");

            File dstMasterConf = new File(PathUtil.join(SaltConstant.SALT_CONF_HOME, SaltConstant.MASTER_CONF_NAME));
            if (deployFile(srcMasterConf, dstMasterConf)) {
                ShellUtils.run("service salt-master restart");
            }
        } finally {
            srcMasterConf.delete();
        }
    }

    private void deployCommonStates() {
        if (CoreGlobalProperty.UNIT_TEST_ON) {
            return;
        }

        deployModule("salt/zstacklib");
    }

    private void prepareJinjaVariables() throws IOException {
        Properties props = System.getProperties();
        Map<String, String> envVars = new HashMap<String, String>();
        Map<String, String> vars = new HashMap<String, String>();
        for (String key : props.stringPropertyNames()) {
            String val = props.getProperty(key);
            if (key.startsWith("salt.env.")) {
                String[] tuples = key.split("\\.");
                if (tuples.length != 3) {
                    throw new IllegalArgumentException(String.format("invalid salt environment variable[%s], it must be in form of 'salt.env.variableName'", key));
                }
                String envName = tuples[2];
                envVars.put(envName, val);
            } else if (key.startsWith("salt.var.")) {
                String[] tuples = key.split("\\.");
                if (tuples.length != 3) {
                    throw new IllegalArgumentException(String.format("invalid salt variable[%s], it must be in form of 'salt.var.variableName'", key));
                }
                String varName = tuples[2];
                vars.put(varName, val);
            }
        }

        String varModulePath = PathUtil.join(masterFileRoots, "variables");
        File varModule = new File(varModulePath);
        if (!varModule.exists()) {
            varModule.mkdirs();
        }

        StringBuilder sb = new StringBuilder();
        if (!envVars.isEmpty()) {
            List<String> dicts = new ArrayList<String>();
            for (Map.Entry<String, String> e : envVars.entrySet()) {
                dicts.add(String.format("'%s':'%s'", e.getKey(), e.getValue()));
            }
            sb.append(String.format("{%% set cmd_env = {%s} %%}\n", StringUtils.join(dicts, ",")));
        }

        if (!vars.isEmpty()) {
            for (Map.Entry<String, String> e : vars.entrySet()) {
                sb.append(String.format("{%% set %s = '%s' %%}\n", e.getKey(), e.getValue()));
            }
        }

        File varFile = new File(PathUtil.join(varModulePath, "var.sls"));
        FileUtils.writeStringToFile(varFile, sb.toString());
    }

    @Override
    public boolean start() {
        try {
            prepareSaltMaster();
            prepareJinjaVariables();
        } catch (IOException e) {
            throw new CloudRuntimeException(e);
        }

        saltBootstrapScriptPath = PathUtil.findFileOnClassPath("salt/salt-bootstrap.sh", true).getAbsolutePath();
        saltMinionConfPath = PathUtil.findFileOnClassPath(String.format("salt/%s", SaltConstant.MINION_CONF_NAME), true).getAbsolutePath();

        deployCommonStates();
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public void setMasterMaxOpenFiles(int masterMaxOpenFiles) {
        this.masterMaxOpenFiles = masterMaxOpenFiles;
    }

    public void setMasterWorkerThreads(int masterWorkerThreads) {
        this.masterWorkerThreads = masterWorkerThreads;
    }

    @SuppressWarnings("rawtypes")
    public class ModuleWalker extends DirectoryWalker {
        @Override
        protected void handleFile(File file, int depth, Collection results) {
            results.add(file);
        }

        public void doWalk(File start, Collection result) throws IOException {
            walk(start, result);
        }
    }

    private boolean isNeedToDeploy(String moduleName, String modulePath) throws IOException {
        boolean needed = false;

        try {
            String destModulePath = PathUtil.join(this.masterFileRoots, moduleName);
            File dest = new File(destModulePath);
            if (!dest.exists()) {
                logger.debug(String.format("%s is not existing, need to deploy salt module[%s]", destModulePath, moduleName));
                needed = true;
                return needed;
            }
            List<File> destFiles = new ArrayList<File>(20);
            ModuleWalker walker = new ModuleWalker();
            walker.doWalk(dest, destFiles);

            List<File> srcFiles = new ArrayList<File>(20);
            walker = new ModuleWalker();
            File src = new File(modulePath);
            walker.doWalk(src, srcFiles);
            if (srcFiles.size() != destFiles.size()) {
                logger.debug(String.format("%s has %s files, %s has %s files, need to deploy salt module[%s]", destModulePath, destFiles.size(), modulePath,
                        srcFiles.size(), moduleName));
                needed = true;
                return needed;
            }

            Map<String, String> srcMd5sum = new HashMap<String, String>(srcFiles.size());
            for (File f : srcFiles) {
                FileInputStream fis = new FileInputStream(f);
                String md5 = DigestUtils.md5Hex(fis);
                srcMd5sum.put(f.getName(), md5);
            }
            Map<String, String> destMd5sum = new HashMap<String, String>(destFiles.size());
            for (File f : destFiles) {
                FileInputStream fis = new FileInputStream(f);
                String md5 = DigestUtils.md5Hex(fis);
                destMd5sum.put(f.getName(), md5);
            }
            for (Map.Entry<String, String> srcEntry : srcMd5sum.entrySet()) {
                String name = srcEntry.getKey();
                String destMd5 = destMd5sum.get(name);
                if (destMd5 == null) {
                    logger.debug(String.format("%s is not existing in %s, need to deploy salt module[%s]", name, destModulePath, moduleName));
                    needed = true;
                    return needed;
                }
                if (!destMd5.equals(srcEntry.getValue())) {
                    logger.debug(String.format("%s's md5 changed[{%s} in %s, {%s} in %s], need to deploy salt module[%s]", name, destMd5, destModulePath,
                            srcEntry.getValue(), modulePath, moduleName));
                    needed = true;
                    return needed;
                }
            }
            logger.debug(String.format("no file changed in puppet module[%s], no need to deploy", moduleName));
            needed = false;
            return needed;
        }  finally {
            moduleChanges.put(moduleName, needed);
        }
    }

    @Override
    public void deployModule(String modulePath) {
        File src = PathUtil.findFolderOnClassPath(modulePath, true);
        if (!src.isDirectory()) {
            throw new CloudRuntimeException(String.format("Cannot find salt module[%s], it's either not existing or not a directory", modulePath));
        }

        String moduleName = src.getName();
        if (moduleName == null) {
            throw new CloudRuntimeException(String.format("Cannot get salt module name from path[%s]", modulePath));
        }

        try {
            if (!isNeedToDeploy(moduleName, src.getAbsolutePath())) {
                return;
            }

            String destModulePath = PathUtil.join(masterFileRoots, moduleName);
            File dest = new File(destModulePath);
            if (dest.exists()) {
                FileUtils.forceDelete(dest);
                FileUtils.forceMkdir(dest);
            }
            FileUtils.copyDirectory(src, dest);
        } catch (Exception e) {
            String err = String.format("Unable to deploy salt module[%s] from %s", moduleName, modulePath);
            throw new CloudRuntimeException(err, e);
        }
    }

    @Override
    public SaltRunner createSaltRunner() {
        return new SaltRunner(saltBootstrapScriptPath, saltMinionConfPath);
    }

    @Override
    public boolean isModuleChanged(String moduleName) {
        Boolean ret = moduleChanges.get(moduleName);
        DebugUtils.Assert(ret != null, String.format("cannot find salt module name[%s]", moduleName));
        return ret;
    }

    public void setMasterFileRoots(String masterFileRoots) {
        this.masterFileRoots = masterFileRoots;
    }
}


text:
'''
A script to check that the executables produced by gitian only contain
certain symbols and are only linked against allowed libraries.

Example usage:

    find ../gitian-builder/build -type f -executable | xargs python3 contrib/devtools/symbol-check.py
'''
import subprocess
import re
import sys
import os
from typing import List, Optional, Tuple

# Debian 8 (Jessie) EOL: 2020. https://wiki.debian.org/DebianReleases#Production_Releases
#
# - g++ version 4.9.2 (https://packages.debian.org/search?suite=jessie&arch=any&searchon=names&keywords=g%2B%2B)
# - libc version 2.19 (https://packages.debian.org/search?suite=jessie&arch=any&searchon=names&keywords=libc6)
#
# Ubuntu 16.04 (Xenial) EOL: 2024. https://wiki.ubuntu.com/Releases
#
# - g++ version 5.3.1 (https://packages.ubuntu.com/search?keywords=g%2B%2B&searchon=names&suite=xenial&section=all)
# - libc version 2.23.0 (https://packages.ubuntu.com/search?keywords=libc6&searchon=names&suite=xenial&section=all)
#
# CentOS 7 EOL: 2024. https://wiki.centos.org/FAQ/General
#
# - g++ version 4.8.5 (http://mirror.centos.org/centos/7/os/x86_64/Packages/)
# - libc version 2.17 (http://mirror.centos.org/centos/7/os/x86_64/Packages/)
#
# Taking the minimum of these as our target.
#
# According to GNU ABI document (https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html) this corresponds to:
#   GCC 4.8.5: GCC_4.8.0
#   (glibc)    GLIBC_2_17
#
MAX_VERSIONS = {
'GCC':       (4,8,0),
'GLIBC':     (2,17),
'LIBATOMIC': (1,0)
}
# See here for a description of _IO_stdin_used:
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=634261#109

# Ignore symbols that are exported as part of every executable
IGNORE_EXPORTS = {
'_edata', '_end', '__end__', '_init', '__bss_start', '__bss_start__', '_bss_end__', '__bss_end__', '_fini', '_IO_stdin_used', 'stdin', 'stdout', 'stderr',
'environ', '_environ', '__environ',
}
READELF_CMD = os.getenv('READELF', '/usr/bin/readelf')
CPPFILT_CMD = os.getenv('CPPFILT', '/usr/bin/c++filt')
OBJDUMP_CMD = os.getenv('OBJDUMP', '/usr/bin/objdump')
OTOOL_CMD = os.getenv('OTOOL', '/usr/bin/otool')

# Allowed NEEDED libraries
ELF_ALLOWED_LIBRARIES = {
# bitcoind and bitcoin-qt
'libgcc_s.so.1', # GCC base support
'libc.so.6', # C library
'libpthread.so.0', # threading
'libm.so.6', # math library
'librt.so.1', # real-time (clock)
'libatomic.so.1',
'ld-linux-x86-64.so.2', # 64-bit dynamic linker
'ld-linux.so.2', # 32-bit dynamic linker
'ld-linux-aarch64.so.1', # 64-bit ARM dynamic linker
'ld-linux-armhf.so.3', # 32-bit ARM dynamic linker
'ld-linux-riscv64-lp64d.so.1', # 64-bit RISC-V dynamic linker
# bitcoin-qt only
'libxcb.so.1', # part of X11
'libfontconfig.so.1', # font support
'libfreetype.so.6', # font parsing
'libdl.so.2' # programming interface to dynamic linker
}
ARCH_MIN_GLIBC_VER = {
'80386':  (2,1),
'X86-64': (2,2,5),
'ARM':    (2,4),
'AArch64':(2,17),
'RISC-V': (2,27)
}

MACHO_ALLOWED_LIBRARIES = {
# bitcoind and bitcoin-qt
'libc++.1.dylib', # C++ Standard Library
'libSystem.B.dylib', # libc, libm, libpthread, libinfo
# bitcoin-qt only
'AppKit', # user interface
'ApplicationServices', # common application tasks.
'Carbon', # deprecated c back-compat API
'CoreFoundation', # low level func, data types
'CoreGraphics', # 2D rendering
'CoreServices', # operating system services
'CoreText', # interface for laying out text and handling fonts.
'Foundation', # base layer functionality for apps/frameworks
'ImageIO', # read and write image file formats.
'IOKit', # user-space access to hardware devices and drivers.
'libobjc.A.dylib', # Objective-C runtime library
}

PE_ALLOWED_LIBRARIES = {
'ADVAPI32.dll', # security & registry
'IPHLPAPI.DLL', # IP helper API
'KERNEL32.dll', # win32 base APIs
'msvcrt.dll', # C standard library for MSVC
'SHELL32.dll', # shell API
'USER32.dll', # user interface
'WS2_32.dll', # sockets
# bitcoin-qt only
'dwmapi.dll', # desktop window manager
'GDI32.dll', # graphics device interface
'IMM32.dll', # input method editor
'ole32.dll', # component object model
'OLEAUT32.dll', # OLE Automation API
'SHLWAPI.dll', # light weight shell API
'UxTheme.dll',
'VERSION.dll', # version checking
'WINMM.dll', # WinMM audio API
}

class CPPFilt(object):
    '''
    Demangle C++ symbol names.

    Use a pipe to the 'c++filt' command.
    '''
    def __init__(self):
        self.proc = subprocess.Popen(CPPFILT_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)

    def __call__(self, mangled):
        self.proc.stdin.write(mangled + '\n')
        self.proc.stdin.flush()
        return self.proc.stdout.readline().rstrip()

    def close(self):
        self.proc.stdin.close()
        self.proc.stdout.close()
        self.proc.wait()

def read_symbols(executable, imports=True) -> List[Tuple[str, str, str]]:
    '''
    Parse an ELF executable and return a list of (symbol,version, arch) tuples
    for dynamic, imported symbols.
    '''
    p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', '-h', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
    (stdout, stderr) = p.communicate()
    if p.returncode:
        raise IOError('Could not read symbols for {}: {}'.format(executable, stderr.strip()))
    syms = []
    for line in stdout.splitlines():
        line = line.split()
        if 'Machine:' in line:
            arch = line[-1]
        if len(line)>7 and re.match('[0-9]+:$', line[0]):
            (sym, _, version) = line[7].partition('@')
            is_import = line[6] == 'UND'
            if version.startswith('@'):
                version = version[1:]
            if is_import == imports:
                syms.append((sym, version, arch))
    return syms

def check_version(max_versions, version, arch) -> bool:
    if '_' in version:
        (lib, _, ver) = version.rpartition('_')
    else:
        lib = version
        ver = '0'
    ver = tuple([int(x) for x in ver.split('.')])
    if not lib in max_versions:
        return False
    return ver <= max_versions[lib] or lib == 'GLIBC' and ver <= ARCH_MIN_GLIBC_VER[arch]

def elf_read_libraries(filename) -> List[str]:
    p = subprocess.Popen([READELF_CMD, '-d', '-W', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
    (stdout, stderr) = p.communicate()
    if p.returncode:
        raise IOError('Error opening file')
    libraries = []
    for line in stdout.splitlines():
        tokens = line.split()
        if len(tokens)>2 and tokens[1] == '(NEEDED)':
            match = re.match(r'^Shared library: \[(.*)\]$', ' '.join(tokens[2:]))
            if match:
                libraries.append(match.group(1))
            else:
                raise ValueError('Unparseable (NEEDED) specification')
    return libraries

def check_imported_symbols(filename) -> bool:
    cppfilt = CPPFilt()
    ok = True
    for sym, version, arch in read_symbols(filename, True):
        if version and not check_version(MAX_VERSIONS, version, arch):
            print('{}: symbol {} from unsupported version {}'.format(filename, cppfilt(sym), version))
            ok = False
    return ok

def check_exported_symbols(filename) -> bool:
    cppfilt = CPPFilt()
    ok = True
    for sym,version,arch in read_symbols(filename, False):
        if arch == 'RISC-V' or sym in IGNORE_EXPORTS:
            continue
        print('{}: export of symbol {} not allowed'.format(filename, cppfilt(sym)))
        ok = False
    return ok

def check_ELF_libraries(filename) -> bool:
    ok = True
    for library_name in elf_read_libraries(filename):
        if library_name not in ELF_ALLOWED_LIBRARIES:
            print('{}: NEEDED library {} is not allowed'.format(filename, library_name))
            ok = False
    return ok

def macho_read_libraries(filename) -> List[str]:
    p = subprocess.Popen([OTOOL_CMD, '-L', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
    (stdout, stderr) = p.communicate()
    if p.returncode:
        raise IOError('Error opening file')
    libraries = []
    for line in stdout.splitlines():
        tokens = line.split()
        if len(tokens) == 1: # skip executable name
            continue
        libraries.append(tokens[0].split('/')[-1])
    return libraries

def check_MACHO_libraries(filename) -> bool:
    ok = True
    for dylib in macho_read_libraries(filename):
        if dylib not in MACHO_ALLOWED_LIBRARIES:
            print('{} is not in ALLOWED_LIBRARIES!'.format(dylib))
            ok = False
    return ok

def pe_read_libraries(filename) -> List[str]:
    p = subprocess.Popen([OBJDUMP_CMD, '-x', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, universal_newlines=True)
    (stdout, stderr) = p.communicate()
    if p.returncode:
        raise IOError('Error opening file')
    libraries = []
    for line in stdout.splitlines():
        if 'DLL Name:' in line:
            tokens = line.split(': ')
            libraries.append(tokens[1])
    return libraries

def check_PE_libraries(filename) -> bool:
    ok = True
    for dylib in pe_read_libraries(filename):
        if dylib not in PE_ALLOWED_LIBRARIES:
            print('{} is not in ALLOWED_LIBRARIES!'.format(dylib))
            ok = False
    return ok

CHECKS = {
'ELF': [
    ('IMPORTED_SYMBOLS', check_imported_symbols),
    ('EXPORTED_SYMBOLS', check_exported_symbols),
    ('LIBRARY_DEPENDENCIES', check_ELF_libraries)
],
'MACHO': [
    ('DYNAMIC_LIBRARIES', check_MACHO_libraries)
],
'PE' : [
    ('DYNAMIC_LIBRARIES', check_PE_libraries)
]
}

def identify_executable(executable) -> Optional[str]:
    with open(filename, 'rb') as f:
        magic = f.read(4)
    if magic.startswith(b'MZ'):
        return 'PE'
    elif magic.startswith(b'\x7fELF'):
        return 'ELF'
    elif magic.startswith(b'\xcf\xfa'):
        return 'MACHO'
    return None

if __name__ == '__main__':
    retval = 0
    for filename in sys.argv[1:]:
        try:
            etype = identify_executable(filename)
            if etype is None:
                print('{}: unknown format'.format(filename))
                retval = 1
                continue

            failed = []
            for (name, func) in CHECKS[etype]:
                if not func(filename):
                    failed.append(name)
            if failed:
                print('{}: failed {}'.format(filename, ' '.join(failed)))
                retval = 1
        except IOError:
            print('{}: cannot open'.format(filename))
            retval = 1
    sys.exit(retval)