text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button android:id="@+id/backButton"
        android:layout_width="396dp"
        android:layout_height="65dp"
        android:text="Back" />

    <TextView
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="pick_contact_msg"/>

    <Button android:id="@+id/pick_contact"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="pick_contact">
        <requestFocus />
    </Button>

    <ListView
        android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview
 * 'settings-internet-known-networks' is the settings subpage listing the
 * known networks for a type (currently always WiFi).
 */
import '//resources/cr_elements/cr_action_menu/cr_action_menu.js';
import '//resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import '//resources/cr_elements/cr_link_row/cr_link_row.js';
import '//resources/cr_elements/icons.m.js';
import '../../settings_shared_css.js';
import './internet_shared_css.js';

import {CrPolicyNetworkBehaviorMojo} from '//resources/cr_components/chromeos/network/cr_policy_network_behavior_mojo.m.js';
import {MojoInterfaceProvider, MojoInterfaceProviderImpl} from '//resources/cr_components/chromeos/network/mojo_interface_provider.m.js';
import {NetworkListenerBehavior} from '//resources/cr_components/chromeos/network/network_listener_behavior.m.js';
import {OncMojo} from '//resources/cr_components/chromeos/network/onc_mojo.m.js';
import {CrActionMenuElement} from '//resources/cr_elements/cr_action_menu/cr_action_menu.js';
import {assert, assertNotReached} from '//resources/js/assert.m.js';
import {afterNextRender, flush, html, Polymer, TemplateInstanceBase, Templatizer} from '//resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {Route, Router} from '../../router.js';
import {DeepLinkingBehavior} from '../deep_linking_behavior.m.js';
import {recordClick, recordNavigation, recordPageBlur, recordPageFocus, recordSearch, recordSettingChange, setUserActionRecorderForTesting} from '../metrics_recorder.m.js';
import {routes} from '../os_route.m.js';
import {RouteObserverBehavior} from '../route_observer_behavior.js';

Polymer({
  _template: html`{__html_template__}`,
  is: 'settings-internet-known-networks-page',

  behaviors: [
    DeepLinkingBehavior,
    NetworkListenerBehavior,
    CrPolicyNetworkBehaviorMojo,
    RouteObserverBehavior,
  ],

  properties: {
    /**
     * The type of networks to list.
     * @type {chromeos.networkConfig.mojom.NetworkType|undefined}
     */
    networkType: {
      type: Number,
      observer: 'networkTypeChanged_',
    },

    /**
     * List of all network state data for the network type.
     * @private {!Array<!OncMojo.NetworkStateProperties>}
     */
    networkStateList_: {
      type: Array,
      value() {
        return [];
      }
    },

    /** @private */
    showAddPreferred_: Boolean,

    /** @private */
    showRemovePreferred_: Boolean,

    /**
     * We always show 'Forget' since we do not know whether or not to enable
     * it until we fetch the managed properties, and we do not want an empty
     * menu.
     * @private
     */
    enableForget_: Boolean,

    /**
     * Contains the settingId of any deep link that wasn't able to be shown,
     * null otherwise.
     * @private {?chromeos.settings.mojom.Setting}
     */
    pendingSettingId_: {
      type: Number,
      value: null,
    },

    /**
     * Used by DeepLinkingBehavior to focus this page's deep links.
     * @type {!Set<!chromeos.settings.mojom.Setting>}
     */
    supportedSettingIds: {
      type: Object,
      value: () => new Set([
        chromeos.settings.mojom.Setting.kPreferWifiNetwork,
        chromeos.settings.mojom.Setting.kForgetWifiNetwork,
      ]),
    },
  },

  /** @private {string} */
  selectedGuid_: '',

  /** @private {?chromeos.networkConfig.mojom.CrosNetworkConfigRemote} */
  networkConfig_: null,

  /** @override */
  created() {
    this.networkConfig_ =
        MojoInterfaceProviderImpl.getInstance().getMojoServiceRemote();
  },

  /**
   * RouteObserverBehavior
   * @param {!Route} route
   * @param {!Route} oldRoute
   * @protected
   */
  currentRouteChanged(route, oldRoute) {
    // Does not apply to this page.
    if (route !== routes.KNOWN_NETWORKS) {
      return;
    }

    this.attemptDeepLink().then(result => {
      if (!result.deepLinkShown && result.pendingSettingId) {
        // Store any deep link settingId that wasn't shown so we can try again
        // in refreshNetworks.
        this.pendingSettingId_ = result.pendingSettingId;
      }
    });
  },

  /** CrosNetworkConfigObserver impl */
  onNetworkStateListChanged() {
    this.refreshNetworks_();
  },

  /** @private */
  networkTypeChanged_() {
    this.refreshNetworks_();
  },

  /**
   * Requests the list of network states from Chrome. Updates networkStates
   * once the results are returned from Chrome.
   * @private
   */
  refreshNetworks_() {
    if (this.networkType === undefined) {
      return;
    }
    const filter = {
      filter: chromeos.networkConfig.mojom.FilterType.kConfigured,
      limit: chromeos.networkConfig.mojom.NO_LIMIT,
      networkType: this.networkType,
    };
    this.networkConfig_.getNetworkStateList(filter).then(response => {
      this.networkStateList_ = response.result;

      // Check if we have yet to focus a deep-linked element.
      if (!this.pendingSettingId_) {
        return;
      }

      this.showDeepLink(this.pendingSettingId_).then(result => {
        if (result.deepLinkShown) {
          this.pendingSettingId_ = null;
        }
      });
    });
  },

  /**
   * @param {!OncMojo.NetworkStateProperties} networkState
   * @return {boolean}
   * @private
   */
  networkIsPreferred_(networkState) {
    // Currently we treat NetworkStateProperties.Priority as a boolean.
    return networkState.priority > 0;
  },

  /**
   * @param {!OncMojo.NetworkStateProperties} networkState
   * @return {boolean}
   * @private
   */
  networkIsNotPreferred_(networkState) {
    return networkState.priority === 0;
  },

  /**
   * @return {boolean}
   * @private
   */
  havePreferred_() {
    return this.networkStateList_.find(
               state => this.networkIsPreferred_(state)) !== undefined;
  },

  /**
   * @return {boolean}
   * @private
   */
  haveNotPreferred_() {
    return this.networkStateList_.find(
               state => this.networkIsNotPreferred_(state)) !== undefined;
  },

  /**
   * @param {!OncMojo.NetworkStateProperties} networkState
   * @return {string}
   * @private
   */
  getNetworkDisplayName_(networkState) {
    return OncMojo.getNetworkStateDisplayName(networkState);
  },

  /**
   * @param {!Event} event
   * @private
   */
  onMenuButtonTap_(event) {
    const button = event.target;
    const networkState =
        /** @type {!OncMojo.NetworkStateProperties} */ (event.model.item);
    this.selectedGuid_ = networkState.guid;
    // We need to make a round trip to Chrome in order to retrieve the managed
    // properties for the network. The delay is not noticeable (~5ms) and is
    // preferable to initiating a query for every known network at load time.
    this.networkConfig_.getManagedProperties(this.selectedGuid_)
        .then(response => {
          const properties = response.result;
          if (!properties) {
            console.warn('Properties not found for: ' + this.selectedGuid_);
            return;
          }
          if (properties.priority &&
              this.isNetworkPolicyEnforced(properties.priority)) {
            this.showAddPreferred_ = false;
            this.showRemovePreferred_ = false;
          } else {
            const preferred = this.networkIsPreferred_(networkState);
            this.showAddPreferred_ = !preferred;
            this.showRemovePreferred_ = preferred;
          }
          this.enableForget_ = !this.isPolicySource(networkState.source);
          /** @type {!CrActionMenuElement} */ (this.$.dotsMenu)
              .showAt(/** @type {!Element} */ (button));
        });
    event.stopPropagation();
  },

  /**
   * @param {!chromeos.networkConfig.mojom.ConfigProperties} config
   * @private
   */
  setProperties_(config) {
    this.networkConfig_.setProperties(this.selectedGuid_, config)
        .then(response => {
          if (!response.success) {
            console.warn(
                'Unable to set properties for: ' + this.selectedGuid_ + ': ' +
                JSON.stringify(config));
          }
        });
    recordSettingChange();
  },

  /** @private */
  onRemovePreferredTap_() {
    assert(this.networkType !== undefined);
    const config = OncMojo.getDefaultConfigProperties(this.networkType);
    config.priority = {value: 0};
    this.setProperties_(config);
    /** @type {!CrActionMenuElement} */ (this.$.dotsMenu).close();
  },

  /** @private */
  onAddPreferredTap_() {
    assert(this.networkType !== undefined);
    const config = OncMojo.getDefaultConfigProperties(this.networkType);
    config.priority = {value: 1};
    this.setProperties_(config);
    /** @type {!CrActionMenuElement} */ (this.$.dotsMenu).close();
  },

  /** @private */
  onForgetTap_() {
    this.networkConfig_.forgetNetwork(this.selectedGuid_).then(response => {
      if (!response.success) {
        console.warn('Froget network failed for: ' + this.selectedGuid_);
      }
    });

    if (this.networkType === chromeos.networkConfig.mojom.NetworkType.kWiFi) {
      recordSettingChange(chromeos.settings.mojom.Setting.kForgetWifiNetwork);
    } else {
      recordSettingChange();
    }

    /** @type {!CrActionMenuElement} */ (this.$.dotsMenu).close();
  },

  /**
   * Fires a 'show-detail' event with an item containing a |networkStateList_|
   * entry in the event model.
   * @param {!Event} event
   * @private
   */
  fireShowDetails_(event) {
    const networkState =
        /** @type {!OncMojo.NetworkStateProperties} */ (event.model.item);
    this.fire('show-detail', networkState);
    event.stopPropagation();
  },

  /**
   * Make sure events in embedded components do not propagate to onDetailsTap_.
   * @param {!Event} event
   * @private
   */
  doNothing_(event) {
    event.stopPropagation();
  },
});

redpajama_set_name: RedPajamaGithub


text:
package org.otfusion.caturday.migrations.files;

import org.otfusion.caturday.migrations.AbstractMigration;
import org.otfusion.caturday.migrations.DatabaseTableName;

// used from MigrationUtils reflection call
@SuppressWarnings("unused")
public class Migration1 extends AbstractMigration {

    @Override
    public int getVersion() {
        return 1;
    }

