text:
package ma.glasnost.orika.converter.builtin;

import java.util.Calendar;
import java.util.Date;

import javax.xml.datatype.XMLGregorianCalendar;

import ma.glasnost.orika.converter.ConverterFactory;

/**
 * BuiltinConverters is a utility class used to register common built-in
 * converters.
 *
 * @author mattdeboer
 *
 */
public abstract class BuiltinConverters {

    /**
     * Registers a common set of built-in converters which can handle many
     * common conversion situations.

     * Specifically, this includes:
     *

     *
ConstructorConverter: converts from the source type to destination
     * type if there is a constructor available on the destination type which
     * takes the source as a single argument.
     *
FromStringConverter: able to convert from a String to enum,
     * primitive, or primitive wrapper.
     *
ToStringconverter: able to convert any type to String
     *
DateAndTimeConverters: convert between common date/time
     * representations
     *

     *
java.util.Calendar
     *
java.util.Date
     *
long / java.lang.Long
     *
javax.xml.datatype.XMLGregorianCalendar
     *
java.sql.Date
     *
java.sql.Time
     *
java.sql.Timestamp
     *

     *
CloneableConverter registered for the following cloneable types:
     *

     *
java.util.Date
     *
java.util.Calendar
     *
javax.xml.datatype.XMLGregorianCalendar
     *

     *

     *
     * @param converterFactory
     *            the converter factory on which to register the converters
     */
    public static void register(ConverterFactory converterFactory) {

        converterFactory.registerConverter(new CopyByReferenceConverter());

        converterFactory.registerConverter(new EnumConverter());

        /*
         * Register to/from string converters
         */
        converterFactory.registerConverter(new FromStringConverter());
        converterFactory.registerConverter(new ToStringConverter());

        /*
         * Register common date/time converters
         */
        converterFactory.registerConverter(new DateAndTimeConverters.DateToXmlGregorianCalendarConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.DateToTimeConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.CalendarToXmlGregorianCalendarConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.XmlGregorianCalendarToTimestampConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.XmlGregorianCalendarToSqlDateConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.XmlGregorianCalendarToTimeConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.LongToXmlGregorianCalendarConverter());

        converterFactory.registerConverter(new DateAndTimeConverters.DateToCalendarConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.CalendarToTimeConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.CalendarToSqlDateConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.LongToCalendarConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.TimestampToCalendarConverter());

        converterFactory.registerConverter(new DateAndTimeConverters.DateToSqlDateConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.LongToSqlDateConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.TimeToSqlDateConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.TimestampToSqlDateConverter());

        converterFactory.registerConverter(new DateAndTimeConverters.LongToTimeConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.TimestampToTimeConverter());

        converterFactory.registerConverter(new DateAndTimeConverters.LongToTimestampConverter());
        converterFactory.registerConverter(new DateAndTimeConverters.DateToTimestampConverter());

        converterFactory.registerConverter(new DateAndTimeConverters.LongToDateConverter());

        /*
         * Register numeric type converter
         */
        converterFactory.registerConverter(new NumericConverters.BigDecimalToDoubleConverter());
        converterFactory.registerConverter(new NumericConverters.BigDecimalToFloatConverter());
        converterFactory.registerConverter(new NumericConverters.BigIntegerToIntegerConverter(false));
        converterFactory.registerConverter(new NumericConverters.BigIntegerToLongConverter(false));

        converterFactory.registerConverter(new NumericConverters.IntegerToShortConverter(false));
        converterFactory.registerConverter(new NumericConverters.LongToIntegerConverter(false));
        converterFactory.registerConverter(new NumericConverters.LongToShortConverter(false));

        converterFactory.registerConverter(new NumericConverters.FloatToShortConverter(false));
        converterFactory.registerConverter(new NumericConverters.FloatToIntegerConverter(false));
        converterFactory.registerConverter(new NumericConverters.FloatToLongConverter(false));

        converterFactory.registerConverter(new NumericConverters.DoubleToShortConverter(false));
        converterFactory.registerConverter(new NumericConverters.DoubleToIntegerConverter(false));
        converterFactory.registerConverter(new NumericConverters.DoubleToLongConverter(false));

        /*
         * Register additional common "cloneable" types
         */
        converterFactory.registerConverter(new CloneableConverter.Builtin(Date.class, Calendar.class, XMLGregorianCalendar.class));
        /*
         * Register converter to instantiate by using a constructor on the
         * destination which takes the source as argument
         */
        converterFactory.registerConverter(new ConstructorConverter());
    }
}


text:
uint8_t setMask;

void setLEDs(const void *value, void *context);

int main( int argc, const char * argv[] ) {
	if (argc != 2) {
        printf("Usage: setleds <bitmask as int>\n");
        return 0;
    }
    setMask = atoi(argv[1]);

    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

	IOHIDManagerRef hidManager = IOHIDManagerCreate( kCFAllocatorDefault, kIOHIDOptionsTypeNone );
	if (!hidManager) return 1;

    NSDictionary* keyboardMatchDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                       [NSNumber numberWithInt: kHIDPage_GenericDesktop],@ kIOHIDDeviceUsagePageKey,
                                       [NSNumber numberWithInt: kHIDUsage_GD_Keyboard],@ kIOHIDDeviceUsageKey, nil];

	if (!keyboardMatchDict) return 2;

	IOHIDManagerSetDeviceMatching( hidManager, (CFDictionaryRef) keyboardMatchDict);

	IOReturn status = IOHIDManagerOpen( hidManager, kIOHIDOptionsTypeNone );
    if (status) return 3;

	CFSetRef keyboards = IOHIDManagerCopyDevices(hidManager);
    if (!keyboards) return 4;

    CFSetApplyFunction(keyboards, setLEDs, NULL);

    CFRelease(hidManager);
    [pool drain];
    return 0;
}

void setLEDs(const void *value, void *context) {
#pragma unused(context)

    IOHIDDeviceRef device = (IOHIDDeviceRef)value;
    if (!IOHIDDeviceConformsTo(device, kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard)) return;
    IOHIDDeviceSetReport(device, kIOHIDReportTypeOutput, 0, &setMask, 1);

}

redpajama_set_name: RedPajamaGithub


text:
require 'wheelhouse'

module PageFragments
  class Plugin < Wheelhouse::Plugin
    config.precompile << "page-fragments/resource.js" << "page-fragments/*.png"

    hook(:resource) do
      content_for(:javascript) { javascript_include_tag("page-fragments/resource") }
    end
  end
end


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.dk.shoppinglist;

public final class R {
    public static final class array {
        public static final int priorities=0x7f050000;
    }
    public static final class attr {
    }
    public static final class color {
        public static final int black=0x7f070001;
        public static final int listcolor=0x7f070000;
        public static final int sky_blue=0x7f070003;
        public static final int white=0x7f070002;
    }
    public static final class dimen {
        /**  Default screen margins, per the Android Design guidelines.

         Example customization of dimensions originally defined in res/values/dimens.xml
         (such as screen margins) for screens with more than 820dp of available width. This
         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).

         */
        public static final int activity_horizontal_margin=0x7f040000;
        public static final int activity_vertical_margin=0x7f040001;
    }
    public static final class drawable {
        public static final int add=0x7f020000;
        public static final int button_normal3=0x7f020001;
        public static final int ic_launcher=0x7f020002;
        public static final int itog=0x7f020003;
        public static final int knopka1=0x7f020004;
        public static final int knopka2=0x7f020005;
        public static final int knopka3=0x7f020006;
        public static final int knopka4=0x7f020007;
        public static final int ooo=0x7f020008;
        public static final int reminder=0x7f020009;
    }
    public static final class id {
        public static final int Price01=0x7f0a0013;
        public static final int RelativeLayout1=0x7f0a0003;
        public static final int action_settings=0x7f0a001a;
        public static final int add=0x7f0a0009;
        public static final int amount=0x7f0a0010;
        public static final int arhiv1=0x7f0a0005;
        public static final int btnActTwo=0x7f0a0006;
        public static final int buttonPrompt=0x7f0a0001;
        public static final int category=0x7f0a000a;
        public static final int editTextDialogUserInput=0x7f0a0019;
        public static final int editTextResult=0x7f0a0002;
        public static final int icon=0x7f0a0011;
        public static final int imageView1=0x7f0a0008;
        public static final int insert=0x7f0a001b;
        public static final int label=0x7f0a000f;
        public static final int layout_root=0x7f0a0017;
        public static final int list_edit_button=0x7f0a000e;
        public static final int list_edit_description=0x7f0a000d;
        public static final int list_edit_price=0x7f0a000c;
        public static final int list_edit_summary=0x7f0a000b;
        public static final int nastr=0x7f0a0007;
        public static final int newsp=0x7f0a0004;
        public static final int price=0x7f0a0012;
        public static final int seekBar1=0x7f0a0015;
        public static final int summa=0x7f0a0000;
        public static final int textView1=0x7f0a0018;
        public static final int textView2=0x7f0a0014;
        public static final int txtPercentage=0x7f0a0016;
    }
    public static final class layout {
        public static final int arhiv=0x7f030000;
        public static final int dialog=0x7f030001;
        public static final int list=0x7f030002;
        public static final int list_details=0x7f030003;
        public static final int list_edit=0x7f030004;
        public static final int list_overview=0x7f030005;
        public static final int list_row=0x7f030006;
        public static final int nas=0x7f030007;
        public static final int promts=0x7f030008;
        public static final int stat=0x7f030009;
    }
    public static final class menu {
        public static final int arhiv=0x7f090000;
        public static final int list_details=0x7f090001;
        public static final int list_overview=0x7f090002;
        public static final int listmenu=0x7f090003;
        public static final int nas=0x7f090004;
        public static final int stat=0x7f090005;
    }
    public static final class string {
        public static final int action_settings=0x7f06000c;
        public static final int app_name=0x7f060001;
        public static final int hello=0x7f060000;
        public static final int hello_world=0x7f06000b;
        public static final int list_description=0x7f060006;
        public static final int list_edit_confirm=0x7f060009;
        public static final int list_edit_description=0x7f060008;
        public static final int list_edit_summary=0x7f060007;
        public static final int list_summary=0x7f060005;
        public static final int menu_delete=0x7f060004;
        public static final int menu_insert=0x7f060003;
        public static final int no_list=0x7f060002;
        public static final int title_activity_arhiv=0x7f06000e;
        public static final int title_activity_list_details=0x7f06000a;
        public static final int title_activity_nas=0x7f06000f;
        public static final int title_activity_stat=0x7f06000d;
    }
    public static final class style {
        /**
        Base application theme, dependent on API level. This theme is replaced
        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.

            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.

        Base application theme for API 11+. This theme completely replaces
        AppBaseTheme from res/values/styles.xml on API 11+ devices.

 API 11 theme customizations can go here.

        Base application theme for API 14+. This theme completely replaces
        AppBaseTheme from BOTH res/values/styles.xml and
        res/values-v11/styles.xml on API 14+ devices.

 API 14 theme customizations can go here.
         */
        public static final int AppBaseTheme=0x7f080000;
        /**  Application theme.
 All customizations that are NOT specific to a particular API-level can go here.
         */
        public static final int AppTheme=0x7f080001;
    }
}


text:
package google

import (
	"fmt"
	"log"
	"reflect"
	"strings"
	"time"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func resourceSecretManagerSecret() *schema.Resource {
	return &schema.Resource{
		Create: resourceSecretManagerSecretCreate,
		Read:   resourceSecretManagerSecretRead,
		Update: resourceSecretManagerSecretUpdate,
		Delete: resourceSecretManagerSecretDelete,

		Importer: &schema.ResourceImporter{
			State: resourceSecretManagerSecretImport,
		},

		Timeouts: &schema.ResourceTimeout{
			Create: schema.DefaultTimeout(20 * time.Minute),
			Update: schema.DefaultTimeout(20 * time.Minute),
			Delete: schema.DefaultTimeout(20 * time.Minute),
		},

		Schema: map[string]*schema.Schema{
			"replication": {
				Type:     schema.TypeList,
				Required: true,
				ForceNew: true,
				Description: `The replication policy of the secret data attached to the Secret. It cannot be changed
after the Secret has been created.`,
				MaxItems: 1,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"automatic": {
							Type:         schema.TypeBool,
							Optional:     true,
							ForceNew:     true,
							Description:  `The Secret will automatically be replicated without any restrictions.`,
							ExactlyOneOf: []string{"replication.0.automatic", "replication.0.user_managed"},
						},
						"user_managed": {
							Type:        schema.TypeList,
							Optional:    true,
							ForceNew:    true,
							Description: `The Secret will automatically be replicated without any restrictions.`,
							MaxItems:    1,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"replicas": {
										Type:        schema.TypeList,
										Required:    true,
										ForceNew:    true,
										Description: `The list of Replicas for this Secret. Cannot be empty.`,
										MinItems:    1,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"location": {
													Type:        schema.TypeString,
													Required:    true,
													ForceNew:    true,
													Description: `The canonical IDs of the location to replicate data. For example: "us-east1".`,
												},
												"customer_managed_encryption": {
													Type:        schema.TypeList,
													Optional:    true,
													ForceNew:    true,
													Description: `Customer Managed Encryption for the secret.`,
													MaxItems:    1,
													Elem: &schema.Resource{
														Schema: map[string]*schema.Schema{
															"kms_key_name": {
																Type:        schema.TypeString,
																Required:    true,
																ForceNew:    true,
																Description: `Describes the Cloud KMS encryption key that will be used to protect destination secret.`,
															},
														},
													},
												},
											},
										},
									},
								},
							},
							ExactlyOneOf: []string{"replication.0.automatic", "replication.0.user_managed"},
						},
					},
				},
			},
			"secret_id": {
				Type:        schema.TypeString,
				Required:    true,
				ForceNew:    true,
				Description: `This must be unique within the project.`,
			},
			"expire_time": {
				Type:     schema.TypeString,
				Computed: true,
				Optional: true,
				Description: `Timestamp in UTC when the Secret is scheduled to expire. This is always provided on output, regardless of what was sent on input.
A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".`,
			},
			"labels": {
				Type:     schema.TypeMap,
				Optional: true,
				Description: `The labels assigned to this Secret.

Label keys must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes,
and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}

Label values must be between 0 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes,
and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}\p{N}_-]{0,63}

No more than 64 labels can be assigned to a given resource.

An object containing a list of "key": value pairs. Example:
{ "name": "wrench", "mass": "1.3kg", "count": "3" }.`,
				Elem: &schema.Schema{Type: schema.TypeString},
			},
			"rotation": {
				Type:        schema.TypeList,
				Optional:    true,
				Description: `The rotation time and period for a Secret. At 'next_rotation_time', Secret Manager will send a Pub/Sub notification to the topics configured on the Secret. 'topics' must be set to configure rotation.`,
				MaxItems:    1,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"next_rotation_time": {
							Type:     schema.TypeString,
							Optional: true,
							Description: `Timestamp in UTC at which the Secret is scheduled to rotate.
A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up to nine fractional digits. Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".`,
							RequiredWith: []string{"rotation.0.rotation_period"},
						},
						"rotation_period": {
							Type:     schema.TypeString,
							Optional: true,
							ForceNew: true,
							Description: `The Duration between rotation notifications. Must be in seconds and at least 3600s (1h) and at most 3153600000s (100 years).
If rotationPeriod is set, 'next_rotation_time' must be set. 'next_rotation_time' will be advanced by this period when the service automatically sends rotation notifications.`,
						},
					},
				},
				RequiredWith: []string{"topics"},
			},
			"topics": {
				Type:        schema.TypeList,
				Optional:    true,
				Description: `A list of up to 10 Pub/Sub topics to which messages are published when control plane operations are called on the secret or its versions.`,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"name": {
							Type:     schema.TypeString,
							Required: true,
							Description: `The resource name of the Pub/Sub topic that will be published to, in the following format: projects/*/topics/*.
For publication to succeed, the Secret Manager Service Agent service account must have pubsub.publisher permissions on the topic.`,
						},
					},
				},
				RequiredWith: []string{"rotation"},
			},
			"ttl": {
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Description: `The TTL for the Secret.
A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".`,
			},
			"create_time": {
				Type:        schema.TypeString,
				Computed:    true,
				Description: `The time at which the Secret was created.`,
			},
			"name": {
				Type:     schema.TypeString,
				Computed: true,
				Description: `The resource name of the Secret. Format:
'projects/{{project}}/secrets/{{secret_id}}'`,
			},
			"project": {
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
				ForceNew: true,
			},
		},
		UseJSONNumber: true,
	}
}