    @Override
    public void addStatements() {
        statements.add("CREATE TABLE " + DatabaseTableName.CATS + "(" +
                "   id TEXT PRIMARY KEY," +
                "   image_url TEXT," +
                "   provider_name TEXT" +
                ");");
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-parent</artifactId>
        <version>0.9.0-rc3-SNAPSHOT</version>
    </parent>

    <artifactId>dropwizard-servlets</artifactId>
    <name>Dropwizard Servlet Support</name>

    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard</groupId>
            <artifactId>dropwizard-util</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-annotation</artifactId>
            <version>${metrics3.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>${metrics3.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <!-- this is required because jetty-server pom
            put servlet-api into default scope when it should
            always be provided scope so it doesn't get compiled.
            without this there are security exceptions because
            javax.servlet-api jar is not signed -->
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>${jetty.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <testResources>
            <testResource>
                <directory>src/test/more-resources</directory>
            </testResource>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>
    </build>
</project>


text:
package release

import (
	"fmt"
	"path/filepath"
	"time"

	pivnet "github.com/pivotal-cf/go-pivnet/v7"
	"github.com/pivotal-cf/go-pivnet/v7/logger"
	"github.com/pivotal-cf/pivnet-resource/v3/metadata"
)

type ReleaseUploader struct {
	s3            s3Client
	pivnet        uploadClient
	logger        logger.Logger
	sha256Summer  sha256Summer
	md5Summer     md5Summer
	metadata      metadata.Metadata
	sourcesDir    string
	productSlug   string
	asyncTimeout  time.Duration
	pollFrequency time.Duration
	skipPolling   bool
}

type ProductFileMetadata struct {
	description        string
	fileVersion        string
	docsURL            string
	systemRequirements []string
	platforms          []string
	includedFiles      []string
	uploadAs           string
	fileType           string
}

//go:generate counterfeiter --fake-name UploadClient . uploadClient
type uploadClient interface {
	FindProductForSlug(slug string) (pivnet.Product, error)
	CreateProductFile(pivnet.CreateProductFileConfig) (pivnet.ProductFile, error)
	AddProductFile(productSlug string, releaseID int, productFileID int) error
	ProductFiles(productSlug string) ([]pivnet.ProductFile, error)
	ProductFile(productSlug string, productFileID int) (pivnet.ProductFile, error)
	DeleteProductFile(productSlug string, releaseID int) (pivnet.ProductFile, error)
}

//go:generate counterfeiter --fake-name S3Client . s3Client
type s3Client interface {
	ComputeAWSObjectKey(string) (string, string, error)
	UploadFile(string) error
}

//go:generate counterfeiter --fake-name Sha256Summer . sha256Summer
type sha256Summer interface {
	SumFile(filepath string) (string, error)
}

//go:generate counterfeiter --fake-name Md5Summer . md5Summer
type md5Summer interface {
	SumFile(filepath string) (string, error)
}

func NewReleaseUploader(
	s3 s3Client,
	pivnet uploadClient,
	logger logger.Logger,
	sha256Summer sha256Summer,
	md5Summer md5Summer,
	metadata metadata.Metadata,
	sourcesDir,
	productSlug string,
	asyncTimeout time.Duration,
	pollFrequency time.Duration,
	skipPolling bool,
) ReleaseUploader {
	return ReleaseUploader{
		s3:            s3,
		pivnet:        pivnet,
		logger:        logger,
		sha256Summer:  sha256Summer,
		md5Summer:     md5Summer,
		metadata:      metadata,
		sourcesDir:    sourcesDir,
		productSlug:   productSlug,
		asyncTimeout:  asyncTimeout,
		pollFrequency: pollFrequency,
		skipPolling:   skipPolling,
	}
}

func (u ReleaseUploader) Upload(release pivnet.Release, exactGlobs []string) error {
	for _, exactGlob := range exactGlobs {

		awsObjectKey, _, err := u.s3.ComputeAWSObjectKey(exactGlob)
		if err != nil {
			return err
		}

		fileData := u.getFileData(exactGlob)

		productFiles, err := u.pivnet.ProductFiles(u.productSlug)
		if err != nil {
			return err
		}

		var productFile pivnet.ProductFile
		var foundMatchingFile bool
		for _, pf := range productFiles {
			if pf.AWSObjectKey == awsObjectKey {
				foundMatchingFile = true

				matched, err := u.hasSameFileContent(exactGlob, pf)
				if err != nil {
					return err
				}
				productFile = pf

				if !matched {
					return fmt.Errorf("File conflict: the file '%s' could not be uploaded and associated to this release."+
						"  A different file with the same name already exists on S3.  Please recreate the release using a different"+
						" filename for this file or upload the file to this release manually", exactGlob)
				} else {
					u.logger.Info(fmt.Sprintf("An identical file was found on S3, skipping file upload. The existing file %s "+
						"will be associated to this release.", awsObjectKey))
				}
			}
		}

		if !foundMatchingFile {
			u.logger.Info(fmt.Sprintf(
				"Creating product file with remote name: '%s'",
				fileData.uploadAs,
			))

			err := u.s3.UploadFile(exactGlob)
			if err != nil {
				return err
			}

			productFileConfig, err := u.getProductFileConfig(exactGlob, awsObjectKey, fileData, release)
			if err != nil {
				return err
			}

			productFile, err = u.pivnet.CreateProductFile(productFileConfig)
			if err != nil {
				return err
			}

		} else {
			u.logger.Info(fmt.Sprintf(
				"File '%s' already exists, skipping creation",
				fileData.uploadAs,
			))
		}

		u.logger.Info(fmt.Sprintf(
			"Adding product file: '%s' with ID: %d",
			fileData.uploadAs,
			productFile.ID,
		))

		err = u.pivnet.AddProductFile(u.productSlug, release.ID, productFile.ID)
		if err != nil {
			return err
		}

		err = u.pollForProductFile(productFile)
		if err != nil {
			return fmt.Errorf("error while polling: %s", err)
		}
	}

	return nil
}

func (u ReleaseUploader) pollForProductFile(productFile pivnet.ProductFile) error {
	if u.skipPolling {
		u.logger.Info(fmt.Sprintf(
			"Skipping polling for product file: '%s'",
			productFile.Name,
		))
		return nil
	}

	u.logger.Info(fmt.Sprintf(
		"Polling product file: '%s' for async transfer - will wait up to %v",
		productFile.Name,
		u.asyncTimeout,
	))

	timeoutTimer := time.NewTimer(u.asyncTimeout)
	pollTicker := time.NewTicker(u.pollFrequency)

	for {
		select {
		case <-timeoutTimer.C:
			return fmt.Errorf("timed out")
		case <-pollTicker.C:
			pf, err := u.pivnet.ProductFile(u.productSlug, productFile.ID)
			if err != nil {
				return err
			}

			if pf.FileTransferStatus != "in_progress" {
				u.logger.Info(fmt.Sprintf(
					"Product file: '%s' async transfer complete",
					productFile.Name,
				))

				timeoutTimer.Stop()
				pollTicker.Stop()

				if pf.FileTransferStatus != "complete" {
					return fmt.Errorf("file_transfer_status: %s", pf.FileTransferStatus)
				} else {
					return nil
				}
			}

			u.logger.Info(fmt.Sprintf(
				"Product file: '%s' async transfer incomplete",
				productFile.Name,
			))
		}
	}
}

func (u ReleaseUploader) hasSameFileContent(fileName string, productFile pivnet.ProductFile) (bool, error) {
	fileContentsSHA256, _, err := u.calculateHashes(fileName)
	if err != nil {
		return false, err
	}

	if productFile.SHA256 == fileContentsSHA256 {
		u.logger.Debug(fmt.Sprintf(
			"Found an existing product file (AWSObjectKey: '%s') that exactly matches the upload file. Skipping deletion and creation",
			productFile.AWSObjectKey,
		))
		return true, nil
	}
	return false, nil
}

func (u ReleaseUploader) getProductFileConfig(exactGlob string, awsObjectKey string, fileData ProductFileMetadata, release pivnet.Release) (pivnet.CreateProductFileConfig, error) {
	fileContentsSHA256, fileContentsMD5, err := u.calculateHashes(exactGlob)
	if err != nil {
		return pivnet.CreateProductFileConfig{}, err
	}

	fileVersion := release.Version
	if fileData.fileVersion != "" {
		fileVersion = fileData.fileVersion
	}
	productFileConfig := pivnet.CreateProductFileConfig{
		ProductSlug:        u.productSlug,
		Name:               fileData.uploadAs,
		AWSObjectKey:       awsObjectKey,
		FileVersion:        fileVersion,
		SHA256:             fileContentsSHA256,
		MD5:                fileContentsMD5,
		Description:        fileData.description,
		FileType:           fileData.fileType,
		DocsURL:            fileData.docsURL,
		SystemRequirements: fileData.systemRequirements,
		Platforms:          fileData.platforms,
		IncludedFiles:      fileData.includedFiles,
	}
	return productFileConfig, err
}

func (u ReleaseUploader) getFileData(exactGlob string) ProductFileMetadata {
	var fileData ProductFileMetadata

	fileData.uploadAs = filepath.Base(exactGlob)
	fileData.fileType = "Software"

	for _, f := range u.metadata.ProductFiles {
		if f.File == exactGlob {
			u.logger.Info(fmt.Sprintf(
				"exact glob '%s' matches metadata file: '%s'",
				exactGlob,
				f.File,
			))

			if f.UploadAs != "" {
				u.logger.Info(fmt.Sprintf(
					"uploading '%s' to remote filename: '%s' instead",
					exactGlob,
					f.UploadAs,
				))
				fileData.uploadAs = f.UploadAs
			}

			fileData.description = f.Description

			if f.FileType != "" {
				fileData.fileType = f.FileType
			}

			if f.FileVersion != "" {
				fileData.fileVersion = f.FileVersion
			}

			if f.DocsURL != "" {
				fileData.docsURL = f.DocsURL
			}

			if len(f.SystemRequirements) > 0 {
				fileData.systemRequirements = f.SystemRequirements
			}

			if len(f.Platforms) > 0 {
				fileData.platforms = f.Platforms
			}

			if len(f.IncludedFiles) > 0 {
				fileData.includedFiles = f.IncludedFiles
			}
		} else {
			u.logger.Info(fmt.Sprintf(
				"exact glob '%s' does not match metadata file: '%s'",
				exactGlob,
				f.File,
			))
		}
	}
	return fileData
}

func (u ReleaseUploader) calculateHashes(fileName string) (string, string, error) {
	fullFilepath := filepath.Join(u.sourcesDir, fileName)
	fileContentsSHA256, err := u.sha256Summer.SumFile(fullFilepath)
	if err != nil {
		return "", "", err
	}

	fileContentsMD5, err := u.md5Summer.SumFile(fullFilepath)
	if err != nil {
		return "", "", err
	}
	return fileContentsSHA256, fileContentsMD5, nil
}


text:
import {Vue, vueConf} from './base.js';
import utils from './mixins/utils.js';

// layout componenets
import Boilerplate from './components/_templates/boilerplate/boilerplate.vue';
import Textbooks from './components/textbooks/textbooks.vue';

// Vuex Stores
import instSchedule from './vuex/store/schedule/instructor';
import studSchedule from './vuex/store/schedule/student';
import textbooks from './vuex/store/textbooks';

vueConf.store.registerModule('inst_schedule', instSchedule);
vueConf.store.registerModule('stud_schedule', studSchedule);
vueConf.store.registerModule('textbooks', textbooks);

vueConf.store.commit('addVarToState', {
  name: 'page',
  value: {
    hideTitle: false,
    title: `${utils.methods.pageTitleFromTerm(window.textbookTerm)} Textbooks`,
  },
});

Vue.component('myuw-boilerplate', Boilerplate);
Vue.component('myuw-textbooks', Textbooks);

new Vue({
  ...vueConf,
});


text:
package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;

import classes.Model;
import services.MyClient;
import util.Utilidades;

public class Main extends JFrame implements ActionListener, MouseListener{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private JPanel contentPane;
	private JTextField txtUser;
	private JPasswordField txtPass;
	private JTextField txtServer;
	private JButton btnConnect, btnUpload, btnDownload, btnExit;
	private JList<String> list;
	private JLabel lblTxt;
	private JLabel lblError;
	private MyClient ftpClient;
	private JButton btnDisconnect;
	private String selectedItem;
	private JButton btnCrearDirectorio;
	private JButton btnEliminarDirectorio;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				try {
					Main frame = new Main();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Main() {
		setMinimumSize(new Dimension(1024, 728));
		setMaximumSize(new Dimension(1024, 728));
		setResizable(false);
		setTitle("Simple FTP Client");
		setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		setBounds(100, 100, 716, 482);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		GridBagLayout gbl_contentPane = new GridBagLayout();
		gbl_contentPane.columnWidths = new int[]{61, 0, 0, 124, 0, 0, 122, 55, 0};
		gbl_contentPane.rowHeights = new int[]{47, 0, 0, 0, 0, 0, 0, 0, -11, 0, 0, 59, 0, 0, 0};
		gbl_contentPane.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
		gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		contentPane.setLayout(gbl_contentPane);

		JLabel lblUsuario = new JLabel("Usuario:");
		GridBagConstraints gbc_lblUsuario = new GridBagConstraints();
		gbc_lblUsuario.insets = new Insets(0, 0, 5, 5);
		gbc_lblUsuario.gridx = 1;
		gbc_lblUsuario.gridy = 1;
		contentPane.add(lblUsuario, gbc_lblUsuario);

		txtUser = new JTextField();
		GridBagConstraints gbc_txtUser = new GridBagConstraints();
		gbc_txtUser.insets = new Insets(0, 0, 5, 5);
		gbc_txtUser.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtUser.gridx = 3;
		gbc_txtUser.gridy = 1;
		contentPane.add(txtUser, gbc_txtUser);
		txtUser.setColumns(10);

		JLabel lblServidorFtp = new JLabel("Servidor FTP:");
		GridBagConstraints gbc_lblServidorFtp = new GridBagConstraints();
		gbc_lblServidorFtp.insets = new Insets(0, 0, 5, 5);
		gbc_lblServidorFtp.anchor = GridBagConstraints.EAST;
		gbc_lblServidorFtp.gridx = 5;
		gbc_lblServidorFtp.gridy = 1;
		contentPane.add(lblServidorFtp, gbc_lblServidorFtp);

		txtServer = new JTextField();
		GridBagConstraints gbc_txtServer = new GridBagConstraints();
		gbc_txtServer.insets = new Insets(0, 0, 5, 5);
		gbc_txtServer.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtServer.gridx = 6;
		gbc_txtServer.gridy = 1;
		contentPane.add(txtServer, gbc_txtServer);
		txtServer.setColumns(10);

		JLabel lblConstrasea = new JLabel("Contraseña:");
		GridBagConstraints gbc_lblConstrasea = new GridBagConstraints();
		gbc_lblConstrasea.insets = new Insets(0, 0, 5, 5);
		gbc_lblConstrasea.gridx = 1;
		gbc_lblConstrasea.gridy = 2;
		contentPane.add(lblConstrasea, gbc_lblConstrasea);

		txtPass = new JPasswordField();
		GridBagConstraints gbc_txtPass = new GridBagConstraints();
		gbc_txtPass.insets = new Insets(0, 0, 5, 5);
		gbc_txtPass.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtPass.gridx = 3;
		gbc_txtPass.gridy = 2;
		contentPane.add(txtPass, gbc_txtPass);

		btnConnect = new JButton("Conectar");
		btnConnect.setFont(new Font("Lucida Grande", Font.BOLD, 13));
		GridBagConstraints gbc_btnConnect = new GridBagConstraints();
		gbc_btnConnect.insets = new Insets(0, 0, 5, 5);
		gbc_btnConnect.gridx = 5;
		gbc_btnConnect.gridy = 2;
		contentPane.add(btnConnect, gbc_btnConnect);

		btnDisconnect = new JButton("Desconectarse");
		GridBagConstraints gbc_btnDisconnect = new GridBagConstraints();
		gbc_btnDisconnect.insets = new Insets(0, 0, 5, 5);
		gbc_btnDisconnect.gridx = 6;
		gbc_btnDisconnect.gridy = 2;
		contentPane.add(btnDisconnect, gbc_btnDisconnect);

		btnUpload = new JButton("Subir");
		btnUpload.setFont(new Font("Lucida Grande", Font.BOLD, 13));
		GridBagConstraints gbc_btnUpload = new GridBagConstraints();
		gbc_btnUpload.insets = new Insets(0, 0, 5, 5);
		gbc_btnUpload.gridx = 6;
		gbc_btnUpload.gridy = 3;
		contentPane.add(btnUpload, gbc_btnUpload);

		btnDownload = new JButton("Descargar");
		btnDownload.setFont(new Font("Lucida Grande", Font.BOLD, 13));
		GridBagConstraints gbc_btnDownload = new GridBagConstraints();
		gbc_btnDownload.insets = new Insets(0, 0, 5, 5);
		gbc_btnDownload.gridx = 6;
		gbc_btnDownload.gridy = 4;
		contentPane.add(btnDownload, gbc_btnDownload);

		btnCrearDirectorio = new JButton("Crear Directorio");
		btnCrearDirectorio.setFont(new Font("Lucida Grande", Font.BOLD, 13));
		GridBagConstraints gbc_btnCrearDirectorio = new GridBagConstraints();
		gbc_btnCrearDirectorio.insets = new Insets(0, 0, 5, 5);
		gbc_btnCrearDirectorio.gridx = 6;
		gbc_btnCrearDirectorio.gridy = 5;
		contentPane.add(btnCrearDirectorio, gbc_btnCrearDirectorio);

		btnEliminarDirectorio = new JButton("Eliminar Directorio");
		btnEliminarDirectorio.setFont(new Font("Lucida Grande", Font.BOLD, 13));
		GridBagConstraints gbc_btnEliminarDirectorio = new GridBagConstraints();
		gbc_btnEliminarDirectorio.insets = new Insets(0, 0, 5, 5);
		gbc_btnEliminarDirectorio.gridx = 6;
		gbc_btnEliminarDirectorio.gridy = 6;
		contentPane.add(btnEliminarDirectorio, gbc_btnEliminarDirectorio);

		btnExit = new JButton("Salir");
		btnExit.setForeground(Color.BLACK);
		btnExit.setFont(new Font("Lucida Grande", Font.BOLD, 13));
		GridBagConstraints gbc_btnExit = new GridBagConstraints();
		gbc_btnExit.insets = new Insets(0, 0, 5, 5);
		gbc_btnExit.gridx = 6;
		gbc_btnExit.gridy = 7;
		contentPane.add(btnExit, gbc_btnExit);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		GridBagConstraints gbc_scrollPane = new GridBagConstraints();
		gbc_scrollPane.gridheight = 5;
		gbc_scrollPane.gridwidth = 4;
		gbc_scrollPane.insets = new Insets(0, 0, 5, 5);
		gbc_scrollPane.fill = GridBagConstraints.BOTH;
		gbc_scrollPane.gridx = 1;
		gbc_scrollPane.gridy = 4;
		contentPane.add(scrollPane, gbc_scrollPane);

		list = new JList<>();
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scrollPane.setViewportView(list);

		lblTxt = new JLabel("-");
		GridBagConstraints gbc_lblTxt = new GridBagConstraints();
		gbc_lblTxt.insets = new Insets(0, 0, 5, 5);
		gbc_lblTxt.gridx = 1;
		gbc_lblTxt.gridy = 9;
		contentPane.add(lblTxt, gbc_lblTxt);

		lblError = new JLabel("-");
		lblError.setForeground(Color.RED);
		lblError.setHorizontalTextPosition(SwingConstants.LEFT);
		lblError.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_lblError = new GridBagConstraints();
		gbc_lblError.insets = new Insets(0, 0, 5, 5);
		gbc_lblError.gridx = 1;
		gbc_lblError.gridy = 10;
		contentPane.add(lblError, gbc_lblError);

		// add action listeners
		btnConnect.addActionListener(this);
		btnDisconnect.addActionListener(this);
		btnExit.addActionListener(this);
		btnDownload.addActionListener(this);
		btnUpload.addActionListener(this);
		btnCrearDirectorio.addActionListener(this);
		btnEliminarDirectorio.addActionListener(this);
		list.addMouseListener(this);

		btnConnect.setEnabled(true);
		btnDownload.setEnabled(false);
		btnUpload.setEnabled(false);
		btnDisconnect.setEnabled(false);

		int opt = JOptionPane.showConfirmDialog(this, "¿Desea cargar la direccion del servidor por defecto?", "Servidor por defecto", JOptionPane.YES_NO_OPTION);
		if(opt == JOptionPane.YES_OPTION){
			txtServer.setText(Model.FTP_SERVER_ADDR);
		}

		ftpClient = new MyClient(txtUser, txtPass, txtServer, list, lblTxt, lblError);

	}

	@Override
	public void actionPerformed(ActionEvent e) {

		if(e.getSource() == btnConnect){

			if(!txtUser.getText().equalsIgnoreCase("") &&
					!new String(txtPass.getPassword()).equalsIgnoreCase("") && !txtServer.getText().equalsIgnoreCase("")){

				int out = ftpClient.getConnection();

				if(out == 0) out = ftpClient.logUser();

				switch(out){

				case 1:
					JOptionPane.showMessageDialog(this, "Usuario logeado correctamente.");
					btnConnect.setEnabled(false);
					btnDownload.setEnabled(false);
					btnUpload.setEnabled(true);
					btnDisconnect.setEnabled(true);

					try {
						ftpClient.changeDirAndInflateList();
					} catch (Exception e1) {
						e1.printStackTrace();
					}
					break;
				case 0:
					JOptionPane.showMessageDialog(this, "Datos logeo incorrectos.");
					break;
				case -1:
					JOptionPane.showMessageDialog(this, "Error al establecer conexion con el servidor");
					break;
				}

			}else {
				JOptionPane.showMessageDialog(this, "Debes completar todos los campos para poder logearte...");
			}

		}else if(e.getSource() == btnExit){
			if(btnConnect.isEnabled())
				try {
					ftpClient.disconnectClient();
					System.exit(0);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			else
				JOptionPane.showMessageDialog(this, "Debes cerrar sesion antes de desconectarte!", "Error", JOptionPane.WARNING_MESSAGE);
		}else if(e.getSource() == btnDownload){

			String file = Utilidades.sliceSelectedItem(selectedItem);
			ftpClient.downloadFile(file);

		}else if(e.getSource() == btnUpload){

			JFileChooser jFile = new JFileChooser();
			jFile.setDialogTitle("Seleccione el fichero a subir");
			jFile.setFileSelectionMode(JFileChooser.FILES_ONLY);
			int result = jFile.showDialog(this, "Subir");

			if(result == JFileChooser.APPROVE_OPTION){

				File fich = jFile.getSelectedFile();
				ftpClient.uploadFile(fich);

			}

		}else if(e.getSource() == btnDisconnect){

			if(!btnConnect.isEnabled())
				try {
					ftpClient.logoutClient();
				} catch (IOException e1) {
					e1.printStackTrace();
				}

			btnConnect.setEnabled(true);
			btnDownload.setEnabled(false);
			btnUpload.setEnabled(false);
			btnDisconnect.setEnabled(false);

			ftpClient.clearList();
		}else if(e.getSource() == btnCrearDirectorio){

			String newDirName = JOptionPane.showInputDialog("Introduce el nombre del nuevo fichero");

			if(!newDirName.equals("")) ftpClient.createDir(newDirName);
		}else if(e.getSource() == btnEliminarDirectorio){

			if(list.isSelectionEmpty()) {
				ftpClient.deleteDir();
			}else if(!isDir(list.getSelectedValue())){
				ftpClient.deleteFile(list.getSelectedValue());
			}

		}
	}

	@Override
	public void mouseClicked(MouseEvent e) {

		if(e.getSource() == list){

			if(list.getSelectedIndex() == 0){
				btnEliminarDirectorio.setText("Eliminar Directorio");
				try {
					ftpClient.changeToParentDirAndInflateList();
				} catch (Exception e1) {
				}
			}else {

				selectedItem = list.getSelectedValue();

				lblTxt.setText(selectedItem);

				if(isDir(selectedItem)){
					btnDownload.setEnabled(false);
					btnEliminarDirectorio.setText("Eliminar Directorio");
					String dir = Utilidades.sliceSelectedItem(selectedItem).trim();
					ftpClient.setSelectedDirectory(dir);
					try {
						ftpClient.changeDirAndInflateList();
					} catch (Exception e1) {
					}

				}else {
					btnEliminarDirectorio.setText("Eliminar Archivo");
					btnDownload.setEnabled(true);
				}

			}
		}
	}

	@Override
	public void mousePressed(MouseEvent e) {
	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	}

	@Override
	public void mouseExited(MouseEvent e) {
	}

	private boolean isDir(String item){
		return item.startsWith("(DIR)");
	}
}


text:
using Sisacon.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Sisacon.Domain.Enuns.AccountType;

namespace Sisacon.Domain.ValueObjects
{
    public class BankDetails : BaseEntity
    {
        #region Constants

        public const int MAX_LENGTH_BANK = 50;
        public const int MAX_LENGTH_ACCOUNTNUMBER = 10;
        public const int MAX_LENGTH_AGENCY = 10;

        #endregion

        #region Propeties

        public string Bank { get; set; }
        public string AccountNumber { get; set; }
        public string Agency { get; set; }
        public eAccountType eTipoConta { get; set; }

        #endregion
    }
}


text:
namespace System.ComponentModel.Composition
{
    public interface ITrans_StronglyTypedStructure
    {
        string String1 { get; }
        string String2 { get; }
        int[] Numbers { get; }
        CreationPolicy Policy { get; }
        Type Type { get; }
    }

    public interface ITrans_AddinMetadata
    {
        string Name { get; }
        string Version { get; }
        string Id { get; }
    }

    public interface ITrans_MetadataTests_CustomMetadata
    {
        bool PropertyName { get; }
    }

    public interface ITrans_MetadataTests_MetadataView
    {
        string Value
        {
            get;
        }
    }

    public interface ITrans_MetadataTests_MetadataView2 : ITrans_MetadataTests_MetadataView
    {
        new int Value
        {
            get;
        }
    }

    public interface ITrans_MetadataTests_MetadataView3 : ITrans_MetadataTests_MetadataView
    {
        string Value2
        {
            get;
        }
    }

    public interface ITrans_MetadataTests_MetadataViewWithPropertySetter
    {
        string Value
        {
            get;
            set;
        }
    }

    public interface ITrans_MetadataTests_MetadataViewWithMethod
    {
        string Value
        {
            get;
        }
        void Method();
    }

    public interface ITrans_MetadataTests_MetadataViewWithEvent
    {
        string Value
        {
            get;
        }
        event EventHandler TestEvent;
    }

    public interface ITrans_MetadataTests_MetadataViewWithIndexer
    {
        string Value
        {
            get;
        }
        string this[object o] { get; }
    }
}


text:
"""Test Z-Wave workarounds."""
from homeassistant.components.zwave import const, workaround
from tests.mock.zwave import MockNode, MockValue

def test_get_device_no_component_mapping():
    """Test that None is returned."""
    node = MockNode(manufacturer_id=' ')
    value = MockValue(data=0, node=node)
    assert workaround.get_device_component_mapping(value) is None

def test_get_device_component_mapping():
    """Test that component is returned."""
    node = MockNode(manufacturer_id='010f', product_type='0b00')
    value = MockValue(data=0, node=node,
                      command_class=const.COMMAND_CLASS_SENSOR_ALARM)
    assert workaround.get_device_component_mapping(value) == 'binary_sensor'

def test_get_device_no_mapping():
    """Test that no device mapping is returned."""
    node = MockNode(manufacturer_id=' ')
    value = MockValue(data=0, node=node)
    assert workaround.get_device_mapping(value) is None

def test_get_device_mapping_mt():
    """Test that device mapping mt is returned."""
    node = MockNode(manufacturer_id='0047', product_type='5a52')
    value = MockValue(data=0, node=node)
    assert workaround.get_device_mapping(value) == 'workaround_no_position'

def test_get_device_mapping_mtii():
    """Test that device mapping mtii is returned."""
    node = MockNode(manufacturer_id='013c', product_type='0002',
                    product_id='0002')
    value = MockValue(data=0, node=node, index=0)
    assert workaround.get_device_mapping(value) == 'trigger_no_off_event'


text:
//******************************************************************************************************
//  MeterSettingsSheet.cs - Gbtc
//
//  Copyright © 2019, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
//  file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  09/24/2019 - Stephen C. Wills
//       Generated original version of source code.
//
//******************************************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using GSF.Collections;
using GSF.Data.Model;
using openXDA.Model;

namespace FaultData.Configuration
{
    public class MeterSettingsSheet
    {
        public MeterSettingsSheet(Meter meter)
        {
            Meter = meter;
            Sheet = ToSheet(meter);
        }

        public MeterSettingsSheet(XDocument sheet)
        {
            Meter = ToMeter(sheet);
            Sheet = sheet;
        }

        public MeterSettingsSheet(TableOperations<MeterConfiguration> meterConfigurationTable, MeterConfiguration meterConfiguration)
        {
            string sheetText = meterConfigurationTable.Unpatch(meterConfiguration);
            XDocument sheet = XDocument.Parse(sheetText);
            Meter = ToMeter(sheet);
            Sheet = sheet;
        }

        public Meter Meter { get; }
        public XDocument Sheet { get; }

        public void UpdateConfiguration(TableOperations<MeterConfiguration> meterConfigurationTable, string configKey) =>
            meterConfigurationTable.PatchLatestConfiguration(Meter, configKey, Sheet.ToString());

        private XDocument ToSheet(Meter meter)
        {
            XDocument sheet = new XDocument();
            XElement rootElement = new XElement("meterSettingsSheet");
            sheet.Add(rootElement);

            XElement meterElement = new XElement("meter");
            meterElement.Add(new XElement(nameof(meter.ID), meter.ID));
            meterElement.Add(new XElement(nameof(meter.AssetKey), meter.AssetKey));
            meterElement.Add(new XElement(nameof(meter.LocationID), meter.LocationID));
            meterElement.Add(new XElement(nameof(meter.Name), meter.Name));
            meterElement.Add(new XElement(nameof(meter.Alias), meter.Alias));
            meterElement.Add(new XElement(nameof(meter.ShortName), meter.ShortName));
            meterElement.Add(new XElement(nameof(meter.Make), meter.Make));
            meterElement.Add(new XElement(nameof(meter.Model), meter.Model));
            meterElement.Add(new XElement(nameof(meter.TimeZone), meter.TimeZone));
            meterElement.Add(new XElement(nameof(meter.Description), meter.Description));
            rootElement.Add(meterElement);

            XElement locationElement = new XElement("location");
            locationElement.Add(new XElement(nameof(meter.Location.ID), meter.Location.ID));
            locationElement.Add(new XElement(nameof(meter.Location.LocationKey), meter.Location.LocationKey));
            locationElement.Add(new XElement(nameof(meter.Location.Name), meter.Location.Name));
            locationElement.Add(new XElement(nameof(meter.Location.Alias), meter.Location.Alias));
            locationElement.Add(new XElement(nameof(meter.Location.ShortName), meter.Location.ShortName));
            locationElement.Add(new XElement(nameof(meter.Location.Latitude), meter.Location.Latitude));
            locationElement.Add(new XElement(nameof(meter.Location.Longitude), meter.Location.Longitude));
            locationElement.Add(new XElement(nameof(meter.Location.Description), meter.Location.Description));
            rootElement.Add(locationElement);

            // Start With Assets
            IEnumerable<Asset> assets = meter.MeterAssets
                .Select(meterLine => meterLine.Asset)
                .OrderBy(asset => asset.ID);

            //Save individual Assets (Except LineSegments)
            List<LineSegment> lineSegments = new List<LineSegment>();
            List<AssetConnection> assetConnections = new List<AssetConnection>();

            foreach (Asset asset in assets)
            {
                XElement assetElement = new XElement("asset"); ;

                switch (asset.AssetTypeID)
                {
                    case ((int)AssetType.Breaker):
                        assetElement = new XElement("breaker");
                        Breaker breaker = Breaker.DetailedBreaker(asset, asset.ConnectionFactory?.Invoke());
                        assetElement.Add(new XElement(nameof(breaker.VoltageKV), breaker.VoltageKV));
                        assetElement.Add(new XElement(nameof(breaker.ThermalRating), breaker.ThermalRating));
                        assetElement.Add(new XElement(nameof(breaker.Speed), breaker.Speed));
                        assetElement.Add(new XElement(nameof(asset.ID), asset.ID));
                        assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey));
                        assetElement.Add(new XElement(nameof(asset.Description), asset.Description));
                        assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName));
                        break;

                    case ((int)AssetType.Bus):
                        assetElement = new XElement("bus");
                        Bus bus = Bus.DetailedBus(asset, asset.ConnectionFactory?.Invoke());
                        assetElement.Add(new XElement(nameof(bus.VoltageKV), bus.VoltageKV));
                        assetElement.Add(new XElement(nameof(asset.ID), asset.ID));
                        assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey));
                        assetElement.Add(new XElement(nameof(asset.Description), asset.Description));
                        assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName));
                        break;
                    case ((int)AssetType.CapacitorBank):
                        assetElement = new XElement("capacitorBank");
                        CapBank capBank = CapBank.DetailedCapBank(asset, asset.ConnectionFactory?.Invoke());
                        assetElement.Add(new XElement(nameof(capBank.VoltageKV), capBank.VoltageKV));
                        //assetElement.Add(new XElement(nameof(capBank.NumberOfBanks), capBank.NumberOfBanks));
                        //assetElement.Add(new XElement(nameof(capBank.CansPerBank), capBank.CansPerBank));
                        //assetElement.Add(new XElement(nameof(capBank.CapacitancePerBank), capBank.CapacitancePerBank));
                        assetElement.Add(new XElement(nameof(asset.ID), asset.ID));
                        assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey));
                        assetElement.Add(new XElement(nameof(asset.Description), asset.Description));
                        assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName));
                        break;
                    case ((int)AssetType.Transformer):
                        assetElement = new XElement("transformer");
                        Transformer xfr = Transformer.DetailedTransformer(asset, asset.ConnectionFactory?.Invoke());
                        assetElement.Add(new XElement(nameof(xfr.ThermalRating), xfr.ThermalRating));
                        assetElement.Add(new XElement(nameof(xfr.SecondaryVoltageKV), xfr.SecondaryVoltageKV));
                        assetElement.Add(new XElement(nameof(xfr.PrimaryVoltageKV), xfr.PrimaryVoltageKV));
                        assetElement.Add(new XElement(nameof(xfr.Tap), xfr.Tap));
                        assetElement.Add(new XElement(nameof(xfr.X0), xfr.X0));
                        assetElement.Add(new XElement(nameof(xfr.R0), xfr.R0));
                        assetElement.Add(new XElement(nameof(xfr.X1), xfr.X1));
                        assetElement.Add(new XElement(nameof(xfr.R1), xfr.R1));
                        assetElement.Add(new XElement(nameof(asset.ID), asset.ID));
                        assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey));
                        assetElement.Add(new XElement(nameof(asset.Description), asset.Description));
                        assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName));
                        break;
                    case ((int)AssetType.Line):
                        assetElement = new XElement("line");
                        Line line = Line.DetailedLine(asset);
                        assetElement.Add(new XElement(nameof(line.VoltageKV), line.VoltageKV));
                        assetElement.Add(new XElement(nameof(line.MaxFaultDistance), line.MaxFaultDistance));
                        assetElement.Add(new XElement(nameof(line.MinFaultDistance), line.MinFaultDistance));
                        assetElement.Add(new XElement(nameof(asset.ID), asset.ID));
                        assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey));
                        assetElement.Add(new XElement(nameof(asset.Description), asset.Description));
                        assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName));
                        lineSegments.AddRange(line.Segments);
                        break;
                    case ((int)AssetType.LineSegement):
                        lineSegments.Add(LineSegment.DetailedLineSegment(asset, asset.ConnectionFactory?.Invoke()));
                        break;
                    default:
                        assetElement = new XElement("asset");
                        assetElement.Add(new XElement(nameof(asset.ID), asset.ID));
                        assetElement.Add(new XElement(nameof(asset.AssetKey), asset.AssetKey));
                        assetElement.Add(new XElement(nameof(asset.Description), asset.Description));
                        assetElement.Add(new XElement(nameof(asset.AssetName), asset.AssetName));
                        break;
                }

                assetConnections.AddRange(asset.Connections.Where(item => item.ParentID == asset.ID));
                rootElement.Add(assetElement);
            }

            //Deal with special Cases... If it is a line we need to keep the Line Segments...
            foreach (LineSegment lineSegment in lineSegments)
            {
                XElement lineSegmentElement = new XElement("lineSegment");
                lineSegmentElement.Add(new XElement(nameof(lineSegment.ThermalRating), lineSegment.ThermalRating));
                lineSegmentElement.Add(new XElement(nameof(lineSegment.X0), lineSegment.X0));
                lineSegmentElement.Add(new XElement(nameof(lineSegment.R0), lineSegment.R0));
                lineSegmentElement.Add(new XElement(nameof(lineSegment.X1), lineSegment.X1));
                lineSegmentElement.Add(new XElement(nameof(lineSegment.R1), lineSegment.R1));
                lineSegmentElement.Add(new XElement(nameof(lineSegment.ID), lineSegment.ID));
                lineSegmentElement.Add(new XElement(nameof(lineSegment.Length), lineSegment.Length));
                lineSegmentElement.Add(new XElement(nameof(lineSegment.AssetKey), lineSegment.AssetKey));
                lineSegmentElement.Add(new XElement(nameof(lineSegment.Description), lineSegment.Description));
                lineSegmentElement.Add(new XElement(nameof(lineSegment.AssetName), lineSegment.AssetName));
                assetConnections.AddRange(lineSegment.Connections.Where(item => item.ParentID == lineSegment.ID));
                rootElement.Add(lineSegmentElement);
            }

            //Deal with Asset -> Asset Connections.....
            foreach (AssetConnection assetConnection in assetConnections)
            {
                if (assets.Select(item => item.ID).Contains(assetConnection.ChildID)|| lineSegments.Select(item => item.ID).Contains(assetConnection.ChildID))
                {
                    XElement assetConnectionElement = new XElement("assetConnection");
                    assetConnectionElement.Add(new XElement(nameof(assetConnection.ID), assetConnection.ID));
                    assetConnectionElement.Add(new XElement(nameof(assetConnection.ChildID), assetConnection.ChildID));
                    assetConnectionElement.Add(new XElement(nameof(assetConnection.ParentID), assetConnection.ParentID));
                    assetConnectionElement.Add(new XElement(nameof(assetConnection.AssetRelationshipTypeID), assetConnection.AssetRelationshipTypeID));
                    rootElement.Add(assetConnectionElement);
                }
            }

            // That is it for Assets

            IEnumerable<Channel> channels = meter.Channels
                .OrderBy(channel => channel.ID);

            foreach (Channel channel in channels)
            {
                if (channel.ID == 0)
                    continue;

                XElement channelElement = new XElement("channel");
                channelElement.Add(new XElement(nameof(channel.ID), channel.ID));
                channelElement.Add(new XElement(nameof(channel.MeterID), channel.MeterID));
                channelElement.Add(new XElement(nameof(channel.AssetID), channel.AssetID));
                channelElement.Add(new XElement(nameof(channel.MeasurementTypeID), channel.MeasurementTypeID));
                channelElement.Add(new XElement(nameof(channel.MeasurementType), channel.MeasurementType.Name));
                channelElement.Add(new XElement(nameof(channel.MeasurementCharacteristicID), channel.MeasurementCharacteristicID));
                channelElement.Add(new XElement(nameof(channel.MeasurementCharacteristic), channel.MeasurementCharacteristic.Name));
                channelElement.Add(new XElement(nameof(channel.PhaseID), channel.PhaseID));
                channelElement.Add(new XElement(nameof(channel.Phase), channel.Phase.Name));
                channelElement.Add(new XElement(nameof(channel.Name), channel.Name));
                channelElement.Add(new XElement(nameof(channel.SamplesPerHour), channel.SamplesPerHour));
                channelElement.Add(new XElement(nameof(channel.PerUnitValue), channel.PerUnitValue));
                channelElement.Add(new XElement(nameof(channel.HarmonicGroup), channel.HarmonicGroup));
                channelElement.Add(new XElement(nameof(channel.Description), channel.Description));
                channelElement.Add(new XElement(nameof(channel.Enabled), channel.Enabled));
                rootElement.Add(channelElement);
            }

            IEnumerable<Series> seriesList = meter.Series
                .OrderBy(series => series.ID);

            foreach (Series series in seriesList)
            {
                if (series.ID == 0)
                    continue;

                XElement seriesElement = new XElement("series");
                seriesElement.Add(new XElement(nameof(series.ID), series.ID));
                seriesElement.Add(new XElement(nameof(series.ChannelID), series.ChannelID));
                seriesElement.Add(new XElement(nameof(series.SeriesTypeID), series.SeriesTypeID));
                seriesElement.Add(new XElement(nameof(series.SeriesType), series.SeriesType.Name));
                seriesElement.Add(new XElement(nameof(series.SourceIndexes), series.SourceIndexes));
                rootElement.Add(seriesElement);
            }

            IEnumerable<AssetLocation> assetLocations = meter.Location.AssetLocations
                .OrderBy(assetLocation => assetLocation.ID);

            foreach (AssetLocation assetLocation in assetLocations)
            {
                XElement meterLocationLineElement = new XElement("assetLocation");
                meterLocationLineElement.Add(new XElement(nameof(assetLocation.ID), assetLocation.ID));
                meterLocationLineElement.Add(new XElement(nameof(assetLocation.LocationID), assetLocation.LocationID));
                meterLocationLineElement.Add(new XElement(nameof(assetLocation.AssetID), assetLocation.AssetID));
                rootElement.Add(meterLocationLineElement);
            }

            IEnumerable<MeterAsset> meterAssets = meter.MeterAssets
                .OrderBy(meterAsset => meterAsset.ID);

            foreach (MeterAsset meterAsset in meterAssets)
            {
                XElement meterLineElement = new XElement("meterAsset");
                meterLineElement.Add(new XElement(nameof(meterAsset.ID), meterAsset.ID));
                meterLineElement.Add(new XElement(nameof(meterAsset.MeterID), meterAsset.MeterID));
                meterLineElement.Add(new XElement(nameof(meterAsset.AssetID), meterAsset.AssetID));
                rootElement.Add(meterLineElement);
            }

            return sheet;
        }

        private Meter ToMeter(XDocument sheet)
        {
            double? ToNullableDouble(string str)
            {
                if (string.IsNullOrEmpty(str))
                    return null;

                return Convert.ToDouble(str);
            }

            XElement rootElement = sheet.Root;

            Meter meter = new Meter()
            {
                MeterAssets = new List<MeterAsset>(),
                Channels = new List<Channel>()
            };

            XElement meterElement = rootElement.Element("meter");
            meter.ID = Convert.ToInt32((string)meterElement.Element(nameof(meter.ID)));
            meter.AssetKey = (string)meterElement.Element(nameof(meter.AssetKey));
            meter.LocationID = Convert.ToInt32((string)meterElement.Element(nameof(meter.LocationID)));
            meter.Name = (string)meterElement.Element(nameof(meter.Name));
            meter.Alias = (string)meterElement.Element(nameof(meter.Alias));
            meter.ShortName = (string)meterElement.Element(nameof(meter.ShortName));
            meter.Make = (string)meterElement.Element(nameof(meter.Make));
            meter.Model = (string)meterElement.Element(nameof(meter.Model));
            meter.TimeZone = (string)meterElement.Element(nameof(meter.TimeZone));
            meter.Description = (string)meterElement.Element(nameof(meter.Description));

            Location location = new Location()
            {
                Meters = new List<Meter>(),
                AssetLocations = new List<AssetLocation>()
            };

            XElement meterLocationElement = rootElement.Element("location");
            location.ID = Convert.ToInt32((string)meterLocationElement.Element(nameof(location.ID)));
            location.LocationKey = (string)meterLocationElement.Element(nameof(location.LocationKey));
            location.Name = (string)meterLocationElement.Element(nameof(location.Name));
            location.Alias = (string)meterLocationElement.Element(nameof(location.Alias));
            location.ShortName = (string)meterLocationElement.Element(nameof(location.ShortName));
            location.Latitude = Convert.ToDouble((string)meterLocationElement.Element(nameof(location.Latitude)));
            location.Longitude = Convert.ToDouble((string)meterLocationElement.Element(nameof(location.Longitude)));
            location.Description = (string)meterLocationElement.Element(nameof(location.Description));
            location.Meters.Add(meter);
            meter.Location = location;

            // This needs to be adjusted to work for Assets of all Types
            Dictionary<int, Asset> assets = new Dictionary<int, Asset>();

            foreach (XElement breakerElement in rootElement.Elements("breaker"))
            {

                Breaker breaker = new Breaker()
                {
                    AssetLocations = new List<AssetLocation>(),
                    MeterAssets = new List<MeterAsset>(),
                    DirectChannels = new List<Channel>(),
                    Connections = new List<AssetConnection>(),
                    AssetTypeID = (int)AssetType.Breaker
                };
                breaker.VoltageKV = Convert.ToDouble((string)breakerElement.Element(nameof(breaker.VoltageKV)));
                breaker.ThermalRating = Convert.ToDouble((string)breakerElement.Element(nameof(breaker.ThermalRating)));
                breaker.Speed = Convert.ToDouble((string)breakerElement.Element(nameof(breaker.Speed)));
                breaker.ID = Convert.ToInt32((string)breakerElement.Element(nameof(breaker.ID)));
                breaker.AssetKey = (string)breakerElement.Element(nameof(breaker.AssetKey));
                breaker.Description = (string)breakerElement.Element(nameof(breaker.Description));
                breaker.AssetName = (string)breakerElement.Element(nameof(breaker.AssetName));
                assets.Add(breaker.ID, breaker);
            }

            foreach (XElement busElement in rootElement.Elements("bus"))
            {

                Bus bus = new Bus()
                {
                    AssetLocations = new List<AssetLocation>(),
                    MeterAssets = new List<MeterAsset>(),
                    DirectChannels = new List<Channel>(),
                    Connections = new List<AssetConnection>(),
                    AssetTypeID = (int)AssetType.Bus
                };
                bus.VoltageKV = Convert.ToDouble((string)busElement.Element(nameof(bus.VoltageKV)));
                bus.ID = Convert.ToInt32((string)busElement.Element(nameof(bus.ID)));
                bus.AssetKey = (string)busElement.Element(nameof(bus.AssetKey));
                bus.Description = (string)busElement.Element(nameof(bus.Description));
                bus.AssetName = (string)busElement.Element(nameof(bus.AssetName));

                assets.Add(bus.ID, bus);
            }

            foreach (XElement capacitorBankElement in rootElement.Elements("capacitorBank"))
            {

                CapBank capBank = new CapBank()
                {
                    AssetLocations = new List<AssetLocation>(),
                    MeterAssets = new List<MeterAsset>(),
                    DirectChannels = new List<Channel>(),
                    Connections = new List<AssetConnection>(),
                    AssetTypeID = (int)AssetType.CapacitorBank
                };
                capBank.VoltageKV = Convert.ToDouble((string)capacitorBankElement.Element(nameof(capBank.VoltageKV)));
                //capBank.NumberOfBanks = Convert.ToInt32((string)capacitorBankElement.Element(nameof(capBank.NumberOfBanks)));
                //capBank.CansPerBank = Convert.ToInt32((string)capacitorBankElement.Element(nameof(capBank.CansPerBank)));
                //capBank.CapacitancePerBank = Convert.ToDouble((string)capacitorBankElement.Element(nameof(capBank.CapacitancePerBank)));

                capBank.ID = Convert.ToInt32((string)capacitorBankElement.Element(nameof(capBank.ID)));
                capBank.AssetKey = (string)capacitorBankElement.Element(nameof(capBank.AssetKey));
                capBank.Description = (string)capacitorBankElement.Element(nameof(capBank.Description));
                capBank.AssetName = (string)capacitorBankElement.Element(nameof(capBank.AssetName));

                assets.Add(capBank.ID, capBank);
            }

            foreach (XElement xfrElement in rootElement.Elements("transformer"))
            {

                Transformer xfr = new Transformer()
                {
                    AssetLocations = new List<AssetLocation>(),
                    MeterAssets = new List<MeterAsset>(),
                    DirectChannels = new List<Channel>(),
                    Connections = new List<AssetConnection>(),
                    AssetTypeID = (int)AssetType.Transformer
                };
                xfr.ThermalRating = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.ThermalRating)));
                xfr.SecondaryVoltageKV = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.SecondaryVoltageKV)));
                xfr.PrimaryVoltageKV = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.PrimaryVoltageKV)));
                xfr.Tap = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.Tap)));
                xfr.R0 = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.R0)));
                xfr.X0 = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.X0)));
                xfr.R1 = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.R1)));
                xfr.X1 = Convert.ToDouble((string)xfrElement.Element(nameof(xfr.X1)));

                xfr.ID = Convert.ToInt32((string)xfrElement.Element(nameof(xfr.ID)));
                xfr.AssetKey = (string)xfrElement.Element(nameof(xfr.AssetKey));
                xfr.Description = (string)xfrElement.Element(nameof(xfr.Description));
                xfr.AssetName = (string)xfrElement.Element(nameof(xfr.AssetName));

                assets.Add(xfr.ID, xfr);
            }

            foreach (XElement lineElement in rootElement.Elements("line"))
            {

                Line line = new Line()
                {
                    AssetLocations = new List<AssetLocation>(),
                    MeterAssets = new List<MeterAsset>(),
                    DirectChannels = new List<Channel>(),
                    Connections = new List<AssetConnection>(),
                    AssetTypeID = (int)AssetType.Line,
                    Segments = new List<LineSegment>()
                };
                line.VoltageKV = Convert.ToDouble((string)lineElement.Element(nameof(line.VoltageKV)));
                line.MaxFaultDistance = Convert.ToInt32((string)lineElement.Element(nameof(line.MaxFaultDistance)));
                line.MinFaultDistance = Convert.ToInt32((string)lineElement.Element(nameof(line.MinFaultDistance)));

                line.ID = Convert.ToInt32((string)lineElement.Element(nameof(line.ID)));
                line.AssetKey = (string)lineElement.Element(nameof(line.AssetKey));
                line.Description = (string)lineElement.Element(nameof(line.Description));
                line.AssetName = (string)lineElement.Element(nameof(line.AssetName));

                assets.Add(line.ID, line);
            }

            foreach (XElement lineSegmentElement in rootElement.Elements("lineSegment"))
            {

                LineSegment lineSegment = new LineSegment()
                {
                    AssetLocations = new List<AssetLocation>(),
                    MeterAssets = new List<MeterAsset>(),
                    DirectChannels = new List<Channel>(),
                    Connections = new List<AssetConnection>(),
                    AssetTypeID = (int)AssetType.LineSegement
                };
                lineSegment.ThermalRating = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.ThermalRating)));
                lineSegment.R0 = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.R0)));
                lineSegment.X0 = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.X0)));
                lineSegment.R1 = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.R1)));
                lineSegment.X1 = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.X1)));
                lineSegment.Length = Convert.ToDouble((string)lineSegmentElement.Element(nameof(lineSegment.Length)));

                lineSegment.ID = Convert.ToInt32((string)lineSegmentElement.Element(nameof(lineSegment.ID)));
                lineSegment.AssetKey = (string)lineSegmentElement.Element(nameof(lineSegment.AssetKey));
                lineSegment.Description = (string)lineSegmentElement.Element(nameof(lineSegment.Description));
                lineSegment.AssetName = (string)lineSegmentElement.Element(nameof(lineSegment.AssetName));

                assets.Add(lineSegment.ID, lineSegment);
            }
            foreach (XElement assetConnectionElement in rootElement.Elements("assetConnection"))
            {
                AssetConnection assetConnection = new AssetConnection();

                assetConnection.ID = Convert.ToInt32((string)assetConnectionElement.Element(nameof(assetConnection.ID)));
                assetConnection.ChildID = Convert.ToInt32((string)assetConnectionElement.Element(nameof(assetConnection.ChildID)));
                assetConnection.ParentID = Convert.ToInt32((string)assetConnectionElement.Element(nameof(assetConnection.ParentID)));
                assetConnection.AssetRelationshipTypeID = Convert.ToInt32((string)assetConnectionElement.Element(nameof(assetConnection.AssetRelationshipTypeID)));

                assets[assetConnection.ChildID].Connections.Add(assetConnection);
                assets[assetConnection.ParentID].Connections.Add(assetConnection);

                if (assets[assetConnection.ChildID].AssetTypeID == (int)AssetType.Line && assets[assetConnection.ParentID].AssetTypeID == (int)AssetType.LineSegement)
                {
                    Line line = (Line)assets[assetConnection.ChildID];
                    LineSegment lineSegment = (LineSegment)assets[assetConnection.ParentID];
                    line.Segments.Add(lineSegment);
                    lineSegment.Line = line;
                    assets[assetConnection.ChildID] = line;
                    assets[assetConnection.ParentID] = lineSegment;
                }
                else if (assets[assetConnection.ParentID].AssetTypeID == (int)AssetType.Line && assets[assetConnection.ChildID].AssetTypeID == (int)AssetType.LineSegement)
                {
                    Line line = (Line)assets[assetConnection.ParentID];
                    LineSegment lineSegment = (LineSegment)assets[assetConnection.ChildID];
                    line.Segments.Add(lineSegment);
                    lineSegment.Line = line;
                    assets[assetConnection.ParentID] = line;
                    assets[assetConnection.ChildID] = lineSegment;
                }

                assetConnection.Child = assets[assetConnection.ChildID];
                assetConnection.Parent = assets[assetConnection.ParentID];
            }

            Dictionary<int, Channel> channels = new Dictionary<int, Channel>();
            Dictionary<int, MeasurementType> measurementTypes = new Dictionary<int, MeasurementType>();
            Dictionary<int, MeasurementCharacteristic> measurementCharacteristics = new Dictionary<int, MeasurementCharacteristic>();
            Dictionary<int, Phase> phases = new Dictionary<int, Phase>();

            foreach (XElement channelElement in rootElement.Elements("channel"))
            {
                Channel channel = new Channel() { Series = new List<Series>() };
                channel.ID = Convert.ToInt32((string)channelElement.Element(nameof(channel.ID)));
                channel.MeterID = Convert.ToInt32((string)channelElement.Element(nameof(channel.MeterID)));
                channel.AssetID = Convert.ToInt32((string)channelElement.Element(nameof(channel.AssetID)));
                channel.MeasurementTypeID = Convert.ToInt32((string)channelElement.Element(nameof(channel.MeasurementTypeID)));
                channel.MeasurementCharacteristicID = Convert.ToInt32((string)channelElement.Element(nameof(channel.ID)));
                channel.PhaseID = Convert.ToInt32((string)channelElement.Element(nameof(channel.PhaseID)));
                channel.Name = (string)channelElement.Element(nameof(channel.Name));
                channel.SamplesPerHour = Convert.ToDouble((string)channelElement.Element(nameof(channel.SamplesPerHour)));
                channel.PerUnitValue = ToNullableDouble((string)channelElement.Element(nameof(channel.PerUnitValue)));
                channel.HarmonicGroup = Convert.ToInt32((string)channelElement.Element(nameof(channel.HarmonicGroup)));
                channel.Description = (string)channelElement.Element(nameof(channel.Description));
                channel.Enabled = Convert.ToBoolean((string)channelElement.Element(nameof(channel.Enabled)));
                channels.Add(channel.ID, channel);

                channel.MeasurementType = measurementTypes.GetOrAdd(channel.MeasurementTypeID, id => new MeasurementType()
                {
                    ID = id,
                    Name = (string)channelElement.Element(nameof(channel.MeasurementType))
                });

                channel.MeasurementCharacteristic = measurementCharacteristics.GetOrAdd(channel.MeasurementCharacteristicID, id => new MeasurementCharacteristic()
                {
                    ID = id,
                    Name = (string)channelElement.Element(nameof(channel.MeasurementCharacteristic))
                });

                channel.Phase = phases.GetOrAdd(channel.PhaseID, id => new Phase()
                {
                    ID = id,
                    Name = (string)channelElement.Element(nameof(channel.Phase))
                });

                channel.Meter = meter;
                meter.Channels.Add(channel);

                channel.Asset = assets[channel.AssetID];
                channel.Asset.DirectChannels.Add(channel);
            }

            Dictionary<int, SeriesType> seriesTypes = new Dictionary<int, SeriesType>();

            foreach (XElement seriesElement in rootElement.Elements("series"))
            {
                Series series = new Series();
                series.ID = Convert.ToInt32((string)seriesElement.Element(nameof(series.ID)));
                series.ChannelID = Convert.ToInt32((string)seriesElement.Element(nameof(series.ChannelID)));
                series.SeriesTypeID = Convert.ToInt32((string)seriesElement.Element(nameof(series.SeriesTypeID)));
                series.SourceIndexes = (string)seriesElement.Element(nameof(series.SourceIndexes));

                series.SeriesType = seriesTypes.GetOrAdd(series.SeriesTypeID, id => new SeriesType()
                {
                    ID = id,
                    Name = (string)seriesElement.Element(nameof(series.SeriesType))
                });

                series.Channel = channels[series.ChannelID];
                series.Channel.Series.Add(series);
            }

            foreach (XElement assetLocationElement in rootElement.Elements("assetLocation"))
            {
                AssetLocation assetLocation = new AssetLocation();
                assetLocation.ID = Convert.ToInt32((string)assetLocationElement.Element(nameof(assetLocation.ID)));
                assetLocation.LocationID = Convert.ToInt32((string)assetLocationElement.Element(nameof(assetLocation.LocationID)));
                assetLocation.AssetID = Convert.ToInt32((string)assetLocationElement.Element(nameof(assetLocation.AssetID)));

                assetLocation.Location = location;
                location.AssetLocations.Add(assetLocation);

                assetLocation.Asset = assets[assetLocation.AssetID];
                assetLocation.Asset.AssetLocations.Add(assetLocation);
            }

            foreach (XElement meterAssetElement in rootElement.Elements("meterAsset"))
            {
                MeterAsset meterAsset= new MeterAsset();
                meterAsset.ID = Convert.ToInt32((string)meterAssetElement.Element(nameof(meterAsset.ID)));
                meterAsset.MeterID = Convert.ToInt32((string)meterAssetElement.Element(nameof(meterAsset.MeterID)));
                meterAsset.AssetID = Convert.ToInt32((string)meterAssetElement.Element(nameof(meterAsset.AssetID)));

                meterAsset.Meter = meter;
                meter.MeterAssets.Add(meterAsset);

                meterAsset.Asset = assets[meterAsset.AssetID];
                meterAsset.Asset.MeterAssets.Add(meterAsset);
            }

            return meter;
        }
    }
}


text:
#include "test_util.h"

#include "flash.h"
#include "string.h"
#include "system.h"
#include "task.h"
#include "write_protect.h"

static bool write_protect_enabled;

test_static int test_write_protect(void)
{
	TEST_EQ(write_protect_is_asserted(), write_protect_enabled, "%d");

	return EC_SUCCESS;
}

test_static int test_ro_protection_enabled(void)
{
	TEST_BITS_SET(crec_flash_get_protect(), EC_FLASH_PROTECT_RO_NOW);

	return EC_SUCCESS;
}

test_static int test_system_is_locked(void)
{
	if (!write_protect_is_asserted() ||
	    (~crec_flash_get_protect() & EC_FLASH_PROTECT_RO_NOW))
		TEST_EQ(system_is_locked(), 0, "%d");
	else
		TEST_EQ(system_is_locked(), 1, "%d");

	return EC_SUCCESS;
}

static void print_usage(void)
{
	ccprintf("usage: runtest [wp_on|wp_off]\n");
}

void test_run_step(uint32_t state)
{
	/*
	 * Step 1: Check if reported write protect and system_is_locked()
	 * output is correct. Since RO protection is not enabled at this point
	 * we expect system_is_locked() to return 0. If write protect is
	 * enabled then attempt to enable RO protection.
	 */
	if (state & TEST_STATE_MASK(TEST_STATE_STEP_1)) {
		RUN_TEST(test_write_protect);
		RUN_TEST(test_system_is_locked);

		if (test_get_error_count())
			test_reboot_to_next_step(TEST_STATE_FAILED);
		else if (write_protect_enabled) {
			ccprintf("Request RO protection at boot\n");
			crec_flash_set_protect(EC_FLASH_PROTECT_RO_AT_BOOT,
					       EC_FLASH_PROTECT_RO_AT_BOOT);
			test_reboot_to_next_step(TEST_STATE_STEP_2);
		} else {
			/* Write protect is disabled, nothing else to do */
			test_reboot_to_next_step(TEST_STATE_PASSED);
		}
	}
	/*
	 * Step 2: Check if hardware write protect is enabled, RO protection
	 * is enabled and system_is_locked() returns 1.
	 */
	else if (state & TEST_STATE_MASK(TEST_STATE_STEP_2)) {
		/* Expect hardware write protect to be enabled */
		write_protect_enabled = true;
		RUN_TEST(test_write_protect);
		RUN_TEST(test_ro_protection_enabled);
		RUN_TEST(test_system_is_locked);
		if (test_get_error_count())
			test_reboot_to_next_step(TEST_STATE_FAILED);
		else
			test_reboot_to_next_step(TEST_STATE_PASSED);
	}
}