func resourceSecretManagerSecretCreate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	userAgent, err := generateUserAgentString(d, config.userAgent)
	if err != nil {
		return err
	}

	obj := make(map[string]interface{})
	labelsProp, err := expandSecretManagerSecretLabels(d.Get("labels"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
		obj["labels"] = labelsProp
	}
	replicationProp, err := expandSecretManagerSecretReplication(d.Get("replication"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("replication"); !isEmptyValue(reflect.ValueOf(replicationProp)) && (ok || !reflect.DeepEqual(v, replicationProp)) {
		obj["replication"] = replicationProp
	}
	topicsProp, err := expandSecretManagerSecretTopics(d.Get("topics"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("topics"); !isEmptyValue(reflect.ValueOf(topicsProp)) && (ok || !reflect.DeepEqual(v, topicsProp)) {
		obj["topics"] = topicsProp
	}
	expireTimeProp, err := expandSecretManagerSecretExpireTime(d.Get("expire_time"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("expire_time"); !isEmptyValue(reflect.ValueOf(expireTimeProp)) && (ok || !reflect.DeepEqual(v, expireTimeProp)) {
		obj["expireTime"] = expireTimeProp
	}
	ttlProp, err := expandSecretManagerSecretTtl(d.Get("ttl"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("ttl"); !isEmptyValue(reflect.ValueOf(ttlProp)) && (ok || !reflect.DeepEqual(v, ttlProp)) {
		obj["ttl"] = ttlProp
	}
	rotationProp, err := expandSecretManagerSecretRotation(d.Get("rotation"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("rotation"); !isEmptyValue(reflect.ValueOf(rotationProp)) && (ok || !reflect.DeepEqual(v, rotationProp)) {
		obj["rotation"] = rotationProp
	}

	url, err := replaceVars(d, config, "{{SecretManagerBasePath}}projects/{{project}}/secrets?secretId={{secret_id}}")
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] Creating new Secret: %#v", obj)
	billingProject := ""

	project, err := getProject(d, config)
	if err != nil {
		return fmt.Errorf("Error fetching project for Secret: %s", err)
	}
	billingProject = project

	// err == nil indicates that the billing_project value was found
	if bp, err := getBillingProject(d, config); err == nil {
		billingProject = bp
	}

	res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate))
	if err != nil {
		return fmt.Errorf("Error creating Secret: %s", err)
	}
	if err := d.Set("name", flattenSecretManagerSecretName(res["name"], d, config)); err != nil {
		return fmt.Errorf(`Error setting computed identity field "name": %s`, err)
	}

	// Store the ID now
	id, err := replaceVars(d, config, "projects/{{project}}/secrets/{{secret_id}}")
	if err != nil {
		return fmt.Errorf("Error constructing id: %s", err)
	}
	d.SetId(id)

	log.Printf("[DEBUG] Finished creating Secret %q: %#v", d.Id(), res)

	return resourceSecretManagerSecretRead(d, meta)
}

func resourceSecretManagerSecretRead(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	userAgent, err := generateUserAgentString(d, config.userAgent)
	if err != nil {
		return err
	}

	url, err := replaceVars(d, config, "{{SecretManagerBasePath}}projects/{{project}}/secrets/{{secret_id}}")
	if err != nil {
		return err
	}

	billingProject := ""

	project, err := getProject(d, config)
	if err != nil {
		return fmt.Errorf("Error fetching project for Secret: %s", err)
	}
	billingProject = project

	// err == nil indicates that the billing_project value was found
	if bp, err := getBillingProject(d, config); err == nil {
		billingProject = bp
	}

	res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil)
	if err != nil {
		return handleNotFoundError(err, d, fmt.Sprintf("SecretManagerSecret %q", d.Id()))
	}

	if err := d.Set("project", project); err != nil {
		return fmt.Errorf("Error reading Secret: %s", err)
	}

	if err := d.Set("name", flattenSecretManagerSecretName(res["name"], d, config)); err != nil {
		return fmt.Errorf("Error reading Secret: %s", err)
	}
	if err := d.Set("create_time", flattenSecretManagerSecretCreateTime(res["createTime"], d, config)); err != nil {
		return fmt.Errorf("Error reading Secret: %s", err)
	}
	if err := d.Set("labels", flattenSecretManagerSecretLabels(res["labels"], d, config)); err != nil {
		return fmt.Errorf("Error reading Secret: %s", err)
	}
	if err := d.Set("replication", flattenSecretManagerSecretReplication(res["replication"], d, config)); err != nil {
		return fmt.Errorf("Error reading Secret: %s", err)
	}
	if err := d.Set("topics", flattenSecretManagerSecretTopics(res["topics"], d, config)); err != nil {
		return fmt.Errorf("Error reading Secret: %s", err)
	}
	if err := d.Set("expire_time", flattenSecretManagerSecretExpireTime(res["expireTime"], d, config)); err != nil {
		return fmt.Errorf("Error reading Secret: %s", err)
	}
	if err := d.Set("rotation", flattenSecretManagerSecretRotation(res["rotation"], d, config)); err != nil {
		return fmt.Errorf("Error reading Secret: %s", err)
	}

	return nil
}

func resourceSecretManagerSecretUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	userAgent, err := generateUserAgentString(d, config.userAgent)
	if err != nil {
		return err
	}

	billingProject := ""

	project, err := getProject(d, config)
	if err != nil {
		return fmt.Errorf("Error fetching project for Secret: %s", err)
	}
	billingProject = project

	obj := make(map[string]interface{})
	labelsProp, err := expandSecretManagerSecretLabels(d.Get("labels"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
		obj["labels"] = labelsProp
	}
	topicsProp, err := expandSecretManagerSecretTopics(d.Get("topics"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("topics"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, topicsProp)) {
		obj["topics"] = topicsProp
	}
	expireTimeProp, err := expandSecretManagerSecretExpireTime(d.Get("expire_time"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("expire_time"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, expireTimeProp)) {
		obj["expireTime"] = expireTimeProp
	}
	rotationProp, err := expandSecretManagerSecretRotation(d.Get("rotation"), d, config)
	if err != nil {
		return err
	} else if v, ok := d.GetOkExists("rotation"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, rotationProp)) {
		obj["rotation"] = rotationProp
	}

	url, err := replaceVars(d, config, "{{SecretManagerBasePath}}projects/{{project}}/secrets/{{secret_id}}")
	if err != nil {
		return err
	}

	log.Printf("[DEBUG] Updating Secret %q: %#v", d.Id(), obj)
	updateMask := []string{}

	if d.HasChange("labels") {
		updateMask = append(updateMask, "labels")
	}

	if d.HasChange("topics") {
		updateMask = append(updateMask, "topics")
	}

	if d.HasChange("expire_time") {
		updateMask = append(updateMask, "expireTime")
	}

	if d.HasChange("rotation") {
		updateMask = append(updateMask, "rotation")
	}
	// updateMask is a URL parameter but not present in the schema, so replaceVars
	// won't set it
	url, err = addQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")})
	if err != nil {
		return err
	}

	// err == nil indicates that the billing_project value was found
	if bp, err := getBillingProject(d, config); err == nil {
		billingProject = bp
	}

	res, err := sendRequestWithTimeout(config, "PATCH", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate))

	if err != nil {
		return fmt.Errorf("Error updating Secret %q: %s", d.Id(), err)
	} else {
		log.Printf("[DEBUG] Finished updating Secret %q: %#v", d.Id(), res)
	}

	return resourceSecretManagerSecretRead(d, meta)
}

func resourceSecretManagerSecretDelete(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	userAgent, err := generateUserAgentString(d, config.userAgent)
	if err != nil {
		return err
	}

	billingProject := ""

	project, err := getProject(d, config)
	if err != nil {
		return fmt.Errorf("Error fetching project for Secret: %s", err)
	}
	billingProject = project

	url, err := replaceVars(d, config, "{{SecretManagerBasePath}}projects/{{project}}/secrets/{{secret_id}}")
	if err != nil {
		return err
	}

	var obj map[string]interface{}
	log.Printf("[DEBUG] Deleting Secret %q", d.Id())

	// err == nil indicates that the billing_project value was found
	if bp, err := getBillingProject(d, config); err == nil {
		billingProject = bp
	}

	res, err := sendRequestWithTimeout(config, "DELETE", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutDelete))
	if err != nil {
		return handleNotFoundError(err, d, "Secret")
	}

	log.Printf("[DEBUG] Finished deleting Secret %q: %#v", d.Id(), res)
	return nil
}

func resourceSecretManagerSecretImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
	config := meta.(*Config)
	if err := parseImportId([]string{
		"projects/(?P<project>[^/]+)/secrets/(?P<secret_id>[^/]+)",
		"(?P<project>[^/]+)/(?P<secret_id>[^/]+)",
		"(?P<secret_id>[^/]+)",
	}, d, config); err != nil {
		return nil, err
	}

	// Replace import id for the resource id
	id, err := replaceVars(d, config, "projects/{{project}}/secrets/{{secret_id}}")
	if err != nil {
		return nil, fmt.Errorf("Error constructing id: %s", err)
	}
	d.SetId(id)

	return []*schema.ResourceData{d}, nil
}

func flattenSecretManagerSecretName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenSecretManagerSecretCreateTime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenSecretManagerSecretLabels(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenSecretManagerSecretReplication(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return nil
	}
	original := v.(map[string]interface{})
	if len(original) == 0 {
		return nil
	}
	transformed := make(map[string]interface{})
	transformed["automatic"] =
		flattenSecretManagerSecretReplicationAutomatic(original["automatic"], d, config)
	transformed["user_managed"] =
		flattenSecretManagerSecretReplicationUserManaged(original["userManaged"], d, config)
	return []interface{}{transformed}
}
func flattenSecretManagerSecretReplicationAutomatic(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v != nil
}

func flattenSecretManagerSecretReplicationUserManaged(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return nil
	}
	original := v.(map[string]interface{})
	if len(original) == 0 {
		return nil
	}
	transformed := make(map[string]interface{})
	transformed["replicas"] =
		flattenSecretManagerSecretReplicationUserManagedReplicas(original["replicas"], d, config)
	return []interface{}{transformed}
}
func flattenSecretManagerSecretReplicationUserManagedReplicas(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return v
	}
	l := v.([]interface{})
	transformed := make([]interface{}, 0, len(l))
	for _, raw := range l {
		original := raw.(map[string]interface{})
		if len(original) < 1 {
			// Do not include empty json objects coming back from the api
			continue
		}
		transformed = append(transformed, map[string]interface{}{
			"location":                    flattenSecretManagerSecretReplicationUserManagedReplicasLocation(original["location"], d, config),
			"customer_managed_encryption": flattenSecretManagerSecretReplicationUserManagedReplicasCustomerManagedEncryption(original["customerManagedEncryption"], d, config),
		})
	}
	return transformed
}
func flattenSecretManagerSecretReplicationUserManagedReplicasLocation(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenSecretManagerSecretReplicationUserManagedReplicasCustomerManagedEncryption(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return nil
	}
	original := v.(map[string]interface{})
	if len(original) == 0 {
		return nil
	}
	transformed := make(map[string]interface{})
	transformed["kms_key_name"] =
		flattenSecretManagerSecretReplicationUserManagedReplicasCustomerManagedEncryptionKmsKeyName(original["kmsKeyName"], d, config)
	return []interface{}{transformed}
}
func flattenSecretManagerSecretReplicationUserManagedReplicasCustomerManagedEncryptionKmsKeyName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenSecretManagerSecretTopics(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return v
	}
	l := v.([]interface{})
	transformed := make([]interface{}, 0, len(l))
	for _, raw := range l {
		original := raw.(map[string]interface{})
		if len(original) < 1 {
			// Do not include empty json objects coming back from the api
			continue
		}
		transformed = append(transformed, map[string]interface{}{
			"name": flattenSecretManagerSecretTopicsName(original["name"], d, config),
		})
	}
	return transformed
}
func flattenSecretManagerSecretTopicsName(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenSecretManagerSecretExpireTime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenSecretManagerSecretRotation(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	if v == nil {
		return nil
	}
	original := v.(map[string]interface{})
	if len(original) == 0 {
		return nil
	}
	transformed := make(map[string]interface{})
	transformed["next_rotation_time"] =
		flattenSecretManagerSecretRotationNextRotationTime(original["nextRotationTime"], d, config)
	transformed["rotation_period"] =
		flattenSecretManagerSecretRotationRotationPeriod(original["rotationPeriod"], d, config)
	return []interface{}{transformed}
}
func flattenSecretManagerSecretRotationNextRotationTime(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func flattenSecretManagerSecretRotationRotationPeriod(v interface{}, d *schema.ResourceData, config *Config) interface{} {
	return v
}

func expandSecretManagerSecretLabels(v interface{}, d TerraformResourceData, config *Config) (map[string]string, error) {
	if v == nil {
		return map[string]string{}, nil
	}
	m := make(map[string]string)
	for k, val := range v.(map[string]interface{}) {
		m[k] = val.(string)
	}
	return m, nil
}

func expandSecretManagerSecretReplication(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	l := v.([]interface{})
	if len(l) == 0 || l[0] == nil {
		return nil, nil
	}
	raw := l[0]
	original := raw.(map[string]interface{})
	transformed := make(map[string]interface{})

	transformedAutomatic, err := expandSecretManagerSecretReplicationAutomatic(original["automatic"], d, config)
	if err != nil {
		return nil, err
	} else if val := reflect.ValueOf(transformedAutomatic); val.IsValid() && !isEmptyValue(val) {
		transformed["automatic"] = transformedAutomatic
	}

	transformedUserManaged, err := expandSecretManagerSecretReplicationUserManaged(original["user_managed"], d, config)
	if err != nil {
		return nil, err
	} else if val := reflect.ValueOf(transformedUserManaged); val.IsValid() && !isEmptyValue(val) {
		transformed["userManaged"] = transformedUserManaged
	}

	return transformed, nil
}

func expandSecretManagerSecretReplicationAutomatic(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	if v == nil || !v.(bool) {
		return nil, nil
	}

	return struct{}{}, nil
}

func expandSecretManagerSecretReplicationUserManaged(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	l := v.([]interface{})
	if len(l) == 0 || l[0] == nil {
		return nil, nil
	}
	raw := l[0]
	original := raw.(map[string]interface{})
	transformed := make(map[string]interface{})

	transformedReplicas, err := expandSecretManagerSecretReplicationUserManagedReplicas(original["replicas"], d, config)
	if err != nil {
		return nil, err
	} else if val := reflect.ValueOf(transformedReplicas); val.IsValid() && !isEmptyValue(val) {
		transformed["replicas"] = transformedReplicas
	}

	return transformed, nil
}

func expandSecretManagerSecretReplicationUserManagedReplicas(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	l := v.([]interface{})
	req := make([]interface{}, 0, len(l))
	for _, raw := range l {
		if raw == nil {
			continue
		}
		original := raw.(map[string]interface{})
		transformed := make(map[string]interface{})

		transformedLocation, err := expandSecretManagerSecretReplicationUserManagedReplicasLocation(original["location"], d, config)
		if err != nil {
			return nil, err
		} else if val := reflect.ValueOf(transformedLocation); val.IsValid() && !isEmptyValue(val) {
			transformed["location"] = transformedLocation
		}

		transformedCustomerManagedEncryption, err := expandSecretManagerSecretReplicationUserManagedReplicasCustomerManagedEncryption(original["customer_managed_encryption"], d, config)
		if err != nil {
			return nil, err
		} else if val := reflect.ValueOf(transformedCustomerManagedEncryption); val.IsValid() && !isEmptyValue(val) {
			transformed["customerManagedEncryption"] = transformedCustomerManagedEncryption
		}

		req = append(req, transformed)
	}
	return req, nil
}

func expandSecretManagerSecretReplicationUserManagedReplicasLocation(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandSecretManagerSecretReplicationUserManagedReplicasCustomerManagedEncryption(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	l := v.([]interface{})
	if len(l) == 0 || l[0] == nil {
		return nil, nil
	}
	raw := l[0]
	original := raw.(map[string]interface{})
	transformed := make(map[string]interface{})

	transformedKmsKeyName, err := expandSecretManagerSecretReplicationUserManagedReplicasCustomerManagedEncryptionKmsKeyName(original["kms_key_name"], d, config)
	if err != nil {
		return nil, err
	} else if val := reflect.ValueOf(transformedKmsKeyName); val.IsValid() && !isEmptyValue(val) {
		transformed["kmsKeyName"] = transformedKmsKeyName
	}

	return transformed, nil
}

func expandSecretManagerSecretReplicationUserManagedReplicasCustomerManagedEncryptionKmsKeyName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandSecretManagerSecretTopics(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	l := v.([]interface{})
	req := make([]interface{}, 0, len(l))
	for _, raw := range l {
		if raw == nil {
			continue
		}
		original := raw.(map[string]interface{})
		transformed := make(map[string]interface{})

		transformedName, err := expandSecretManagerSecretTopicsName(original["name"], d, config)
		if err != nil {
			return nil, err
		} else if val := reflect.ValueOf(transformedName); val.IsValid() && !isEmptyValue(val) {
			transformed["name"] = transformedName
		}

		req = append(req, transformed)
	}
	return req, nil
}

func expandSecretManagerSecretTopicsName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandSecretManagerSecretExpireTime(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandSecretManagerSecretTtl(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandSecretManagerSecretRotation(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	l := v.([]interface{})
	if len(l) == 0 || l[0] == nil {
		return nil, nil
	}
	raw := l[0]
	original := raw.(map[string]interface{})
	transformed := make(map[string]interface{})

	transformedNextRotationTime, err := expandSecretManagerSecretRotationNextRotationTime(original["next_rotation_time"], d, config)
	if err != nil {
		return nil, err
	} else if val := reflect.ValueOf(transformedNextRotationTime); val.IsValid() && !isEmptyValue(val) {
		transformed["nextRotationTime"] = transformedNextRotationTime
	}

	transformedRotationPeriod, err := expandSecretManagerSecretRotationRotationPeriod(original["rotation_period"], d, config)
	if err != nil {
		return nil, err
	} else if val := reflect.ValueOf(transformedRotationPeriod); val.IsValid() && !isEmptyValue(val) {
		transformed["rotationPeriod"] = transformedRotationPeriod
	}

	return transformed, nil
}

func expandSecretManagerSecretRotationNextRotationTime(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}

func expandSecretManagerSecretRotationRotationPeriod(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {
	return v, nil
}


text:
'use strict';
/**
 * This part of the application is responsible for handling the routes api/v1. It delegates
 * the requests mounted on that path to the handlers via express-load.
 */

var path = require('path');
var fs = require('fs');
var express = require('express');
var debug = require('debug')('fanscount:api:init');
var app = module.exports = express();

var apiRoutesPath = './api/v1/routes';

function initializeRoutes() {
    var routes = fs.readdirSync(apiRoutesPath);

    for (var i = routes.length; i--;) {
        if (routes[i] === 'error.js') {
            continue;
        }

        initializeRoute(routes[i]);
    }

    initializeRoute('error.js');
}

function initializeRoute(route) {
    var routerPath = path.join(process.cwd(), apiRoutesPath, route);
    var router = require(routerPath);

    router(app);
}

debug('initializing api routes');
initializeRoutes();


text:
NSString *DQTwitterFriendsCoordinatorErrorDomain = @"DQTwitterFriendsCoordinatorErrorDomain";
const NSInteger DQTwitterFriendsCoordinatorUnknownErrorCode = 1000;

@interface DQTwitterFriendsCoordinator ()

@property (nonatomic, strong) DQTwitterController *twitterController;
@property (nonatomic, strong, readwrite) DQPublicServiceController *publicServiceController;
@property (nonatomic, strong, readwrite) DQPrivateServiceController *privateServiceController;
@property (nonatomic, strong, readwrite) NSMutableIndexSet *selectedFriends;
@property (nonatomic, strong) NSString *invitationMessage;

@end

@implementation DQTwitterFriendsCoordinator

- (instancetype)initWithTwitterController:(DQTwitterController *)twitterController publicServiceController:(DQPublicServiceController *)publicServiceController privateServiceController:(DQPrivateServiceController *)privateServiceController
{
    if ([self class] == [DQTwitterFriendsCoordinator class])
    {
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
        {
            self = [[DQPadTwitterFriendsCoordinator alloc] initWithTwitterController:twitterController publicServiceController:publicServiceController privateServiceController:privateServiceController];
        }
        else
        {
            self = [[DQPhoneTwitterFriendsCoordinator alloc] initWithTwitterController:twitterController publicServiceController:publicServiceController privateServiceController:privateServiceController];
        }
    }
    else
    {
        self = [super init];
        if (self)
        {
            _twitterController = twitterController;
            _privateServiceController = privateServiceController;
            _publicServiceController = publicServiceController;
            _followingOrInvitedFriends = [[NSMutableIndexSet alloc] init];
            _selectedFriends = [[NSMutableIndexSet alloc] init];
        }
    }
    return self;
}

#pragma mark - DQFriendListViewControllerDataSource

- (NSString *)emptyFriendListMessageForFriendListViewController:(DQFriendListViewController *)friendListViewController
{
    return DQLocalizedString(@"It looks like you don't have any Twitter friends to invite.", @"The user has no Twitter friends available to invite display message");
}

- (NSString *)authorizationRequestMessageForFriendListViewController:(DQFriendListViewController *)friendListViewController
{
    return DQLocalizedString(@"Connect with Twitter to see your list of friends.\nThen choose friends you'd like to add.", @"Prompt to connect with Twitter to invite friends display message");
}

- (NSString *)authorizationFailedMessageForFriendListViewController:(DQFriendListViewController *)friendListViewController
{
    return DQLocalizedString(@"Authorization with Twitter failed. Please try again.", @"Twitter authorization failed, prompt to try again");
}

- (NSUInteger)numberOfRowsInFriendListViewController:(DQFriendListViewController *)friendListViewController
{
    return [self.friends count];
}

- (NSString *)friendListViewController:(DQFriendListViewController *)friendListViewController displayNameAtIndex:(NSUInteger)index
{
    return [[self.friends objectAtIndex:index] valueForKey:@"name"];
}

- (NSString *)friendListViewController:(DQFriendListViewController *)friendListViewController avatarImageURLAtIndex:(NSUInteger)index
{
    return [[self.friends objectAtIndex:index] valueForKey:@"profile_image_url"];
}

- (NSString *)friendListViewController:(DQFriendListViewController *)friendListViewController dqUsernameAtIndex:(NSUInteger)index
{
    NSNumber *friendID = [[self.friends objectAtIndex:index] valueForKey:@"id"];
    return [[self.friendsOnDrawQuest objectForKey:friendID] objectForKey:@"username"];
}

- (NSUInteger)numberOfInvitesSentOrPendingForFriendListViewController:(DQFriendListViewController *)friendListViewController
{
    return self.invitesSent;
}

#pragma mark - DQFriendListViewControllerDelegate

- (void)friendListViewController:(DQFriendListViewController *)friendListViewController hasPermissionsWithCompletionBlock:(void (^)(BOOL))completionBlock failureBlock:(void (^)(NSError *))failureBlock
{
    [self.twitterController hasTwitterAccess:completionBlock failureBlock:failureBlock];
}

- (void)friendListViewController:(DQFriendListViewController *)friendListViewController requestPermissionsWithCancellationBlock:(dispatch_block_t)cancellationBlock completionBlock:(dispatch_block_t)completionBlock failureBlock:(void (^)(NSError *))failureBlock accountSelectedBlock:(dispatch_block_t)accountSelectedBlock fromView:(UIView *)view
{
    [self.twitterController requestTwitterAccessInView:view cancellationBlock:cancellationBlock accountSelectedBlock:accountSelectedBlock completionBlock:completionBlock failureBlock:failureBlock];
}

- (DQButton *)friendListViewController:(DQFriendListViewController *)friendListViewController requestAccessButtonWithTappedBlock:(DQButtonBlock)tappedBlock
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
    {
        DQButton *twitterButton = [DQButton buttonWithType:UIButtonTypeCustom];
        UIImage *twitterButtonImage = [UIImage imageNamed:@"button_twitter_long"];
        [twitterButton setBackgroundImage:twitterButtonImage forState:UIControlStateNormal];
        twitterButton.frame = CGRectMake(0.0, 0.0, twitterButtonImage.size.width, twitterButtonImage.size.height);
        twitterButton.tappedBlock = tappedBlock;
        return twitterButton;
    }
    else
    {
        DQButton *twitterButton = [DQButton buttonWithImage:[UIImage imageNamed:@"button_twitter_long"]];
        twitterButton.tappedBlock = tappedBlock;
        return twitterButton;
    }
}

- (void)friendListViewController:(DQFriendListViewController *)friendListViewController loadFriendsWithCompletionBlock:(dispatch_block_t)completionBlock failureBlock:(void (^)(NSError *error))failureBlock noFriendsBlock:(dispatch_block_t)noFriendsBlock
{
    if ([self.friends count])
    {
        if (completionBlock)
        {
            completionBlock();
        }
    }
    else
    {
        __weak typeof(self) weakSelf = self;
        __block BOOL twitterFriendsRequestActive = YES;
        __weak __block DQHTTPRequest *twitterFollowersOnDrawQuestRequest = nil;

        __block NSError *twitterFriendsRequestError = nil;
        __block NSError * twitterFollowersOnDrawQuestError = nil;

        dispatch_block_t errorBlock = ^{
            if ( ! (twitterFriendsRequestActive || twitterFollowersOnDrawQuestRequest))
            {
                // both requests have completed, and the second one failed, calling errorBlock
                // or, the first one failed and the second one completed but dataReceivedBlock
                // called errorBlock because it noticed that one of the errors was set
                if (failureBlock)
                {
                    if (twitterFriendsRequestError)
                    {
                        failureBlock(twitterFriendsRequestError);
                    }
                    else
                    {
                        // this really shouldn't happen because this is only called if one of those errors is
                        // set to a non-nil value, so this message should never see the user. Included for the
                        // sake of completeness and so that if you DO see this error, you can find it in the
                        // source and fix the bug
                        NSDictionary *userInfo = @{NSLocalizedDescriptionKey: DQLocalizedString(@"An unknown error occurred.", @"Generic unknown error message")};
                        NSError *error = [NSError errorWithDomain:DQTwitterFriendsCoordinatorErrorDomain code:DQTwitterFriendsCoordinatorUnknownErrorCode userInfo:userInfo];
                        failureBlock(error);
                    }
                }
            }
        };

        dispatch_block_t dataReceivedBlock = ^{
            if ( ! (twitterFriendsRequestActive || twitterFollowersOnDrawQuestRequest))
            {
                if (twitterFriendsRequestError)
                {
                    errorBlock();
                }
                else
                {
                    if ([weakSelf.friends count])
                    {
                        NSMutableArray *drawQuestFriends = [NSMutableArray new];
                        NSMutableArray *twitterFriends = [NSMutableArray new];
                        NSMutableDictionary *twitterFriendsOnDrawQuest = [NSMutableDictionary dictionary];

                        NSMutableArray *alphaSortFriends = [NSMutableArray arrayWithArray:weakSelf.friends];
                        NSSortDescriptor *alphaSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
                        [alphaSortFriends sortUsingDescriptors:[NSArray arrayWithObject:alphaSort]];

                        for (NSDictionary *friend in alphaSortFriends)
                        {
                            // We don't need the whole thing
                            NSDictionary *smallerFriend = [NSDictionary dictionaryWithObjectsAndKeys:friend[@"id"], @"id", friend[@"screen_name"], @"screen_name", friend[@"name"], @"name", friend[@"profile_image_url"], @"profile_image_url", nil];
                            if (weakSelf.followersOnDrawQuest[friend[@"id"]])
                            {
                                [drawQuestFriends addObject:smallerFriend];
                                twitterFriendsOnDrawQuest[friend[@"id"]] = weakSelf.followersOnDrawQuest[friend[@"id"]];
                                NSUInteger index = [drawQuestFriends count] - 1;
                                if ([weakSelf.followersOnDrawQuest[friend[@"id"]] boolForKey:@"viewer_is_following"])
                                {
                                    [weakSelf.followingOrInvitedFriends addIndex:index];
                                }
                                else
                                {
                                    [weakSelf.selectedFriends addIndex:index];
                                }
                            }
                            else
                            {
                                [twitterFriends addObject:smallerFriend];
                            }
                        }

                        weakSelf.friends = [drawQuestFriends arrayByAddingObjectsFromArray:twitterFriends];
                        weakSelf.followersOnDrawQuest = nil;
                        weakSelf.friendsOnDrawQuest = twitterFriendsOnDrawQuest;

                        if (completionBlock)
                        {
                            if (completionBlock)
                            {
                                if (weakSelf.messageForInviteBlock)
                                {
                                    weakSelf.messageForInviteBlock(DQAPIValueShareChannelTypeTwitter, ^void(NSString *message) {
                                        weakSelf.invitationMessage = message;
                                        completionBlock();
                                    });
                                }
                                else
                                {
                                    @throw [NSException exceptionWithName:NSGenericException reason:@"DQTwitterFriendsCoordinator: messageForInviteBlock not defined." userInfo:nil];
                                }
                            }
                        }
                    }
                    else
                    {
                        if (noFriendsBlock)
                        {
                            noFriendsBlock();
                        }
                    }
                }
            }
        };

        // Friends from Twitter Request
        [self.twitterController requestFriendsListForTwitterAccount:^(NSArray *friendsArray) {
            twitterFriendsRequestActive = NO;
            weakSelf.friends = friendsArray;
            dataReceivedBlock();
        } cancellationBlock:^{
            // Do nothing if canceled.
        } failureBlock:^(NSError *error) {
            if (error)
            {
                twitterFriendsRequestError = error;
                errorBlock();
            }
            else // in the strange case that userList is nil and request.error is too, we still need an error to trigger the failureBlock
            {
                NSDictionary *userInfo = @{NSLocalizedDescriptionKey: DQLocalizedString(@"An unknown error occurred communicating with Twitter", @"Unknown Twitter error alert message")};
                twitterFriendsRequestError = [NSError errorWithDomain:DQTwitterFriendsCoordinatorErrorDomain code:DQTwitterFriendsCoordinatorUnknownErrorCode userInfo:userInfo];
                errorBlock();
            }
        }];

        // Twitter friends on DrawQuest Request
        NSString *twitterToken = self.twitterController.twitterAccessToken;
        NSString *twitterSecret = self.twitterController.twitterAccessTokenSecret;

        twitterFollowersOnDrawQuestRequest = [self.privateServiceController requestTwitterFollowersOnDrawQuestWithTwitterToken:twitterToken twitterSecret:twitterSecret completionBlock:^(DQHTTPRequest *request, id JSONObject, NSArray *userList) {
            twitterFollowersOnDrawQuestRequest = nil;
            if (userList)
            {
                NSMutableDictionary *map = [[NSMutableDictionary alloc] initWithCapacity:[userList count]];
                if ([userList count])
                {
                    for (NSDictionary *userDict in userList)
                    {
                        map[userDict[@"twitter_uid"]] = userDict;
                    }
                }
                weakSelf.followersOnDrawQuest = map;
                dataReceivedBlock();
            }
            else
            {
                if (request.error)
                {
                    twitterFollowersOnDrawQuestError = request.error;
                }
                else // in the strange case that userList is nil and request.error is too, we still need an error to trigger the failureBlock
                {
                    NSDictionary *userInfo = @{NSLocalizedDescriptionKey: DQLocalizedString(@"An unknown error occurred communicating with Twitter", @"Unknown Twitter error alert message")};
                    twitterFollowersOnDrawQuestError = [NSError errorWithDomain:DQTwitterFriendsCoordinatorErrorDomain code:DQTwitterFriendsCoordinatorUnknownErrorCode userInfo:userInfo];
                }
                weakSelf.followersOnDrawQuest = @{};
                dataReceivedBlock();
            }
        }];
    }
}

- (UIView *)friendListViewController:(DQFriendListViewController *)friendListViewController accessoryViewAtIndex:(NSUInteger)index
{
    // Default to following DQ friends get a checkmark view that can be deselected
    if ([self.selectedFriends containsIndex:index])
    {
        return [self accessoryViewForFriendsOnDrawQuestWithFriendListViewController:friendListViewController atIndex:index];
    }
    // If we're already following or have invited them, show a checkmark view
    else if ([self.followingOrInvitedFriends containsIndex:index])
    {
        return [self accessoryViewForFriendsInvitedWithFriendListViewController:friendListViewController atIndex:index];
    }
    // Otherwise show a follow or invite button
    else
    {
        return [self accessoryViewForFriendsNotInvitedWithFriendListViewController:friendListViewController atIndex:index];
    }
}

- (void)friendListViewController:(DQFriendListViewController *)friendListViewController didSelectFriendAtIndex:(NSUInteger)index accessoryView:(UIView *)accessoryView
{
    // Don't do anything when tapping a Twitter cell
}

- (void)friendListViewController:(DQFriendListViewController *)friendListViewController sendPendingRequestsWithCancellationBlock:(dispatch_block_t)cancellationBlock completionBlock:(dispatch_block_t)completionBlock failureBlock:(void (^)(NSError *))failureBlock
{
    // We only need to send follow requests for selected people
    if ([self.selectedFriends count])
    {
        NSArray *friendIDsToFollow = [[self.friends objectsAtIndexes:self.selectedFriends] valueForKey:@"id"];
        NSMutableArray *toFollow = [[NSMutableArray alloc] initWithCapacity:[friendIDsToFollow count]];
        for (NSString *userID in friendIDsToFollow)
        {
            [toFollow addObject:self.friendsOnDrawQuest[userID][@"username"]];
        }
        NSArray *drawQuestUsernamesToFollow = [NSArray arrayWithArray:toFollow];

        __weak typeof(self) weakSelf = self;
        [self.twitterController logEvent:DQAnalyticsEventFollow withParameters:@{@"source": @"Add-Friends"}];
        [self.privateServiceController requestFollowForUsersWithNames:drawQuestUsernamesToFollow completionBlock:^(DQHTTPRequest *request, id JSONObject) {
            weakSelf.followingOrInvitedFriends = weakSelf.selectedFriends;
            weakSelf.selectedFriends = [[NSMutableIndexSet alloc] init];
            if (completionBlock)
            {
                completionBlock();
            }
        }];
    }
    else if (completionBlock)
    {
        completionBlock();
    }
}

- (void)followUserAtIndex:(NSInteger)index withCompletionBlock:(void (^)(DQHTTPRequest *request))completionBlock
{
    NSNumber *friendID = [[self.friends objectAtIndex:index] valueForKey:@"id"];

    NSString *dqUsername = [[self.friendsOnDrawQuest objectForKey:friendID] objectForKey:@"username"];
    [self.twitterController logEvent:DQAnalyticsEventFollow withParameters:@{@"source": @"Add-Friends"}];
    [self.privateServiceController requestFollow:YES forUserWithName:dqUsername completionBlock:^(DQHTTPRequest *request, id JSONObject) {
        if (completionBlock)
        {
            completionBlock(request);
        }
    }];
}

- (void)inviteUserAtIndex:(NSInteger)index withCompletionBlock:(void (^)(DQHTTPRequest *request))completionBlock failureBlock:(void (^)(NSError *error))failureBlock
{
    __weak typeof(self) weakSelf = self;
    NSNumber *friendID = [[self.friends objectAtIndex:index] valueForKey:@"id"];

    [self.twitterController sendDirectMessageForTwitterAccount:self.invitationMessage toUserID:[friendID stringValue] cancellationBlock:^{
        // We don't need to do anything here
    } completionBlock:^{
        [weakSelf.privateServiceController requestAddInvitedTwitterFriends:@[[friendID stringValue]] completionBlock:^(DQHTTPRequest *request) {
            if (completionBlock)
            {
                completionBlock(request);
            }
        }];
    } failureBlock:^(NSError *error) {
        if (failureBlock)
        {
            failureBlock(error);
        }
    }];
}

@end


text:
package com.sunny.grokkingalgorithms.design_patterns.iterator.impl;

import com.sunny.grokkingalgorithms.design_patterns.iterator.CustomIterator;

/**
 * Created by sundas on 4/17/2018.
 */
public class ArrayIterator<T> implements CustomIterator<T>{

  private int index;

  public ArrayIterator(T[] ts) {
    this.ts = ts;
  }

  private T[] ts;

  @Override
  public boolean hasNext() {
    if(ts != null && this.index < ts.length){
      return true;
    }
    return false;
  }

  @Override
  public T next() {
    if(ts != null){
      return ts[index++];
    }
    return null;
  }

  @Override
  public T first() {
    if(ts != null && ts.length >= 1){
      return ts[0];
    }
    return null;
  }
}


text:
/*
 * @eFapsPackage  org.efaps.ui.wicket.components.form
 * @eFapsUUID     b9aca56b-392a-4da8-98a6-886df32bb8d0
 * @eFapsApplication eFaps-WebApp
 */

/*
 * This script is needed because when a AjaxSubmit is done with the script from
 * wicket the elements are serialized and filtered. The Filter does not pass the
 * values from inputs of type "file". Therefore this script creates hidden inputs
 * with the same name and value as the filtered one.
 * The script is executed as a precondition script for the ajaxsubmitbehavior
 * from wicket, therefore it must return true to allow the ajaxcall to advance.
 */

function eFapsFileInput(){
  var ins = document.getElementsByTagName("input");

  for (var i = 0; i < ins.length; ++i) {
    if(ins[i].type.toLowerCase() === "file"){
      var fileNode = ins[i];
      var parent = fileNode.parentNode;
      var  node = fileNode.nextSibling;
      var add = true;
      while (node != null) {
        if(node.nodeName == "INPUT"){
          if(node.type == "hidden" && node.name == fileNode.name){
            node.value = fileNode.value;
            add = false;
          }
        }
        node = node.nextSibling;
      }
      if(add){
        var newinput = document.createElement("input");
        newinput.type = "hidden";
        newinput.name = fileNode.name;
        newinput.value = fileNode.value;
        parent.appendChild(newinput);
      }
    }
  }
  return true;
}


text:
wget https://raw.github.com/colinmollenhour/modman/master/modman
mv ./modman /usr/bin
chmod +x /usr/bin/modman


text:
<!DOCTYPE HTML>

  <title>Test for Bug 610212</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>

Mozilla Bug 610212


text:
import warnings
warnings.simplefilter('ignore', Warning)

from solr_tests.tests.admin import *
from solr_tests.tests.inputs import *
from solr_tests.tests.management_commands import *
from solr_tests.tests.solr_query import *
from solr_tests.tests.solr_backend import *
from solr_tests.tests.templatetags import *


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

namespace Domain.Entities
{
    public class EQuestions: IEntity
    {
        public virtual long Id { get; set; }
        public virtual bool Archived { get; protected set; }
        public virtual string usuario{ get; set; }
        public virtual string pregunta { get; set; }
        public virtual string respuesta { get; set; }
        public virtual void Archive()
        {
            throw new NotImplementedException();
        }

        public virtual  void Activate()
        {
            throw new NotImplementedException();
        }
    }
}


text: GPU Accelerated Deadlock Avoidance


text:
package net.hycrafthd.corelib.util.cschematic;

import java.io.File;

import net.hycrafthd.corelib.util.NBTUtil;
import net.minecraft.nbt.*;

public class SchematicWriter {

	private final Schematic schematic;

	public SchematicWriter(Schematic args) {
		this.schematic = args;
	}

	public Schematic getSchematic() {
		return schematic;
	}

	public void write(final File name){
		new Thread(new Runnable() {
			@Override
			public void run() {
				Thread.currentThread().setName("Schematic Builder");
				try{
				BlockObj[] blockar = schematic.getBlocks();
				NBTTagList list = new NBTTagList();
				for (BlockObj blockObj : blockar) {
					if(blockObj != null){
					NBTTagCompound comp = blockObj.toNBT();
					list.appendTag(comp);
					}
				}
				NBTTagCompound tag = new NBTTagCompound();
				tag.setTag("List", list);
				tag.setInteger("X", schematic.disx);
				tag.setInteger("Y", schematic.disy);
				tag.setInteger("Z", schematic.disz);
				NBTUtil.writeNBTToFile(tag, name);
				}catch(Throwable th){
					System.err.println("Failed to Save Schematic");
			    }
			}
		}).start();
	}

}


text:
import { Base } from './base'
import { SqlString } from '../collectors'
import { PostgresqlEngine } from '../engines'

class PostgresqlVisitor extends Base {
  constructor() {
    super()
    this.collector = new SqlString(this.engine)
  }

  get engine() {
    return new PostgresqlEngine()
  }

}

export { PostgresqlVisitor }


text:
package org.apache.commons.vfs2.provider.tar;

import org.apache.commons.vfs2.AbstractProviderTestConfig;
import org.apache.commons.vfs2.AbstractVfsTestCase;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.ProviderTestSuite;
import org.apache.commons.vfs2.impl.DefaultFileSystemManager;

import junit.framework.Test;

/**
 * Tests for the Tar file system, using a tar file nested inside another tar file.
 */
public class NestedTgzTestCase extends AbstractProviderTestConfig {
    /**
     * Creates the test suite for nested tar files.
     */
    public static Test suite() throws Exception {
        return new ProviderTestSuite(new NestedTgzTestCase(), true);
    }

    /**
     * Returns the base folder for tests.
     */
    @Override
    public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
        // Locate the base Tar file
        final String tarFilePath = AbstractVfsTestCase.getTestResource("nested.tgz").getAbsolutePath();
        final String uri = "tgz:file:" + tarFilePath + "!/test.tgz";
        final FileObject tarFile = manager.resolveFile(uri);

        // Now build the nested file system
        final FileObject nestedFS = manager.createFileSystem(tarFile);
        return nestedFS.resolveFile("/");
    }

    /**
     * Prepares the file system manager.
     */
    @Override
    public void prepare(final DefaultFileSystemManager manager) throws Exception {
        manager.addProvider("tgz", new TarFileProvider());
        manager.addExtensionMap("tgz", "tgz");
        manager.addProvider("tar", new TarFileProvider());
    }
}


text:
layout: post
title: Brad's Awards for the 2010s
comments: yes
tags: reflecting
---
As is tradition, I'm looking back on the closing decade with a nostalgic eye and an awards-show themed post.

As usual, there are no trophies on offer, but I *am* more than willing to email a PDF certificate to those winners who want something to stick to their fridge.

The HRH The Prince Harry, Duke of Sussex Award for Excellence in Partying

Brett Ryan

For sustained excellence in the field of throwing parties.

No one else has thrown as many high quality parties this decade as Brett has. Most famously, the annual Beefy's Birthday Pub Crawl, but also just SO MANY 'just because' parties, and I think that the tail end of The Beefyville might have just snuck into this decade? If not, I'm going to give partial credit anyway.

Truly, you are the host with the most.

The Defecating Penguin Award for Doing Cool Shit with me

Laura Blake

Extremely challenging to choose this one, because I try and make a point of only doing cool shit.

However, as my relationship with Laura largely consists of 'flying to the same state and jamming as much fun as possible into the number of minutes available,' on a purely percentage basis I think I have done more cool stuff with Laura than anyone else this decade.

The Good Times Award for Greatest Altitude Achieved

Annie Phelan

I don't know what our cruising altitude was that time we flew to America, but I assume it was higher than a regular domestic flight is. That was a good time though. Not the flight so much as the adventure at the other end, obviously.
10/10, would adventure with again.

The "The Mountain Goats Award" for Making It Through This Year (Though It Killed You)

This award is for everyone. Over the past ten years, you've overcome your challenges and achieved so much. I'm really proud of you guys.

We've made it to 2020!

Can't wait to see what you all achieve next 😊

The Chairman Kaga Memorial Award for Fine Dining

Sarah Chan

For indulging Tom's ridiculous special dietary requirements (and denying me a second meal) at your wedding and arranging for the world's fanciest and most expensiveist Vegemite sandwich ever.

The Saint Nicholas of Myra Award for most Christmas Spirit

My Housemate Kate

There's a lot to like about living with Kate: adventures, work stories, her amazing couch.

But one thing I didn't realise for nearly 12 months was how deeply she gets into Christmas. Our house spends December bedecked with enough LED lighting to land a cesna in the outback and I. am. here for it.

the Samuel E. Wright Memorial Award for being Better Down Where it's Wetter

Cairns Moot

Ahhh, that one day when Queensland Rovers took me on a scenic tour of the waterfalls, transparent pools, uncomfortably clear and deep lakes and natural waterslides all around the Cairns region.

Definitely the single best water (and road trip/singing) based day of the decade.

I would go on that adventure again in a heartbeat, and you all should come with.

The Louis Daguerre Award for Drawing with Light

Hannah Stockfeld

 may have only known Hannah for just over half this decade, but I'm reasonably confident that there is no one with whom I am in more photos with during the past ten years.

I very nearly changed my 'no trophies' rule to present this as the Golden Selfie Stick, complete with golden selfie stick; but the galaxy needs order.

Hannah is also the NAB/AFL Rising Star, the newest friend who made the best impact on my decade.

and, finally, the coveted Copulating Jelly Baby Award for being Fucking Sweet:

When I was thinking about what was the best event I did this decade, two main things came to mind.

Firstly, that time we went to Tom's birthday at Wet n Wild and went and found a bunch of waterfalls and swimming holes afterward.

And then secondly, the time I went out to dinner on Sunday night because Slav-Dogs was comin' to town and ended up going on a lightning mid-week ski adventure to Mt Hotham.

So I'm giving this award to both of those events.

Because I can.


text:
package com.zxy.commons.web.security;

import javax.annotation.PostConstruct;

import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.zxy.commons.web.constant.ShiroConstant;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 登录和授权
 *
 *

 * View Source
 *
 * @param <T> session class type
 * @author zhaoxunyong@qq.com
 * @version 1.0
 * @since 1.0
 */
//@Transactional(readOnly = true)
public abstract class AbstractCustomerShiroDbRealm<T> extends AuthorizingRealm {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * session检查
     *

     * 检查用户名与密码是否正确?

     * 正确: 返回需要缓存的session对象

     * 错误: 抛出{@code org.apache.shiro.authz.AuthorizationInfo}异常
     *
     * @param username username
     * @param password password
     * @return 需要缓存的session对象
     * @throws AuthenticationException AuthenticationException
     */
    protected abstract T sessionCheck(String username, String password) throws AuthenticationException;

    /**
     * 添加角色权限到shiro中
     *
     * @param simpleAuthorizationInfo simpleAuthorizationInfo
     * @param sessionObject sessionObject
     */
    protected abstract void addRoleAndPermissions(SimpleAuthorizationInfo simpleAuthorizationInfo, T sessionObject);

    /**
     * 认证回调函数,登录时调用.
     */
//    @Transactional(readOnly = false, rollbackFor = Exception.class)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
        Preconditions.checkArgument(authcToken instanceof UsernamePasswordToken, "AuthenticationToken is not UsernamePasswordToken instance.");
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        // 获得用户名与密码
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());
        T sessionObject = sessionCheck(username, password);
        String decodePassword = Hashing.sha1().hashBytes(String.valueOf(token.getPassword()).getBytes()).toString();
        return new SimpleAuthenticationInfo(sessionObject, decodePassword.toCharArray(), getName());

    }

    /**
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
     */
//    @Transactional(readOnly = true)
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        @SuppressWarnings("unchecked")
        T sessionObject = (T)principals.getPrimaryPrincipal();
        // 授权只有一次
//        if (!shiroUser.isHasFillData()) {
//            checkAndFillData(shiroUser);
//        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        // 基于Role的权限信息
//        info.addRole(shiroUser.getEmpJob());// 职位理解成角色
//        // 基于Permission的权限信息
//        info.addStringPermissions(shiroUser.getPermissions());
        addRoleAndPermissions(info, sessionObject);
        return info;
    }

    /**
     * 设定Password校验的Hash算法与迭代次数.
     */
    @PostConstruct
    public void initCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(ShiroConstant.HASH_ALGORITHM);
        matcher.setHashIterations(ShiroConstant.HASH_INTERATIONS);
        setCredentialsMatcher(matcher);
    }
}


text:
*Angular elements* are Angular components packaged as *custom elements* \(also called Web Components\), a web standard for defining new HTML elements in a framework-agnostic way.

For the sample application that this page describes, see the <live-example></live-example>.

[Custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements) are a Web Platform feature currently supported by Chrome, Edge \(Chromium-based\), Firefox, Opera, and Safari, and available in other browsers through polyfills \(see [Browser Support](#browser-support)\).
A custom element extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code.
The browser maintains a `CustomElementRegistry` of defined custom elements, which maps an instantiable JavaScript class to an HTML tag.

The `@angular/elements` package exports a `createCustomElement()` API that provides a bridge from Angular's component interface and change detection functionality to the built-in DOM API.

Transforming a component to a custom element makes all of the required Angular infrastructure available to the browser.
Creating a custom element is simple and straightforward, and automatically connects your component-defined view with change detection and data binding, mapping Angular functionality to the corresponding built-in HTML equivalents.

We are working on custom elements that can be used by web apps built on other frameworks.
A minimal, self-contained version of the Angular framework is injected as a service to support the component's change-detection and data-binding functionality.
For more about the direction of development, check out this [video presentation](https://www.youtube.com/watch?v=Z1gLFPLVJjY&t=4s).

## Using custom elements

Custom elements bootstrap themselves - they start automatically when they are added to the DOM, and are automatically destroyed when removed from the DOM.
Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular terms or usage conventions.

|                                                | Details |
|:---                                            |:---     |
| Easy dynamic content in an Angular application | Transforming a component to a custom element provides a straightforward path to creating dynamic HTML content in your Angular application. HTML content that you add directly to the DOM in an Angular application is normally displayed without Angular processing, unless you define a *dynamic component*, adding your own code to connect the HTML tag to your application data, and participate in change detection. With a custom element, all of that wiring is taken care of automatically.                                                                                |
| Content-rich applications                      | If you have a content-rich application, such as the Angular app that presents this documentation, custom elements let you give your content providers sophisticated Angular functionality without requiring knowledge of Angular. For example, an Angular guide like this one is added directly to the DOM by the Angular navigation tools, but can include special elements like `<code-snippet>` that perform complex operations. All you need to tell your content provider is the syntax of your custom element. They don't need to know anything about Angular, or anything about your component's data structures or implementation. |

### How it works

Use the `createCustomElement()` function to convert a component into a class that can be registered with the browser as a custom element.
After you register your configured class with the browser's custom-element registry, use the new element just like a built-in HTML element in content that you add directly into the DOM:

<my-popup message="Use Angular!"></my-popup>

When your custom element is placed on a page, the browser creates an instance of the registered class and adds it to the DOM.
The content is provided by the component's template, which uses Angular template syntax, and is rendered using the component and DOM data.
Input properties in the component correspond to input attributes for the element.

## Transforming components to custom elements

Angular provides the `createCustomElement()` function for converting an Angular component, together with its dependencies, to a custom element.
The function collects the component's observable properties, along with the Angular functionality the browser needs to create and destroy instances, and to detect and respond to changes.

The conversion process implements the `NgElementConstructor` interface, and creates a
constructor class that is configured to produce a self-bootstrapping instance of your component.

Use the built-in [`customElements.define()`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/define) function to register the configured constructor and its associated custom-element tag with the browser's [`CustomElementRegistry`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry).
When the browser encounters the tag for the registered element, it uses the constructor to create a custom-element instance.

Avoid using the [`@Component`](api/core/Component) [selector](api/core/Directive#selector) as the custom-element tag name.
This can lead to unexpected behavior, due to Angular creating two component instances for a single DOM element:
One regular Angular component and a second one using the custom element.

### Mapping

A custom element *hosts* an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs.
Component properties and logic maps directly into HTML attributes and the browser's event system.

*   The creation API parses the component looking for input properties, and defines corresponding attributes for the custom element.
    It transforms the property names to make them compatible with custom elements, which do not recognize case distinctions.
    The resulting attribute names use dash-separated lowercase.
    For example, for a component with `@Input('myInputProp') inputProp`, the corresponding custom element defines an attribute `my-input-prop`.

*   Component outputs are dispatched as HTML [Custom Events](https://developer.mozilla.org/docs/Web/API/CustomEvent), with the name of the custom event matching the output name.
    For example, for a component with `@Output() valueChanged = new EventEmitter()`, the corresponding custom element dispatches events with the name "valueChanged", and the emitted data is stored on the event's `detail` property.
    If you provide an alias, that value is used; for example, `@Output('myClick') clicks = new EventEmitter<string>();` results in dispatch events with the name "myClick".

For more information, see Web Component documentation for [Creating custom events](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events#Creating_custom_events).

## Browser support for custom elements

The recently-developed [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements) Web Platform feature is currently supported natively in a number of browsers.

| Browser                 | Custom Element Support |
|:---                     |:---                    |
| Chrome                  | Supported natively.    |
| Edge \(Chromium-based\) | Supported natively.    |
| Firefox                 | Supported natively.    |
| Opera                   | Supported natively.    |
| Safari                  | Supported natively.    |

To add the `@angular/elements` package to your workspace, run the following command:

npm install @angular/elements --save

## Example: A Popup Service

Previously, when you wanted to add a component to an application at runtime, you had to define a *dynamic component*, and then you would have to load it, attach it to an element in the DOM, and wire up all of the dependencies, change detection, and event handling, as described in [Dynamic Component Loader](guide/dynamic-component-loader).

Using an Angular custom element makes the process much simpler and more transparent, by providing all of the infrastructure and framework automatically —all you have to do is define the kind of event handling you want.
\(You do still have to exclude the component from compilation, if you are not going to use it in your application.\)

The following Popup Service example application defines a component that you can either load dynamically or convert to a custom element.

| Files                | Details |
|:---                  |:---     |
| `popup.component.ts` | Defines a simple pop-up element that displays an input message, with some animation and styling.                                                                                |
| `popup.service.ts`   | Creates an injectable service that provides two different ways to invoke the `PopupComponent`; as a dynamic component, or as a custom element Notice how much more setup is required for the dynamic-loading method.         |
| `app.module.ts`      | Adds the `PopupComponent` in the module's `declarations` list.                                                                                |
| `app.component.ts`   | Defines the application's root component, which uses the `PopupService` to add the pop-up to the DOM at run time. When the application runs, the root component's constructor converts `PopupComponent` to a custom element. |

For comparison, the demo shows both methods.
One button adds the popup using the dynamic-loading method, and the other uses the custom element.
The result is the same; only the preparation is different.

## Typings for custom elements

Generic DOM APIs, such as `document.createElement()` or `document.querySelector()`, return an element type that is appropriate for the specified arguments.
For example, calling `document.createElement('a')` returns an `HTMLAnchorElement`, which TypeScript knows has an `href` property.
Similarly, `document.createElement('div')` returns an `HTMLDivElement`, which TypeScript knows has no `href` property.

When called with unknown elements, such as a custom element name \(`popup-element` in our example\), the methods return a generic type, such as `HTMLElement`, because TypeScript can't infer the correct type of the returned element.

Custom elements created with Angular extend `NgElement` \(which in turn extends `HTMLElement`\).
Additionally, these custom elements will have a property for each input of the corresponding component.
For example, our `popup-element` has a `message` property of type `string`.

There are a few options if you want to get correct types for your custom elements.
Assume you create a `my-dialog` custom element based on the following component:

@Component(…)
class MyDialog {
  @Input() content: string;
}

The most straightforward way to get accurate typings is to cast the return value of the relevant DOM methods to the correct type.
For that, use the `NgElement` and `WithProperties` types \(both exported from `@angular/elements`\):

const aDialog = document.createElement('my-dialog') as NgElement & WithProperties<{content: string}>;
aDialog.content = 'Hello, world!';
aDialog.content = 123;  // <-- ERROR: TypeScript knows this should be a string.
aDialog.body = 'News';  // <-- ERROR: TypeScript knows there is no `body` property on `aDialog`.

This is a good way to quickly get TypeScript features, such as type checking and autocomplete support, for your custom element.
But it can get cumbersome if you need it in several places, because you have to cast the return type on every occurrence.

An alternative way, that only requires defining each custom element's type once, is augmenting the `HTMLElementTagNameMap`, which TypeScript uses to infer the type of a returned element based on its tag name \(for DOM methods such as `document.createElement()`, `document.querySelector()`, etc.\):

declare global {
  interface HTMLElementTagNameMap {
    'my-dialog': NgElement & WithProperties<{content: string}>;
    'my-other-element': NgElement & WithProperties<{foo: 'bar'}>;
    …
  }
}

Now, TypeScript can infer the correct type the same way it does for built-in elements:

document.createElement('div')               //--> HTMLDivElement (built-in element)
document.querySelector('foo')               //--> Element        (unknown element)
document.createElement('my-dialog')         //--> NgElement & WithProperties<{content: string}> (custom element)
document.querySelector('my-other-element')  //--> NgElement & WithProperties<{foo: 'bar'}>      (custom element)

@reviewed 2022-02-28


text:
<?php

namespace Site\CoreDomainBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Site\CoreDomain\Category\Category;
use Site\CoreDomain\Product\RepositoryInterface;
use Knp\Component\Pager\Paginator;

class ManufacturerRepositoryDoctrine extends EntityRepository implements RepositoryInterface
{
    /**
     * @param $slug
     * @return mixed
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function findOneBySlug($slug)
    {
    }
}


text:
namespace Caching
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class CachebleUserControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CacheControl.Text = "Last cache at " + DateTime.Now.TimeOfDay.ToString();
        }
    }
}


text:
class AddProviderTypeIdToProvider < ActiveRecord::Migration

  PROVIDER_TYPES = { 0 => "Mock", 1 => "Amazon EC2", 2 => "GoGrid", 3 => "Rackspace", 4 => "RHEV-M", 5 => "OpenNebula" }
  INVERTED_PROVIDER_TYPES = PROVIDER_TYPES.invert

  def self.up
    add_column :providers, :provider_type_id, :integer, :null => false, :default => 100
    rename_column :providers, :provider_type, :provider_type_int
    transform_provider_type_column
    remove_column :providers, :provider_type_int
  end

  def self.down
    add_column :providers, :provider_type_temporary, :integer
    transform_provider_type_column_back
    rename_column :providers, :provider_type_temporary, :provider_type
    remove_column :providers, :provider_type_id
  end

  def self.transform_provider_type_column
    Provider.all.each do |provider|
      provider.update_attribute(:provider_type_id, ProviderType.first(:conditions => {:name => PROVIDER_TYPES[provider.provider_type_int]}).id)
    end
  end

  def self.transform_provider_type_column_back
    Provider.all.each do |provider|
      provider.update_attribute(:provider_type_temporary, INVERTED_PROVIDER_TYPES[provider.provider_type.name])
    end
  end
end