int task_test(void *unused)
{
	test_run_multistep();
	return EC_SUCCESS;
}

void run_test(int argc, const char **argv)
{
	test_reset();

	if (IS_ENABLED(CONFIG_SYSTEM_UNLOCKED)) {
		ccprintf("Please disable CONFIG_SYSTEM_UNLOCKED before "
			 "running this test\n");
		test_fail();
		return;
	}

	if (argc < 2) {
		print_usage();
		test_fail();
		return;
	}

	if (strncmp(argv[1], "wp_on", 5) == 0)
		write_protect_enabled = true;
	else if (strncmp(argv[1], "wp_off", 6) == 0) {
		write_protect_enabled = false;
		if (IS_ENABLED(CONFIG_WP_ALWAYS)) {
			ccprintf("Hardware write protect always enabled. "
				 "Please disable CONFIG_WP_ALWAYS before "
				 "running this test\n");
			test_fail();
			return;
		}
	} else {
		print_usage();
		test_fail();
		return;
	}

	msleep(30); /* Wait for TASK_ID_TEST to initialize */
	task_wake(TASK_ID_TEST);
}


text:
package hostnameutils

import (
	"strings"
)

func Reverse(hostname string) string {
	chunks := strings.Split(hostname, ".")

	for i, j := 0, len(chunks)-1; i < j; i, j = i+1, j-1 {
		chunks[i], chunks[j] = chunks[j], chunks[i]
	}

	reverse_hostname := strings.Join(chunks, ".")

	return reverse_hostname
}

func ReverseOffset(hostname string, offset int8) string {
	chunks := strings.Split(hostname, ".")

	for i, j := 0, len(chunks)-1; i < j; i, j = i+1, j-1 {
		chunks[i], chunks[j] = chunks[j], chunks[i]
	}

	reverse_hostname := strings.Join(chunks[offset:], ".")

	return reverse_hostname
}


text:
/**
 * convert numbers to pretty formatted human readable sentences
 *
 *
 * example:
 *    toWords(352) -> "three hundred fifty-two"
 *
 *    toWordsOrdinal(352) -> "three hundred fifty-second"
 *
 *
 *
 *
 *
 *
 */

import {isFinite} from '../is';
import {
    TEN,
    ONE_HUNDRED,
    ONE_THOUSAND,
    ONE_MILLION,
    ONE_BILLION,
    ONE_TRILLION,
    LESS_THAN_TWENTY,
    TENTHS_LESS_THAN_HUNDRED,
    ORDINAL_LESS_THAN_THIRTEEN,
    ENDS_WITH_DOUBLE_ZERO_PATTERN,
    ENDS_WITH_TEEN_PATTERN,
    ENDS_WITH_Y_PATTERN,
    ENDS_WITH_ZERO_THROUGH_TWELVE_PATTERN
} from './constants';

/**
 * Converts an integer into words.
 * If number is decimal, the decimals will be removed.
 * @example toWords(12) => 'twelve'
 * @param {number|string} number
 * @param {boolean} asOrdinal
 * @returns {string}
 */
export default function toWords(number, asOrdinal) {
    number = parseInt(number, 10);
    if (!isFinite(number)) {
        return "Infinity";
    }

    var words = generateWords(number);
    return asOrdinal ? makeOrdinal(words) : words;
}

/**
 * Converts a number into ordinal words.
 * @example toWordsOrdinal(12) => 'twelfth'
 * @param {number|string} number
 * @returns {string}
 */
export function toWordsOrdinal(number) {
    return toWords(number, true);
}

export function toOrdinal(number) {
    var num = parseInt(number, 10);
    if (!isFinite(num)) {
        return "Infinite";
    }
    var str = String(num);
    var lastTwoDigits = num % 100;
    var betweenElevenAndThirteen = lastTwoDigits >= 11 && lastTwoDigits <= 13;
    var lastChar = str.charAt(str.length - 1);
    return str + (betweenElevenAndThirteen ? 'th'
            : lastChar === '1' ? 'st'
            : lastChar === '2' ? 'nd'
            : lastChar === '3' ? 'rd'
            : 'th');
}

function generateWords(number, words = []) {
    var remainder = 0;
    var word = "";

    // We're done
    if (0 === number) {
        return !words.length ? 'zero' : words.join(' ').replace(/,$/, '');
    }

    // If negative, prepend "minus"
    if (number < 0) {
        words.push('minus');
        number = Math.abs(number);
    }

    if (number < 20) {
        remainder = 0;
        word = LESS_THAN_TWENTY[number];

    } else if (number < ONE_HUNDRED) {
        remainder = number % TEN;
        word = TENTHS_LESS_THAN_HUNDRED[Math.floor(number / TEN)];
        // In case of remainder, we need to handle it here to be able to add the "-"
        if (remainder) {
            word += '-' + LESS_THAN_TWENTY[remainder];
            remainder = 0;
        }

    } else if (number < ONE_THOUSAND) {
        remainder = number % ONE_HUNDRED;
        word = generateWords(Math.floor(number / ONE_HUNDRED)) + ' hundred';

    } else if (number < ONE_MILLION) {
        remainder = number % ONE_THOUSAND;
        word = generateWords(Math.floor(number / ONE_THOUSAND)) + ' thousand,';

    } else if (number < ONE_BILLION) {
        remainder = number % ONE_MILLION;
        word = generateWords(Math.floor(number / ONE_MILLION)) + ' million,';

    } else if (number < ONE_TRILLION) {
        remainder = number % ONE_BILLION;
        word = generateWords(Math.floor(number / ONE_BILLION)) + ' billion,';

    } else if (number >= ONE_TRILLION) {
        remainder = number % ONE_TRILLION;
        word = generateWords(Math.floor(number / ONE_TRILLION)) + ' trillion,';

    }

    words.push(word);

    return generateWords(remainder, words);
}

/**
 * Converts a number-word into an ordinal number-word.
 * @example makeOrdinal('one') => 'first'
 * @param {string} words
 * @returns {string}
 */
function makeOrdinal(words) {
    // Ends with *00 (100, 1000, etc.) or *teen (13, 14, 15, 16, 17, 18, 19)
    if (ENDS_WITH_DOUBLE_ZERO_PATTERN.test(words) || ENDS_WITH_TEEN_PATTERN.test(words)) {
        return words + 'th';
    }
    // Ends with *y (20, 30, 40, 50, 60, 70, 80, 90)
    else if (ENDS_WITH_Y_PATTERN.test(words)) {
        return words.replace(ENDS_WITH_Y_PATTERN, 'ieth');
    }
    // Ends with one through twelve
    else if (ENDS_WITH_ZERO_THROUGH_TWELVE_PATTERN.test(words)) {
        return words.replace(ENDS_WITH_ZERO_THROUGH_TWELVE_PATTERN, replaceWithOrdinalVariant);
    }
    return words;
}

function replaceWithOrdinalVariant(match, numberWord) {
    return ORDINAL_LESS_THAN_THIRTEEN[numberWord];
}


text:
const initialState = {
  started: false,
  succeeded: false,
  errored: false,
  ended: false
};

function createProgram(state = initialState, { type }) {
  switch (type) {
    case 'CREATE_PROGRAM_STARTED':
      return {
        started: true,
        succeeded: false,
        errored: false,
        ended: false
      };
    case 'CREATE_PROGRAM_SUCCESS':
      return {
        started: false,
        succeeded: true,
        errored: false,
        ended: false
      };
    case 'CREATE_PROGRAM_ERROR':
      return {
        started: false,
        succeeded: false,
        errored: true,
        ended: false
      };
    case 'CREATE_PROGRAM_ENDED':
      return {
        started: false,
        succeeded: false,
        errored: false,
        ended: true
      };
    default:
      return state;
  }
}

export default createProgram;


text:
Package.describe({
  summary: "Foundation 5 with Sass support"
});

Package.on_use(function (api) {
  api.use("scss", ['client', 'server']);
  api.imply('scss', ['client', 'server']);
  api.use('ui', 'client');
  api.use('jquery', 'client');

  api.add_files([
    "js/vendor/modernizr.js",
    "js/foundation/foundation.js",
    "js/foundation/foundation.abide.js",
    "js/foundation/foundation.accordion.js",
    "js/foundation/foundation.alert.js",
    "js/foundation/foundation.clearing.js",
    "js/foundation/foundation.dropdown.js",
    "js/foundation/foundation.equalizer.js",
    "js/foundation/foundation.interchange.js",
    "js/foundation/foundation.joyride.js",
    "js/foundation/foundation.magellan.js",
    "js/foundation/foundation.offcanvas.js",
    "js/foundation/foundation.orbit.js",
    "js/foundation/foundation.reveal.js",
    "js/foundation/foundation.slider.js",
    "js/foundation/foundation.tab.js",
    "js/foundation/foundation.tooltip.js",
    "js/foundation/foundation.topbar.js",
    "foundation.js"
  ], "client");
});

Package.on_test(function(api) {
  api.use("foundation5-sass");
  api.use(["scss", "tinytest", "test-helpers"]);

  api.add_files([
      "test.scss",
      "test.js"
    ], "client");
});


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <!-- This LinearLayout represents the contents of the screen  -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- The ActionBar displayed at the top -->
        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

        <!-- The main content view where fragments are loaded -->
        <FrameLayout
            android:id="@+id/flContent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>


text:
package chav1961.purelib.cdb.interfaces;

@FunctionalInterface
public interface SignatureKeeper {
	String getSignature();
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <button onclick="postVisitors(document.referrer)">방문하기</button>

    <button onclick="getVisitors()">방문자 수 확인</button>


text:
var game = new Phaser.Game(960, 600, Phaser.CANVAS, 'phaser-game', { preload: preload, create: create, update: update, render: render });

function preload() {

    game.load.tilemap('map', 'assets/tilemap_example_1920-600.json', null, Phaser.Tilemap.TILED_JSON);

    game.load.image('tileset','assets/tileset.png');

    game.load.image('fundo', 'assets/fundo_1920-600.jpg');

    game.load.spritesheet('saci', 'assets/saci_75-116.png', 75, 116);

    game.load.image('coxa', 'assets/coxa.png');

    game.load.image('caximbo', 'assets/caximbo_183-82.png');

    //game.load.image('phaser', 'assets/sprites/arrow.png');
    // game.load.spritesheet('coin', 'assets/sprites/coin.png', 32, 32);

}

var cursors;
var map;
var coins;
var player;

var layer;
var sprite;

function create() {

    game.physics.startSystem(Phaser.Game.ARCADE);
    game.physics.arcade.gravity.y = 800;

    var bg = game.add.tileSprite(0,0,1920,600,'fundo');
    //bg.fixedToCamera = true;

    map = game.add.tilemap('map');
    map.addTilesetImage('tileset','tileset');

    layer = map.createLayer('Camada de Tiles 1');
    layer.resizeWorld(); //seta o mundo com as alterações feitas
    map.setCollisionBetween(0,3, true,'Camada de Tiles 1'); // 0 espaco vazio 1 em diante os tiles do tileset

    /* Creating player  */
    player = game.add.sprite(50, game.height -180 , 'saci');
    game.physics.enable(player, Phaser.Physics.ARCADE);
    player.body.gravity.y = 500;
    player.scale.set(0.5,0.5);
    player.body.collideWorldBounds = true;

    player.animations.add('walk', [0,1], 6, true);
    game.camera.follow(player);

    coxas = game.add.group();
    coxas.enableBody = true;
    map.createFromObjects('Camada de Objetos 1', 4, 'coxa', 0,true,false, coxas);
    coxas.forEach(function (coxa){ coxa.body.allowGravity = false}, this); // faz com que as coxas nao caiam

    /*
    //  Here we create our coins group
    coins = game.add.group();
    coins.enableBody = true;

    //  And now we convert all of the Tiled objects with an ID of 34 into sprites within the coins group
    map.createFromObjects('Object Layer 1', 34, 'coin', 0, true, false, coins);

    //  Add animations to all of the coin sprites
    coins.callAll('animations.add', 'animations', 'spin', [0, 1, 2, 3, 4, 5], 10, true);
    coins.callAll('animations.play', 'animations', 'spin');

    sprite = game.add.sprite(260, 100, 'phaser');
    sprite.anchor.set(0.5);

    game.physics.arcade.enable(sprite);

    //  This adjusts the collision body size.
    sprite.body.setSize(32, 32, 16, 16);

    //  We'll set a lower max angular velocity here to keep it from going totally nuts
    sprite.body.maxAngular = 500;

    //  Apply a drag otherwise the sprite will just spin and never slow down
    sprite.body.angularDrag = 50;

    game.camera.follow(sprite);

    cursors = game.input.keyboard.createCursorKeys();*/

}

function update() {

   game.physics.arcade.collide(player, layer);
   game.physics.arcade.overlap(coxas, player, eatCoxa, null,this);

   handleKeyDown();

}

function handleKeyDown() {

            // PEGA A ENTRADA (tecla pressionada):
            if ( game.input.keyboard.isDown (Phaser.Keyboard.RIGHT) ) { // vai para esquerda

                player.x += 10;
                player.animations.play('walk');

            } else if ( game.input.keyboard.isDown (Phaser.Keyboard.LEFT) ) { // vai para esquerda

                player.x -= 10;
                player.animations.play('walk');

            } else {

                player.animations.stop();
                player.frame = 0;

            }

            if ( game.input.keyboard.isDown (Phaser.Keyboard.UP) ) { // vai para esquerda

                //console.log("press up: " + this.player.body.touching.down);

                if (player.body.onFloor()) {
                    player.animations.stop();
                    player.frame = 0;

                    player.body.velocity.y = -600;
                }

            }
};

function eatCoxa (player, coxa){
    coxa.kill();
}

function render() {

    game.debug.body(player);

}


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

using Amazon.DynamoDBv2.Model;
using System.IO;
using Amazon.Runtime.Internal.Util;
using Amazon.Util;

namespace Amazon.DynamoDBv2.DocumentModel
{
    /// <summary>
    /// A DynamoDBEntry that represents a DynamoDB null (NULL) type.
    /// </summary>
    public class DynamoDBNull : DynamoDBEntry
    {
        /// <summary>
        /// Default Constructor.
        /// </summary>
        public DynamoDBNull() { }

        /// <summary>
        /// Constant DynamoDBNull for the Null value.
        /// </summary>
        public static readonly DynamoDBNull Null = new DynamoDBNull();

        #region Overrides

        internal override AttributeValue ConvertToAttributeValue(AttributeConversionConfig conversionConfig)
        {
            return new AttributeValue
            {
                NULL = true
            };
        }

        /// <summary>
        /// Implement the Clone method.
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new DynamoDBNull();
        }

        /// <summary>
        /// Implement the Equals method.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(object obj)
        {
            var otherNull = obj as DynamoDBNull;
            if (otherNull == null)
                return false;

            return true;
        }

        /// <summary>
        /// Implement the GetHashCode method.
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            return 0;
        }

        #endregion
    }
}


text:
using System.Text.RegularExpressions;
using SourceCodeIndexer.STAC.TextExtractors;

namespace SourceCodeIndexer.STAC.FileStats
{
    public class CPlusPlusFileStatReader : FileStatReaderBase
    {
        public CPlusPlusFileStatReader()
        {
            CommentsAndStringLiteralsRegexStringRegex = new Regex(RegularExpressions.CSharpRegexCommentAndStringLiteral);
        }

        public override Regex CommentsAndStringLiteralsRegexStringRegex { get; }
    }
}


text:
desc "Project issues tools - sub-commands : open [user], closed [user]"
flags :after => "Only show issues updated after a certain date"
flags :label => "Only show issues with a certain label"
usage "github issues [type]"
command :issues do |arg1, arg2|
  return if !helper.project
  user ||= helper.owner

  case arg1
  when 'open', 'closed'
    data = helper.get_issues_for(nil, arg1)
    helper.print_issues(data, options)
  when 'web'
    if arg2.nil?
      helper.open_url helper.issues_page_for(user)
    else
      helper.open_url helper.issues_page_for(arg2)
    end
  # default to open issues on the current project
  when nil
    data = helper.get_issues_for(nil)
    helper.print_issues(data, options)
  # When the user passes something that looks like "<user>/<repo>"
  when /^(.*)\/(.*)$/
    if arg2.nil?
      data = helper.get_issues_for(arg1)
    else
      data = helper.get_issues_for(arg1, arg2)
    end
    helper.print_issues(data, options)
  else
    helper.print_issues_help
  end
end